Rate Limiting
Per-tenant rate limiter with fixed-window (default) or sliding-window counting, per-tenant overrides, and standard X-RateLimit headers.
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
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
algorithm | Behavior |
|---|---|
'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. |
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:
| Header | Description |
|---|---|
X-RateLimit-Limit | Maximum requests in the window |
X-RateLimit-Remaining | Requests remaining in the window |
X-RateLimit-Reset | Unix time (seconds) when the current window ends |
X-RateLimit-Tenant | Tenant ID the limit applies to |
Exceeding the Limit
Over-limit requests never reach next() as a normal request:
- AxilJS response (has
status()andjson()):429with{ "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Rate limit exceeded for tenant \"<id>\".", "retryAfterMs": 12345 } } - Raw Node response:
429,Retry-Afterheader in seconds, body{ "error": "Rate limit exceeded" } - No way to respond: an
ErrorwithstatusandstatusCodeset to429is passed tonext(err)
Custom Key Extraction
Override how rate-limit keys are generated. The tenant rule is still chosen by
req.locals.tenant.id.
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.
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
| Option | Type | Default | Description |
|---|---|---|---|
defaultRule | { max: number; windowMs: number } | — (required) | Rule for tenants without an override |
tenantRules | Record<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?