Cloud

Rate Limiting

Per-tenant sliding window rate limiter with configurable rules.

2 min readDocumentationEdit this page

Overview

The rate limiter enforces per-tenant request limits using a sliding window counter. Each tenant can have its own rate limit, and standard rate-limit headers are set automatically on every response.

Usage

typescript
import { tenantRateLimiter } from '@axiljs/cloud'
 
app.use(tenantRateLimiter({
  defaultRule: { max: 100, windowMs: 60_000 },
  tenantRules: {
    'free-tier':    { max: 10,     windowMs: 60_000 },
    'pro-tier':     { max: 1000,   windowMs: 60_000 },
    'enterprise':   { max: 10_000, windowMs: 60_000 },
  },
}))

Response Headers

Every response includes standard rate-limit headers:

HeaderDescription
X-RateLimit-LimitMaximum requests in the window
X-RateLimit-RemainingRequests remaining in the window
X-RateLimit-ResetUnix timestamp when the window resets
X-RateLimit-TenantThe tenant ID the limit applies to

Exceeding the Limit

When a tenant exceeds their limit, the middleware returns:

  • HTTP 429 Too Many Requests
  • JSON body with retryAfterMs indicating when to retry

Custom Key Extraction

Override how rate-limit keys are generated:

typescript
app.use(tenantRateLimiter({
  defaultRule: { max: 100, windowMs: 60_000 },
  keyExtractor: (req) => `${req.locals.tenant?.id}:${req.path}`,
}))

Bypassing System Paths

Exclude health checks and metrics endpoints from rate limiting to prevent dashboards from being throttled during heavy load testing.

typescript
app.use((req, res, next) => {
  const path = req.path
  if (path === '/health' || path === '/metrics' || path === '/dashboard') {
    return next()
  }
  return tenantRateLimiter({
    defaultRule: { max: 100, windowMs: 60_000 },
  })(req, res, next)
})

Options Reference

OptionTypeDefaultDescription
defaultRule{ max, windowMs }—Fallback rate limit
tenantRulesRecord<string, { max, windowMs }>{}Per-tenant overrides
keyExtractor(req) => stringtenant:method:pathCustom key function

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY