A rate limiter for a public API
An API behind several servers needs fair per-customer limits that hold across all of them.
To design a rate limiter, pick an algorithm such as token bucket, keep each customer's counters in a fast shared store so every server agrees, make the check-and-decrement atomic, return a 429 with a retry hint, and decide whether the limiter fails open or closed when its store is down.
The system today: A company sells a public API. Requests reach a load balancer, which spreads them over eight identical API servers, and each server talks to the same database. There is no limit today: one customer's runaway script recently slowed everyone down.
What has to change: Design rate limiting so each customer gets a fair quota (for example 100 requests a minute, with short bursts allowed), the limit holds across all eight servers, and a rejected request tells the caller when to retry. The limiter must not become the new bottleneck or a single point of failure.
Questions to ask first
- What are we limiting by: API key, user, IP address, or endpoint?
- Is it a hard limit or can the system be a little generous under failure?
- Do different customer plans have different limits, and how quickly can a limit change?
- What should happen if the limiter's own storage is unavailable?
Where the interviewer digs in
- Choosing an algorithm: fixed window, sliding window, token bucket and what each does at the edges
- A shared counter store and making check-and-decrement atomic
- Where the limiter runs (gateway, middleware, sidecar) and the failure behaviour
What a strong answer covers
- Compares at least two algorithms and picks one with reasons; token bucket suits bursts, a sliding window gives smoother fairness.
- Keeps the counters in a fast shared store, makes the read-modify-write atomic (a script or an atomic increment), and notes the extra network hop per request.
- Returns a clear rejection (HTTP 429 with a retry-after hint) and rate-limit headers.
- Decides what happens when the store fails (fail open or fail closed) and says why; considers per-server local limits as a fallback or an optimisation.
Common mistakes
- Counting per server, so the real limit is eight times the stated one.
- A read-then-write on the counter, which lets concurrent requests slip past the limit.
- A fixed window that allows twice the limit around the boundary, without noticing.