← Problems

Distributed Rate Limiter

mediummid / senior15 min read · 6 diagrams · 3 decisions
Start timed practice

Limit requests per client across a fleet of API servers with low latency and predictable behaviour under failure.

Try it before you read it

You will remember far more of this walkthrough if you attempt the problem first. Run it as a timed 45-minute practice, then come back and compare stage by stage. Each section below opens with what the interviewer wants from that stage and how long to spend on it.

Requirements

~5 min

In the interview: Clarify functional requirements (what the system must do) and non-functional ones (scale, latency, availability, consistency). State what is out of scope.

Functional

  • Limit the number of requests a client can make in a time window (e.g. 100 requests/minute per API key).
  • Rules are configurable per endpoint, per client tier and per dimension (user id, API key, IP).
  • Rejected requests get a 429 with headers that tell the client when to retry.
  • Limits apply across the whole fleet, not per server: 100/min means 100/min no matter which server handles the request.
  • Operators can change limits without redeploying.

Non-functional

  • Added latency on the request path must be tiny: p99 < 2 ms for the limit check.
  • High availability: the limiter must never take the API down. Decide explicitly what happens when the limiter's state store is unreachable.
  • Accuracy: a few percent over-admission under contention is acceptable; a 2× burst at window edges is not.
  • Memory per tracked client must be small, since there can be tens of millions of keys.

Out of scope

  • DDoS mitigation at the network layer (that lives in the CDN/WAF).
  • Billing and quota accounting over months (a different system with exact counts).

Back-of-envelope estimates

~5 min

In the interview: Estimate QPS (read and write), storage over 5 years, bandwidth and cache size. Show the arithmetic.

Assumptions

  • 10M daily active API clients, 1M concurrently active in any given minute.
  • Fleet handles 100K requests/s at peak; every request does one limit check.
  • One rule per request on average, two counters per rule for sliding window.

Throughput on the state store

  • 100K checks/s × 1 atomic operation each = 100K ops/s. A single Redis node does ~100K–200K simple ops/s, so plan 2–4 shards for headroom, more if you run Lua scripts that touch several keys. Throughput, not memory, is what decides the shard count.
  • With client-side batching (pre-aggregation, see deep dives) this can drop 10× to ~10K ops/s, which a single node absorbs with room to spare.

Memory

  • Per key: key string (~40 B) + counter (8 B) + window timestamp (8 B) + Redis overhead (~50 B) ≈ 100 B.
  • 1M active clients × 2 keys × 100 B ≈ 200 MB. Even 10M clients ≈ 2 GB. Fits one Redis node; shard for throughput, not for memory.
  • Sliding window log instead: 100 req/min × 8 B timestamps × 1M clients ≈ 800 MB per minute of history. This is why the log is only for low-volume limits such as login attempts.

Latency budget

  • Same-AZ Redis round trip ≈ 0.3–0.5 ms. Lua script execution ≈ 10–50 µs. Total ≈ 1 ms, which meets the p99 < 2 ms target with one round trip. Two round trips (read then write) would not, and would also be racy because another server could change the counter between them.

Rule storage

  • Thousands of rules, a few hundred bytes each: kilobytes. Cache the whole rule set in every server's memory and refresh every ~30 s, so rule lookup never touches the network.

API design

~5 min

In the interview: Define the core endpoints, their inputs, outputs and error cases.

Internal check API (called by the gateway or middleware)

  • allow(key: string, ruleId: string, cost = 1) → { allowed: boolean, limit, remaining, resetAt, retryAfter? }
  • The key is built from the dimension, e.g. "user:123", "ip:203.0.113.5" or "apikey:abc:endpoint:/search".
  • cost lets expensive endpoints consume more than one token.

Client-facing behaviour

  • 429 Too Many Requests when rejected.
  • Headers on every response: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (epoch seconds). On 429 add Retry-After (seconds).
  • Response body: { error: "rate_limited", retryAfter: 12 }.

Rule management API (operators)

  • PUT /v1/rules/{ruleId} with { dimension, match: { endpoint?, tier? }, limit, windowSeconds, burst?, algorithm }
  • GET /v1/rules, DELETE /v1/rules/{ruleId}.
  • Rules are versioned; servers pull the latest version on a timer or get a push via a config channel.

Notes

  • Never return a 429 without Retry-After: clients will hammer you with immediate retries.
  • Soft-limit mode: log and allow but do not reject. Use it to dry-run a new rule before enforcing.

Data model

~5 min

In the interview: Define the main entities, keys, indexes, and pick a storage technology with a reason.

Counter state (Redis, ephemeral)

  • Token bucket: key → { tokens: number, lastRefillMs: number }. Store as a hash or two fields packed into one string.
  • Sliding window counter: two keys, "{key}:{currentWindow}" and "{key}:{previousWindow}", each an integer with EXPIRE = 2 × window.
  • Keys expire automatically; nothing needs a cleanup job.

Rule store (durable, tiny)

  • rule_id (PK), dimension (user | api_key | ip), match (endpoint pattern, tier), limit, window_seconds, burst, algorithm, mode (enforce | log), version, updated_at.
  • Lives in a relational DB or a config service (etcd, Consul). Read-heavy, written rarely.

Audit / metrics (append-only)

  • Rejections are emitted as events { key, rule_id, ts } to a stream for dashboards and abuse detection. Do not write these synchronously to a database.

Storage choice

  • Redis for counters: in-memory, single-threaded per shard so Lua scripts run atomically, sub-millisecond, TTLs built in.
  • Memcached would also work for fixed windows (incr + expire) but lacks Lua, so sliding windows and token buckets get racy.
  • A SQL database is wrong here: 100K read-modify-write transactions per second on hot rows is exactly what relational row locks are bad at.

Blue: services · Green: durable stores · Yellow: caches · Purple: queues · Red: third parties · Dashed arrows: asynchronous.

Data model

Counters are ephemeral and expire on their own; rules are durable and tiny; rejections are an append-only stream. Say that no table needs a cleanup job.

High-level design

~10 min

In the interview: Draw the main components and the request flow for reads and writes. Keep it simple first.

Request path
1. The client's request arrives at the API gateway (or a middleware in each service), which is the one place every request passes through.
2. The gateway's rate-limit middleware builds the counter key from the request: the user id from the auth token, or the client IP, combined with the rule id, for example "user:123:search". It then looks up the rules that match this endpoint and client tier in its in-memory rule cache, with no network call.
3. For each matching rule it sends one atomic Lua script to Redis. The script refills the bucket or rolls the window based on the current time, reads the count, increments it if the request is allowed, and returns whether it passed plus the remaining budget and reset time. Because Redis runs the script as a single operation, two gateways checking the same key cannot both see the last token.
4. If allowed, the gateway forwards the request to the backend service and later attaches X-RateLimit-* headers to the response. If rejected, it returns 429 with Retry-After immediately; the backend never sees the request, which is the point.

Control path

  • Operators write rules through a rules service into a durable store.
  • Every gateway instance polls the rules service every ~30 s (or subscribes to a change feed) and swaps its in-memory rule set atomically, so a request always sees either the old set or the new set, never a mix.

Observability path

  • The middleware emits allow/reject counters to the metrics pipeline and rejection events (key, rule, timestamp) to a stream, so abuse dashboards can see which clients are being limited without querying Redis.

Why the gateway?

  • One implementation, one place to tune. Services stay stateless and simple. Service-specific limits are still possible: the gateway knows the route, so rules can match on endpoint.

Why Redis is on the critical path, and what that costs

  • One extra network hop per request (~1 ms). The alternative, local counters on each server, cannot give a fleet-wide limit because each server would only see its own share of a client's traffic. The deep dives cover how to survive Redis being slow or down.
High-level design
Build it up
Step 1 of 4
Limit check

Limits apply across the whole fleet, so every API gateway instance checks each request against a shared Redis cluster: one atomic EVALSHA call, about 1 ms. Only allowed requests reach the backend services; the rest get a 429 with Retry-After.

Say: Redis is on the critical path; I’ll cover what happens when it’s down.

Faded boxes arrive in a later step; outlined boxes are new in this one.

The gateway middleware does one atomic Redis call per request and either forwards or returns 429. Rules flow in from the side on a timer; metrics and rejection events leave asynchronously. Say that Redis is on the critical path and that you will cover what happens when it is down.

Deep dives

~10 min

In the interview: Pick the 2–3 hardest parts (bottlenecks, hot paths, failure modes) and go deep.

1. Token bucket maths and the atomic Lua script

  • Picture a bucket of capacity B (the allowed burst) that is refilled at r tokens/second, and every request takes a token. For 100 req/min with burst 20: r = 100/60 ≈ 1.67 tokens/s, B = 20, so a quiet client can fire 20 requests at once and then sustain 100 per minute.
  • On each request the script computes tokens = min(B, tokens + (now − lastRefill) × r), which credits the tokens earned since the last check without ever exceeding the capacity. If tokens ≥ cost it subtracts cost and allows; otherwise it rejects and reports retryAfter = (cost − tokens) / r, the time until enough tokens have accrued.
  • Doing GET then SET from the app is a race: two servers read tokens = 1 and both allow. Put the whole read-compute-write in a Lua script: EVALSHA script 1 key now rate burst cost. Redis runs it atomically on the shard, so the counter is exact.
  • Store tokens and lastRefill in one hash; set EXPIRE to the time it takes to refill fully, so a key that has not been touched for that long is dropped and idle clients cost no memory.

2. Sliding window counter with two keys

  • Fixed windows allow 2× bursts: a client can send 100 at 0:59 and another 100 at 1:01, 200 requests in two seconds, because the counter resets at the minute boundary. A sliding window log fixes this exactly but stores a timestamp per request, which is the 800 MB per minute from the estimates.
  • Approximation: keep one counter for the current window and one for the previous window, and estimate the count over the last 60 s as estimated = prev × (1 − elapsedFractionOfWindow) + current. For a 60 s window at 1:15, elapsed fraction is 0.25, so estimated = prev × 0.75 + current: three quarters of the previous minute still falls inside the sliding 60 s.
  • Two INCRs and two EXPIREs, or one Lua script. Memory is two integers per key. The error is bounded and small for uniform traffic because it assumes requests were spread evenly across the previous window; interviewers accept it as the production answer.

3. Fail open or fail closed?

  • When Redis is unreachable or slow (the gateway's timeout fires at ~5 ms), fail open means allow the request and log that the check was skipped; fail closed means reject it with a 429 or 503.
  • Default to fail open for public APIs: a limiter outage should not become an API outage. Protect the backends with a local fallback limiter, a per-server token bucket set to limit / N servers, so each server admits roughly its share and you are not fully unprotected.
  • Fail closed for security-sensitive limits (login attempts, OTP verification), where admitting too many attempts is worse than turning the endpoint away for a while.
  • Use a circuit breaker: after K consecutive Redis errors, stop calling Redis for a few seconds and use the local fallback, then send a single probe request to see whether Redis has recovered before resuming.

4. Rate limit headers and client behaviour

  • X-RateLimit-Limit (the cap), X-RateLimit-Remaining (how many requests the client has left in this window), X-RateLimit-Reset (epoch seconds when the window resets or the bucket is full). On 429 add Retry-After in seconds, rounded up, so the client knows exactly how long to wait.
  • Clients should back off with jitter; document it. Without Retry-After, a mobile fleet retrying every second turns a limit into a self-inflicted DDoS, because every rejected request is immediately replaced by another.
  • Return the headers on allowed responses too, so well-behaved clients can pace themselves from the remaining count and never see a 429.

5. Multiple dimensions, hot keys and local pre-aggregation

  • To limit by user and by IP at once, evaluate each rule in turn, allow only if all pass, and decrement all. If the second rule rejects after the first already incremented, the first counter is over by one; accept that small error, or run both checks in one Lua script with both keys on the same shard, which you force with hash tags like {user:123} in the key names.
  • Hot keys: one abusive client at 50K req/s sends every check for its key to the one Redis shard that owns it. Mitigation: once a key is over its limit, the gateway caches the rejection locally until resetAt (which the script already returned), so it answers 429 from memory and Redis is not asked again for the rest of the window.
  • Pre-aggregation for very high limits (e.g. 1M/min for a partner): each gateway counts the partner's requests locally and flushes its subtotal to Redis every 100 ms with INCRBY. Accuracy drops to ±(servers × flush interval × rate), the requests that slipped through before the next flush, but Redis load drops 10–100×.

6. Distributed clocks and window boundaries

  • Use Redis TIME inside the Lua script as the clock, not each server's clock. Gateways with skewed clocks would otherwise disagree on when a window ends and how many tokens have been earned, and the same client could be treated differently depending on which server it hit.
Deep dive: one atomic check in Redis

Read-compute-write must be a single Lua script so two gateways cannot both see the last token. The script uses Redis TIME as the clock and returns remaining and reset so the gateway can set headers without a second call.

Deep dive: sliding window counter with two keys

Two integers per client: the previous window and the current one. The weighted estimate smooths the 2× edge burst of fixed windows at the cost of being approximate. Both keys expire after two windows so idle clients cost nothing.

Deep dive: fail open with a local fallback

When Redis times out, a circuit breaker stops calling it and the gateway falls back to a per-server token bucket sized at limit ÷ N. The API stays up with an approximate limit; auth-sensitive rules fail closed instead.

Deep dive: hot keys and local pre-aggregation

For very high limits, each gateway counts locally and flushes with INCRBY every 100 ms, cutting Redis load by 10–100×. For a client already over its limit, the gateway caches the rejection until resetAt so Redis is never asked again.

Key decisions

The choices this design turns on. For each, know the options, what you give up with each, and the condition that would make you pick differently: that condition is usually the interviewer’s next question.

Which limiting algorithm?

Token bucket

  • Allows short bursts
  • Memory-cheap: two numbers per key
  • Burst size needs tuning
  • Slightly harder to explain to clients
Pick when: APIs where bursts are acceptable (most public APIs).

Fixed window counter

  • Simplest to implement
  • Cheap
  • 2× burst at window edges
Pick when: Rough limits where edge bursts do not matter.

Sliding window log

  • Exact
  • Stores a timestamp per request → memory heavy
Pick when: Low-volume, strict limits (e.g. login attempts).
Used in this design

Sliding window counter

  • Smooths edge bursts
  • Memory-cheap
  • Approximate
Pick when: High-volume limits that need smoothing.

Where does the counter live?

Local in-memory per server

  • Zero network latency
  • No shared dependency
  • Limit is per-server, so effective limit = N × configured
  • Sticky sessions needed for accuracy
Pick when: Approximate limits are fine or traffic is sticky.
Used in this design

Centralised Redis

  • Accurate global limit
  • Atomic INCR/EXPIRE or Lua scripts
  • Adds a round trip
  • Redis is now on the critical path
Pick when: Accuracy matters and you can afford ~1 ms.

Where in the request path?

Inside each service

  • Fine-grained per-endpoint rules
  • Duplicated logic
  • Inconsistent behaviour
Pick when: Limits are genuinely service-specific.
Used in this design

API gateway / middleware

  • Centralised
  • Services stay simple
  • One policy fits all unless configurable
Pick when: Microservices behind a gateway.

Wrap-up

~5 min

In the interview: Summarise the key decisions, what you gave up, and what you would do with more time.

Summary of decisions

  • Sliding window counter by default, because it blocks the double burst at window edges with two integers per key; token bucket where bursts are a feature; both as atomic Lua scripts in Redis so the check is exact.
  • Centralised Redis for accuracy, because only a shared counter can see a client's traffic across the whole fleet, with a local per-server fallback limiter and a circuit breaker for availability.
  • Fail open for public APIs, because a limiter outage must not become an API outage; fail closed for auth-sensitive endpoints, where over-admission is the bigger risk.
  • Enforcement at the gateway with rules cached in memory and refreshed every 30 s, so services stay simple and rule lookup costs no network call.
  • Full X-RateLimit-* and Retry-After headers on every response, so clients can pace themselves instead of retrying blindly.

What was given up

  • Exactness: the sliding window counter is an approximation, and multi-dimension checks can over-count by one.
  • Rule changes take up to 30 s to apply everywhere, the polling interval.
  • One extra hop on every request, about 1 ms.

With more time

  • Per-client dynamic limits driven by abuse scores, global quotas over days/months in a separate accounting system, and a dry-run mode that reports what each new rule would reject before enforcing it.

What good looks like

What an interviewer expects you to cover at each level. Pick your target level and tick what your last attempt covered; the gaps are what to practise next.

Assess against:
0/5

Interviewer follow-ups

Questions that come after the main design. Answer each out loud in under two minutes, naming the part of the design that changes.

  1. How do you avoid a thundering herd when limits reset?
  2. Can you rate limit without any shared state at all?
Ready to try it under time?
45 minutes, seven stages, then a side-by-side review against this walkthrough.
Start timed practice

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayAPI gateway, Gateway A, Gateway B, Gateway, Gateway CAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon ElastiCacheRedis cluster, Redis shard, RedisMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon EC2 Auto ScalingBackend services, Rules service, BackendCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon Kinesis Data StreamsMetrics + rejection streamPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar
Amazon DynamoDBRule storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra