Building a Concurrent Per-Client Throttling Service at Scale
System DesignModel answerLast updated
Design a throttling component that caps each client's request rate under heavy concurrency and millions of checks per second, then extend it across many servers.
Your team runs an API platform and needs a component that throttles traffic so no single client can overload the backend. Design it, and sketch the core implementation.
Cover the following points:
- Per-client quota. Enforce a cap for each caller, identified by user ID, IP address, or API key, for example a fixed number of requests per second.
- Concurrency safety. Many worker threads will call the limiter at once. Per-client state must never be corrupted, and the limiter must never admit more traffic than the quota allows because of races.
- Throughput. The component must handle millions of checks per second with very low added latency. Identify the bottlenecks and how you would remove them.
- Algorithm. Choose a throttling algorithm (token bucket, leaky bucket, fixed window, sliding window, etc.). State its burst behavior, accuracy and fairness, and what you give up compared with the alternatives.
- State layout. Describe what you store for each client and in which data structures, including how memory stays bounded.
- Denied requests. Say what the caller experiences when a request is over quota (an error status, a retry hint, queuing or delaying).
- Multi-instance deployment. Explain how the design changes when the service runs on many machines and any one client's requests can reach any of them.
Before designing, list the clarifying questions you would ask: what the limit is scoped to (user, IP, route, or global), whether bursts are acceptable or the rate must be strict, single node versus distributed, exact versus approximate counting, and what should happen when the limiter itself fails.
Hints
Hint 1
Start by writing down the assumptions (key scope, burst tolerance, exact vs approximate, failure mode). Each one pushes you toward a different algorithm and architecture.
Hint 2
Pick an algorithm whose per-client state is just a couple of numbers and that refills lazily on each check, so no background timer is needed. Then ask what the read-modify-write race looks like and how to make it atomic cheaply (lock striping, CAS).
Hint 3
For scale-out, compare three options: a central atomic store, routing each key to one owner node, and local enforcement with periodic syncing or token leasing. Weigh accuracy against added latency and availability.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first
| Question | Why it matters | Assumption here |
|---|---|---|
| Scope: user, IP, API key, route, global? | Defines the key and its cardinality | Key = (api_key, route), IP for unauthenticated traffic |
| Bursts allowed? | Token bucket vs. strict smoothing | Bursts up to capacity B |
| Single node or distributed? | Local memory vs. shared state | Design single-node first, then distribute |
| Exact or approximate? | Exact global limits cost a network hop per check | A few percent over-admission is tolerable |
| Failure mode? | Availability vs. protection | Fail open for ordinary APIs, fail closed for login and expensive endpoints |
Scale assumptions: about 2M checks/s across 50 instances (~40K/s each), 10M active keys, and under 1 ms of added p99 latency.
2. Algorithm: token bucket
| Algorithm | Bursts | Accuracy | State | Comment |
|---|---|---|---|---|
| Fixed window | Up to 2x at window edges | Weak at boundaries | One counter | Simplest |
| Sliding log | None | Exact | O(N) timestamps | Memory heavy |
| Sliding window counter | Smoothed | Approximate | Two counters | Good for "N per minute" |
| Leaky bucket | None | Exact output rate | Queue | Adds delay |
| Token bucket | Up to B | Exact long-run rate | Two numbers | Chosen |
Token bucket gives O(1) state, a precise long-run rate, a bounded burst, and per-key fairness (one client cannot drain another's budget). Refill is lazy, computed at check time:
tokens = min(B, tokens + (now - last) * rate)
last = now
admit if tokens >= cost, then tokens -= cost
Use a monotonic clock so wall-clock adjustments cannot create or destroy tokens.
3. State and memory
Per key: tokens (float or fixed-point), last_refill_ns (int64), and a reference to the rule (tier, rate, burst). That is roughly 40 bytes of payload, ~100 bytes with map overhead, so 10M keys is about 1 GB per node.
Store entries in a sharded concurrent map: hash(key) % S with S between 256 and 4096, each shard holding its own lock and dictionary. Eviction is free of correctness cost: an idle bucket would have refilled to full, so entries idle longer than B/rate can be dropped by an LRU or periodic sweep. Cap entries per shard as a safety net.
4. Thread safety
The hazard is a read-modify-write race: two threads read tokens = 1, both admit, both write 0, and two requests pass instead of one.
- Single global lock. Correct but a bottleneck. Reject.
- Lock striping. Lock only the owning shard. The critical section is a few arithmetic operations (tens of nanoseconds), so contention is low. This is the default.
- CAS per entry. Pack fixed-point tokens and a timestamp delta in one 64-bit word and loop on compare-and-swap. Best for very hot keys in Java, Go, or C++.
import threading, time, math
class Bucket:
__slots__ = ("tokens", "last")
def __init__(self, cap, now):
self.tokens, self.last = float(cap), now
class Limiter:
def __init__(self, rate, cap, shards=1024):
self.rate, self.cap = rate, cap
self.shards = [({}, threading.Lock()) for _ in range(shards)]
def allow(self, key, cost=1):
table, lock = self.shards[hash(key) % len(self.shards)]
now = time.monotonic()
with lock:
b = table.get(key)
if b is None:
b = table[key] = Bucket(self.cap, now)
b.tokens = min(self.cap, b.tokens + (now - b.last) * self.rate)
b.last = now
if b.tokens >= cost:
b.tokens -= cost
return True, int(b.tokens), 0.0
wait = (cost - b.tokens) / self.rate
return False, 0, math.ceil(wait * 1000) / 1000
Complexity is O(1) time per check and O(K) memory for K active keys. (In CPython the GIL limits parallelism; production would use Go, Java, or C++ with the same structure.)
5. High QPS
| Bottleneck | Mitigation |
|---|---|
| Lock contention | More shards, CAS on hot entries, per-core shards with key-pinned routing |
| One very hot key | Token leasing: each thread takes a batch (say 100 tokens) from the shared bucket and spends it locally |
| Allocation and GC | Pre-sized maps, object pools, compact structs |
| Clock syscalls | Coarse cached monotonic clock refreshed every ~1 ms |
| Network round trips | Local decisions with batching |
| Unbounded keys | TTL eviction, per-shard cap |
A local check costs about 100 ns, so 40K/s per instance is trivial.
6. Rejection behavior
Return HTTP 429 Too Many Requests with a Retry-After header computed from the deficit ((cost - tokens)/rate), plus optional X-RateLimit-Remaining and X-RateLimit-Limit. Add jitter to the hint to avoid synchronized retries. Delaying or queuing suits internal batch callers but ties up connections under attack, so prefer fast rejection at the edge. Log and meter rejections per key and consider penalizing abusers.
7. Distributed scaling
A. Central store (Redis Cluster). A Lua script performs refill, check, and decrement atomically in one round trip. Gives exact global limits, but adds ~0.3-1 ms per request, needs ~20+ shards for 2M ops/s, and puts Redis in the critical path.
B. Sticky routing. The gateway consistent-hashes each key to one limiter node, so state lives in one place and logic stays local. Costs an extra hop, risks hot-key imbalance, and rebalancing causes a brief over-admission window.
C. Local enforcement with global sync (approximate). Each instance holds a share of the global budget, or leases token batches from a coordinator, and reconciles periodically. Scales best and survives store outages, with accuracy off by roughly the lease size times instance count.
A common hybrid is C for most tiers and A for strict tiers (billing, security). On store failure, apply the chosen failure mode: fall back to local limits at rate / N_instances rather than fully open.
8. Common mistakes
- Fixed windows that allow a 2x burst at the boundary.
- Using wall-clock time instead of monotonic time.
- A global lock or a background refill thread per key.
- Never evicting idle keys, leading to memory leaks and attacker-driven blowup.
- Ignoring hot keys and the failure mode of the shared store.
- Returning 429 with no retry hint.