Rate Limiter System Design
A distributed API rate limiter in front of many services
By Ankur NayakReviewed
Cap how many requests each client can make, across a fleet of gateway servers, without adding noticeable latency. Built from a token-bucket check at the edge, a shared Redis counter store and rules that change without a deploy.
Open in Studio· edit a copy- Users
- 10M API clients
- Throughput
- ~1M requests/s checked
- Storage
- ~1 GB of counters
- Added latency budget
- < 1 ms p99
- State per client
- 2 numbers
Requirements
Functional
- Limit requests per client, API key, user or IP, per rule
- Different limits per endpoint and pricing tier
- Return 429 Too Many Requests with Retry-After and limit headers
- Change rules at runtime without redeploying
Non-functional
- Adds under 1 ms of latency to each request
- Limits hold across all gateway servers, not per server
- If the limiter store fails, the API stays up (fail open)
- Highly available and horizontally scalable
In depth
Where the limiter lives
A rate limiter can sit in the client, in each service, or at the edge. The edge (the API gateway) is the usual answer: it sees every request first, so abusive traffic is rejected before it costs anything downstream, and every service gets protection without writing any code.
The catch is that a gateway is a fleet of servers behind a load balancer. If each server counted on its own, a client spreading requests across 50 gateways would get 50 times its limit. The counters must be shared.
One round trip per request
Each client's limit is stored as a token bucket: a token count and the time it was last refilled. To check a request, the gateway runs a small atomic script in Redis that adds the tokens earned since the last refill, takes one if available, and returns the result. That is a single sub-millisecond round trip, and because the read-modify-write happens inside the store, two gateways can't race and both spend the last token.
Rules ("100 requests per second for the free tier on /search") change far less often than counters, so each gateway caches them in memory and refreshes them in the background. The hot path never reads the rules database.
Failing well
The limiter is now on the critical path of every request, so its failure mode matters more than its algorithm. If the counter store is unreachable, rejecting everything would turn a limiter problem into a full outage. Most APIs fail open: they allow traffic, ideally under a conservative per-server limit, and alert. Limits that protect security, like login attempts, can fail closed instead.
Stripe describes going beyond per-client limits with load shedders that, under fleet-wide stress, drop low-priority traffic first so critical requests keep succeeding.
What interviewers look for
- Choosing and explaining an algorithm (token bucket, sliding window)
- Making limits global across servers, and atomic
- Latency budget: one round trip, rules cached locally
- Clear 429 responses with Retry-After
- A deliberate fail-open or fail-closed decision
Components
API Client
Client. An app or integration calling the public API with an API key.
Load Balancer
Load balancer. Spreads traffic across gateway instances; any instance may receive any client's request.
Building block: Load Balancer
API Gateway
Rate-limit middlewareAPI gateway. Checks every request against the applicable limits before forwarding it.
Why: Rejecting at the edge means abusive traffic never reaches, or costs, the backend services.
Building block: API Gateway, Rate Limiting Algorithms
Identify Client
Service. Extracts the API key, user ID or IP the rules apply to.
Rule Matcher
Service. Finds the rules for this client tier and endpoint.
Local Rule Cache
In-processCache. Rules cached in memory and refreshed every few seconds.
Token Bucket Check
Service. Atomically refills and takes a token in the shared store; one round trip.
Building block: Rate Limiting Algorithms
Allow / 429
Service. Forwards the request or returns 429 with Retry-After and X-RateLimit-* headers.
Counter Store
Redis ClusterCache. Holds each client's bucket (tokens, last refill time). Updated atomically with a server-side script.
Why: In-memory, sub-millisecond, and shards keys across nodes; the limit must be shared by every gateway instance.
Building block: Cache, Consistent Hashing
Rules Store
Config DBSQL database. Source of truth for limits per tier, endpoint and customer override.
Rules Service
Service. Admin API to edit rules; gateways poll it or receive pushed updates.
Backend Services
Service. The actual APIs; they only see traffic that passed the limiter.
Load Shedder
Service. Under fleet-wide overload, drops low-priority traffic first to keep critical requests flowing.
Metrics & Alerts
Monitoring. Counts allowed vs. throttled requests per rule to tune limits and spot abuse.
Request flows
Request within the limit
- The client calls the API; the load balancer picks any gateway instance.
- The gateway identifies the client and finds its rule in the local rule cache.
- One atomic script refills the client's bucket for elapsed time and takes a token; tokens remain.
- The request is forwarded to the backend with X-RateLimit-Remaining set.
- The client gets its normal response.
Client exceeds the limit
- A misbehaving client sends a burst of requests.
- Each request still goes through the gateway check.
- The bucket is empty, so the atomic script returns 'deny' and how long until the next token.
- The gateway answers 429 with Retry-After; the backend never sees the request.
Failure scenarios
What if: counter store is unreachable?
The gateway cannot check shared buckets. Rather than reject all traffic, it fails open: it falls back to a conservative per-instance limit so the API stays up while abuse is still loosely bounded.
User impact: Normal clients see no change; limits are temporarily less precise.
- Fail open with local in-memory buckets
- Replicate the counter store and spread it across zones
- Short timeout (a few ms) on the limiter call
What if: rules store is down?
Gateways keep enforcing the last rules they cached, so limiting is unaffected; only rule changes are delayed.
- Cache rules in every gateway with a long expiry
- Ship a default rule set with the gateway
Trade-offs
Centralised counters vs. local counters
A shared Redis store for exact global limits, with local limits as a fallback.
- Pros
- Limits hold no matter which gateway a request hits
- Simple mental model for customers
- Cons
- One network round trip per request
- The store must be highly available
Alternatives: Local counters with periodic sync (cheaper, approximate); Sticky routing of each client to one gateway
Token bucket vs. sliding window
Token bucket for API limits.
- Pros
- Allows reasonable bursts
- Two numbers per client
- Cons
- Bursts up to the bucket size can surprise downstreams
Alternatives: Sliding window counter (Cloudflare reports 0.003% error); Sliding log for strict, low-volume limits
Fail open vs. fail closed
Fail open for general API limits; fail closed for security limits like login attempts.
- Pros
- A limiter outage doesn't become an API outage
- Cons
- Abuse is less constrained during the outage
Frequently asked questions
Which algorithm should a rate limiter use?
Token bucket is the usual default for APIs: it allows short bursts while enforcing an average rate, and needs only two numbers per client. Stripe uses a token bucket for its request rate limiter. A sliding window counter is a good alternative when you want a smoother limit.
How do you keep limits consistent across many gateway servers?
Store the counters in a shared, low-latency store such as Redis and update them atomically with a server-side script, so every gateway sees the same bucket. Shard the counters by client key so the store scales horizontally.
What should happen if the rate limiter's datastore fails?
For general API limits, fail open: let requests through, ideally with a conservative per-server limit, because rejecting everything turns a limiter outage into a full outage. Security-sensitive limits such as login attempts can fail closed.
What HTTP response should a throttled request get?
429 Too Many Requests, with a Retry-After header saying when to try again, and headers that show the limit and remaining quota so well-behaved clients can slow down before hitting it.
Building blocks used
Sources
- Scaling your API with rate limiters · Stripe
- How we built rate limiting capable of scaling to millions of domains · Cloudflare Blog
- Rate Limiting pattern · Microsoft Azure Architecture Center
- The Architecture of Uber's API gateway · Uber Engineering