Building a Throttling Service for a Multi-Node API Fleet
System DesignModel answerLast updated
Design a throttling layer that caps per-key request rates with burst tolerance, first on one machine, then across many app servers, covering consistency, clock drift, failures, and observability.
Problem
Your company exposes a public API served by hundreds of stateless application instances. You need a throttling component that keeps each caller's traffic under a configured requests-per-second ceiling, while optionally permitting short bursts above the steady rate.
Design it end to end. Your answer should cover:
- Requirements and scale. State your assumptions: what a "caller" is (user, API key, IP, tenant plus endpoint), the number of keys, total QPS, latency budget, and how much overshoot is tolerable.
- Two algorithms. Compare a token-bucket approach with a sliding-window approach. For each, describe the per-key state, time and space complexity, and how you guarantee correctness when many threads hit the same key at once. Sketch an implementation of both.
- Going distributed. Extend the design to many instances sharing the same limits. Discuss:
- centralized store (for example Redis) versus sharded or local counters,
- clock skew between machines,
- atomicity of the check-and-update step,
- idempotency when clients retry,
- failure modes such as node loss and partial updates,
- how to keep enforcement consistent and fair.
- Interface and configuration. Define the API your services call, the response a rejected client sees, and an example rule configuration.
- Operations. Describe the metrics and alerts you would use to detect saturation and misbehavior.
State the trade-offs behind each decision rather than only the final choice.
Hints
Hint 1
Start by deciding whether the limiter should fail open or fail closed when its backing store is unreachable, and whether that answer differs by rule.
Hint 2
The refill, compare, and deduct steps must be a single atomic read-modify-write per key; think about striped locks locally and server-side scripts in a shared store.
Hint 3
Never compare timestamps produced by different machines. Use a monotonic clock locally, and the store's own clock for shared state.
Hint 4
Per-request calls to a central store become the bottleneck for hot keys. Consider letting instances borrow batches of capacity and spend them locally.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
- Scope: Limit per key, where a key might be a user, API key, IP, or tenant+endpoint. Each rule has a sustained rate and a burst size. Requests may carry a cost (an expensive endpoint counts as 5). Rejections return
429withRetry-After. - Scale (assumed): about 1M QPS overall, 500 instances, 10M active keys, per-key limits from 1 to 50k QPS.
- Latency: under 1 ms p99 for a local decision, under 3 ms when a remote store is involved.
- Accuracy vs. availability: 1-5% overshoot is acceptable. The limiter must never cause an outage, so default to fail-open, and use fail-closed only for abuse or cost-critical rules such as login attempts.
2. Interface and configuration
allow(key, rule_id, cost=1, request_id=None)
-> Decision(allowed, remaining, retry_after_ms)
HTTP responses include RateLimit-Limit, RateLimit-Remaining, and Retry-After. Rules are pushed by a config service and hot-reloaded:
rules:
- id: api-per-key
match: {header: X-API-Key}
algorithm: token_bucket
rate_per_sec: 100
burst: 300
failure_mode: open
- id: login-per-ip
match: {ip: true, path: /login}
algorithm: sliding_window
limit: 10
window_sec: 60
failure_mode: closed
3. Algorithms
Token bucket. State is (tokens, last_ts). On each request, lazily add elapsed * rate tokens (capped at capacity), then subtract cost if enough remain. O(1) time and space. Bursts up to capacity are allowed, and long-run throughput never exceeds the rate.
Sliding window.
- Log: store every timestamp in the window. Exact, but O(limit) space per key.
- Counter: keep the current and previous fixed-window counts and estimate
prev * (1 - elapsed/W) + curr. O(1) time and space, and it avoids the 2x burst at fixed-window boundaries. The estimate is accurate when traffic is roughly uniform within a window. - Best for "N per window" policies where a burst parameter is meaningless.
import threading, time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate, self.cap = rate, capacity
self.state = {}
self.locks = [threading.Lock() for _ in range(256)]
def allow(self, key, cost=1.0):
with self.locks[hash(key) % 256]:
now = time.monotonic()
tok, last = self.state.get(key, (self.cap, now))
tok = min(self.cap, tok + max(0.0, now - last) * self.rate)
ok = tok >= cost
if ok:
tok -= cost
self.state[key] = (tok, now)
return ok
class SlidingCounter:
def __init__(self, limit, window):
self.limit, self.w = limit, window
self.state = {} # key -> [win_start, prev, curr]
self.locks = [threading.Lock() for _ in range(256)]
def allow(self, key, cost=1):
with self.locks[hash(key) % 256]:
now = time.monotonic()
s = self.state.setdefault(key, [0.0, 0, 0])
start = now - (now % self.w)
if start != s[0]:
s[1] = s[2] if start - s[0] == self.w else 0
s[2], s[0] = 0, start
weight = 1 - (now - start) / self.w
if s[1] * weight + s[2] + cost <= self.limit:
s[2] += cost
return True
return False
Concurrency correctness.
- Refill, check, and deduct must be one atomic step, otherwise two threads can both see one token and both proceed.
- Striped locks give per-key serialization with bounded memory and low contention.
- Use a monotonic clock so wall-clock adjustments cannot mint tokens, and clamp negative elapsed time to zero.
- Evict idle keys (TTL or LRU) to bound memory.
4. Distributed design
Option A: central store (Redis Cluster). Shard keys across primaries; 1M QPS needs roughly 10-20 shards. Implement the token bucket as a Lua script so the read-modify-write is atomic across all instances. Use the store's TIME rather than the caller's clock, set a TTL slightly above the time to fully refill, and return both the decision and the remaining tokens.
Option B: local limiters with a static share (limit / N). No network hop, but it is unfair when the load balancer is skewed, under-admits when one instance sees most of a key's traffic, and breaks when N changes during autoscaling.
Option C (recommended at scale): hybrid leasing. Instances borrow a batch of tokens (say 10% of capacity) from the central store and serve from memory, refilling asynchronously when the local balance runs low. This cuts store traffic 10-100x for hot keys, and global error is bounded by the lease size. Low-rate keys go straight to the store.
Clock skew.
- Never compare timestamps from different app servers.
- Each key lives on one primary, so that node's clock is the single authority.
- After failover the new primary's clock may differ: clamp negative elapsed time to zero and cap positive jumps at "refill to full".
Atomicity and multi-key limits. One key, one script, all-or-nothing. For hierarchical limits (tenant plus user), use hash tags like {tenant42}:user7 so both keys share a slot and a single script can update both. Alternatively, check the stricter limit first and accept a small over-count on the other.
Idempotency. Clients retry on timeouts, which could double-charge tokens. Accept a request_id, store it briefly (for example a short-TTL key), and return the earlier decision if it is seen again. Retried requests that were already admitted should not consume more capacity.
Failure modes.
- Store unreachable: apply the rule's failure mode. Fail-open rules fall back to a conservative local limiter (for example
limit / N) rather than unlimited traffic; fail-closed rules reject. - Primary loss: replication is asynchronous, so a promoted replica may have slightly stale state. The effect is a brief over-admission, which fits the accuracy budget.
- Partial updates: avoided by scripts and by lease accounting that records grants before they are spent. Unused leased tokens expire with the lease, which under-admits slightly rather than over-admits.
- Hot keys: leasing and local caching of "denied until T" decisions protect the shard.
Fairness. Per-key buckets stop one caller from starving others. Add per-tenant parent limits so a tenant with many keys cannot exceed its plan, and cap lease sizes so one instance cannot hoard a hot key's tokens.
5. Monitoring and alerting
- Allowed vs. rejected counts per rule and per top-N key; sudden jumps in rejection rate.
- Decision latency p50/p99, split by local vs. remote.
- Store CPU, memory, ops/sec per shard, and hot-key skew.
- Fail-open and fail-closed event counts (page if fail-open persists beyond a few minutes).
- Lease refill latency and the fraction of requests served locally.
- Clock-offset and failover events.
- Alert on saturation: a shard above ~70% CPU, a key rejecting over 50% of traffic for several minutes, or config-push lag.
6. Common mistakes
- Using wall-clock time or per-instance clocks for shared state.
- Doing get-then-set from the client instead of an atomic script.
- Choosing fail-closed globally, turning a limiter outage into an API outage.
- Using fixed windows and ignoring boundary bursts.
- Forgetting key eviction, so memory grows without bound.
- Treating a retry as a new request.