Rate Limiting
How rate limiters count requests, how the five common algorithms differ, where to run the limiter, and what interviewers ask about it.
On this page
A rate limiter caps how many requests a client may make in a period of time and rejects the requests over the cap. It protects a service from being overloaded by one client, shares capacity fairly between clients, enforces the limits of a paid plan, and slows down attacks such as password guessing.
Without a limit, one client with a retry bug or a runaway script can use most of the capacity of an API, and every other client sees slow responses or errors. The limiter adds a check to every request and needs state that all servers share.
Where the limiter sits
For every request the limiter builds a key, such as the API key, looks up how much of that key's allowance has been used, and either lets the request through or rejects it.
Counting algorithms
The algorithms differ in how much state they keep per key, whether they allow bursts, and how they behave at the boundary between two time periods.
Fixed window counter
The limiter keeps one counter per key for each fixed period, such as each calendar minute. Every request adds one, requests are rejected once the counter passes the limit, and a new counter starts when the minute ends. It needs only one number per key.
Its weakness is the window edge. With a limit of 100 a minute, a client can send 100 requests at 0:59 and 100 more at 1:00. Both windows stay within the limit, but the server received 200 requests in two seconds. Use a fixed window for coarse quotas where this does not matter, such as 10,000 calls a day.
Sliding window log
The limiter stores the timestamp of every accepted request for each key. On a new request it removes timestamps older than the window, counts the rest, and accepts the request only if the count is below the limit. The result is exact and has no edge effect.
The cost is memory, because a limit of 1,000 requests a minute means up to 1,000 stored timestamps for each active client. Pick it for low limits that must be exact, such as five login attempts in 15 minutes.
Sliding window counter
The limiter keeps the counters for the current and the previous fixed window, and estimates the requests in the last full window by weighting the previous count by how much of it still overlaps. With a limit of 100 a minute, 80 requests in the previous minute and 30 so far in a minute that is 15 seconds old, the estimate is 30 + 80 × 45/60 = 90, so the request is allowed.
This removes the edge spike of the fixed window while storing two numbers per key. It is approximate, because it assumes the previous window's requests were spread evenly. Pick it for a plain "N requests per minute" rule without bursts.
Token bucket
Each key has a bucket that holds up to a fixed number of tokens, the capacity, and gains tokens at a steady refill rate. Every request removes one token, and a request that finds the bucket empty is rejected. The limiter needs no timer: when a request arrives, it adds the tokens that accumulated since the previous request, up to the capacity, and then takes one.
The capacity sets how large a burst is allowed, and the refill rate sets the long-term average. It needs two numbers per key, the token count and the time of the last refill. It is the usual choice for API limits because real clients send short bursts. Its drawback is that a full bucket lets a burst reach the backend, so the capacity must be a burst the backend can handle.
on request at time now: tokens = min(capacity, tokens + (now - last) * rate) last = now if tokens >= 1: tokens = tokens - 1 allow else: reject with 429- bucket0●1●2●3●4●
- now
- 0
- tokens
- 5
- allowed
- 0
- rejected
- 0
1A new client starts with a full bucket of 5 tokens.
- bucket01234
- now
- 0
- tokens
- 0
- allowed
- 5
- rejected
- 0
2Five requests arrive at t = 0. Each takes a token and is allowed. This burst is what the capacity permits.
- bucket01234
- now
- 0.2
- tokens
- 0.2
- allowed
- 5
- rejected
- 1
3At t = 0.2 only 0.2 tokens have been added, which is less than 1, so the request is rejected with a 429 and
Retry-After: 1. - bucket0●1●234
- now
- 3
- tokens
- 2
- allowed
- 6
- rejected
- 1
4At t = 3 the bucket has gained 2.8 tokens, so it holds 0.2 + 2.8 = 3. The request takes one and is allowed.
- bucket0●1●2●3●4
- now
- 10
- tokens
- 4
- allowed
- 7
- rejected
- 1
5At t = 10 the refill would give 2 + 7 = 9 tokens, but the bucket holds only 5, so idle time saves at most one burst. The request takes one token.
Leaky bucket
Requests are added to a queue of fixed size, and the queue is drained at a fixed rate. If the queue is full when a request arrives, the request is rejected.
A token bucket passes a burst through immediately, while a leaky bucket holds the burst in the queue and releases it at an even pace. The price is added latency for queued requests. Pick it when the next system needs a steady rate, such as a partner API that rejects anything over 50 calls a second. It is less common for protecting your own API, because queued requests make clients wait instead of failing fast.
What to limit by
API key or user id
For authenticated callers, the API key or user id is the best key, because it identifies one customer and the limit can follow their plan. It cannot protect the login step itself, because the caller is not yet authenticated.
IP address
The IP address is available for every request, so it is the key for login pages, sign-ups and flood protection. Many users can share one address, such as an office or a mobile network, so a strict per-IP limit blocks innocent users, and an attacker can rotate through addresses to avoid it. Use the IP address before authentication and the account or key afterwards.
Different limits for different tiers and endpoints
Real systems have several limits at once. A free plan might get 60 requests a minute and a paid plan 600, and an expensive search or export endpoint gets a lower limit than a simple read. Build the key from the customer and the endpoint group, load the limit values from configuration, and allow a request only if it passes every limit that applies.
Where the limiter runs
A client can limit its own calls, which helps cooperating clients, but the server cannot rely on it. The limiter therefore runs in one of two places on the server side.
At the edge or API gateway
Most limiters run in the API gateway or in a proxy at the edge. The gateway sees every request before any service does, so rejected requests cost the backend nothing, and the rules are in one place. This is the default for per-customer quotas.
Inside a service
A service can limit the calls it receives from other internal services, or the calls it makes to an outside dependency. The second case is the common one: a service that calls a payment provider limited to 50 calls a second needs its own limiter on that outgoing traffic, which the gateway cannot provide.
Counting across many servers
If the gateway runs on ten nodes and each node counts requests on its own, a client whose requests are spread across the nodes can send ten times the limit. There are three ways to keep the count consistent.
A central store with atomic operations
All nodes keep their counters in one shared in-memory store, such as Redis, and every request updates it. The count is exact, which makes this the default for quotas. It adds a network call to every request, and the store must handle the total request rate.
The update must be atomic. If a node reads the counter, checks it, and writes it back as separate steps, two nodes can both read 99 and both write 100, and the client has made 101 requests. Use an atomic increment, or a short server-side script that refills the bucket and takes a token in a single step. A related problem is incrementing a counter and setting its expiry as two commands: if the process stops between them, the counter never expires and the client stays blocked. Take timestamps from the store's own clock, because the clocks of the gateway nodes differ slightly and that skews the refill calculation.
Splitting the limit across nodes
Each of the ten nodes is given a tenth of the limit and counts locally, with no shared state and no extra network call. This works only if the load balancer spreads each client's requests evenly over the nodes. If one client's traffic lands mostly on one node, that node rejects requests while the others sit idle, and the client sees a limit lower than it paid for.
Local counts synchronised periodically
Each node counts locally and sends its counts to the others, or to a shared store, about once a second. Requests are fast because they never wait for the network. The limit can be exceeded by whatever arrives between two synchronisations, and the overshoot grows with the number of nodes. It suits flood protection but not strict quotas.
Client responses, limiter failure and multiple regions
What the client receives
A rejected request gets the status 429 Too Many Requests. The response should include a Retry-After header with the number of seconds to wait, so the client does not have to guess. Many APIs also send headers with the limit, the remaining allowance and the reset time on every response, so clients can slow down before they are rejected. Clients should respond to a 429 by waiting for the Retry-After time and then retrying with exponential backoff and random jitter. Without jitter, all rejected clients retry at the same moment and cause the same overload again.
What happens when the limiter is down
If the counter store is unreachable, the limiter must choose between two behaviours. Failing open means allowing every request, so a limiter outage does not become an outage of the whole API, at the price of having no protection for a while. Failing closed means rejecting requests, which keeps protection but turns the limiter into a single point of failure. A general-purpose API should fail open, ideally falling back to a coarse local limit on each node. Login and other endpoints that attackers target should fail closed, or use a strict local limit.
Rate limiting across regions
A single global counter store adds a cross-region round trip to every request. The usual answer is a counter store in each region, with each region allowed a share of the global limit, so the limit is exact within a region and approximate overall.
In the interview
Bring up rate limiting when the design has a public API, an expensive endpoint, a login, or a dependency with its own limits. Say the key, the algorithm, where it runs and how counters are shared, for example: "I would limit per API key with a token bucket at the gateway, keep the counters in a shared in-memory store, and return 429 with a Retry-After header." Use a token bucket unless a requirement points elsewhere: a sliding window when bursts must not be allowed, and a leaky bucket when you must send traffic at a steady rate.
Questions to expect:
- "Which algorithm would you use?" A token bucket, because real clients send short bursts and the bucket allows them while holding the average rate. If no burst is acceptable, use a sliding window counter.
- "What is wrong with a fixed window?" A client can send the full limit at the end of one window and again at the start of the next, so twice the limit arrives in a short time.
- "How does it work with many servers?" Keep the counters in a shared in-memory store and update them atomically, so two servers cannot both read the same value and both accept. If the extra network call is too slow or the limit can be approximate, count locally and synchronise periodically.
- "What if the limiter goes down?" Fail open for a general API so the limiter does not take it down, and fail closed or use a strict local limit for login and similar endpoints.
- "What should a client do on a 429?" Wait for the
Retry-Aftertime and retry with exponential backoff and jitter. Retrying immediately makes the overload worse.
How would you stop one customer from overloading the API?
I would put a token bucket per API key in the gateway. It allows the short bursts that normal clients send and caps the average rate. With several gateway nodes, the counters live in a shared in-memory store, and refilling and taking a token happens in one atomic script.
And if that store goes down?
For this API I would fail open, with each node falling back to a local limit of the total divided by the number of nodes. For the login endpoint I would fail closed, because that is where an attacker gains most from having no limit.
A token bucket has capacity 10 and refills 2 tokens a second. It is empty at t = 0. A request arrives at t = 3. How many tokens are left after it is allowed?
A partner API rejects anything over 50 calls a second, and your own traffic to it comes in bursts. Which limiter fits your outgoing calls?
What to practise next
The full design, with per-endpoint rules, regions and failure handling, is in Design a Rate Limiter. Counters spread over many cache nodes rely on consistent hashing, and the retry behaviour of clients is covered in Idempotency and Retries.