SYSTEM DESIGN SKETCHBOOK / PRACTICE SHEET / NO. 09
Design an API rate limiter
A public API sits behind a fleet of gateway servers. Customers call it with API keys, and each plan allows a certain request rate with some room for short bursts. Without limits, one buggy client in a retry loop can take the API down for everyone; with sloppy limits, paying customers get rejected for no reason.
Requirements
- Limit requests per API key per endpoint group, for example 100 requests per second with bursts up to 200 on the standard plan.
- Reject over-limit requests with HTTP 429, a Retry-After value, and headers showing the limit and what remains.
- Change a customer's limits without redeploying gateways; the change takes effect within a minute.
- Limits apply to the key as a whole, not per gateway server.
Constraints and assumptions
- 2 million requests per second at peak across 300 gateway nodes in 3 regions.
- 5 million API keys exist; about 50,000 are active in any given minute.
- The limiter may add at most 2 ms at p99 to a request.
- Brief over-admission is acceptable (up to about 10% for a few seconds); rejecting a customer who is under their limit is not.
- An abusive or broken client may send 50,000 requests per second on a single key.
Out of scope for the first sketch
Bot detection and IP reputation · Network-layer DDoS protection · Billing for usage
Draw your design
Rough math and notes
SYSTEM DESIGN SKETCHBOOK / FOLLOW-UPS
Design an API rate limiter
Finish your first sketch before answering these. Cross out freely.
- Which algorithm do you use, and what exactly is stored per key? What goes wrong at the edge of a fixed one-second window?
- The shared counter store is unreachable for 30 seconds. Do requests go through or get rejected? Is the answer the same for every endpoint?
- One key sends 50,000 requests per second. What does that do to your counter store, and how do you protect it?
- The same key is used from two regions at once. How do you enforce one limit without a cross-region round trip on every request?
- Product adds a monthly quota of 10 million calls per customer, billed per call. What changes compared with the per-second limit?
Compare afterwards: worked approaches and reading at sketchbook /questions/rate-limiter/review