Per-User Throttling for a Multiplayer Game API at Scale
System DesignModel answerLast updated
Design a distributed service that caps each user's request volume per rolling minute across many app servers, rejecting excess calls with HTTP 429 while staying fast and available.
Throttle Abusive Traffic on a Game Backend
You are building the throttling layer for the backend of a large online game. Peak load is in the millions of requests per second. Each request carries a user_id, and every user must stay within a quota, for example 100 requests per minute, measured over a rolling window.
What the system must do
- Track each user's request volume over a rolling time window and block requests that exceed the quota.
- Reject blocked requests with HTTP
429 Too Many Requests.
Quality attributes
- Latency: the check must add very little time to each request.
- Scalability: throughput must grow with traffic, with no sharp degradation.
- Accuracy vs. availability: being slightly imprecise is acceptable. Under extreme load, prefer staying fast and available over being perfectly exact.
What to cover in your answer
- Which limiting algorithm you choose (fixed window, sliding window, token bucket, leaky bucket, or a variant) and why.
- Where counters live and how you handle heavy concurrent access to them.
- How many application servers share state and stay consistent enough.
- What happens when the limiter or its backing store fails.
State your assumptions about scale (peak requests per second, active users, number of servers) and use them for rough capacity estimates.
Hints
Hint 1
Do an estimate first: peak requests per second, active users per minute, and bytes of state per user. These numbers should decide between storing every timestamp and storing just a couple of counters.
Hint 2
A check-then-increment done as two separate calls is racy when many servers hit the same key. Think about how to make the decision and the update a single atomic step, and how to keep one user's data on one shard.
Hint 3
Not every request needs a network call to the shared store. Consider what a server can remember locally about users who are already blocked, and how far local counts can drift if they are synced periodically.
Hint 4
Decide ahead of time what the limiter does when the store is unreachable, and whether that answer should differ between a browsing endpoint and a purchase or login endpoint.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale assumptions
Numbers first, since they drive the design:
- Peak traffic: about 5M requests/s.
- Around 10M distinct users active in any minute.
- Default quota of 100 requests/min, adjustable per user tier.
- Latency budget: roughly 1 ms at p99 added to the request path.
- Small over-admission (a few percent) is fine. Rejecting legitimate users because the limiter itself is down is not.
Assumptions to confirm: enforcement sits at the API gateway (or a sidecar), and limits are per region, with global limits discussed as an extension.
2. Interface
Internal call from the gateway:
allow(user_id, policy_id) -> { allowed, remaining, reset_ms }
On rejection the client gets 429 plus Retry-After, X-RateLimit-Limit and X-RateLimit-Remaining. Retry-After spreads out retries and avoids a thundering herd when the window resets.
3. Algorithm
| Algorithm | State per user | Accuracy | Verdict |
|---|---|---|---|
| Fixed window | 1 counter | Up to 2x burst at window edges | Too coarse |
| Sliding log | One timestamp per request | Exact | 10M users x up to 100 entries is tens of GB |
| Sliding window counter | 2 counters | Very close to exact | Best fit |
| Token bucket | tokens + last refill time | Exact rate and burst | Good if bursts are intended |
| Leaky bucket | queue | Smooths output | Adds latency, suited to shaping |
I would choose the sliding window counter. Keep the count for the current window and the previous one, then estimate:
estimate = prev * (1 - elapsed / window) + curr
allow if estimate < limit
This assumes requests in the previous window were evenly spread, which is accurate to within a few percent in practice. Memory: about 2 keys x 60 B = 120 B per user, so 10M users is about 1.2 GB. That is small enough for a sharded in-memory store.
4. Storage and data model
Use a sharded Redis cluster:
key: rl:{user_id}:{window_index}
value: integer
TTL: 2 x window (expires on its own, no cleanup job)
Using {user_id} as a hash tag puts both of a user's windows on the same shard, so one atomic script can touch both. Policies (limit, window, burst) and the user-to-tier mapping live in a config service and are pushed to and cached on every gateway.
5. Atomic check-and-increment
A read followed by a write would let two servers both pass at 99/100. Run the whole decision as one Lua script on the shard:
-- KEYS[1]=curr, KEYS[2]=prev; ARGV: limit, window_ms, elapsed_ms
local curr = tonumber(redis.call('GET', KEYS[1]) or '0')
local prev = tonumber(redis.call('GET', KEYS[2]) or '0')
local est = prev * (1 - ARGV[3]/ARGV[2]) + curr
if est >= tonumber(ARGV[1]) then return {0, curr} end
curr = redis.call('INCR', KEYS[1])
redis.call('PEXPIRE', KEYS[1], 2 * ARGV[2])
return {1, curr}
Redis is single-threaded per shard, so the script is atomic with no distributed lock. One round trip per check.
Capacity: a shard handles roughly 100-150k scripts/s. For 5M rps with 2x headroom, plan for about 60-80 primary shards, each with a replica. Sharding by user_id means no cross-shard coordination.
6. Reducing load on the store
Calling Redis for every request works but is expensive (5M ops/s, about 0.3-0.5 ms per in-DC round trip). Options:
- Fully centralized: exact, but highest cost.
- Fully local: each of N servers enforces
limit/N. This breaks with uneven load balancing or a changing N. - Hybrid (recommended):
- Negative cache: once a user is rejected, the gateway remembers "blocked until reset time" locally. Abusive traffic is most of what gets limited, and it stops reaching Redis.
- Batched sync: gateways count locally and flush deltas every ~100 ms with pipelined
INCRBY, reading back the global total. Worst-case over-admission is aboutservers x rate x sync_interval, a bounded and quantifiable error. - Token leasing: a gateway takes a batch (say 10 tokens) for a heavy user and spends them locally.
7. Failure handling
- Timeouts and circuit breaker: use a 2-5 ms timeout on Redis calls. After repeated failures, open the breaker so requests stop waiting.
- Fail open with degraded local limiting: when Redis is unreachable, gateways enforce an in-memory approximation (
limit / estimated_N). Failing closed would turn a limiter outage into a platform outage. - Exception: for login, payments or purchases, failing closed (or using a stricter local limit) can be justified. Make this a per-endpoint policy.
- Shard failover: a replica is promoted. Asynchronous replication may lose a few seconds of counts, causing brief over-admission, which is acceptable.
- Hot keys: one abusive user can hit a single key hard. The negative cache absorbs most of it, and a single Redis key can sustain around 100k ops/s anyway.
- Clock skew: derive window boundaries from Redis
TIMEinside the script, or accept a few ms of skew, which only nudges window edges.
8. Trade-offs to state
- Accuracy vs. latency: batching and caching trade bounded over-admission for taking Redis off most request paths.
- Fail open vs. closed: a business decision per endpoint, not a technical default.
- Global vs. regional: synchronous cross-region checks are too slow. Split quotas per region by traffic share and reconcile asynchronously.
9. Common mistakes
- Choosing a sliding log without computing its memory cost.
- Non-atomic read-then-write that over-admits under concurrency.
- Splitting the quota evenly across servers and assuming balanced traffic.
- Failing closed by default, so a Redis blip takes down the game.
- Forgetting
Retry-After, which leads to synchronized retry storms. - Ignoring hot keys and config distribution.