Rate Limiting
A single client sending thousands of requests per second — by accident or on purpose — can slow your API for everyone, run up your cloud bill or brute-force a login form. Rate limiting caps how many requests a client may make in a time window and answers the rest with 429 Too Many Requests.
Choosing a key
A limiter counts requests per key:
| Key | Good for | Watch out |
|---|---|---|
client IP (req.ip) |
anonymous traffic | many users can share one IP (offices, mobile carriers); behind a proxy set app.set('trust proxy', 1) |
| user id | authenticated APIs | needs authentication to run first |
| API key | public developer APIs | per-plan limits |
| IP + route | login forms | stops password guessing on one endpoint |
Algorithms
| Algorithm | Idea | Trade-off |
|---|---|---|
| Fixed window | count per clock window (e.g. per minute) | simple; allows bursts at window edges |
| Sliding window | count requests in the last N seconds | smoother; stores timestamps |
| Token bucket | tokens refill at a steady rate; each request spends one | allows short bursts, enforces an average rate |
A fixed-window limiter, step by step
The clock is injected so the example can "move time" deterministically. Real code would use Date.now():
class FixedWindowLimiter {
private hits = new Map<string, { windowStart: number; count: number }>();
constructor(private limit: number, private windowMs: number, private now: () => number) {}
check(key: string) {
const t = this.now();
const windowStart = t - (t % this.windowMs);
let entry = this.hits.get(key);
if (!entry || entry.windowStart !== windowStart) {
entry = { windowStart, count: 0 };
this.hits.set(key, entry);
}
entry.count++;
return {
allowed: entry.count <= this.limit,
remaining: Math.max(0, this.limit - entry.count),
resetInMs: windowStart + this.windowMs - t,
};
}
}
let clock = 10_000;
const limiter = new FixedWindowLimiter(3, 1000, () => clock);
for (const step of [0, 100, 100, 100, 800, 100]) {
clock += step;
const r = limiter.check('1.2.3.4');
console.log(`t=${clock} allowed=${r.allowed} remaining=${r.remaining} resetIn=${r.resetInMs}ms`);
}t=10000 allowed=true remaining=2 resetIn=1000ms
t=10100 allowed=true remaining=1 resetIn=900ms
t=10200 allowed=true remaining=0 resetIn=800ms
t=10300 allowed=false remaining=0 resetIn=700ms
t=11100 allowed=true remaining=2 resetIn=900ms
t=11200 allowed=true remaining=1 resetIn=800ms
As Express middleware
Wrap the limiter in a middleware factory and send the standard headers so well-behaved clients can slow down on their own:
const express = require('express');
function rateLimit({ limit, windowMs, key = (req) => req.ip, now }) {
const hits = new Map();
return (req, res, next) => {
const t = now();
const windowStart = t - (t % windowMs);
const k = key(req);
let entry = hits.get(k);
if (!entry || entry.windowStart !== windowStart) {
entry = { windowStart, count: 0 };
hits.set(k, entry);
}
entry.count++;
const resetSeconds = Math.ceil((windowStart + windowMs - t) / 1000);
res.set({
'RateLimit-Limit': String(limit),
'RateLimit-Remaining': String(Math.max(0, limit - entry.count)),
'RateLimit-Reset': String(resetSeconds),
});
if (entry.count > limit) {
res.set('Retry-After', String(resetSeconds));
return res.status(429).json({ error: 'Too many requests, slow down' });
}
next();
};
}
let fakeClock = 60_000;
const app = express();
app.use('/api', rateLimit({
limit: 2,
windowMs: 60_000,
key: (req) => req.get('X-Api-Key') ?? req.ip,
now: () => fakeClock,
}));
app.get('/api/quote', (req, res) => res.json({ quote: 'Make it work, then make it fast.' }));
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/api/quote`;
const call = async (apiKey) => {
const res = await fetch(url, { headers: { 'X-Api-Key': apiKey } });
const h = (n) => res.headers.get(n);
console.log(apiKey, res.status, `remaining=${h('ratelimit-remaining')} retry-after=${h('retry-after')}`);
};
await call('team-a');
await call('team-a');
await call('team-a');
await call('team-b'); // a different key has its own budget
fakeClock += 60_000; // next window
await call('team-a');
server.close();
});team-a 200 remaining=1 retry-after=null
team-a 200 remaining=0 retry-after=null
team-a 429 remaining=0 retry-after=60
team-b 200 remaining=1 retry-after=null
team-a 200 remaining=1 retry-after=null
Production concerns
| Concern | Solution |
|---|---|
| several server instances each count separately | keep counters in a shared store such as Redis |
| memory grows with every new IP | expire old entries (Redis EXPIRE, or periodic cleanup) |
| real client IP hidden by a load balancer | app.set('trust proxy', 1) so req.ip reads X-Forwarded-For safely |
| login brute force | a much stricter limit on /login, keyed by IP and account |
In practice, reach for the express-rate-limit package (with a Redis store for multi-instance deployments), or enforce limits at the edge — in your reverse proxy, API gateway or CDN.
const { rateLimit } = require('express-rate-limit');
app.use('/api', rateLimit({ windowMs: 60_000, limit: 100, standardHeaders: 'draft-8' }));Tip: Clients should treat
429like a polite "come back later": waitRetry-Afterseconds, then retry with exponential backoff.
Test yourself
Which status code signals that a client exceeded its rate limit?
- 403
- 409
- 429
- 503
Why does an in-memory limiter break when you run four server instances?
- Memory is too small
- Each instance counts separately, so the real limit becomes four times higher
- Express can't run on multiple instances
- 429 isn't supported behind load balancers
What is a weakness of the fixed-window algorithm?
- It can't count requests
- It allows bursts around window boundaries
- It needs a database
- It only works for POST