Full answer
Request id middleware:
- Accept an id from a trusted header (x-request-id) or create one with crypto.randomUUID().
- Put it on req (req.id) and on the response header, and include it in every log line and error response.
- Validate or limit the length of incoming ids, because they end up in logs.
Token bucket rate limiter:
- Each client (IP address, API key or user id) has a bucket with capacity C tokens and a refill rate R tokens per second.
- On a request, add the tokens earned since the last request (elapsed seconds times R, up to C), then remove one. If there is none, reject.
- Compared with a fixed window counter, a token bucket allows short bursts up to C but keeps the long-term average at R, and it has no boundary effect at the window edge.
- Answer 429 Too Many Requests and send Retry-After in seconds. Also useful: RateLimit-Limit and RateLimit-Remaining style headers.
Design points:
- Key choice matters. Behind a proxy, req.ip needs app.set('trust proxy', ...) or every client looks the same.
- Memory: remove idle buckets (a periodic sweep or an LRU), or the map grows without end.
- Several servers need a shared store such as Redis with an atomic script. An in-memory limiter limits each process separately.
- Inject the clock (a now function) so tests do not wait.
- Put the limiter early in the chain, after the request id, so rejected requests are still logged with an id.
- For production use a tested library, but know how it works.
const express = require('express');
const crypto = require('node:crypto');
function requestId() {
return (req, res, next) => {
const incoming = req.get('x-request-id');
req.id = incoming && /^[\w-]{1,64}$/.test(incoming) ? incoming : crypto.randomUUID();
res.set('x-request-id', req.id);
next();
};
}
function rateLimit({ capacity, refillPerSecond, now = Date.now }) {
const buckets = new Map(); // key -> { tokens, last }
return (req, res, next) => {
const key = req.ip;
const time = now();
const bucket = buckets.get(key) || { tokens: capacity, last: time };
const earned = ((time - bucket.last) / 1000) * refillPerSecond;
bucket.tokens = Math.min(capacity, bucket.tokens + earned);
bucket.last = time;
if (bucket.tokens < 1) {
buckets.set(key, bucket);
const wait = Math.ceil((1 - bucket.tokens) / refillPerSecond);
return res.status(429).set('Retry-After', String(wait)).json({ error: 'too many requests', requestId: req.id });
}
bucket.tokens -= 1;
buckets.set(key, bucket);
next();
};
}
let fakeNow = 1_000_000; // a controllable clock for the demo
const app = express();
app.use(requestId());
app.use(rateLimit({ capacity: 3, refillPerSecond: 1, now: () => fakeNow }));
app.get('/marks', (req, res) => res.json({ ok: true, requestId: req.id }));
const server = app.listen(0, '127.0.0.1', async () => {
const url = 'http://127.0.0.1:' + server.address().port + '/marks';
const call = async (label, headers = {}) => {
const res = await fetch(url, { headers });
const body = await res.json();
console.log(label.padEnd(26), res.status, '| retry-after:', res.headers.get('retry-after') || '-', '| id echoed:', res.headers.get('x-request-id') === body.requestId);
};
await call('request 1');
await call('request 2');
await call('request 3 (custom id)', { 'x-request-id': 'client-abc-123' });
await call('request 4 (bucket empty)');
fakeNow += 1000; // one second passes, one token comes back
await call('request 5 after 1 second');
await call('request 6 (empty again)');
server.close();
});The clock is a plain variable, so a second passes without any waiting. The custom request id is accepted because it matches the allowed pattern. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): request 1 200 | retry-after: - | id echoed: true request 2 200 | retry-after: - | id echoed: true request 3 (custom id) 200 | retry-after: - | id echoed: true request 4 (bucket empty) 429 | retry-after: 1 | id echoed: true request 5 after 1 second 200 | retry-after: - | id echoed: true request 6 (empty again) 429 | retry-after: 1 | id echoed: true
Key points
- Request ids connect logs, responses and errors.
- Token bucket: capacity allows bursts, refill rate sets the average.
- Return 429 with Retry-After.
- Choose the key carefully and clean up idle buckets.
- A multi-server setup needs a shared store.
Common mistakes
- Using req.ip behind a proxy without trust proxy, so all users share one bucket.
- Never removing old buckets.
- Counting rejected requests as spent tokens.
- Running the limiter per process and expecting a global limit.
Follow-ups
- How does a sliding window limiter differ from a token bucket?
- How would you implement this limiter in Redis?
- How would you give different limits to different API keys?
Tips
- Explain burst versus average in one line.
- Mention Retry-After and the clock injection.
- State the multi-server limitation.