Cloud

Rate Limiting

Per-tenant rate limiter with fixed-window (default) or sliding-window counting, per-tenant overrides, and standard X-RateLimit headers.

3 min readUpdated DocumentationEdit this page
On this page8

Overview

tenantRateLimiter() enforces per-tenant request limits. Each tenant can have its own rule, and standard rate-limit headers are set on every response. Counters live in memory on the instance.

Register it after multiTenancy(): the tenant is read from req.locals.tenant, and requests without one are counted as 'anonymous'.

Usage

TypeScript
TS
1import { multiTenancy, tenantRateLimiter } from '@axiljs/cloud'
2
3app.use(multiTenancy({ resolveTenant }))
4app.use(tenantRateLimiter({
5  defaultRule: { max: 100, windowMs: 60_000 },
6  tenantRules: {
7    // keys are tenant IDs (req.locals.tenant.id)
8    'acme-corp':  { max: 1000,   windowMs: 60_000 },
9    'big-client': { max: 10_000, windowMs: 60_000 },
10  },
11}))

By default the key is ${tenantId}:${method}:${path}, so each tenant gets a separate budget per endpoint.

Algorithms

algorithmBehavior
'fixed' (default)One counter per key that resets when the window ends. Every request, including rejected ones, counts until the reset.
'sliding'Sliding window counter: the previous window's count is weighted by how much of it still overlaps the current window. Rejected requests are not counted.
TypeScript
TS
1app.use(tenantRateLimiter({
2  defaultRule: { max: 100, windowMs: 60_000 },
3  algorithm: 'sliding',
4}))

Response Headers

When the response exposes res.raw.setHeader (as AxilJS responses do), every request gets:

HeaderDescription
X-RateLimit-LimitMaximum requests in the window
X-RateLimit-RemainingRequests remaining in the window
X-RateLimit-ResetUnix time (seconds) when the current window ends
X-RateLimit-TenantTenant ID the limit applies to

Exceeding the Limit

Over-limit requests never reach next() as a normal request:

  • AxilJS response (has status() and json()): 429 with { "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Rate limit exceeded for tenant \"<id>\".", "retryAfterMs": 12345 } }
  • Raw Node response: 429, Retry-After header in seconds, body { "error": "Rate limit exceeded" }
  • No way to respond: an Error with status and statusCode set to 429 is passed to next(err)

Custom Key Extraction

Override how rate-limit keys are generated. The tenant rule is still chosen by req.locals.tenant.id.

TypeScript
TS
1app.use(tenantRateLimiter({
2  defaultRule: { max: 100, windowMs: 60_000 },
3  keyExtractor: (req) => `${req.locals.tenant?.id}:${req.ip}`,
4}))

Bypassing System Paths

Exclude health checks and metrics endpoints so dashboards are not throttled during load tests. Create the limiter once; building a new one per request would reset its counters every time.

TypeScript
TS
1const limiter = tenantRateLimiter({
2  defaultRule: { max: 100, windowMs: 60_000 },
3})
4
5app.use((req, res, next) => {
6  if (req.path === '/health' || req.path === '/metrics' || req.path === '/dashboard') {
7    return next()
8  }
9  return limiter(req, res, next)
10})

Options Reference

OptionTypeDefaultDescription
defaultRule{ max: number; windowMs: number }— (required)Rule for tenants without an override
tenantRulesRecord<string, RateLimitRule>{}Per-tenant overrides keyed by tenant ID
keyExtractor(req) => string`${tenantId}:${method}:${path}`Custom counter key
algorithm'fixed' | 'sliding''fixed'Counting algorithm

Note

RateLimitRule also declares an optional pathPattern field, but the middleware does not read it in 0.3.3. Use keyExtractor or a wrapper middleware (as above) for per-path rules.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY