{"record":{"id":"a9bb744e28f5ab56","repo":"thedotmack/claude-mem","slug":"rate-limited","errorCode":"rate_limited","errorMessage":"Rate limit exceeded (${opts.max} requests / ${opts.windowSec}s)","messagePattern":"Rate limit exceeded \\((.+?) requests / (.+?)s\\)","errorType":"http","errorClass":null,"httpStatus":429,"severity":"warning","filePath":"src/server/middleware/rate-limit.ts","lineNumber":42,"sourceCode":"async function enforceRateLimit(\n  repo: PostgresRateLimitRepository,\n  opts: { windowSec: number; max: number },\n  subject: string,\n  res: Response,\n  next: NextFunction,\n): Promise<Response | void> {\n  const start = floorToWindow(Date.now(), opts.windowSec);\n  const resetMs = start.getTime() + opts.windowSec * 1000;\n  const result = await repo.hit({ subjectId: subject, windowStart: start, limit: opts.max });\n  res.setHeader('X-RateLimit-Limit', String(opts.max));\n  res.setHeader('X-RateLimit-Remaining', String(Math.max(0, opts.max - result.count)));\n  // Unix-seconds reset time — the conventional companion to Retry-After that\n  // most client libraries read to schedule automatic retries.\n  res.setHeader('X-RateLimit-Reset', String(Math.ceil(resetMs / 1000)));\n  if (!result.allowed) {\n    const retryAfter = Math.max(1, Math.ceil((resetMs - Date.now()) / 1000));\n    res.setHeader('Retry-After', String(retryAfter));\n    return res.status(429).json({\n      error: 'rate_limited',\n      message: `Rate limit exceeded (${opts.max} requests / ${opts.windowSec}s)`,\n    });\n  }\n  return next();\n}\n\n/** Fixed-window per-key limiter: `max` requests per `windowSec`. */\nexport function requireRateLimit(pool: PostgresPool, opts: { windowSec: number; max: number }): RequestHandler {\n  const repo = new PostgresRateLimitRepository(pool);\n  return async (req: Request, res: Response, next: NextFunction) => {\n    const subject = req.authContext?.apiKeyId;\n    if (!subject) return next(); // unauthenticated / local-dev bypass: nothing to limit\n    try {\n      return await enforceRateLimit(repo, opts, subject, res, next);\n    } catch (error) {\n      logger.warn('HTTP', 'rate limit check failed; allowing request (fail open)', {\n        error: error instanceof Error ? error.message : String(error),","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/d8bc9755e74915e5c3b999181e10a67c889bce2a/src/server/middleware/rate-limit.ts#L24-L60","documentation":"enforceRateLimit returns 429 with code rate_limited when the sliding/fixed window check (result.allowed === false) rejects the request. Response includes Retry-After and X-RateLimit-Reset headers describing when the caller may retry.","triggerScenarios":"More than opts.max requests issued within opts.windowSec from the same identity (key/IP), causing the limiter to deny and emit 'Rate limit exceeded (max requests / windowSec s)'.","commonSituations":"Batch scripts or CI loops polling the API without backoff; multiple workers sharing one API key; retry storms after an earlier outage; misconfigured client concurrency.","solutions":["Read the Retry-After / X-RateLimit-Reset response headers and delay the next request accordingly.","Add exponential backoff with jitter to your HTTP client for 429 responses.","Reduce request concurrency or batch operations to stay under opts.max per window.","If the limit is genuinely too low for your workload, raise opts.max in the server's rate-limit configuration."],"exampleFix":"// before\nfor (const ev of events) await fetch(url, opts); // bursts past limit\n// after\nfor (const ev of events) {\n  const res = await fetch(url, opts);\n  if (res.status === 429) {\n    await new Promise(r => setTimeout(r, Number(res.headers.get('Retry-After')) * 1000));\n  }\n}","handlingStrategy":"retry","validationCode":"function canSend(nowMs, lastSentMs, maxPerWindow, windowMs) {\n  return nowMs - lastSentMs >= windowMs / maxPerWindow;\n}","typeGuard":null,"tryCatchPattern":"async function sendWithBackoff(fn, retries = 3) {\n  for (let i = 0; ; i++) {\n    const res = await fn();\n    if (res.status !== 429 || i >= retries) return res;\n    const wait = Number(res.headers.get('Retry-After') ?? 2 ** i);\n    await new Promise(r => setTimeout(r, wait * 1000 + Math.random() * 500));\n  }\n}","preventionTips":["Honor Retry-After and X-RateLimit-Reset headers on every 429.","Throttle client concurrency below opts.max per window.","Batch multiple operations into one request where the API allows it.","Add jittered exponential backoff instead of tight retry loops."],"tags":["rate-limit","http-429","backoff","middleware"],"backgroundTag":"rate-limit-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"}