Rate limiting
The classic algorithms, why a per-server counter breaks the moment you have more than one server, and how shared state, and a decision about failure, fix it. With an interactive 3D system you can break yourself.
ConceptApplied13 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 1 data model
- 1 API design
- 2 code samples
- 5 interviewer follow-ups
- 3 self-checks
On this page12 sectionsLLDSenior depth
Read first: Load balancing, Caching, Consistency and availability
- Compare fixed window, sliding window, token bucket and leaky bucket.
- Explain why independent per-instance counters let through up to instances x limit.
- Describe a shared counter in Redis and why the check must be atomic.
- Decide what the limiter does when its shared store is unreachable: fail open, fail closed, or fall back to local.
Break a distributed rate limiter in 3D
A guided, explorable system. Change the limit and the traffic, stop instances, take Redis offline under three failure policies, and watch local, divided and shared counters give different answers on identical requests.
Open the interactive2 code samples (64 lines), collapsed so the explanation stays in focus.
A rate limiter caps how many requests a client may make in a period of time. It protects a system from abuse and accidents, keeps one noisy client from starving everyone else, and puts a ceiling on cost. It looks like a ten-line problem. It becomes a real distributed systems problem the moment your service runs on more than one server.
- Abuse and attacks. Credential stuffing, scraping, and floods of automated requests such as OTP or login attempts. When each code is an SMS, a flood also runs up a bill (the notification service lesson covers SMS pumping, and encryption, secrets and abuse puts rate limits into a layered defence).
- Fairness. One client should not consume capacity meant for all.
- Stability. Limits stop a retry storm or a buggy client from taking down a dependency.
- Cost control. Especially for paid downstream APIs.
Decide the key you limit by (user ID, API key, IP address, or a combination), the limit and window (for example, 100 requests per minute), and the response: usually HTTP 429 "Too Many Requests", with a Retry-After header so well-behaved clients know when to come back (the API design lesson puts limits, retries and errors into one contract).
Fixed window counter. Keep a count per client per clock window (say, each minute). Increment on each request; reject above the limit. Cheap and simple. The flaw is the boundary: a client can send a full quota at the end of one window and another full quota at the start of the next, allowing up to twice the limit within a single window-length span.
Sliding window log. Store a timestamp for every request in the window. To decide, drop timestamps older than the window, count what remains, and allow the request only if the count is below the limit. It is exact, but it stores one entry per request, which is memory-heavy at scale. This is the algorithm the interactive world uses, because its behaviour is easiest to see.
Sliding window counter. Approximate the sliding window by combining the current and previous fixed windows, weighted by how far you are into the current one. Small memory, close accuracy.
Token bucket. A bucket holds up to a maximum number of tokens and refills at a steady rate. Each request spends a token; no token, no request. It allows short bursts up to the bucket size while enforcing a long-run average. Very common in practice.
Leaky bucket. Requests enter a queue and drain at a fixed rate. Used as a queue, it smooths bursts into a steady output at the price of delaying requests; used as a meter, it simply rejects whatever exceeds the rate.
| Algorithm | Memory | Accuracy | Allows bursts |
|---|---|---|---|
| Fixed window | Very low | Boundary spikes | Yes, at edges |
| Sliding window log | High | Exact | Up to the limit, never more per window |
| Sliding window counter | Low | Close | Slightly |
| Token bucket | Low | Good | Yes, by design |
| Leaky bucket | Low | Good | As a queue: absorbs bursts, outputs at a steady rate |
At the edge (CDN or API gateway), in a shared middleware layer, or inside each service. The earlier you reject, the less work the rest of the system does, but the less context you have. Many systems layer them: a coarse limit at the edge, finer limits in services.
Imagine a limit of 5 requests per window and three application instances behind a load balancer. Each instance keeps its own counter in memory.
Spread requests evenly and each instance sees about a third of the traffic. Each one thinks "I have only seen 2, I am well under 5" and lets everything through. The system as a whole has accepted far more than 5. In the worst case it allows instances x limit, and the more you scale out, the weaker the protection gets, exactly when you need it most.
There are three families of answer, and the interesting part is seeing how each behaves on identical traffic.
1. Local counters (what goes wrong)
Simple and fast, no dependencies. But the effective limit is the sum of every instance's limit, and it drifts as instances are added or removed. It is only accurate if routing happens to be sticky per client.
2. Divide the limit
Give each instance limit divided by the number of instances. Total is bounded, no shared state needed. The problem is uneven traffic: if one client's requests mostly land on one instance (sticky routing, a hot key), that instance rejects requests long before the client has actually exceeded the real limit, so legitimate users get refused while the system as a whole has room.
3. Shared state
Keep the counters in one place that every instance consults, commonly Redis. Now every instance sees the same count and the system-wide limit is enforced regardless of how traffic is distributed.
One subtle requirement: the check must be atomic. "Read the count, compare, then write" as three separate steps lets two instances both read 4 and both allow the fifth request. Use a single atomic operation: for a fixed window, an increment whose expiry is set in the same step (a small Lua script or a transaction, because INCR followed by a separate EXPIRE can leave a counter with no expiry if the client dies in between); for a sliding window, a Lua script that removes expired entries, counts, and records the new request. A sorted set keyed by timestamp implements the sliding window log neatly, and a token bucket needs only two stored values per key (the token count and the last refill time). Take timestamps from the store's own clock so instances with skewed clocks cannot disagree.
One atomic check
With shared state, the check and the take must be a single step. If a gateway reads the count and then writes it back, two requests can read the same value and both pass. Run the whole decision inside the store as one script.
tokensfloat
current tokens; fractional so refill is smooth
last_refillint
milliseconds, taken from the Redis server clock
Set a TTL slightly longer than the time to refill fully, so idle buckets expire on their own.
- Latency. Every request now includes a network round trip to the store. Mitigate by keeping the store close, pipelining, or letting instances take small batches of tokens locally and refill from the store in bulk (trading some accuracy for speed).
- Hot keys. One very busy client concentrates load on one key. Shard the store, and consider limiting a hot key locally first.
- It is another dependency. Which leads to the most important design question.
This is the question that separates a thoughtful answer from a textbook one. The limiter is in the request path. If Redis is unreachable, you must choose a policy:
| Policy | Behaviour | Good when | Risk |
|---|---|---|---|
| Fail open | Allow everything | Availability matters most and the limit is a convenience | Protection disappears exactly when things are already unhealthy; an attacker who can degrade Redis disables the limit |
| Fail closed | Reject everything | Protecting something fragile or expensive, or a security control such as login attempts | A limiter outage becomes a full outage for legitimate users |
| Fall back to local | Use per-instance counters | You want bounded damage with no total outage | Accuracy degrades to instances x limit until Redis returns |
Falling back to local counters is often the most defensible default for general APIs; fail closed fits narrow, high-risk endpoints. In the interactive world you can take Redis offline and watch each policy play out on the same traffic: fail-open lets a flood straight through, fail-closed refuses everyone including legitimate requests, and the local fallback sits in between.
The token bucket from the algorithms list, as code. Tokens drip in at a steady rate up to a capacity; each request spends some; a request that finds too few is rejected. Capacity is the burst allowance and the refill rate is the sustained rate. Refilling lazily, when a request arrives, means no timer runs for idle clients.
C# · TokenBucket
using System;
public sealed class TokenBucket
{
private readonly double _capacity;
private readonly double _refillPerSecond;
private readonly Func<DateTime> _now;
private double _tokens;
private DateTime _lastRefill;
public TokenBucket(double capacity, double refillPerSecond, Func<DateTime> now)
{
_capacity = capacity;
_refillPerSecond = refillPerSecond;
_now = now;
_tokens = capacity; // start full: a new client gets its burst
_lastRefill = now();
}
/// <summary>Spend tokens if there are enough. False means rejected, and nothing is spent.</summary>
public bool TryTake(double cost = 1)
{
Refill();
if (_tokens < cost) return false;
_tokens -= cost;
return true;
}
/// <summary>How long until enough tokens exist: the value for a Retry-After header.</summary>
public TimeSpan RetryAfter(double cost = 1)
{
Refill();
return _tokens >= cost ? TimeSpan.Zero : TimeSpan.FromSeconds((cost - _tokens) / _refillPerSecond);
}
private void Refill()
{
DateTime now = _now();
double elapsed = (now - _lastRefill).TotalSeconds;
if (elapsed <= 0) return; // the clock did not move, or went backwards: add nothing
_tokens = Math.Min(_capacity, _tokens + elapsed * _refillPerSecond);
_lastRefill = now;
}
}The clock is injected, so a test can move time without waiting:
C#
using System.Diagnostics;
var clock = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bucket = new TokenBucket(capacity: 5, refillPerSecond: 1, now: () => clock);
int allowed = 0;
for (int i = 0; i < 8; i++) if (bucket.TryTake()) allowed++;
Debug.Assert(allowed == 5); // a burst of five, then rejected
TimeSpan wait = bucket.RetryAfter();
Debug.Assert(wait == TimeSpan.FromSeconds(1)); // empty, refilling at one token a second
clock = clock.AddSeconds(2);
bool first = bucket.TryTake(), second = bucket.TryTake(), third = bucket.TryTake();
Debug.Assert(first && second && !third); // two seconds bought two tokens
clock = clock.AddSeconds(3600); // an idle hour does not bank an hour of tokens
int burst = 0;
for (int i = 0; i < 10; i++) if (bucket.TryTake()) burst++;
Debug.Assert(burst == 5);This object lives in one process, which is exactly the local-counter trap described above. In a fleet the same arithmetic runs inside the shared store as one atomic script, so the read, the refill and the spend cannot interleave. What the caller sees on a rejection matters too:
- auth
- none, limited by phone number and by IP
- body
- { "phone": "+15555550123" }
- 202accepted, the code is on its way
- 429limit reached; Retry-After holds the seconds to wait
- 503the limiter's store is down and the policy is fail-closed
The numbers above are easy to read and easy to forget. The interactive companion makes them stick. In it you can change the limit and window, send bursts or sustain an attack, stop instances, route all traffic to one instance, and compare local, divided and shared counting side by side. It also shows the one case where they all agree: with a single instance, local counting is exactly right, and the problem only appears when you scale out.
When asked to design a rate limiter, cover these in order:
- Requirements: key, limit, window, hard or soft limit, per-endpoint or global.
- Algorithm choice and why (usually token bucket or sliding window).
- Where it sits (gateway, middleware) and what it returns: HTTP 429, ideally with a
Retry-Afterheader (RFC 6585 says a server may include it). Many APIs also sendX-RateLimit-*headers, and an IETF draft proposes standardRateLimitfields. - The multi-server problem: why local counters fail, and the shared store with an atomic check.
- Failure policy when the store is down.
- Scale: shard the store by key, keep it close, batch tokens locally if latency matters.
Interviewer follow-upL6What is wrong with "read the counter, then write it back"?How to answer
It races. Two requests read the same value, both see room, and both increment, so the limit is exceeded. Make the decision atomic: an atomic increment for a fixed window, or a script or transaction inside the store for token buckets and sliding windows. The principle is to move the check and update to where the data lives.
Interviewer follow-upL6The gateway servers have different clocks. What breaks in a sliding window?How to answer
Each server computes window boundaries differently, so the same request can be inside the window for one server and outside it for another, and refill amounts drift. Use a single time source for the decision, such as the store's own clock inside the script, instead of each server's clock.
Interviewer follow-upL7Enforce one global limit across three regions. What are the trade-offs?How to answer
A single shared counter adds cross-region latency to every request and creates a dependency on a far region. Practical options: give each region a share of the limit and rebalance periodically, replicate counts asynchronously and accept overshoot bounded by the sync interval, or route each user to a home region that owns their counter. Decide how strict the limit must be: a billing-critical quota differs from protecting a service from overload.
Interviewer follow-upL5Token bucket or leaky bucket: what is the difference?How to answer
A token bucket allows bursts up to its capacity and then limits the average rate: tokens build up while a client is quiet and are spent per request. A leaky bucket smooths output to a constant rate: requests join a queue and leave at a fixed pace, and arrivals that overflow it are dropped. Use a token bucket when short bursts are fine and the average matters (most public APIs), and a leaky bucket when the downstream needs a steady rate.
Interviewer follow-upL6What should the client see when a request is rejected?How to answer
HTTP 429 (Too Many Requests) with a Retry-After header saying when to try again, so well-behaved clients back off instead of hammering. Use the same shape for every limit, and name which limit was hit when that helps debugging, but do not leak details an attacker could use to tune around a security limit. Rejecting must be cheap: do it before any expensive work, or a flood of rejected requests still costs you.
A single-server rate limiter is trivial. A distributed one needs shared state and an atomic check, and a deliberate answer to "what if the shared state is unavailable". Choose the algorithm for the burst behaviour you want, and choose the failure policy for the endpoint you are protecting.
Try answering out loud before you reveal each answer.
QuestionThree instances each enforce a limit of 5 with local counters. What is the worst case for the whole system?Reveal answer
Up to 15 requests (instances times limit), and it grows as you add instances.
QuestionWhy must the check against Redis be atomic?Reveal answer
With separate read, compare and write steps, two instances can both read 4 and both allow the fifth request. Use a single atomic operation, a script or a transaction.
QuestionRedis is unreachable. What do fail open, fail closed and local fallback each do?Reveal answer
Fail open allows everything, so protection disappears. Fail closed rejects everything, so legitimate users have an outage. Local fallback uses per-instance counters: damage is bounded, but accuracy drops to instances times limit.