Security

Rate Limiting

Per-client request throttling with custom keys from the full request, skip rules, pluggable stores and 429 responses with Retry-After.

4 min readUpdated DocumentationEdit this page
On this page6

Usage

TypeScript
TS
import { rateLimit } from '@axiljs/security'
app.use(rateLimit({ max: 100, windowMs: 60000 }))

Per-route limits

TypeScript
TS
1app.post('/auth/login',
2  rateLimit({ max: 5, windowMs: 900000 }),
3  loginHandler
4)

Each rateLimit() call has its own store, so limiters with different windows never share counters.

Options

OptionDefaultDescription
windowMs60000Window length in ms
max100Requests allowed per key per window
message'Too many requests, please try again later'Error message for the 429
keyGeneratorreq => req.ip(req) => string, receives the full request
skip—(req) => boolean, receives the full request; true bypasses the limiter
headerstrueSend X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
storenew MemoryStoreA RateLimitStore (increment(key, windowMs), reset(key)) shared across instances, e.g. Redis

Exceeding the limit passes a TooManyRequestsError (HTTP 429, code RATE_LIMIT_EXCEEDED) to the error handlers and sets a Retry-After header.

Custom keys and skip rules

Note

Changed in 0.3.3: keyGenerator and skip receive the full request (ip, headers, params, path, method, locals, …), not only ip and headers. Route params are already populated when the limiter runs, including when it is registered with app.use().

TypeScript
TS
1// One budget per webhook source: /hooks/github and /hooks/stripe are limited separately
2app.post('/hooks/:source',
3  rateLimit({ max: 30, keyGenerator: (req) => `webhook:${req.params.source}` }),
4  webhookHandler
5)
6
7// Per API key, and never limit health checks
8app.use(rateLimit({
9  max: 1000,
10  keyGenerator: (req) => String(req.headers['x-api-key'] ?? req.ip),
11  skip: (req) => req.path === '/health'
12}))

Warning

The default key is req.ip. Since 0.3.3 req.ip ignores X-Forwarded-For unless server.trustProxy is set. Behind a load balancer without trustProxy, every client shares the proxy's IP and therefore one budget; with trustProxy: true and no proxy that overwrites the header, clients can forge X-Forwarded-For to dodge the limit.

Across cluster workers

Note

New in 0.3.4: ClusterStore and installClusterRateLimitPrimary().

In cluster mode (for example serve() from @axiljs/scale, one node:cluster worker per core) each worker is a separate process, so the default MemoryStore lets every worker accept the full max. ClusterStore sends each hit to the primary process over IPC, and the primary keeps a single set of counters.

TypeScript
TS
1import cluster from 'node:cluster'
2import { rateLimit, ClusterStore, installClusterRateLimitPrimary } from '@axiljs/security'
3
4if (cluster.isPrimary) {
5  // Once in the primary; serves current and future workers. Returns a disposer.
6  installClusterRateLimitPrimary()
7  // ... fork workers
8} else {
9  app.use(rateLimit({ max: 100, store: new ClusterStore({ namespace: 'api' }) }))
10  app.post('/login', rateLimit({
11    max: 5,
12    windowMs: 900000,
13    store: new ClusterStore({ namespace: 'login' })
14  }), login)
15}

With serve(), call installClusterRateLimitPrimary() in the onPrimary hook instead of checking cluster.isPrimary yourself.

ClusterStore optionDefaultDescription
namespace'default'Keeps the counters of different limiters apart on the primary. Use a distinct namespace per limiter
timeoutMs1000How long a worker waits for the primary before counting locally
fallbackCooldownMs5000After a timeout or send failure, count locally for this long before trying the primary again, so a missing primary does not add timeoutMs to every request
  • Fail-open. If the primary does not answer (not installed, busy or gone), hits are counted in a worker-local MemoryStore, so requests are never blocked by the primary. While degraded, the limit applies per worker rather than cluster-wide.
  • Same code without a cluster. Outside a cluster worker, ClusterStore behaves exactly like MemoryStore (synchronously). isClustered is true when counts go through the primary.
  • One machine only. Counters live in the primary's memory: they are shared by the workers of one machine, not across machines.
  • installClusterRateLimitPrimary() is idempotent: repeated calls return the same disposer. The disposer stops listening and drops every counter. ClusterStore#close() stops listening for replies and frees the worker's local counters.

Across servers

Note

New in 0.3.5: SqlRateLimitStore in @axiljs/stores.

For several servers, keep the counters in a shared database with SqlRateLimitStore. Every hit is one atomic upsert on PostgreSQL and SQLite (an upsert plus SELECT in one transaction on MySQL), so concurrent hits on different servers get distinct counts:

TypeScript
TS
1import { SqlRateLimitStore, fromConnection } from '@axiljs/stores'
2
3app.use(rateLimit({
4  windowMs: 60_000,
5  max: 100,
6  store: new SqlRateLimitStore(fromConnection(db), { table: 'api_rate_limits', cleanupIntervalMs: 60_000 })
7}))

The same key in one table shares one window, so give limiters with different windows separate tables (or distinct key prefixes). See the store reference and Running multiple instances.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY