Stop any one user from sending too many requests, across many servers, without slowing everyone down.
“Design a rate limiter.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Asking before drawing | The prompt does not say who is limited, by what, or what happens at the limit. A strong candidate pins down the key, the rule, the response, and whether it must be exact. |
| Knowing the algorithms, briefly | Token bucket, leaky bucket, fixed and sliding window are assumed knowledge. Name them, say when each fits, and move on. The depth is elsewhere. |
| Distributed correctness | One server is easy. Many servers sharing a count is the real question: races, atomic updates, and what exact even means. |
| Latency and failure thinking | The limiter is on the path of every request. It must be fast, and it must never become the outage. Fail open or closed is a real decision. |
| Trade-offs | Exact versus fast, central versus local, strict versus friendly. There is no single right answer, only reasoned ones. |
A rate limiter answers one question for every request: “has this caller used too much?” We build it as a small check that runs in the API gateway, backed by fast shared counters in a sharded Redis cluster. Rules (who, how much, which algorithm) live in a config store and are pushed to the gateways without a deploy.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Who is limited, by what key, what happens at the limit, exact or approximate, fail open or closed. |
| 2. Estimate | 3 | Checks per second, counters in memory, Redis nodes, latency budget. |
| 3. API and data | 5 | The check call, the rule format, the counter layout, response headers. |
| 4. High-level design | 8 | Where it sits, rules flow, Redis shards, local fast path. One request path. |
| 5. Deep dives | 15 | Atomic counting, then latency with local leasing, then failure behaviour, then fairness and abuse. |
| 6. Scale and failures | 7 | Hot key, Redis down, multi-region, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Is this a client-side or server-side limiter? Where does it run? | A client-side limiter can be bypassed. Where it runs decides the whole shape of the design. | Server-side, in front of our public API. | We build a gateway or middleware component. Client behaviour is guidance only (Retry-After). |
| What do we limit by: user, API key, IP address, endpoint, tenant? | The key decides what we count and how many counters exist. | By API key and by IP, with different limits per endpoint. | Several rules can apply to one request. Counters are keyed by (rule, identity). |
| Is the limit hard, or may a short burst go over? | Bursts change the algorithm: token bucket allows them, a strict window does not. | Short bursts are fine, a sustained rate is not. | Token bucket as the default. |
| How exact must it be? Is 5% over the limit acceptable? | Exact across many servers is expensive. Approximate is cheap and fast. | A small error is fine. Never let one caller overload us. | We can use local leasing and async sync. We do not need a global lock. |
| What happens when someone is over the limit: reject, queue, or slow down? | Decides the response and whether we need a queue. | Reject with HTTP 429 and tell them when to retry. | Stateless reject, no queue. Response needs Retry-After and rate-limit headers. |
| If the limiter itself is down, should requests go through or be blocked? | This is fail open versus fail closed. It is a product decision. | Let traffic through. We would rather be briefly unprotected than be down. | Short timeouts, fail open, a small local fallback limit, and alerts. |
| Can limits change at runtime, and do they differ by plan? | Hard-coded limits need a deploy to change. Plans mean many rules. | Yes. Free, pro and enterprise plans, changed by an operator. | A rules service with versioning, and gateways that hot-reload rules. |
| One region or global? Do servers share one count across regions? | A single global count needs cross-region traffic on every request. | Start with one region. Mention multi-region. | One Redis cluster for now. Say how multi-region would work later. |
| How many requests per second, and how many distinct callers? | Sets the number of checks per second and counters in memory. | About 1 million requests per second at peak and 10 million active callers. | Throughput is the main constraint. Memory is small. |
| How much latency may the limiter add? | It runs on every request, so it must be nearly free. | Under 2 ms at the 99th percentile. | One in-zone call, pipelined. A local fast path for busy keys. |
| Assumption | Value |
|---|---|
| API traffic at peak | 1,000,000 requests per second |
| API traffic on average | 300,000 requests per second |
| Limit checks per request (per key and per IP) | 2 |
| Active callers (keys and IPs) in a window | 10 million |
| Counters per caller | 2 |
| Memory per counter, with overhead | about 100 bytes |
| One Redis node, simple operations | about 100,000 per second |
| Target load on a node | 50% (headroom for spikes and failover) |
| Round trip to Redis in the same zone | about 0.5 ms |
| Size of one check (request plus reply) | about 200 bytes |
| What | Maths | Result |
|---|---|---|
| Checks per second (peak) | 1,000,000 × 2 | 2,000,000 per second |
| Checks per second (average) | 300,000 × 2 | 600,000 per second |
| Counters in memory | 10,000,000 callers × 2 | 20 million counters |
| Memory for counters | 20,000,000 × 100 bytes | 2 GB (4 GB with a replica) |
| Redis nodes if every check is a remote call (100% busy) | 2,000,000 ÷ 100,000 | 20 primaries |
| Redis nodes with headroom (50% load) | 20 ÷ 0.5 | 40 primaries |
| Remote calls if busy keys lease 10 tokens at a time (80% of traffic) | (0.2 × 2,000,000) + (0.8 × 2,000,000 ÷ 10) = 400,000 + 160,000 | 560,000 per second |
| Redis nodes after leasing (50% load) | 560,000 ÷ 100,000 = 5.6, then ÷ 0.5 | about 12 primaries |
| Network traffic to Redis, without leasing | 2,000,000 × 200 bytes | 400 MB/s in total (about 3.2 Gbit/s), or 10 MB/s per node over 40 nodes |
| Latency added | one pipelined call, both checks in the same round trip | about 0.5 ms, inside the 2 ms budget |
| Sliding log, worst case (every key at a limit of 1,000 per minute, about 40 bytes per entry) | 10,000,000 × 1,000 × 40 bytes | 400 GB, about 200 times the 2 GB of counters |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/check | { rule, key, cost? } | 200 { allowed, remaining, limit, resetMs, retryAfterMs } | Internal call from the gateway (or a library call). Returns a decision, never an error for 'over limit'. Cost lets one heavy request count as several. |
| GET | /v1/rules | none | 200 { version, rules: [...] } | Gateways poll or stream this and keep rules in memory. A version number makes updates safe to roll out. |
| PUT | /v1/rules/{id} | { domain, match, limit, unit, algorithm, burst } | 200 { version } | Operators only. Validated, versioned, audited. Takes effect in seconds, no deploy. |
| GET | /v1/usage/{key} | none | 200 { rule, used, limit, resetMs } | For support and dashboards. Reads counters, never changes them. |
- id: public-api-search
domain: api
match: { endpoint: "/v1/search", method: "GET" }
key: [ api_key ] # what to count by (could also be ip, tenant)
limit: 100 # requests ...
unit: minute # ... per minute
burst: 20 # extra short-term allowance
algorithm: token_bucket
on_error: fail_open # what to do if the limiter cannot answer| Counter layout (Redis) | Stored as | Memory and notes |
|---|---|---|
| Token bucket | A hash per key: tokens (number), last_refill (timestamp) | Two numbers. About 100 bytes with overhead. Refill is computed on read, so nothing runs in the background. |
| Sliding window counter | Two fixed-window counters (this window and the last), weighted by how far into this window we are | Two small integers. Smooth, and almost as cheap as a fixed window. An approximation, usually within a few percent. |
| Fixed window | One integer per key per window, with a TTL equal to the window | Cheapest. Allows a burst of up to twice the limit around a window boundary. |
| Sliding log | A sorted set of one timestamp per request | Exact, but 1 entry per request. 400 GB in our worst case, so avoid at scale. |
| Response header | Meaning |
|---|---|
| HTTP 429 Too Many Requests | The caller is over the limit. |
| Retry-After: 12 | Seconds until the caller may try again. Good clients wait for it. |
| X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset | A widely used set that shows the limit, what is left, and when it resets. A standard RateLimit header is in draft, so name which one you use. |
| Component | What it does |
|---|---|
| Limiter filter (in the gateway) | Finds the matching rules, builds the key, makes the check, and either forwards the request or returns 429. It holds the rules in memory. |
| Local fast path | In-process counters and token leases for very busy keys, so most requests do not need a remote call. |
| Redis cluster | Holds the counters. Sharded by key with consistent hashing, so one key always lives on one primary. Each primary has a replica. |
| Lua script | Runs inside Redis and does read, refill, compare and update as one atomic step. One round trip per check. |
| Rules service and config store | Validates and versions rules, and pushes them to the gateways. The gateways keep working with their last good rules if this service is down. |
| Metrics and alerts | Allowed, rejected, errors and latency, by rule. A jump in errors means the limiter is the problem, not the callers. |
The problem: Many gateways check the same key at the same moment. If each one reads the count, adds one, and writes it back, two of them can read the same number and both write the same result, so a request is lost from the count. This is the lost update, and it lets callers go over the limit.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Read, then write from the app | GET the counter, compare, then SET counter + 1. | Easy to write. | Racy: two servers read the same value and both write it back. Under load the limit is simply wrong. |
| Atomic INCR with EXPIRE (fixed window) | INCR the counter for the window key. If it is 1, set EXPIRE to the window length. Reject when the count is over the limit. | One atomic command, very fast, tiny memory. | Allows up to twice the limit around a window boundary. INCR and EXPIRE are two commands, so a crash between them can leave a key that never expires, unless they are in a script. |
| Lua script (token bucket or sliding window) | One script does read, refill, compare and write inside Redis. Redis runs a script without interleaving other commands, so it is atomic. | Exact for that key, any algorithm, one round trip. | A script runs on one thread. Keep it tiny and avoid loops over big sets. |
| Optimistic transaction (WATCH / MULTI) | WATCH the key, read it, then write in a MULTI. If the key changed in between, the transaction fails and the client retries. | Needs no script. | Under contention on a hot key, retries pile up. More round trips. |
The check and the update must be one atomic step. Redis runs one script at a time on a node, and a key lives on exactly one primary, so the script sees a consistent bucket and no two gateways can interleave. It costs one network round trip, and it supports any algorithm, which a bare INCR does not.
For the token bucket we store tokens and last_refill. On each call we add elapsed × rate tokens (up to the bucket size), then take the cost if there is enough. Use Redis's own clock (TIME) inside the script, or pass one timestamp, so that gateways with slightly different clocks do not disagree about how much time has passed.
-- KEYS[1] = bucket key ARGV: rate (tokens/s), capacity, cost
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000) -- milliseconds, Redis's own clock
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or tonumber(ARGV[2]) -- new key starts full
local ts = tonumber(b[2]) or now
tokens = math.min(tonumber(ARGV[2]), tokens + (now - ts) / 1000 * tonumber(ARGV[1])) -- refill
local allowed = tokens >= tonumber(ARGV[3])
if allowed then tokens = tokens - tonumber(ARGV[3]) end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(tonumber(ARGV[2]) / tonumber(ARGV[1]) * 1000) * 2) -- idle keys vanish
return { allowed and 1 or 0, math.floor(tokens) }0.5 × 10 = 5 tokens, so 5 more requests pass. After 2 seconds it has refilled to the 20 cap (it never goes above). That is the burst plus sustained-rate behaviour we promised.The problem: Two million checks a second is a lot of Redis calls, and every call adds latency and load. One very busy key (a large customer) lands on a single node and can overload it, however many nodes we have.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Remote call for every request | Each check goes to Redis. | Exact and simple. Counts are always global. | About 40 primaries at our scale. Redis is on the critical path of every request. A hot key still hits one node. |
| Local counters, synced every second | Each gateway counts locally and sends the totals to Redis every second. | Far fewer calls. Very fast. | Between syncs, each gateway admits up to the full limit by itself, so the real limit can be exceeded by up to servers × limit. |
| Token leasing | A gateway takes a batch of N tokens from Redis in one call and spends them from memory. When they run out it takes another batch. | Remote calls drop by about N. Over-admission is bounded by servers × N, and tokens never exceed what Redis handed out. | Tokens can sit unused on one gateway while another is told no. Small limits and large N do not mix. |
| Split a hot key into sub-keys | Divide the limit across several Redis keys (for example 8 shards of limit ÷ 8), and pick one per request. | Spreads one hot key across nodes. | A caller can be rejected on a sub-key that is full while others have room. Needs a good split. |
Most keys are quiet and need no tricks: one pipelined call per check is cheap. For the few busy keys we lease. With a batch of 10 tokens, a gateway calls Redis once per 10 requests, so remote calls drop by about 10 times for those keys. The leased tokens come out of the same bucket, so the global limit is never silently doubled: the worst error is that some tokens sit unused for a moment.
Choose the batch size from the limit: for a key with a limit of 100 a minute across 20 gateways, a batch of 10 would let 20 × 10 = 200 tokens be held at once, which is more than the whole limit. So set batch ≈ limit ÷ (gateways × 4), and do not lease at all for small limits. Sharding is by consistent hashing on the key, and pipelining sends both checks for one request in one call.
| Setting | Remote calls per second | Worst-case extra requests | Good for |
|---|---|---|---|
| No leasing (batch 1) | 2,000,000 | 0 | Small limits, strict plans |
| Lease 10 on busy keys (80% of traffic) | 560,000 | up to servers × 10 per window | High limits, busy keys |
| Lease 100 on a very busy key | about 1/100 of that key's calls | up to servers × 100 per window | Huge limits only (100,000 per minute and up) |
The problem: The limiter is on the path of every request. If Redis is slow or down, a naive limiter makes the whole API slow or down. The limiter protects the system, so it must never be the cause of the outage.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fail closed | If the check fails, reject the request. | No unprotected traffic. Safe for abuse-sensitive actions (login, password reset, SMS sending). | A Redis problem becomes a full outage of the API. |
| Fail open | If the check fails or times out, allow the request. | The API stays up. Right for most read traffic. | Briefly unprotected. A slow Redis can also add delay to every request unless the timeout is short. |
| Fail open with a local fallback | On error, use a small in-memory limit on each gateway (for example the limit ÷ number of gateways, or a flat per-IP cap). | Stays up and still stops the worst abuse. Needs no remote call. | Approximate. A bit more code. |
Use a short timeout (about 2 ms) so a slow Redis cannot slow every request, and a circuit breaker so that after a run of failures the gateway stops calling Redis for a few seconds and goes straight to the fallback. Make fail open or closed a per-rule setting: fail open for normal reads, fail closed for a login or an SMS send, where an unprotected endpoint is worse than a brief error.
Counters do not need to be durable. If a Redis primary fails and a replica takes over, the last moments of counts may be missing, so callers briefly get a little extra. That is acceptable and far cheaper than synchronous persistence. Alert on the error rate of the limiter itself, so we notice quickly.
| Situation | What the gateway does |
|---|---|
| Redis replies in time | Use its answer. |
| Redis is slow (over 2 ms) | Treat as an error: use the fallback for this request. Count it in a metric. |
| Many errors in a row (breaker opens) | Skip Redis for a few seconds and use the local fallback only. Try again with a trickle of requests. |
| Primary fails and a replica is promoted | A few seconds of errors, then normal. Counters may have lost a little, so callers briefly get a bit extra. |
| A sensitive rule (login, SMS) | Fail closed: reject, or ask for a CAPTCHA. |
The problem: A real limiter has many rules at once, and callers try to get around them. IP limits punish people behind a shared office or mobile network, spoofed headers fake an IP, and a limiter alone does not stop an attack.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One global limit per key | Every key gets the same limit. | Simple. | No plans, no fairness across endpoints, one heavy endpoint can use the whole allowance. |
| Layered limits | Check several rules per request: per key, per IP, per endpoint, and a global cap. Reject if any says no. | Protects each resource, and gives different plans different numbers. | More counters and more checks per request (we budgeted 2). |
| Cost-based (weighted) limits | A heavy request such as export or search costs several tokens. | Reflects real load. Fair. | Needs a cost table that is kept up to date. |
Layering lets us protect different things: a per-key limit for fairness, a per-IP limit for anonymous abuse, a per-endpoint limit for expensive routes, and a global limit as a last safety valve. A plan is just a different number in the same rule. Weighted costs make a 5-second export count as 10 tokens, not 1.
For identity, do not trust a client-supplied header such as X-Forwarded-For unless it was added by our own load balancer, and then read the right-most address we trust. Use an authenticated key as the main identity, and use the IP only for anonymous traffic. Remember a limiter is not a DDoS shield: it protects the application from abuse by known callers. Volume attacks need a CDN and network protection.
| Layer | Counts by | Protects against |
|---|---|---|
| Per key | API key and endpoint group | One customer using more than their plan |
| Per IP | Client IP (after the trusted proxy) | Anonymous scraping and credential stuffing |
| Per endpoint | Route | Expensive routes being overwhelmed |
| Per tenant | Customer account | Many keys of one customer adding up |
| Global | Everything | A last safety valve for the backend |
Retry-After and wait. If there is none, back off exponentially with random jitter, so a thousand clients do not all retry at the same second. Never retry in a tight loop.A teaching model with a fixed script (no random numbers). “OVER” marks requests admitted after the limit was already used up, counted in arrival order. In lease mode a server that is told “no tokens left” remembers it until the window ends, so it stops calling the store.
| Bottleneck | Fix |
|---|---|
| Redis throughput (2M checks a second) | Shard by key with consistent hashing, pipeline both checks into one call, and lease tokens for busy keys. About 12 primaries with leasing, 40 without. |
| One hot key (a huge customer) on one node | Lease tokens at the gateway, and split the limit across a few sub-keys. A node can also be given a bigger machine for a short time. |
| Added latency on every request | Same-zone Redis, one pipelined call, a tiny script, a 2 ms timeout, and a local fast path. |
| Gateway memory for rules | Rules are few and small. Compile them into a lookup table by endpoint when loaded. |
| Rules push to many gateways | Version numbers and a short poll with jitter. A gateway keeps its last good version if a push fails. |
| Counters for idle callers piling up | A TTL on every key, set to about twice the time the bucket needs to refill. Idle keys disappear on their own. |
| Cross-region counting | A share of the limit per region, or a periodic sync. Accept an approximation instead of a cross-region call on each request. |
| Failure | How the design copes |
|---|---|
| Redis is slow | A 2 ms timeout per check, then the local fallback for that request. The circuit breaker opens if errors continue. |
| A Redis primary dies | A replica is promoted in seconds. Counters may have lost a moment of updates, so callers briefly get a bit extra. Alert on it. |
| The whole Redis cluster is down | Fail open (or closed for sensitive rules) with the local fallback limit. The API stays up. |
| The rules service is down | Gateways keep their last good rules. Nothing changes for callers. Operators cannot edit rules until it returns. |
| A bad rule is pushed (limit 0 for everyone) | Validate before saving, roll out by version with a quick rollback, and watch the rejected-rate metric. A sudden jump pages someone. |
| A gateway restarts | It loses its local token lease only (a few tokens). Counters in Redis are untouched. It reloads rules and starts again. |
A rate-limit filter in the API gateway, with rules held in memory and pushed from a rules service. Counters live in a sharded Redis cluster and are updated by a small atomic Lua script, using a token bucket by default. Busy keys lease batches of tokens to avoid a remote call per request. The limiter has a short timeout, a circuit breaker, and fails open with a local fallback, so it never becomes the outage. It returns 429 with Retry-After and rate-limit headers.
| Decision | What we gain | What it costs |
|---|---|---|
| Token bucket by default | Allows bursts, uses two numbers per key, and is easy to explain to customers. | A caller can spend the whole bucket at once. Not as smooth as a leaky bucket. |
| A Lua script in Redis | Exact and atomic for a key, in one round trip. | A script runs on a single thread, so it must stay tiny. It ties the design to Redis. |
| Token leasing for busy keys | About 3 to 10 times fewer remote calls, and a lighter Redis. | The limit becomes approximate, bounded by servers × batch. Tokens can be stranded. |
| Fail open with a local fallback | The API stays up when the limiter breaks. | Briefly weaker protection. Sensitive rules need fail closed. |
| Counters not durable | Fast and cheap. No disk on the hot path. | A failover can lose a few seconds of counts, so callers get a little extra. |
| Approximate multi-region limits | No cross-region call on each request. | A caller can exceed the global limit by a margin if they spread requests across regions. |
Know the algorithms in one line each, then show you can count correctly across servers.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Limits must be exact, with no over-admission | No token leasing and no local sync. Every check is one atomic remote call. Accept the extra Redis load and latency, and do not fail open. |
| Limits per customer across all their keys | Add a tenant rule and key. A request checks both the key counter and the tenant counter in one pipelined call. |
| Global limit across three regions | A share of the limit per region, with a periodic sync, or a primary region that other regions ask. State the margin of error. |
| Limit by bandwidth, not by request count | Use cost equal to bytes. The token bucket works the same with bigger costs, and the check happens after the size is known. |
| Queue requests instead of rejecting them | Add per-tenant queues and a leaky-bucket drain. Needs a maximum queue length and timeouts. Response time goes up. |
| Limit logins and one-time codes more strictly | Separate strict rules, key by account and IP, fail closed, and add a CAPTCHA step after a few failures. |
| The limiter must work inside each microservice (not only at the edge) | A client library or sidecar that reads the same rules and talks to the same Redis, with local leasing to stay fast. |
| Very small limits (for example 3 per hour) | No leasing. Use an atomic counter with a long window. A sliding log is fine here, because the memory per key is tiny. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts with the algorithm. Never asks what is limited, how exact, or what happens on failure. | Asks about the key, the response, burst and scale, and writes them down. | Asks about fail open vs closed, accuracy and where it runs, and says what is out of scope (DDoS, billing). |
| Estimation | No numbers, or says memory is the problem. | Checks per second and counters, with correct maths. | Sees that throughput, not memory, is the constraint, and uses it to justify sharding and token leasing. |
| Algorithms | Names one algorithm with no reason. | Compares token bucket, leaky bucket and windows, and picks one. | States the cost and trade-off of each, such as the fixed-window boundary burst and sliding-log memory, in one line each. |
| Distributed correctness | Says use a shared counter, with no atomicity. | Names the race and fixes it with an atomic operation or a Lua script. | Explains the script, the clock source, and why a transaction or lock is worse, with the refill maths. |
| Failure and trade-offs | Assumes Redis never fails. | Explains fail open vs closed, and a timeout. | Adds a circuit breaker, a local fallback, per-rule policy, and the cost of losing counters. |
| Communication | Silent for long periods, or lists techniques with no reason. | Follows the 7 steps and explains choices. | Summarises each step, checks in, and states clearly what is approximate and by how much. |
| Mistake | Do this instead |
|---|---|
| Spending the whole interview re-explaining the four algorithms | One line each, pick one, and move on. The depth is in distributed counting and failure. |
| Read-then-write on a shared counter | Make the check and update atomic with a Lua script or an atomic command, and name the lost update. |
| Putting a remote call on the critical path with no timeout | A short timeout, a circuit breaker, and a decision to fail open or closed. |
| Saying the limiter must be 100% exact | Ask how exact it must be. State the cost of exactness and where you accept a small, bounded error. |
| Limiting only by IP | Use the authenticated key as the main identity, the IP for anonymous traffic, and never trust a client-sent IP header. |
| Using the sliding log at scale | Do the memory maths (one entry per request) and use a sliding window counter or token bucket. |
| Ignoring the client side of the contract | Return 429 with Retry-After and rate-limit headers, and say how a good client should back off with jitter. |
| Presenting the limiter as DDoS protection | Say it protects against heavy callers, and that volume attacks need a CDN and network protection. |
The four algorithms in detail, with a single-server simulator.
Where the limiter usually sits.
How counters are spread over Redis shards.
Stop calling a failing limiter and use the fallback.
What to do when one customer owns a whole shard.
The 2 ms limit on the check.
What a rate limiter does not do.
Why Redis, and what its scripts give you.