Skip to content
SD-9 · Back to the write-up

Design a API Rate Limiter

One token bucket per key in a shared, sharded store; gateways take tokens in batches, and fail open if the store is slow.

Follow a request

Clients
Edge
Gateways
Services and data
API clientWith an API key
Edge + LBCoarse IP limits
API gatewaysLimiter built in
Counter store8 shards by key
Rules configCached in gateways
Limit events1% sampled
API backendThe real services
Usage analyticsPer key and rule
1client → edge · GET /v1/ordersA client calls the API with key k_9f3c. The edge checks the IP is not flooding and passes it on.1 / 7

The numbers, at a glance

Of every 10 requests……1 calls the counter store
1 store call9 from the local stash
What a flooder getsA 1,000-a-minute key, by where we count
Buckets are tiny30M buckets × 100 bytes
So the store is sharded for calls per second, not for memory.

A check, in order

Batched path shown; rules come from the gateway’s local copy. With tokens already in the stash, steps 2 and 3 disappear.

Client
Gateway
Counter store
Backend
1 GET /v1/orders, key k_9f3c
2 script: refill, take 10
3 granted 10, 812 left
4 forward
5 200
6 200 + X-RateLimit headers
RequestResponseAsync, does not block

Where the counts live

The decision this question is really about.

Each gateway
Leaks N×
gateway 1: 1,000gateway 2: 1,000
… × 40
40,000 a minute
+ No network call.− 40 gateways, 40× the limit.
Sticky by key
Hot spots
hash(key) → gateway 7
all of k_9f3c on 7
gateway 7 overloaded
+ Exact local counts.− A hot key melts one gateway.
Shared + batched
Our pick
any gateway
take 10 tokensspend locally
≈ 1,050 a minute
+ One bucket, 10× fewer calls.− A store to run and fail around.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ≈ 10,000 req/sMake it work
API clients
API gatewayRules config
API backend
One gateway, buckets in its memory; exact because there is only one.
Stage 2 · ≈ 100,000 req/sShare the counts
API clients
Edge + LB
API gateways × 4Counter store
API backend
Rules cached in every gateway; buckets in a shared store updated by one atomic script.
Stage 3 · ≈ 1M req/sScale and survive
API clients
Edge + LB
API gateways × 40Sharded counter store
API backendLimit eventsUsage analytics
8 shards, tokens in batches of 10, fail open after 5 ms, sampled events.
Was this walkthrough useful?Your vote tells us what to improve next.