thedotmack/claude-mem · warning

rate_limited

rate_limited

Error message

Rate limit exceeded (${opts.max} requests / ${opts.windowSec}s)

What it means

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.

Solutions

  1. Read the Retry-After / X-RateLimit-Reset response headers and delay the next request accordingly.
  2. Add exponential backoff with jitter to your HTTP client for 429 responses.
  3. Reduce request concurrency or batch operations to stay under opts.max per window.
  4. If the limit is genuinely too low for your workload, raise opts.max in the server's rate-limit configuration.

Example fix

// before
for (const ev of events) await fetch(url, opts); // bursts past limit
// after
for (const ev of events) {
  const res = await fetch(url, opts);
  if (res.status === 429) {
    await new Promise(r => setTimeout(r, Number(res.headers.get('Retry-After')) * 1000));
  }
}
Defensive patterns

Strategy: retry

Validate before calling

function canSend(nowMs, lastSentMs, maxPerWindow, windowMs) {
  return nowMs - lastSentMs >= windowMs / maxPerWindow;
}

Try / catch

async function sendWithBackoff(fn, retries = 3) {
  for (let i = 0; ; i++) {
    const res = await fn();
    if (res.status !== 429 || i >= retries) return res;
    const wait = Number(res.headers.get('Retry-After') ?? 2 ** i);
    await new Promise(r => setTimeout(r, wait * 1000 + Math.random() * 500));
  }
}

Prevention

When it happens

Trigger: 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)'.

Common situations: 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.

Related errors


AI-assisted analysis of thedotmack/claude-mem@d8bc9755e7 (2026-09-17). Data as JSON: /api/errors/a9bb744e28f5ab56. Report an issue: GitHub.

Appendix: source

Thrown at src/server/middleware/rate-limit.ts:42

async function enforceRateLimit(
  repo: PostgresRateLimitRepository,
  opts: { windowSec: number; max: number },
  subject: string,
  res: Response,
  next: NextFunction,
): Promise<Response | void> {
  const start = floorToWindow(Date.now(), opts.windowSec);
  const resetMs = start.getTime() + opts.windowSec * 1000;
  const result = await repo.hit({ subjectId: subject, windowStart: start, limit: opts.max });
  res.setHeader('X-RateLimit-Limit', String(opts.max));
  res.setHeader('X-RateLimit-Remaining', String(Math.max(0, opts.max - result.count)));
  // Unix-seconds reset time — the conventional companion to Retry-After that
  // most client libraries read to schedule automatic retries.
  res.setHeader('X-RateLimit-Reset', String(Math.ceil(resetMs / 1000)));
  if (!result.allowed) {
    const retryAfter = Math.max(1, Math.ceil((resetMs - Date.now()) / 1000));
    res.setHeader('Retry-After', String(retryAfter));
    return res.status(429).json({
      error: 'rate_limited',
      message: `Rate limit exceeded (${opts.max} requests / ${opts.windowSec}s)`,
    });
  }
  return next();
}

/** Fixed-window per-key limiter: `max` requests per `windowSec`. */
export function requireRateLimit(pool: PostgresPool, opts: { windowSec: number; max: number }): RequestHandler {
  const repo = new PostgresRateLimitRepository(pool);
  return async (req: Request, res: Response, next: NextFunction) => {
    const subject = req.authContext?.apiKeyId;
    if (!subject) return next(); // unauthenticated / local-dev bypass: nothing to limit
    try {
      return await enforceRateLimit(repo, opts, subject, res, next);
    } catch (error) {
      logger.warn('HTTP', 'rate limit check failed; allowing request (fail open)', {
        error: error instanceof Error ? error.message : String(error),

View on GitHub (pinned to d8bc9755e7)