Skip to content

RateLimitOptions

Defined in: src/http/cache/RateLimit.ts:34

HTTP rate-limiting middleware backed by a Cache (Redis recommended for multi-process deployments; InMemoryCache for single-process).

Algorithm: fixed-window counter. The key derived from the request is incremented on every request; the first increment seeds the TTL to windowMs. Once the counter exceeds max, the wrapper short- circuits with a 429 Too Many Requests response carrying a Retry-After header.

Why fixed-window over token-bucket / sliding-log?

  • One Redis op per request (INCR + EXPIRE). Cheap, atomic.
  • Industry-standard for “X requests per minute” guarantees.
  • The well-known burst-at-window-boundary edge case (2× quota in a small window around the rollover) is acceptable for almost every real use-case. If you need precision, a sliding window would be a separate primitive.

Usage:

const limited = rateLimit({ cache: ext.cache(), windowMs: 60_000, max: 100, key: (req) => req.headers[‘x-forwarded-for’] ?? '', }); route(post(‘/api/expensive’, limited(handler)));

readonly cache: Cache

Defined in: src/http/cache/RateLimit.ts:36

Backing cache. Should be a shared/distributed one (Redis) in prod.


readonly key: (req) => string | Promise<string>

Defined in: src/http/cache/RateLimit.ts:42

Identity function — typically derives from IP, user id, or API key.

HttpRequest

string | Promise<string>


readonly optional keyPrefix?: string

Defined in: src/http/cache/RateLimit.ts:47

Cache-key namespace prepended to the user key. Defaults to 'rl:' so multiple rate-limiters in the same cache don’t collide.


readonly max: number

Defined in: src/http/cache/RateLimit.ts:40

Maximum requests allowed per window per key.


readonly optional onLimit?: (ctx) => HttpResponse

Defined in: src/http/cache/RateLimit.ts:53

Custom 429 response builder. Receives the limit context for full control over the body / headers. Default: a plain 429 with Retry-After (seconds-rounded-up).

RateLimitContext

HttpResponse


readonly windowMs: number

Defined in: src/http/cache/RateLimit.ts:38

Length of the rolling window in milliseconds.