A rolling window means: at any moment, count the requests in the last 60 seconds, not in the current clock minute. The direct way is a log: keep the time of each allowed request, drop the ones older than the window, and allow the request only if fewer than N remain. A fixed counter that resets every minute is simpler but lets 2N through around the reset. The "annotation" is a higher-order function: it takes the endpoint handler and returns a wrapper that checks the limiter first. For an endpoint the limit is per client (a Map keyed by user or IP), and a blocked request gets 429 Too Many Requests with a Retry-After header. Then discuss memory (the log keeps up to N timestamps per client; a token bucket keeps two numbers) and several servers (the counts must live in a shared store).
Implement a rate limiter attribute/decoration/annotation on top of an API endpoint. Caps to N requests per minute with a rolling window. Source A and Source B
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The wrapper keeps the times of the calls it allowed, oldest first. On each call it drops the times that have left the window, and if limit are still there it throws; otherwise it records the time and calls through with the same this and arguments. Blocked calls aren't recorded, so hammering a blocked endpoint doesn't extend the block. The checks show the window rolling (a call is allowed again exactly 60 s after the oldest one) and that there's no double burst across a minute boundary. Its gap: one limit shared by every caller.
// Rolling window: keep the time of every allowed call. A call is allowed if fewer than `limit`// of them happened in the last `windowMs`.function rateLimit(fn, { limit, windowMs = 60_000 }) {const times = []; // oldest firstreturn function (...args) {const now = Date.now();while (times.length && times[0] <= now - windowMs) times.shift(); // fell out of the windowif (times.length >= limit) throw new Error('rate limit exceeded');times.push(now);return fn.apply(this, args);};}
passes 6 checks run on every build, against the native method where there is one
- allows `limit` calls, then throws
- the window rolls: a call is allowed again 60 s after the oldest one
- not a fixed window: no double burst across a minute boundary
- blocked calls don't count against the limit
- keeps this, arguments and the return value
- the weakness: one shared limit for every caller
createLimiter keeps one log per key. take(key) returns whether the request is allowed, how many are left, and how long until the oldest request leaves the window. rateLimited(handler, options) is the decorator for an endpoint: it picks the key from the request (IP by default, or a user id), and over the limit it answers 429 with Retry-After in whole seconds without calling the handler. sweep() removes clients with nothing left in the window; run it on a timer so the map doesn't grow without bound.
// An endpoint is limited per client, and a blocked client should be told when to come back.function createLimiter({ limit, windowMs = 60_000 }) {const logs = new Map(); // key -> times of allowed requests, oldest firstreturn {take(key) {const now = Date.now();const times = logs.get(key) ?? [];while (times.length && times[0] <= now - windowMs) times.shift();if (times.length >= limit) {return { allowed: false, remaining: 0, retryAfterMs: times[0] + windowMs - now };}times.push(now);logs.set(key, times);return { allowed: true, remaining: limit - times.length, retryAfterMs: 0 };},// Forget clients with nothing left in the window, so the map doesn't grow forever.sweep() {const now = Date.now();for (const [key, times] of logs) {if (times[times.length - 1] <= now - windowMs) logs.delete(key);}return logs.size;},};}// The "annotation": wrap a handler. Over the limit, answer 429 and say when to retry.function rateLimited(handler, { limit, windowMs = 60_000, keyOf = (req) => req.ip }) {const limiter = createLimiter({ limit, windowMs });return function (req, res) {const { allowed, retryAfterMs } = limiter.take(keyOf(req));if (!allowed) {res.statusCode = 429;res.setHeader('Retry-After', Math.ceil(retryAfterMs / 1000)); // secondsres.end('Too Many Requests');return;}return handler.call(this, req, res);};}
passes 7 checks run on every build, against the native method where there is one
- each client has its own limit
- reports what's left and when to retry
- the window rolls per client
- sweep forgets idle clients only
- the wrapped handler runs under the limit
- over the limit: 429 with Retry-After in seconds, and the handler isn't called
- keyOf chooses what a client is
The log costs up to limit numbers per client. A token bucket stores a token count and a time: the bucket refills at a steady rate up to its capacity and each request spends a token. It allows short bursts and is O(1) per client, but it enforces an average rate, not an exact count per window, so say which one the product needs. limited(options) has the shape of a standard method decorator: it receives the method and returns the replacement, so with decorator syntax it's written @limited({ limit: 100 }) above the method. It accepts any limiter with take(key).
// The log keeps up to `limit` timestamps per client. A token bucket keeps two numbers per// client: it holds up to `capacity` tokens, gains one every `refillEveryMs`, and a request// spends one. Bursts up to `capacity` are allowed; the long-run rate is one per `refillEveryMs`.function createTokenBucket({ capacity, refillEveryMs }) {const buckets = new Map(); // key -> { tokens, at }return {take(key) {const now = Date.now();const bucket = buckets.get(key) ?? { tokens: capacity, at: now };bucket.tokens = Math.min(capacity, bucket.tokens + (now - bucket.at) / refillEveryMs);bucket.at = now;buckets.set(key, bucket);if (bucket.tokens < 1) {return { allowed: false, retryAfterMs: Math.ceil((1 - bucket.tokens) * refillEveryMs) };}bucket.tokens -= 1;return { allowed: true, retryAfterMs: 0 };},};}function createLimiter({ limit, windowMs = 60_000 }) {const logs = new Map();return {take(key) {const now = Date.now();const times = logs.get(key) ?? [];while (times.length && times[0] <= now - windowMs) times.shift();if (times.length >= limit) return { allowed: false, retryAfterMs: times[0] + windowMs - now };times.push(now);logs.set(key, times);return { allowed: true, retryAfterMs: 0 };},};}// As a real decorator (TC39 decorators, TypeScript 5): `@limited({ limit: 100 })` above a// method. A method decorator receives the method and returns its replacement. Any limiter with// take(key) fits, so the algorithm can change without touching the endpoints.function limited({ keyOf = (req) => req.ip, limiter, ...options }) {const gate = limiter ?? createLimiter(options);return function (method) {return function (req, ...rest) {const { allowed, retryAfterMs } = gate.take(keyOf(req));if (!allowed) throw Object.assign(new Error('Too Many Requests'), { status: 429, retryAfterMs });return method.call(this, req, ...rest);};};}
passes 7 checks run on every build, against the native method where there is one
- token bucket: a burst up to capacity, then blocked
- token bucket: one token back per interval, with the wait reported
- token bucket: never holds more than capacity
- token bucket: clients are separate
- decorator: wraps a method, keeps this, throws a 429 error over the limit
- decorator: the rolling window lets a call through after 60 s
- decorator: any limiter with take(key) can be plugged in
429 Too Many Requests
The status code for a client that has sent too many requests in a given time. The response may include Retry-After to say how long to wait.
express-rate-limit
The common Express middleware has the same parts: a window, a limit, a key generator (IP by default) and a pluggable store, so counts can be shared by several servers.
Token bucket
The classic algorithm for limiting an average rate while allowing bursts, used widely in networking and API gateways.
A counter that resets every minute when a rolling window was asked for: a client can send N just before the reset and N just after.
One global limit instead of one per client.
Recording blocked requests, so a client that keeps retrying is never let back in.
Never removing old timestamps or idle clients: memory grows without bound.
Returning 429 with no
Retry-After, so clients can only guess and retry at once.Keeping counts in one server's memory when the endpoint runs on several servers.
Losing
thisand the arguments in the wrapper.
How does this work across several servers?
The counts have to live in a store every server shares, such as Redis, and the check-and-record must be one atomic step there, or two servers can both allow the last request.
Fixed window, sliding log, sliding counter, token bucket?
Fixed window: one counter, but up to 2N around a reset. Sliding log: exact, up to N timestamps per client. Sliding counter: two counters weighted by how far into the window you are, approximate and cheap. Token bucket: two numbers, allows bursts, enforces an average rate.
What key should identify a client?
A user id or API key when the request is authenticated. IP is the fallback, but many users can share one IP and one user can have many. Behind a proxy the real address is in a forwarded header, which can only be trusted if your own proxy sets it.
What should the client do with a 429?
Wait at least Retry-After, then retry with backoff and some randomness so that many clients don't all return at the same instant.
- developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
- developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- en.wikipedia.org/wiki/Token_bucket
- github.com/tc39/proposal-decorators
- typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html
- github.com/express-rate-limit/express-rate-limit