Hierarchical Multi-Tenant Rate Limiter Design
System DesignModel answerLast updated
Design a distributed limiter that enforces global, regional, and per-endpoint quotas at 500K RPS with sub-10ms overhead and graceful degradation.
Context
You are designing the traffic-control layer for a large public API platform. Every incoming request must be evaluated against several quota rules at once before it reaches a backend service.
Task
Design a rate limiting service that enforces policies at three tiers simultaneously:
- Per API key, globally — one budget across the entire worldwide fleet of datacenters.
- Per datacenter — a regional cap applied to all traffic handled there.
- Per endpoint path — a cap on a specific route (e.g.
/v1/search), possibly scoped per key.
A request is admitted only if every applicable rule still has headroom; otherwise return 429 Too Many Requests.
Requirements
Functional
- Policies express limits over windows, e.g. 100 requests/minute and 5,000 requests/hour.
- Rejections return
429; include limit/remaining/reset information.
Non-functional
- The check itself adds less than 10 ms to the request path.
- The limiter must stay available during storage failures and must not fail closed — a degraded limiter should not reject legitimate traffic outright.
Scale
- 500,000 requests/second aggregate across roughly five regions.
What to Cover
- How counters and policy configuration are stored for fast lookup.
- Where the enforcement decision lives (library, sidecar, or central hop) and why.
- How concurrent increments stay correct across many limiter nodes.
- What happens when the counter store becomes unreachable.
Hints
Hint 1
Do the math first: how many counter operations per second does a request touching three tiers actually generate, and what does that imply for cross-region calls?
Hint 2
Only increments and comparisons are needed — think about which single-round-trip primitive lets you check several counters and commit them together or not at all.
Hint 3
You cannot keep a global per-key budget perfectly synced within 10 ms across continents. What bounded error are you willing to accept, and how do you split the budget so regions rarely collide?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope the problem with numbers
Each request is checked against up to 3 scopes × 2 windows = 6 counters. At 500K RPS that is up to 3M counter operations per second globally. Pinned across ~5 regions, each region sees ~100K RPS nominal with 2–3× peaks.
The decisive constraint is latency: an in-region round trip to a counter store is ~0.5–1 ms; a cross-region call is 50–150 ms. So no cross-region synchronous call can sit on the hot path. Everything else follows from that.
I'd confirm up front: does "global per key" mean the sum across all regions (assume yes)? Is a small, short-lived over-admission — say a few percent for a second or two — acceptable in exchange for latency and availability (assume yes; this is capacity protection, not billing)? Failure posture: fail open with safeguards.
2. APIs
Internal check, called by the enforcement layer:
Check(api_key, region, path, cost=1)
-> {allowed, limit, remaining, reset_at, violated_rule}
Clients see 429 with Retry-After; every response carries X-RateLimit-Limit / Remaining / Reset. An admin API versions and audits policies (PUT /policies/{id} with scope, match, limit, window, algorithm).
3. Data model
Configuration is the rarely-changing source of truth in Postgres/etcd, compiled into an in-memory table on each limiter node keyed by (tier, api_key, path), so policy lookup is an O(1) local operation with no network hop and survives control-plane outages as the last-known-good snapshot.
Counters live in Redis. Keys look like rl:{api_key}:{scope}:{path}:{window_start}. Using the API key as a hash tag co-locates all of one tenant's counters in the same cluster slot, which is what makes a multi-counter atomic check possible.
Algorithm: sliding-window counter (two integers per window, estimated as prev × (1 − elapsed/window) + curr) for "N per minute/hour" policies, because it is O(1) memory and ~99% accurate, avoiding the 2× boundary burst of fixed windows and the unbounded memory of sliding logs. Token bucket where the product wants an explicit burst allowance.
4. Architecture
Client -> edge LB -> service pod + rate-limit sidecar (local policy cache, local buckets)
| one synchronous Lua call
regional Redis cluster (sharded, replicated)
Control plane -> policy service -> streamed config to sidecars
Global budget: regional aggregators --async--> global coordinator (every 1-2 s)
Placement: enforcement belongs in a sidecar or in-process middleware, not a centralized gateway. A central hop adds latency and becomes a 500K RPS choke point. The sidecar holds config locally and talks only to an in-region store.
Two tiers of counting:
- Regional and endpoint limits are checked synchronously in one Lua script against regional Redis — one round trip for all counters in that scope.
- Global per-key limits are enforced by budget leasing. Each region gets a share of the key's global quota proportional to recent demand; aggregators report usage every 1–2 s and the coordinator rebalances. Worst-case overshoot is bounded by
sync_interval × rate, which is acceptable.
Hot keys: for very high-volume tenants, sidecars lease a block of tokens (e.g. 100) from Redis and decrement locally, cutting store operations 10–100×. Sizing: at ~50K ops/s per shard, ~100K RPS per region needs ~4 shards baseline; provision 12–16 primaries with replicas for peak and headroom.
5. Consistency
The classic bug is read-check-write: two nodes both read 99, both admit, count hits 101.
- Single counter:
INCRis atomic — increment, then compare the result; set TTL in the same pipeline. - Multiple counters: incrementing blindly is wrong, because a failed hourly check must not consume endpoint quota. Use one Lua script that reads all relevant counters, evaluates every rule, and only then increments — atomic in Redis, and hash tags guarantee single-shard execution.
- Use Redis
TIMEinside the script for window boundaries, never node clocks, to avoid skew. - Replication is asynchronous, so failover can lose a handful of increments — that leans toward over-admission, consistent with our posture.
6. Failure handling
- 2–5 ms timeout on store calls plus a per-shard circuit breaker.
- On failure, fail open but not unbounded: each sidecar enforces a local fallback of
policy_limit / expected_node_count, so one abusive key still cannot flood backends. - Sidecars keep the last-known-good policy snapshot if the control plane is dark.
- Backend load shedding on concurrency/latency is a separate layer that protects services even when the limiter is fully open.
- Emit and alert on fail-open events; sustained fail-open pages.
7. Trade-offs to state
- Accuracy vs. latency: perfectly consistent global accounting is impossible under 10 ms; we accept bounded over-admission on the global tier and keep regional/endpoint tiers exact.
- Availability vs. precision: fail-open with local caps favors uptime; the alternative (fail closed) violates the stated requirement.
- Batching: local leases cut load but widen the error window — tune the block size to tenant volume.
- Common mistakes: keeping the whole policy in Redis (adds a hop), checking counters with separate GET/SET calls (races), forgetting to co-locate keys (multi-key scripts fail across slots), and failing closed when the store blips.