SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design a Rate Limiter

Stop any one user from sending too many requests, across many servers, without slowing everyone down.

⏱ 30 min readEasy case studyIntermediate21 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a rate limiter.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Asking before drawingThe 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, brieflyToken bucket, leaky bucket, fixed and sliding window are assumed knowledge. Name them, say when each fits, and move on. The depth is elsewhere.
Distributed correctnessOne server is easy. Many servers sharing a count is the real question: races, atomic updates, and what exact even means.
Latency and failure thinkingThe 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-offsExact versus fast, central versus local, strict versus friendly. There is no single right answer, only reasoned ones.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 1M requests per second at peak with 2 checks each is 2M checks per second. That is a throughput problem, not a memory problem: 20M counters at about 100 bytes is only 2 GB.
  • Algorithm: token bucket by default (allows bursts, two numbers per key). Sliding window counter when a smooth limit matters. Avoid the sliding log at scale.
  • Correctness: the check and the update must be one atomic step. Use a small Lua script in Redis, never read-then-write from the app.
  • Speed: one Redis call in the same zone is about 0.5 ms. For very busy keys, a server leases a batch of tokens and spends them from memory, so the store is called far less.
  • Failure: the limiter must not be the outage. Short timeout, then fail open with a small local limit as a safety net. Losing counters on a failover only means a brief over-admission.
  • Answer: 429 with Retry-After and rate-limit headers, so good clients back off. Say it is not a DDoS shield.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Who is limited, by what key, what happens at the limit, exact or approximate, fail open or closed.
2. Estimate3Checks per second, counters in memory, Redis nodes, latency budget.
3. API and data5The check call, the rule format, the counter layout, response headers.
4. High-level design8Where it sits, rules flow, Redis shards, local fast path. One request path.
5. Deep dives15Atomic counting, then latency with local leasing, then failure behaviour, then fairness and abuse.
6. Scale and failures7Hot key, Redis down, multi-region, monitoring.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change your design. Hint: think about what is being limited, how exact it must be, where the limiter runs, and what happens when the limiter itself breaks.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Decide allow or reject for each request, by caller and by endpoint
  • •Support several rules at once (per key, per IP, per endpoint)
  • •Return 429 with when to retry, and headers that show the limit and what is left
  • •Change rules at runtime without a deploy
  • •Allow short bursts, but hold a sustained rate
Non-functional (how well)
  • •Latency: under 2 ms at p99 for a check
  • •Available: the limiter must never be the cause of an outage (fail open)
  • •Scale: 1M requests per second at peak, 10M active callers
  • •Accuracy: a few percent over the limit is acceptable, never a flood
  • •Cheap: rejecting a request must cost far less than serving it
Out of scope (say it)
  • •A full DDoS defence (that is a CDN and network job)
  • •Billing and monthly quotas (a different, slower system)
  • •A queue that delays requests instead of rejecting them
  • •A user interface for editing rules
🎤
Say it out loud
“Let me confirm the scope. This is a server-side limiter in front of our public API. We limit by API key and by IP, with different limits per endpoint, and a short burst is fine but a sustained rate is not. Over the limit we reject with a 429 and tell the caller when to retry. I will design for about a million requests per second at peak, 10 million active callers, under 2 milliseconds added, and a small error margin is acceptable. If the limiter breaks, we let traffic through. Rules change at runtime. I will leave DDoS defence and billing quotas out. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: how many checks per second, how many counters, how much memory, and how many Redis nodes? Which of these is the real constraint: memory or throughput?

Assumptions (say them first)

AssumptionValue
API traffic at peak1,000,000 requests per second
API traffic on average300,000 requests per second
Limit checks per request (per key and per IP)2
Active callers (keys and IPs) in a window10 million
Counters per caller2
Memory per counter, with overheadabout 100 bytes
One Redis node, simple operationsabout 100,000 per second
Target load on a node50% (headroom for spikes and failover)
Round trip to Redis in the same zoneabout 0.5 ms
Size of one check (request plus reply)about 200 bytes

The arithmetic, line by line

WhatMathsResult
Checks per second (peak)1,000,000 × 22,000,000 per second
Checks per second (average)300,000 × 2600,000 per second
Counters in memory10,000,000 callers × 220 million counters
Memory for counters20,000,000 × 100 bytes2 GB (4 GB with a replica)
Redis nodes if every check is a remote call (100% busy)2,000,000 ÷ 100,00020 primaries
Redis nodes with headroom (50% load)20 ÷ 0.540 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,000560,000 per second
Redis nodes after leasing (50% load)560,000 ÷ 100,000 = 5.6, then ÷ 0.5about 12 primaries
Network traffic to Redis, without leasing2,000,000 × 200 bytes400 MB/s in total (about 3.2 Gbit/s), or 10 MB/s per node over 40 nodes
Latency addedone pipelined call, both checks in the same round tripabout 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 bytes400 GB, about 200 times the 2 GB of counters
What the numbers tell us about the design
  • •Memory is small (2 GB). Throughput is the constraint: 2 million checks a second is far more than one node handles.
  • •A remote call for every request needs about 40 primaries. Leasing tokens to busy keys cuts that to about 12. That is the argument for a local fast path.
  • •The limiter must add well under 2 ms, so use one in-zone round trip, pipeline the two checks, and keep the script tiny.
  • •Counters are tiny, so the choice of algorithm should favour two numbers per key (token bucket, sliding window counter) over a log of every request.
  • •Rejecting must be cheap: a rejected request should cost one counter read, not a database query.
🎤
Say it out loud
“Let me do the maths. A million requests a second at peak with two checks each is two million checks a second. Ten million active callers with two counters each at about 100 bytes is only 2 gigabytes, so memory is not the problem. Throughput is: at 100 thousand operations a node, a remote call per check needs about 20 nodes, 40 with headroom. If busy keys lease ten tokens at a time, remote calls drop to about 560 thousand a second and 12 primaries are enough. So the design needs a fast path that avoids a remote call on every request.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the call the gateway makes to the limiter, the shape of one rule, and the headers the caller sees. Then ask: what do you store per key for a token bucket?

Endpoints

MethodPathRequestResponseNotes
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/rulesnone200 { 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}none200 { rule, used, limit, resetMs }For support and dashboards. Reads counters, never changes them.

Data model

One rule (example, YAML)
- 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 asMemory and notes
Token bucketA 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 counterTwo fixed-window counters (this window and the last), weighted by how far into this window we areTwo small integers. Smooth, and almost as cheap as a fixed window. An approximation, usually within a few percent.
Fixed windowOne integer per key per window, with a TTL equal to the windowCheapest. Allows a burst of up to twice the limit around a window boundary.
Sliding logA sorted set of one timestamp per requestExact, but 1 entry per request. 400 GB in our worst case, so avoid at scale.
Response headerMeaning
HTTP 429 Too Many RequestsThe caller is over the limit.
Retry-After: 12Seconds until the caller may try again. Good clients wait for it.
X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-ResetA 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.
📝Which store, and why
The counters are tiny, hot, and need atomic updates and expiry, so an in-memory store such as Redis is the natural fit, sharded by key (consistent hashing). A relational database is far too slow for a check on every request, and the counters do not need to survive a failure: losing them only means a brief over-admission. Rules are a different thing: few, rarely changed, and must be durable and versioned, so they live in a normal config store or database and are cached in each gateway.
🎤
Say it out loud
“The gateway makes one internal call, check, with the rule and the key, and gets back allowed, remaining and when to retry. Rules are small YAML or JSON documents in a config store, versioned, and pushed to the gateways so they change without a deploy. For a token bucket I store two numbers per key in Redis: the tokens and the last refill time. Refill is computed when we read, so no background job is needed. When we reject, we return 429 with Retry-After and the rate-limit headers.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes for one request. Where does the limiter sit? Where do the counters live, and what happens if that store is slow or down?
Rate limiter: high-level design
📱ClientsAPI keys, IPs
→↓HTTPS
⚖️Load balancer
→↓
API gateway (many copies)
🚦Limiter filterlocal counters + rules cache
🔀Routerforward if allowed
→↓allowed
🖥️API servers
Counters (sharded)
⚡Redis clusterLua script, one call per check
📋Replicasfailover copy
Rules
🗂️Rules servicevalidate, version, audit
↓push or poll
💾Config storedurable
Watching
📈Metricsallowed, rejected, errors
🔔Alertson error rate, latency
The check sits in the gateway. Counters are sharded in Redis. Rules are cached in each gateway. A local fast path avoids a remote call for busy keys.
ComponentWhat 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 pathIn-process counters and token leases for very busy keys, so most requests do not need a remote call.
Redis clusterHolds the counters. Sharded by key with consistent hashing, so one key always lives on one primary. Each primary has a replica.
Lua scriptRuns inside Redis and does read, refill, compare and update as one atomic step. One round trip per check.
Rules service and config storeValidates 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 alertsAllowed, rejected, errors and latency, by rule. A jump in errors means the limiter is the problem, not the callers.
Write path (follow one request)
  1. An operator edits a rule. The rules service validates it (for example, limit above zero and a known algorithm) and stores a new version.
  2. The new version is pushed to every gateway, or fetched on a short poll (for example every 10 seconds).
  3. Each gateway swaps in the new rules in memory, atomically, and keeps the old version if the new one fails to load.
  4. Counters are not part of this path. They are created by the first request that uses them, and removed by a TTL when they are idle.
Read path (follow one request)
  1. A request arrives at the gateway. The limiter filter finds the rules that match (endpoint, method, plan).
  2. It builds the key for each rule, for example api:search:{apiKey}, and adds the IP rule.
  3. For a busy key it first tries its local token lease. If tokens are left, it spends one and goes on (no network call).
  4. Otherwise it calls Redis once, sending both checks in one pipelined call to the shards that hold the keys, with a timeout of about 2 ms.
  5. The Lua script refills the bucket, compares, and returns allowed, remaining and the time to reset. It counts one request if allowed.
  6. If any rule says no, the gateway returns 429 with Retry-After and the headers. Otherwise it adds the headers and forwards the request. If Redis fails or times out, it follows the rule's on_error setting (here fail open).
🎤
Say it out loud
“Here is the picture. The limiter is a filter in the API gateway, so a rejected request never reaches the API servers. Each gateway holds the rules in memory, pushed from a rules service, so changing a rule needs no deploy. Counters live in a sharded Redis cluster, one primary per key range with a replica, and a small Lua script does the check and update in one atomic call. For very busy keys the gateway leases a batch of tokens and spends them locally, so most requests do not make a remote call. If Redis is slow or down, we time out in about two milliseconds and fail open.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Counting correctly across many servers

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.

OptionHow it worksGoodBad
Read, then write from the appGET 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.
Pick
A small Lua script that does refill, check and update in one atomic call

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.

Token bucket as a Lua script (sketch)
-- 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) }
📝Worked example of the refill
Rate 10 tokens a second, capacity 20. A caller sends 20 requests at once: the bucket drops to 0. After 0.5 seconds it has 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.
💡Which algorithm, one line each (full detail is in the Rate Limiting topic)
Token bucket: bursts allowed, two numbers per key, the default. Leaky bucket: smooth output, good to protect a fragile backend. Fixed window: cheapest, but double-limit bursts at the boundary. Sliding window counter: smooth, two integers, an approximation. Sliding log: exact but costs one entry per request.
🎤
Say it out loud
“The core problem is that the check and the update must be one atomic step, or two gateways read the same count and both let a request through. I would put the whole token bucket in a small Lua script: refill from elapsed time, compare, subtract, write. Redis runs it without interleaving, so it is exact for that key in one round trip. I would use Redis's own clock inside the script so gateway clock differences do not matter. A bare INCR with EXPIRE is fine for a fixed window, but it allows double the limit at a boundary.”
5.2

Staying fast: leasing tokens and sharding

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.

OptionHow it worksGoodBad
Remote call for every requestEach 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 secondEach 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 leasingA 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-keysDivide 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.
Pick
Remote atomic check by default, with token leasing for busy keys

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.

SettingRemote calls per secondWorst-case extra requestsGood for
No leasing (batch 1)2,000,0000Small limits, strict plans
Lease 10 on busy keys (80% of traffic)560,000up to servers × 10 per windowHigh limits, busy keys
Lease 100 on a very busy keyabout 1/100 of that key's callsup to servers × 100 per windowHuge limits only (100,000 per minute and up)
⚠️Say the cost out loud
Leasing makes the limit approximate by design. The honest answer to an interviewer is: "exact for small limits, approximate within a known bound for large ones, and the bound is servers × batch."
🎤
Say it out loud
“A remote call for every check would need about 40 Redis primaries and puts Redis on the critical path. For the busy keys I would lease tokens: a gateway takes, say, 10 tokens in one call and spends them locally, so remote calls drop about tenfold. The tokens come out of the same bucket, so we never exceed the limit by more than servers times the batch. I would size the batch to the limit, and not lease at all for small limits. For one very hot key I can also split the limit across a few sub-keys so it spreads across nodes.”
5.3

When the limiter itself fails

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.

OptionHow it worksGoodBad
Fail closedIf 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 openIf 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 fallbackOn 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.
Pick
A short timeout, a circuit breaker, then fail open with a local fallback limit (fail closed only for sensitive endpoints)

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.

SituationWhat the gateway does
Redis replies in timeUse 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 promotedA 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.
📝Multi-region in one paragraph
Keep one Redis cluster per region and enforce a share of the limit in each (for example the limit split by traffic), or sync counts between regions every second or so. A true global exact count needs a cross-region call on every request, which costs 50 to 150 ms, so we accept an approximation. Say that clearly.
🎤
Say it out loud
“The limiter must never be the outage. I would put a two millisecond timeout on the Redis call and a circuit breaker, so a slow or dead Redis cannot slow the API. On error I fail open by default, with a small local fallback limit on each gateway so the worst abuse is still stopped, and fail closed only for sensitive endpoints such as login or sending an SMS. Counters do not need to be durable: if a replica takes over and loses a few seconds, callers briefly get a little extra, which I accept. I would alert on the limiter's own error rate.”
5.4

Fairness, tiers and abuse

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.

OptionHow it worksGoodBad
One global limit per keyEvery key gets the same limit.Simple.No plans, no fairness across endpoints, one heavy endpoint can use the whole allowance.
Layered limitsCheck 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) limitsA heavy request such as export or search costs several tokens.Reflects real load. Fair.Needs a cost table that is kept up to date.
Pick
Layered limits with weighted cost, and a key that does not trust a bare client IP

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.

LayerCounts byProtects against
Per keyAPI key and endpoint groupOne customer using more than their plan
Per IPClient IP (after the trusted proxy)Anonymous scraping and credential stuffing
Per endpointRouteExpensive routes being overwhelmed
Per tenantCustomer accountMany keys of one customer adding up
GlobalEverythingA last safety valve for the backend
💡What a good client does
On 429, read 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.
🎤
Say it out loud
“Real systems need several limits at once: per key for fairness and plans, per IP for anonymous abuse, per endpoint for expensive routes, and a global cap. Heavy requests cost more tokens. For identity I would use the authenticated key first and only use the IP for anonymous traffic, and I would read the client address only from headers our own load balancer sets. I would also be clear that a rate limiter is not a DDoS defence: it protects the app from heavy callers, while volume attacks need a CDN and network protection.”
VisualizerCounting across servers: race, atomic, and token leasingStart with “Read, then write” and add servers to see the limit break. Switch to “One atomic increment” for the exact answer, then to “Lease a batch of tokens” and move the batch size: fewer store calls, but tokens get stranded.
How do the servers count?
The limit is 10 requests in this window. In each round every server gets one request at the same moment. 24 requests in all.
Server 1
Server 2
Server 3
Server 4
Counter in the store
Round 1
allowed
allowed
allowed
allowed
1
Round 2
allowed
allowed
allowed
allowed
2
Round 3
allowed
allowed
OVER
OVER
3
Round 4
OVER
OVER
OVER
OVER
4
Round 5
OVER
OVER
OVER
OVER
5
Round 6
OVER
OVER
OVER
OVER
6
Allowed
24
limit is 10
Rejected
0
Over the limit
14
admitted too many
Store calls
48
a read and a write each
The limit is 10, but 24 requests got through (14 too many). In each round all 4 servers read the same number, all said “allowed”, and all wrote the same new value, so the counter only went up by 1 for 4 requests. The store ended at 6, not 24. This is the lost update, the classic race of read, then write.

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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
If traffic grows 10 times, what breaks first? If Redis dies, what do callers see? If one customer sends half of all traffic, what happens to one shard?

What breaks first, and the fix

BottleneckFix
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 nodeLease 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 requestSame-zone Redis, one pipelined call, a tiny script, a 2 ms timeout, and a local fast path.
Gateway memory for rulesRules are few and small. Compile them into a lookup table by endpoint when loaded.
Rules push to many gatewaysVersion numbers and a short poll with jitter. A gateway keeps its last good version if a push fails.
Counters for idle callers piling upA TTL on every key, set to about twice the time the bucket needs to refill. Idle keys disappear on their own.
Cross-region countingA share of the limit per region, or a periodic sync. Accept an approximation instead of a cross-region call on each request.

What if a part fails?

FailureHow the design copes
Redis is slowA 2 ms timeout per check, then the local fallback for that request. The circuit breaker opens if errors continue.
A Redis primary diesA 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 downFail open (or closed for sensitive rules) with the local fallback limit. The API stays up.
The rules service is downGateways 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 restartsIt loses its local token lease only (a few tokens). Counters in Redis are untouched. It reloads rules and starts again.
What to monitor
  • •Allowed and rejected per second, by rule (a jump in rejected is the first sign of a bad rule)
  • •Limiter latency (p50, p99) and timeout rate, since the limiter must stay under 2 ms
  • •Redis CPU, ops per second per node, memory, and the hottest keys
  • •Circuit breaker state and the number of requests that used the fallback
  • •Rule version on each gateway, so we notice one that is stuck on an old version
Security and abuse
  • •Never trust a client-sent IP header. Use the address set by our own load balancer.
  • •Make keys hard to bypass: limit by authenticated identity first, so changing IP does not reset the limit.
  • •Limit login, password reset and SMS endpoints much more strictly, and fail closed on them.
  • •Do not reveal internal details in 429 bodies. Keep headers to limit, remaining and reset.
  • •A limiter is not a DDoS defence. Put a CDN and network protection in front for volume attacks.

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Token bucket by defaultAllows 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 RedisExact 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 keysAbout 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 fallbackThe API stays up when the limiter breaks.Briefly weaker protection. Sensitive rules need fail closed.
Counters not durableFast 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 limitsNo cross-region call on each request.A caller can exceed the global limit by a margin if they spread requests across regions.
If we had more time, we would…
  • •Multi-region: a share of the limit per region, with a periodic sync to rebalance.
  • •Adaptive limits that tighten automatically when a backend is overloaded (link to back pressure).
  • •Per-tenant dashboards and alerts when a customer is close to the limit, so support can reach out first.
  • •A shadow mode that logs what a new rule would reject, before turning it on.
  • •A load test of the Redis cluster with a hot key, and a failure drill that kills a primary.
🎤
Say it out loud
“To recap: a rate-limit filter in the gateway, rules pushed from a rules service, and counters in a sharded Redis cluster, updated by an atomic Lua token bucket in one round trip. Busy keys lease tokens so most requests make no remote call. The limiter has a two millisecond timeout and a circuit breaker, and it fails open with a local fallback, except on sensitive endpoints. The trade-offs are that leasing makes limits approximate by a known bound, and counters are not durable. With more time I would cover multi-region limits and a shadow mode for new rules.”

Q&ACross-questions (21)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Algorithms and counting

Know the algorithms in one line each, then show you can count correctly across servers.

Scale and performance

Failures and consistency

Identity, abuse and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Limits must be exact, with no over-admissionNo 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 keysAdd a tenant rule and key. A request checks both the key counter and the tenant counter in one pipelined call.
Global limit across three regionsA 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 countUse 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 themAdd 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 strictlySeparate 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.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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).
EstimationNo 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.
AlgorithmsNames 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 correctnessSays 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-offsAssumes 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.
CommunicationSilent 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.

AvoidCommon mistakes on this question

MistakeDo this instead
Spending the whole interview re-explaining the four algorithmsOne line each, pick one, and move on. The depth is in distributed counting and failure.
Read-then-write on a shared counterMake 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 timeoutA short timeout, a circuit breaker, and a decision to fail open or closed.
Saying the limiter must be 100% exactAsk how exact it must be. State the cost of exactness and where you accept a small, bounded error.
Limiting only by IPUse 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 scaleDo the memory maths (one entry per request) and use a sliding window counter or token bucket.
Ignoring the client side of the contractReturn 429 with Retry-After and rate-limit headers, and say how a good client should back off with jitter.
Presenting the limiter as DDoS protectionSay it protects against heavy callers, and that volume attacks need a CDN and network protection.

Revise60-second revision sheet

  • ✔Scale: 1M requests per second, 2 checks each, is 2M checks per second. 20M counters at 100 bytes is 2 GB. Throughput is the constraint.
  • ✔Default algorithm: token bucket. Two numbers per key. Refill is computed on read, so no background job.
  • ✔Fixed window: cheap, but up to 2× the limit around a boundary. Sliding log: exact, but 1 entry per request (400 GB worst case).
  • ✔Correctness: the check and the update must be atomic. Use a Lua script in Redis. Never read-then-write from the app.
  • ✔Clock: use Redis's own TIME inside the script, so gateway clock differences do not matter.
  • ✔Speed: one pipelined call (about 0.5 ms), sharded by key. Lease tokens for busy keys: remote calls 2M to 560K, primaries 40 to about 12.
  • ✔Leasing cost: approximate, bounded by servers × batch. Tokens can be stranded on one gateway.
  • ✔Failure: 2 ms timeout, circuit breaker, fail open with a local fallback. Fail closed for login and SMS.
  • ✔Counters need no durability: a failover loses a few seconds, so callers briefly get a little extra.
  • ✔Response: 429, Retry-After, rate-limit headers. Clients back off with jitter. It is not a DDoS shield.

Read these topics next

Rate Limiting→

The four algorithms in detail, with a single-server simulator.

API Gateway Pattern→

Where the limiter usually sits.

Consistent Hashing→

How counters are spread over Redis shards.

Circuit Breaker→

Stop calling a failing limiter and use the fallback.

Hot Keys→

What to do when one customer owns a whole shard.

Timeouts and Deadlines→

The 2 ms limit on the check.

DDoS Attacks and Defenses→

What a rate limiter does not do.

Redis vs Memcached→

Why Redis, and what its scripts give you.

← Previous
Design Pastebin
Next →
Design a Unique ID Generator