System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Distributed Rate Limiter

Two gateways receive requests from the same customer. With one token left, which request gets through?

Save, progress and topic tools
○ Easy
My progress

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

RecordKey fields
Policy · PostgreSQLsubject, endpoint, bucket capacity, refill rate, version, outage policy
Shared bucket - RedisUnallocated tokens, refill time, policy version and grant identity
Local grant - gateway memoryAccount and route, remaining tokens, expiry and policy version

API design

EndpointResult
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/snapshotFetch 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

  1. Publish limitsPolicy database and config publisher
  2. Intercept requestsClient, gateway and its local token balance
  3. Decide admissionRedis grant owner and replicas
  4. 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.
Distributed Rate Limiter
G client->gw 1. Submit request gw->near 2. Spend locally gw->svc 3. Permit available: forward near->redis 4. Balance too low: reserve redis->near 5. Install grant; retry debit gw->obs 6. Export metrics redis->rep 7. Replicate balance cfg->cp 8. Publish policy change cp->gw 9. Refresh gateway rules cp->redis 10. Apply bucket policy client API Clients Request + identity gw API Gateways Enforce the route policy near Local token balance In-process, per account + route redis Sharded Redis Primaries Atomic batch grants svc Backend Services Allowed requests obs Metrics / Alerts Denials and latency rep Redis Replicas Async copy cfg PostgreSQL / Policy DB Versioned limits cp Config Publisher Deliver rule updates
  • Edge
  • State
  • Compute

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

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

Client / user

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

Gateway / routing

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

Cache / in-memory index

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

Cache / in-memory index

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 service

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

Observability

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

Cache / in-memory index

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

Relational database

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

Coordination / ownership

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?

AlgorithmHow it countsWhen to use it
Token bucketSave unused tokens up to a cap.Use here: short bursts are welcome, sustained traffic has a ceiling.
Sliding window counterEstimate recent traffic from this interval and the previous one.Smooth out boundary spikes when an approximate count is enough.
Fixed windowReset a counter every minute.Simple, but ten calls just before noon and ten just after can all pass.
Deep dive 1

Who gets a limit?

Two keys for one customer share one export budget. Use the account and route to identify it.

Staff lens — Before login, use a coarse IP limit. A whole office can share one address.

Which identity matches the promise to the customer?

Use an key to limit an individual integration, a user ID for a per-person allowance, and an account ID for a shared plan. Add the normalized route when expensive exports need a budget separate from ordinary reads.

Before authentication

An IP limit covers anonymous login attempts, but an entire office may share one address. Keep this first check coarse and switch to authenticated identities when available.

Several limits on one request

An export may need both a user limit and an account-wide cap. Decide whether a rejected export should spend either allowance. If only accepted exports count, both debits must succeed together; independent checks can charge one budget and then reject on the other.

Deep dive 2

Which bursts should pass?

Let an idle customer save up for a short burst. A token bucket does that with a burst size and a refill rate.

Staff lens — If the promise is ten requests in any rolling minute, a burst allowance alone cannot enforce it.

What does the limit actually promise?

If an idle customer may catch up, choose a token bucket. A capacity of ten allows ten immediately; a refill of two per second pays for the next request half a second later. Refill from elapsed time when the bucket is touched.

Choose the contract

If the contract says at most ten in any trailing minute, keep accepted timestamps for an exact count, or agree on an approximation. The clock crossing noon should change nothing.

When the downstream needs steady arrivals

If a provider can accept only one call every half second, pace calls through a bounded queue. Decide how long callers may wait before you reject new work.

Deep dive 3

Redis Lua: who gets the last token?

Two gateways want the last token. One short Lua script checks the balance and reserves the token before the other gateway can claim it.

Staff lens — Lua protects the grant in Redis. Two threads in the gateway still need to debit their local balance atomically.

What belongs inside the Lua script?

Send the bucket key, requested grant size and a grant ID. In one short Redis Lua script: check for a prior grant, refill up to capacity, deduct the batch actually granted, and record the result. In Redis Cluster, keep the bucket and grant record in the same hash slot.

Two different races

With one token left, the first script can reserve one and the next sees zero. Inside the winning gateway, a local debit still decides which request gets that token. Lua only protects the Redis operation.

If a grant reply goes missing

If the reply times out, retry the same grant ID within its validity window. Redis returns the recorded result; the gateway installs it once. execution alone cannot recover a recent grant lost during asynchronous replica failover.

Deep dive 4

Two-tier token buckets: when do we call Redis?

Redis hands out small batches. Each gateway spends its batch locally, so most requests skip the network call.

Staff lens — Bigger batches save trips but can leave nine tokens idle at one gateway while another turns callers away.

Why reserve first instead of reporting later?

The gateway spends only permits already deducted by Redis. If its balance is too low, it requests another grant. In a report-later design, the gateway admits traffic first and settles with Redis afterward; that saves calls too, but can admit excess traffic.

How big should a grant be?

Increase the batch when refill calls slow requests and most grants are used up. Shrink it when permits expire unused: a quiet gateway can hold nine tokens while a busy peer is denied.

When is overshoot bounded?

Reporting later allows a gateway to spend before the shared balance is updated. If 20 gateways each stop at five unacknowledged tokens, at most 100 are outstanding. That bound disappears if they keep admitting during a partition or reset their counts on restart.

Deep dive 5

Hot keys: what if one customer floods a shard?

One busy account keeps hitting the same Redis . Larger grants cut its refill calls; a dedicated protects its neighbors.

Staff lens — If you split a hot key, split its refill rate and burst size too. Four full-size buckets would quadruple the quota.

How do you spot and relieve a hot key?

Look for rising grant latency on one Redis primary. Sample the busiest quota keys on that primary to distinguish one hot tenant from many busy tenants.

Choose the first intervention

If one account repeatedly drains small grants, try larger grants at its busy gateways. If its traffic still hurts neighbors, move the account to a dedicated . That isolates the traffic but leaves one owner doing the work.

If one owner still cannot keep up

If the owner itself is saturated, split both burst capacity and refill rate. A budget of 100 tokens refilling at 20/s could use four sub-buckets of 25 refilling at 5/s each. Uneven routing can exhaust one while another has credit. Giving each the full quota would multiply the allowance by four.

Deep dive 6

Redis is offline. What still works?

Five exports arrive, each costing one token. With three reserved tokens, the gateway forwards three and returns 503 for the other two.

Staff lens — On regional failover, reassign quota only after the old region can no longer spend it.

How do you distinguish an outage from a quota denial?

The gateway can honor a reservation already deducted from Redis until it expires. Once it needs another grant, a timeout leaves the quota unknown.

What the caller sees

Return 429 with a retry delay when the owner confirms there are too few tokens. For a protected export that cannot obtain a decision, return 503. Track these separately so a dependency outage is visible.

If another region takes over

Let the surviving region spend its existing allocation. Before transferring the old region's share, ensure its grants have expired or can no longer be spent. A lower policy limit also needs an explicit deadline for old grants.

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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleChoose a limit per user or tenant. State the allowed burst and estimate peak requests that need a decision.
15–30 minHigh-level designDraw the local spend and forward path first. Then show a Redis refill, the durable policy store and versioned updates.
30–45 minDeep divesTrace two requests for the last permit. Compare batch sizes, unused grants and regional budgets.
45–55 minFailure and recoveryChoose which endpoints fail open or closed if Redis is unavailable. Explain what happens to the limit after failover.
55–60 minWrap-upDescribe 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.

On this page
  1. Problem
  2. Requirements
  3. Numbers, entities and APIs
  4. Trace the architecture
  5. Simulation and engineering control room
  6. Decisions and failures
  7. Interview summary
  8. Test your decisions
  9. Recall questions
  10. Checklist
  11. 60-minute rehearsal

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram