Design a Distributed Rate Limiter
Understanding the Problem
🚦 What is a rate limiter? A rate limiter decides, for every incoming request, whether the caller has already used up their allowance for the current period. If they have, the request is rejected (usually with HTTP
429 Too Many Requests) before it reaches the service behind it. It protects services from overload and abuse, keeps one noisy customer from starving everyone else, and enforces the request limits that come with an API's pricing tiers.
Functional Requirements
Rate limiting sounds like one feature, but the shape changes a lot depending on who sets the limits and where they're enforced. Pin down with your interviewer that we're building a shared, server-side limiter that many services sit behind.
Core Requirements
- The system should identify the caller of each request (user ID, API key or IP address) and decide whether to allow it based on configured limits.
- The system should support several limits at once, per client and per endpoint, such as "100 requests per minute per user" and "10 logins per hour per IP."
- Rejected callers should get a clear response: a
429with headers that say what the limit is and when they can retry. - Operators should be able to change limits without redeploying the services that use them.
Below the line (out of scope)
- Long-term usage quotas tied to billing ("1M API calls per month"). That's a metering problem with different accuracy needs; see /system-design/quota-service.
- Network-layer DDoS protection (SYN floods, volumetric attacks). That's handled upstream by a CDN or scrubbing service.
- Limits on outbound calls that our own services make to third parties.
Non-Functional Requirements
Ask about scale and about how wrong the limiter is allowed to be. For our design: 1M requests per second at peak across a fleet of API gateways, 50M daily active users, and limits measured in seconds to hours.
Core Requirements
- The system should add very little latency to each request: under about 1ms at p99 for the limit check.
- The system should be highly available. If the limiter is down, the API it protects shouldn't be.
- The system should enforce limits globally: a user who spreads requests across 50 gateway instances still gets one allowance, not 50.
- The system should be accurate enough: letting through a few percent extra at the edges is fine; letting through 10x the limit is not.
Below the line (out of scope)
- Exact, auditable counts. Nobody gets billed off this data.
- Strict global consistency across regions. Each region can enforce its own share of a limit.
A quick estimate decides where the work is. Say at most 10M distinct clients are active in any given minute, and each one needs a counter or bucket that takes about 100 bytes in memory once you include key overhead. That's 1GB, which fits on a single machine. Memory is not the problem. Throughput is: 1M checks per second, each a read-modify-write that must be atomic. A single Redis node running small scripts handles on the order of 50k to 100k of those per second, so we'll need on the order of 10 to 20 shards, and every check is a network round trip that has to fit in our latency budget.
The interesting part of this problem is not the counting algorithm, which you can explain in two minutes. It's that the state is shared by every gateway, sits on the hot path of every request, and has to fail without taking the API down with it.
The Set Up
Planning the Approach
We'll decide where the limiter lives, how it identifies callers and finds the right limit, then pick an algorithm and build the shared-state version. The deep dives cover scaling the counter store, atomicity, failure handling and latency.
Defining the Core Entities
- Rule: one limit. Which requests it matches (endpoint, method, client tier), what it keys on (user, API key, IP), and the limit itself, such as 100 requests per 60 seconds with a burst of 20.
- Client key: the identity a rule counts against, built from the request, like
user:8812orip:203.0.113.7. Combined with the rule ID it names one counter. - Counter state: the small piece of data the algorithm keeps per client key and rule, like a token count and a timestamp. It's short-lived and expires when the client goes quiet.
API or System Interface
The limiter has two interfaces: the one services (or the gateway) call internally, and what the end client sees.
// Internal: called by the gateway on every request
checkLimit(request) -> { allowed: bool, limit, remaining, resetAt, retryAfterMs }
// External: what a rejected client receives
HTTP/1.1 429 Too Many Requests
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 23 // seconds until the allowance refills
Retry-After: 23
// Admin: managing rules
PUT /rules/{ruleId} { match, keyBy, limit, windowSec, burst }
GET /rules
Allowed requests also get the RateLimit-* headers, so well-behaved clients can slow down before they hit the wall. Many APIs use X-RateLimit-* names for the same headers.
High-Level Design
1) The system should identify the caller and decide whether to allow the request
First decision: where does the check run? There are four places it could go.
- In the client. Easy to bypass. Useful as a courtesy (an SDK that backs off on its own), never as protection.
- Inside each service, as a library. No extra hop, but every team reimplements it, and each service instance only sees its own traffic.
- In the API gateway, as middleware. Every request already passes through it, it already knows who the caller is after authentication, and it can reject bad traffic before it costs the backend anything.
- As a separate rate limiting service that the gateway or services call over the network. Centralizes the logic, but adds a hop.
We'll put the check in the gateway, with the logic in a shared library, and keep the counters in a shared store. This is the standard answer and what most interviewers expect.
The gateway builds the client key from the request. After authentication it has the user ID or API key. Before authentication, for endpoints like login or signup, all it has is the IP address. IPs are a weak identity: thousands of users can share one carrier-grade NAT address, so IP limits should be generous and reserved for unauthenticated endpoints.
2) The system should support several limits per client and endpoint
Rules live in a Rules Store, a small database (Postgres is fine) behind an admin API. There are maybe a few hundred rules in total, so every gateway keeps the full set in memory and matches each request against it locally. A rule looks like:
- id: login-per-ip
match: { path: "/v1/login", method: POST }
keyBy: ip
limit: 10
windowSec: 3600
- id: api-free-tier
match: { path: "/v1/*", tier: free }
keyBy: apiKey
limit: 100
windowSec: 60
burst: 20
One request can match several rules (a per-endpoint limit and a global per-user limit). The gateway checks all of them, and the request is allowed only if every rule allows it.
For requirement 4, gateways must pick up rule changes without a redeploy. The simple version polls the Rules Store every 30 seconds. A better version has the gateways watch a config system like etcd or a config service, so changes land in seconds. Either way, a rule change taking a few seconds to roll out is fine.
3) Choosing the algorithm
Now, what exactly do we count? There are five standard algorithms, and you should be able to explain each one and why you'd pick one over another.
Fixed window counter. Split time into windows (say, each minute) and keep one counter per client per window: INCR ratelimit:user:8812:202611291405. Reject when it passes the limit. It's one integer and one atomic increment, which is as cheap as it gets. The flaw is at window boundaries: a client can send 100 requests at 14:05:59 and another 100 at 14:06:00, which is 200 requests in two seconds against a limit of 100 per minute.
Sliding window log. Store a timestamp for every request (a Redis sorted set works well), drop the ones older than the window, and count what's left. It's exact, with no boundary problem. But it stores one entry per request: a client allowed 10,000 requests per hour needs 10,000 entries, which is a lot of memory for one counter.
Sliding window counter. Keep fixed-window counts for the current and previous window and weight them. If we're 25% of the way into the current minute, the estimate is:
estimate = previous_count * (1 - 0.25) + current_count
That's two integers per client, and it smooths out the boundary spike. It assumes requests in the previous window were spread evenly, so it's an approximation, but in practice it's within a few percent.
Token bucket. Each client has a bucket that holds up to capacity tokens and refills at rate tokens per second. Each request takes a token; if the bucket is empty, it's rejected. You don't need a timer to refill it: store the token count and the time of the last update, and on each request add elapsed * rate tokens (capped at capacity) before taking one. Two numbers per client, and it has a property the others don't: it allows short bursts up to the capacity while holding the long-run average to the refill rate. That matches how real clients behave (a page load fires 15 API calls at once, then nothing for a while).
Leaky bucket. Requests go into a fixed-size queue that drains at a constant rate. It smooths traffic into a steady stream, which is good for protecting something that can't handle bursts, like a downstream payment provider. But it adds queueing delay, and a gateway holding requests in a queue is more than we want for a limiter that just says yes or no.
| Algorithm | State per client | Bursts | Accuracy |
|---|---|---|---|
| Fixed window | 1 counter | Up to 2x at boundaries | Low at edges |
| Sliding window log | 1 entry per request | No | Exact |
| Sliding window counter | 2 counters | Smoothed | Approximate, good |
| Token bucket | Tokens + timestamp | Up to capacity, by design | Good |
| Leaky bucket | Queue | Smoothed into a fixed rate | Good, adds delay |
We'll use the token bucket as the default, with the sliding window counter as an option for rules where operators think in "N per window" terms. Both need two numbers per client key, so the storage design is the same.
If your interviewer asks which algorithm you'd pick, don't just name one. Say what the product needs. "Do we want to allow bursts?" is the question that separates token bucket from the window algorithms.
4) Rejected callers should get a clear response
When any matching rule says no, the gateway returns 429 immediately, without calling the backend, with Retry-After set from the bucket state (the time until one token refills, 1 / rate seconds for an empty bucket). Allowed requests carry RateLimit-Remaining so clients can see how close they are.
Two details are worth a sentence each:
- Don't count rejected requests against the bucket. Otherwise a client that retries aggressively never recovers, because every retry pushes its reset time further out.
- Some rules shouldn't reject at all. A rule in "shadow mode" only logs what it would have rejected. New limits should always start that way, so you can see who you'd break before you break them.
Now let's make the counter state shared. The simplest version that enforces a global limit puts all counters in one Redis instance. Every gateway, on every request, sends the token bucket logic to Redis and gets back allowed or not.
This works, and for a moderate API it's the whole design. At 1M checks per second, it has three problems: one Redis node can't do that many atomic scripts, the read-then-write needs care to be atomic, and if that Redis goes down, so does every check. The deep dives deal with each.
Potential Deep Dives
1) How do we keep the shared counters fast at 1M checks per second?
Bad Solution: Local Counters on Each Gateway
Approach
Skip the shared store entirely. Each gateway instance keeps token buckets in its own memory and enforces the limit locally. No network hop, no shared dependency.
Challenges
With 50 gateway instances behind a round-robin load balancer, a client spread across all of them gets 50 times its limit. You can divide the limit by the number of instances (each enforces 2 requests per minute of a 100 limit), but traffic isn't spread evenly. A client with a sticky connection to one instance gets 2 per minute, and the count is wrong every time the fleet scales. Local limits are fine as a coarse safety net against a single instance being flooded, but they don't meet the global requirement.
Good Solution: A Sharded Redis Cluster
Approach
Split the counters across a Redis Cluster of, say, 20 primaries, each with a replica. Each client key hashes to one shard (Redis Cluster uses 16,384 hash slots, assigned to primaries), so all checks for one client land on one node and stay atomic there. At 1M checks per second that's about 50k per shard, comfortably within what a node can do, with headroom for spikes.
If a request matches several rules for the same client, put the client ID in a hash tag so all its keys land on the same slot: rl:{user:8812}:api-free-tier and rl:{user:8812}:global. Then one script can check both rules in a single round trip.
Challenges
Hot keys. One shard handles all traffic for one client. A single abusive client sending 200k requests per second can overload its shard, which hurts every other client on that shard. That's the exact traffic we exist to block, so we can't let it take down the limiter.
Great Solution: Sharded Redis plus Local Pre-checks for Hot Keys
Approach
Keep the sharded cluster as the source of truth, and add a small amount of local state in each gateway to absorb the extremes:
- Cache "denied" results locally. When Redis says a client is out of tokens with a retry in 20 seconds, the gateway remembers that and rejects the client's next requests locally until then, without asking Redis. An abusive client hammering us now costs one Redis call per gateway per reset period, not one per request.
- Batch hot clients. For clients with very high limits (a big enterprise customer allowed 50k requests per second), the gateway takes tokens from Redis in chunks (say 100 at a time) and hands them out locally. That cuts Redis calls for that client by 100x, at the cost of a little over-admission if a gateway dies holding unused tokens.
Challenges
Both tricks trade accuracy for load. A client whose bucket refills early (say an operator raises their limit) stays blocked until the local cache entry expires, so keep those entries short and bounded by Retry-After. Token chunking can let a client slightly exceed its limit, since tokens are handed out by many gateways in parallel. For a rate limiter, those trade-offs are almost always fine, and it's worth saying so out loud.
2) How do we make the check atomic?
A token bucket check reads the current state, does some arithmetic and writes the new state. If two gateways do that at the same time for the same client, both can read "1 token left," both allow the request, and both write "0 left." Under heavy concurrency, that race lets clients go well past their limit.
Bad Solution: Read, Compute in the Gateway, Write Back
Approach
HGET the bucket, compute the new token count in the gateway, HSET it back.
Challenges
That's the race described above, and it gets worse exactly when the client is sending lots of concurrent requests, which is when the limit matters. You could add a distributed lock around each check, but that's an extra round trip or two and turns one fast operation into three.
Good Solution: Atomic Commands for Simple Counters
Approach
For fixed window counters, INCR is atomic on its own, so there's nothing to race:
INCR rl:{user:8812}:202611291405 -> 37
EXPIRE rl:{user:8812}:202611291405 120 NX
If the result is over the limit, reject. (EXPIRE ... NX sets the TTL only if the key doesn't have one, which needs Redis 7; otherwise wrap both in a MULTI.)
Challenges
It only works for algorithms that are a single increment. A token bucket needs a read, a refill calculation and a conditional write, which no single built-in command does.
Great Solution: A Lua Script per Check
Approach
Redis runs a Lua script atomically: no other command runs on that node while it executes. So we put the whole token bucket in a script and the race disappears:
-- KEYS[1] = bucket key; ARGV = capacity, refill rate (tokens/sec), cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME') -- use Redis's clock, not the gateway's
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
return { allowed, math.floor(tokens) }
The gateways load the script once with SCRIPT LOAD and call it by hash with EVALSHA, so each check sends a few bytes, not the whole script. Using Redis's own TIME means gateways with slightly different clocks don't disagree about how many tokens have refilled. The PEXPIRE deletes a bucket once it would have refilled anyway, which keeps memory proportional to active clients.
Challenges
Scripts block the node while they run, so they must stay tiny: no loops over large sets. This one does a handful of operations, which takes microseconds. All keys a script touches must live on the same shard, which is why the hash tag from the previous deep dive matters.
"Use a Lua script so the read-modify-write is atomic" is the single most common thing interviewers listen for in this problem. Say it before they have to ask.
3) What happens when Redis is slow or down?
The limiter is on the path of every request, which makes it a dangerous dependency. If a Redis shard fails and the gateway waits on it, every request for clients on that shard waits too.
Fail open or fail closed? For most APIs the answer is fail open: if the gateway can't reach the limiter, it lets the request through. Rate limiting is protection against overload, and turning a limiter outage into a full API outage is the worse result. The exceptions are rules that guard against abuse, like login attempts or password reset, where letting an attacker through unlimited is worse than briefly blocking real users. Make fail-open versus fail-closed a per-rule setting.
Then keep failures short:
- Tight timeouts. If Redis normally answers in 300µs, give up at 5-10ms. A slow answer is as bad as no answer on this path.
- Circuit breaker. After a burst of failures to a shard, stop calling it for a few seconds and apply the fallback straight away, instead of paying the timeout on every request.
- Local fallback limits. While a shard is unreachable, the gateway falls back to its own in-memory buckets with the limit divided by the number of gateway instances. It's the inaccurate local version from deep dive 1, but it's much better than no limiting at all during an outage.
- Replicas. Each Redis primary has a replica, and Redis Cluster (or Sentinel) promotes it if the primary fails. Replication is asynchronous, so a failover can lose the last few updates, meaning a few clients get a slightly fresher bucket than they should. For a rate limiter, that's an acceptable loss; we don't need to pay for synchronous replication.
We don't persist counters to disk at all, or only with infrequent snapshots. If the whole cluster restarts, every bucket starts full. That's a few seconds of slightly generous limits, which is fine.
4) How do we keep the check under a millisecond?
Every request pays for the check, so latency adds up across the system. The budget breaks down roughly as: rule matching in memory (microseconds), one network round trip to Redis (a few hundred microseconds within one availability zone), and script execution (microseconds). That leaves the network trip as the real cost, so most of the work is keeping it to exactly one trip.
- Run Redis in the same region and zone as the gateways, and keep persistent, pooled connections from each gateway. Opening a TCP connection per check would cost more than the check.
- One round trip per request, even with several matching rules. With hash tags, all of one client's rules live on one shard and one script call checks them all. Rules keyed on different identities (one on user, one on IP) land on different shards; send those calls in parallel, not one after another.
- Pipelining. A gateway handling thousands of requests per second can batch the checks bound for the same shard into one pipelined write, which cuts per-call overhead.
- Skip the check where it can't matter. Requests that match no rule, or internal health checks, shouldn't touch Redis at all.
If the budget is even tighter, there's a fully asynchronous option: the gateway decides locally from slightly stale counts and syncs its local counts to Redis every 100ms or so. That takes Redis off the request path completely, at the cost of letting clients overshoot by about one sync interval's worth of traffic. It's a reasonable answer when your interviewer pushes on latency, as long as you say what you're giving up.
5) How do we handle multiple regions?
If the API runs in three regions, a user could in principle use their allowance in each one. A single global counter would need a cross-region round trip on every request, which costs tens of milliseconds and breaks our latency budget.
Most systems don't do that. Instead:
- Enforce per region. Most users are routed to their nearest region and stay there, so a per-region limit is effectively a per-user limit. For the rare user who's spread out, they get at most N times their allowance, which is usually acceptable.
- Split the limit. If that's not acceptable, give each region a share of the global limit, either fixed (a third each) or adjusted every few seconds based on where the client's traffic is actually arriving.
- Sync asynchronously. Each region counts locally and periodically shares its counts with the others, and each region subtracts what the others have used. Limits are enforced within a few seconds of accuracy, which works fine for limits measured in minutes or hours.
Final Design
- A request arrives at an API gateway instance, which authenticates it and builds the client keys (user ID, API key, IP).
- The gateway matches the request against the rules it holds in memory, refreshed from the Rules Store through a config watch.
- If a local "denied" cache entry exists for this client, the gateway returns
429straight away. - Otherwise it calls one Lua token-bucket script on the Redis shard that owns the client's hash tag, checking every matching rule atomically in one round trip.
- Allowed requests go to the backend with
RateLimit-*headers. Rejected ones get429withRetry-After, and the denial is cached locally until then. - If Redis is slow or unreachable, a circuit breaker kicks in and the gateway falls back to local limits, failing open or closed per rule.
What is Expected at Each Level?
Mid-level
You should be able to explain at least two algorithms properly (fixed window and token bucket are the usual pair), including the boundary problem with fixed windows, and put the limiter in the gateway. You should see that a limit enforced on each instance separately isn't a global limit and propose a shared store like Redis. With some prompting, you should spot the read-modify-write race and fix it with an atomic operation.
Senior
You should compare the algorithms on memory, burst behavior and accuracy and choose one for a reason. Expect to design the Redis layer end to end: sharding by client key, hash tags so multiple rules check in one script, Lua for atomicity and TIME for clock skew. You should raise fail-open versus fail-closed on your own and back it with timeouts and circuit breakers, and you should know how to protect the limiter from the hot keys it exists to block.
Staff+
You should treat accuracy as a dial and decide where on it each part of the system belongs: exact enough for login abuse, loose enough for general API traffic, with local caching, token chunking and asynchronous sync as the tools to turn it. Expect to talk about running it: shadow mode for new rules, dashboards of who's being limited, multi-region strategy, and how limits connect to tiers and quotas without the limiter turning into a billing system.