Distributed Rate Limiter
Two gateways receive requests from the same customer. With one token left, which request gets through?
Save, progress and topic tools
Problem statement
Two gateways receive exports from one account. Each can approve requests from tokens it has already reserved. When its balance runs low, the gateway asks the regional Redis owner for another small batch.
Functional requirements
- Per-account, per-route limits (IP before sign-in)
- Per-plan rates and bursts, with weighted request costs
- Over quota: HTTP 429 with Retry-After
- Live policy updates with missed-update recovery
Non-functional requirements
- Regional decision latency: under 5 ms at 100k attempts/s
- 10M active buckets, with isolation for noisy tenants
- One remaining token, one approval across gateways on a healthy primary
- Store outage: 503 for unconfirmed exports, capped fallback for low-risk reads
- Global quota: one budget split across regions
Scale assumptions
- 100,000 requests/s at peak. Even a rejected request needs a decision.
- 10M active buckets at 100 bytes each. Budget about 1 GB before Redis overhead and replicas.
- Example policy: 100 tokens, refilling at 20/s. Two idle seconds restore up to 40 tokens, capped at 100.
Entities
| Record | Key fields |
|---|---|
| Policy · PostgreSQL | subject, endpoint, bucket capacity, refill rate, version, outage policy |
| Shared bucket - Redis | Unallocated tokens, refill time, policy version and grant identity |
| Local grant - gateway memory | Account and route, remaining tokens, expiry and policy version |
API design
| Endpoint | Result |
|---|---|
RESERVE {bucketKey, grantId, requestedTokens} | Gateway-only refill. Return the allocated count, expiry and policy version. Replay the same grant ID safely after a timeout. |
PUT/policies/{id} | Set the rate, burst allowance and outage behavior. Require the expected version so one operator cannot overwrite another change. |
GET/policies/snapshot | Fetch the current rules and versions after startup or a missed update. |
High-level design
How to draw the four boundaries
How to draw this design
- Publish limitsPolicy database and config publisher
- Intercept requestsClient, gateway and its local token balance
- Decide admissionRedis grant owner and replicas
- Serve and observeBackend services and metrics
Spend a local permit and forward. If the balance is too low, reserve a batch in Redis and retry locally.
- State ownership
- PostgreSQL owns policy, Redis owns unallocated tokens, and gateways own their unspent grants.
- Scale
- buckets by the enforced identity and watch hot keys.
- Correctness
- Deduct each grant once at Redis and each request once at the gateway.
- Failure and recovery
- Choose which endpoints fail open or closed when the limiter is unreachable.
- Edge
- State
- Compute
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the journeys step by step
Serve locally
Refill on demand
Observe and replicate
Change a limit
The usual path ends at step 3: spend a reserved token locally and forward. Steps 4 and 5 run only when the gateway needs more tokens.
High-level design component walkthrough
API Clients
Send authenticated requests
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Retries can raise attempted traffic
Connected operations: Submit request
API Gateways
Enforce allow / HTTP 429
Why, tradeoff and connected operations
Centralize admission and routing while keeping business-state ownership downstream.
Tradeoff: Adds latency to every request
Connected operations: Submit request; Spend locally; Permit available: forward; Export metrics; Refresh gateway rules
Local token balance
Spend reserved tokens inside the gateway
Why, tradeoff and connected operations
An local debit admits a request without a Redis trip. A recent confirmed 429 can also be cached briefly.
Tradeoff: Unused permits at a quiet gateway are unavailable to its peers.
Connected operations: Spend locally; Balance too low: reserve; Install grant; retry debit
Sharded Redis Primaries
Allocate tokens to gateways
Why, tradeoff and connected operations
Refill and reserve on the same primary so two gateways cannot reserve the same remaining token while that owner is healthy.
Tradeoff: Hot key and central dependency
Connected operations: Balance too low: reserve; Install grant; retry debit; Replicate balance; Apply bucket policy
Backend Services
Handle accepted requests
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Fail-open can overload backends
Connected operations: Permit available: forward
Metrics / Alerts
429s, Redis latency, fail-open counts
Why, tradeoff and connected operations
Measure failures and saturation; detection does not itself repair authoritative state.
Tradeoff: Monitoring adds cardinality/cost
Connected operations: Export metrics
Redis Replicas
Failover copies across AZs
Why, tradeoff and connected operations
Redis replicas keep copies of the same bucket state for recovery. They improve availability when a primary fails. These are replicas of one store, not another database choice; async lag can lose recent token updates.
Tradeoff: Lag/failover can lose token state
Connected operations: Replicate balance
PostgreSQL / Policy DB
Authoritative limit definitions
Why, tradeoff and connected operations
PostgreSQL stores tenant limits and policy versions durably. Transactions and constraints make administrative updates consistent. suits related configuration records; Redis handles the separate high-frequency bucket updates.
Tradeoff: Policy edits need safe rollout
Connected operations: Publish policy change
Config Publisher
Version events +
Why, tradeoff and connected operations
Make ownership/version changes explicit; downstream resources must reject stale owners.
Tradeoff: Stale versions require
Connected operations: Publish policy change; Refresh gateway rules; Apply bucket policy
Simulation and engineering control room
Deep dives — decisions, failures and recovery
Which rate-limiting algorithm fits?
| Algorithm | How it counts | When to use it |
|---|---|---|
| Token bucket | Save unused tokens up to a cap. | Use here: short bursts are welcome, sustained traffic has a ceiling. |
| Sliding window counter | Estimate recent traffic from this interval and the previous one. | Smooth out boundary spikes when an approximate count is enough. |
| Fixed window | Reset a counter every minute. | Simple, but ten calls just before noon and ten just after can all pass. |
90-second interview summary
I would start by asking which requests share an allowance. For exports I would count by account and route, so switching keys cannot buy a second budget. I would agree on two numbers: how large a burst we welcome and what rate the service can sustain.
On each request the gateway checks its local token balance. If it has enough valid permits it spends the cost atomically and forwards immediately. Otherwise it requests a small batch from the Redis primary for that account and route. Redis deducts the grant before returning it. PostgreSQL stores the rules, and gateways pick up versioned updates.
A larger grant saves round trips but can leave permits at a quiet gateway. I would compare grant traffic with the number of unused permits that expire. During an outage, a protected export can spend its remaining grant. Once it runs out, I return 503. A confirmed quota denial gets 429 and a retry delay.
For a global cap I would divide the allowance across regions and prevent overlapping grants during failover. I would try a new policy in shadow mode, check who it would reject, then enable it for a small group. The decision I would revisit first is how much unused capacity we accept to save a network trip.
Test your design decisions
Redraw the system from memory
Trace a local approval, then redraw the same request with an empty local balance.
An export must pass both a burst limit and a 1,000-per-day cap. What do you clarify first?
Reveal answer
Ask when the day resets and whether rejected attempts count. For accepted requests only, check both balances before charging either. Keeping both counters on the same owner lets one operation do that.
One customer sees more 429s just after a rollout. Is their traffic really up?
Reveal answer
Compare attempted traffic and denials by route and applied version against a control group. Check whether the new limit is lower or a gateway retained an old denial. Restore the prior settings under a newer version if the canary is wrong.
Five permits per gateway are reported asynchronously. What breaks the bound?
Reveal answer
A disconnected gateway that keeps issuing fresh permits can exceed five indefinitely. Stop at the cap until acknowledged and preserve outstanding usage across restarts.
Rehearsal checklist
- Name the bucket key and its owner.
- Show how one operation settles two simultaneous requests.
- Explain when a 429 is justified and what happens when the limiter itself is unavailable.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Choose a limit per user or tenant. State the allowed burst and estimate peak requests that need a decision. |
| 15–30 min | High-level design | Draw the local spend and forward path first. Then show a Redis refill, the durable policy store and versioned updates. |
| 30–45 min | Deep dives | Trace two requests for the last permit. Compare batch sizes, unused grants and regional budgets. |
| 45–55 min | Failure and recovery | Choose which endpoints fail open or closed if Redis is unavailable. Explain what happens to the limit after failover. |
| 55–60 min | Wrap-up | Describe a shadow rollout, then a small canary. Watch decision and denials by route and rule version. Close with the guarantee you would relax to save a network trip. |