{"record":{"id":"235a44a4d18ec50e","repo":"thedotmack/claude-mem","slug":"quota-exceeded","errorCode":"quota_exceeded","errorMessage":"Monthly ${opts.kind} quota reached (${opts.cap})","messagePattern":"Monthly (.+?) quota reached \\((.+?)\\)","errorType":"http","errorClass":null,"httpStatus":402,"severity":"error","filePath":"src/server/middleware/rate-limit.ts","lineNumber":77,"sourceCode":"      logger.warn('HTTP', 'rate limit check failed; allowing request (fail open)', {\n        error: error instanceof Error ? error.message : String(error),\n      });\n      return next();\n    }\n  };\n}\n\n/** Checks month-to-date usage against the cap and answers 402 / next(). */\nasync function enforceMonthlyQuota(\n  repo: PostgresUsageRepository,\n  opts: { kind: string; cap: number },\n  teamId: string,\n  res: Response,\n  next: NextFunction,\n): Promise<Response | void> {\n  const used = await repo.total({ teamId, kind: opts.kind, since: monthStartUtc(new Date()) });\n  if (used >= opts.cap) {\n    return res.status(402).json({\n      error: 'quota_exceeded',\n      message: `Monthly ${opts.kind} quota reached (${opts.cap})`,\n      used,\n      cap: opts.cap,\n    });\n  }\n  return next();\n}\n\n/** Monthly per-team quota on a usage `kind` (e.g. 'request'). 402 when reached. */\nexport function requireMonthlyQuota(pool: PostgresPool, opts: { kind: string; cap: number }): RequestHandler {\n  const repo = new PostgresUsageRepository(pool);\n  return async (req: Request, res: Response, next: NextFunction) => {\n    const teamId = req.authContext?.teamId;\n    if (!teamId) return next();\n    try {\n      return await enforceMonthlyQuota(repo, opts, teamId, res, next);\n    } catch (error) {","sourceCodeStart":59,"sourceCodeEnd":95,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/d8bc9755e74915e5c3b999181e10a67c889bce2a/src/server/middleware/rate-limit.ts#L59-L95","documentation":"enforceMonthlyQuota returns 402 Payment Required with code quota_exceeded when the team's usage count (repo.total for the current UTC month) has reached opts.cap for the given quota kind. The response body includes the used count and cap.","triggerScenarios":"A team makes a request whose kind (e.g. events/generations) is counted and used >= opts.cap since monthStartUtc; every further request of that kind in the same month is rejected.","commonSituations":"End-of-month usage spikes; automated pipelines exhausting the free tier cap; a plan downgrade lowered the cap mid-month; shared team key consumed by many services.","solutions":["Check the response's used and cap fields to confirm the quota state.","Wait for the UTC month to roll over (quota resets at monthStartUtc).","Upgrade the team's plan or raise opts.cap in server configuration.","Reduce usage or move heavy workloads to a team/key with remaining quota."],"exampleFix":"// before\nawait client.createEvent(data); // 402 quota_exceeded, silently retried in a loop\n// after\nconst { used, cap } = await client.getQuota();\nif (used < cap) await client.createEvent(data);\nelse scheduleForNextMonth(data);","handlingStrategy":"fallback","validationCode":"async function hasQuotaRemaining(client, kind, cap) {\n  const { used } = await client.getUsage(kind);\n  return used < cap;\n}","typeGuard":null,"tryCatchPattern":"const res = await fetch(url, opts);\nif (res.status === 402) {\n  const { used, cap } = await res.json();\n  queueForNextBillingMonth(job);\n}","preventionTips":["Track monthly usage client-side and alert before reaching the cap.","Schedule bulk jobs early in the month to leave headroom.","Handle 402 distinctly from other errors — retrying never helps within the month.","Set budget alerts or upgrade the plan if caps are routinely hit."],"tags":["quota","billing","http-402","middleware"],"backgroundTag":"quota-exceeded","analyzedSha":"d8bc9755e74915e5c3b999181e10a67c889bce2a","analyzedAt":"2026-09-17T16:40:26.182Z","contentChangedAt":"2026-09-17T16:40:26.182Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}