Build a Shared Throttling Layer for a Multi-Server Web API
System DesignModel answerLast updated
Design a throttling service that caps per-key request volume across a fleet of servers, with low added latency, correct behavior under concurrency, and a clear plan for backend failures.
Design a Shared Throttling Layer for a Web API
Your company exposes a public HTTP API served by many identical application servers behind a load balancer. You need a throttling component that limits how many calls each client can make in a time window, for example 100 calls per minute per API key.
What the system must do
- Apply limits per API key.
- Allow different limits for different endpoints (for example, a write endpoint may be much stricter than a read endpoint).
- Reject over-limit calls with HTTP
429 Too Many Requests.
Quality targets
- Latency: the check should add very little to each request (aim for under 10 ms).
- Correctness under concurrency: simultaneous calls from one client, landing on different servers, must be counted correctly.
- Scale: thousands of requests per second across the whole cluster.
- Resilience: if the throttling component has trouble, the API must not go down entirely. Decide whether to fail open or fail closed, and when.
What to cover in your answer
- The interface between application code and the throttler, plus what clients see in responses.
- The storage backend for counters or timestamps, and why you picked it.
- The high-level architecture: how app servers talk to the throttler and where enforcement happens.
- How you prevent race conditions when several nodes handle requests for the same client at once.
State your assumptions about traffic and key counts, compare at least two counting algorithms, and discuss failure behavior and trade-offs.
Hints
Hint 1
Start by estimating scale (requests per second, active keys, memory per key) so your storage and latency choices are backed by numbers.
Hint 2
Think about the check-then-act bug: two servers read the same count, both see room, and both let the request through. What single atomic operation avoids it?
Hint 3
Compare fixed window, sliding log, sliding window counter, and token bucket on memory use and accuracy, then pick one and justify it.
Hint 4
Decide separately for each rule what happens when the store is unreachable. A login or payment endpoint may deserve different behavior than a search endpoint.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
A strong answer covers: scoping with numbers, a small interface, an algorithm choice, an atomic in-memory store, enforcement at the gateway, and an explicit position on races and failures.
1. Assumptions and sizing
- Peak of about 50K requests/sec across roughly 100 app servers; every request triggers one check.
- About 10M API keys, about 1M active in a given minute.
- Limits depend on tier and endpoint, e.g.
POST /ordersat 100/min andGET /searchat 1,000/min. - Budget: under 10 ms end to end, so the check should be about 1-2 ms: one round trip to an in-memory store, no disk on the hot path.
- Accuracy within a few percent is fine.
Memory: 1M active keys x ~3 endpoints x 2 counters x ~100 bytes is about 600 MB. That fits in RAM, and 50K ops/sec is well within a small sharded Redis deployment. Shard mainly for headroom and availability.
2. Interface
Internal call from the gateway (library or gRPC sidecar):
CheckLimit(api_key, endpoint, cost=1) ->
{ allowed, limit, remaining, reset_at, retry_after_s }
Client-visible headers on every response: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. On rejection return 429 with Retry-After and a small JSON error body.
Rules (endpoint, tier, limit, window, algorithm) live in a config store (SQL or etcd) and are cached in memory on each node, refreshed by push or polling.
3. Algorithm choice
| Algorithm | Memory per key | Accuracy | Comment |
|---|---|---|---|
| Fixed window | 1 counter | Up to 2x burst at boundaries | Simplest |
| Sliding log | O(limit) timestamps | Exact | Too costly at scale |
| Sliding window counter | 2 counters | ~1% error on smooth traffic | Good default |
| Token bucket | tokens + last refill | Exact, controlled bursts | Best when bursts are allowed |
Sliding window counter estimates usage as:
estimate = current + previous * (1 - elapsed_fraction_of_current_window)
It removes the boundary-doubling flaw of fixed windows at O(1) memory. Use token bucket for endpoints where short bursts are desirable.
4. Storage
Use Redis (Cluster mode): sub-millisecond in-memory operations, atomic INCR/INCRBY, TTLs that clean up old windows, and Lua scripting for multi-step atomicity. Durability matters little; losing counters on failover only briefly lets extra requests through.
Key layout: rl:{api_key}:{endpoint}:{window_start}. The {api_key} hash tag pins all of a client's keys to one slot so multi-key scripts work. TTL is 2x the window so the previous window is still readable.
SQL or DynamoDB counters are too slow and contend heavily under this write rate. Memcached lacks scripting for atomic compound logic.
5. Architecture
Client -> LB -> API gateway / app server (rate-limit middleware, rules cached)
|
v
Redis Cluster (sharded by api_key, replica per shard)
^
Rules service / config DB
- Purely local counters: no network cost, but each server sees a slice of traffic, so the effective limit becomes roughly N x limit unless routing is sticky.
- Centralized Redis: about one 1 ms round trip and globally accurate. This is the primary mechanism.
- Hybrid for hot keys: a node leases a small batch of tokens (say 10) from Redis and spends them locally, trading slight over-admission for far fewer Redis calls.
Enforce in the gateway so rejected calls never reach business logic.
6. Race conditions
The core bug is check-then-act: two nodes both read 99, both decide there is room, and 101 requests pass.
Fixes:
- Increment first, then compare.
INCRreturns a unique post-increment value to each caller, so exactlylimitcallers see a value at or below the limit. Pitfall: a separateEXPIREis not atomic withINCR; a crash in between leaves an immortal key. Combine them inMULTIor a script. - Lua script (standard answer). Redis runs a script atomically, so read, compute, and write cannot interleave:
-- KEYS[1]=current key, KEYS[2]=previous key
-- ARGV: limit, window_s, now_ms, cost
local limit, window = tonumber(ARGV[1]), tonumber(ARGV[2])
local now_ms, cost = tonumber(ARGV[3]), tonumber(ARGV[4])
local curr = tonumber(redis.call('GET', KEYS[1]) or '0')
local prev = tonumber(redis.call('GET', KEYS[2]) or '0')
local elapsed = (now_ms % (window * 1000)) / (window * 1000)
local estimate = curr + prev * (1 - elapsed)
if estimate + cost > limit then
return {0, math.max(0, math.floor(limit - estimate))}
end
curr = redis.call('INCRBY', KEYS[1], cost)
if curr == cost then redis.call('EXPIRE', KEYS[1], window * 2) end
return {1, math.floor(limit - estimate - cost)}
Complexity per check: O(1) time and memory per key, one round trip.
Clock skew: servers may disagree on time and shift window boundaries. Prefer taking time from Redis itself, or keep servers NTP-synced and accept small error.
Avoid distributed locks. They add round trips and new failure modes that a single-shard atomic operation already eliminates.
7. Failure handling and trade-offs
- Use a tight timeout (about 5 ms) and a circuit breaker around Redis calls.
- Fail open by default for general endpoints: availability beats strictness. Fail closed for abuse-prone or costly endpoints such as login, SMS, or payments. Make it a per-rule setting.
- Each shard has a replica with automatic failover. Asynchronous replication may drop a few increments, which is acceptable.
- Optionally fall back to a coarse local limiter while Redis is down, so fail-open is not completely unprotected.
- Accuracy versus cost: exact sliding logs cost memory; the counter approximation is almost always sufficient.
Common mistakes
- Reading the count and writing it back in separate calls.
- Using fixed windows without acknowledging the boundary burst.
- Forgetting TTLs, leading to unbounded memory growth.
- Using one global fail-open/fail-closed policy for every endpoint.
- Putting the limiter deep in business logic instead of at the edge.
- Hot-key blowups from a single huge client, with no mitigation such as local token leasing.
Follow-ups worth preparing
Multi-region limits (per-region quotas vs. async global sync), per-user plus per-IP layered limits, rule hot-reload without restart, and observability (allow/deny rates, Redis latency, rule hit counts).