When a single sorted set hits its single-core CPU ceiling and stalls on 14 GB memory snapshots, shard players by user ID across 16 instances, serve Top-100 from a 500 ms merged cache, and estimate tail ranks in O(1) from a score-range histogram instead of scanning all shards.
TL;DR30-second simplified summary▾
UserId % 16 sharding scales writes linearly, pipelined Kafka consumers ensure durability, and a 500ms singleflight cache shields shards from Top-100 read storms.
Why a Single 14 GB Redis ZSET Collapses at 200K Writes/Sec.
Why this matters: Derive the shard count K = 16 directly from Redis single-thread CPU ceilings, skip-list memory overhead, and OS fork() copy-on-write stalls.
Every ZADD into a Redis Sorted Set updates two structures in memory: a dict mapping userId -> score (~64 bytes) and a probabilistic skip list node with 1-32 forward pointers (~76 bytes). At ~140 bytes per player:
A single Redis process executes commands on one main thread. Even with fast NVMe and 10 Gbps NICs, a single Redis instance saturates around ~80,000–100,000 ZADDs/sec when skip-list depth is levels. At 200,000 writes/sec, commands queue up, p99 latency explodes past seconds, and OOM or dropped connections follow.
Even if Redis were multi-threaded, a 14 GB single-instance heap breaks on persistence and failover. When BGSAVE or AOF rewrite calls fork(), the Linux kernel copies the parent process's page table (~28 MB for 14 GB at 4 KB pages, or worse under Transparent Huge Pages). During 200K writes/sec, copy-on-write page faults duplicate dirty 4 KB/2 MB pages rapidly, doubling RAM usage and stalling the event loop.
Sizing for 50% safety margin (target and per shard) yields:
At (userId % 16), each shard holds 6.25M players (~875 MB RAM) and 12,500 writes/sec.
Breaking the 1-Core Redis Ceiling with K=16 Hash Sharding
Sharding 100M players across 16 Redis nodes drops per-shard load to 875 MB and 12.5K writes/sec.
| Choice | What it buys | What it costs |
|---|---|---|
| Single 14 GB Redis ZSET | O(log N) exact ZREVRANK in 1 call; zero scatter-gather. | Saturates 1 CPU core at ~90K ZADD/s; multi-second fork() stalls; 14 GB blast radius. |
| Score-Range Sharding | Top-K reads hit only the highest score shard. | Massive write skew on beginner score ranges; non-atomic cross-shard moves on score jumps. |
| K=16 Hash Sharding (userId % 16) | Uniform 12.5K ZADD/s & ~875 MB/shard; single-shard atomic ZADD. | Global Top-K requires merging K=16 shards (solved via 500 ms cache). |
Surviving Bursts: Kafka Partitioned WAL & Pipelined ZADD.
Why this matters: Explain why direct synchronous API-to-Redis writes drop updates during failovers and how userId-partitioned Kafka + pipelining protects ordering.
If the Score API calls Redis ZADD synchronously inside the HTTP handler, two things break under load: (1) 200,000 individual TCP round-trips/sec burn huge kernel epoll/syscall overhead; (2) a 3-second Redis primary failover drops or times out 600,000 score updates.
Instead, POST /v1/scores validates the payload, publishes an event (userId, absoluteScore, ts, matchId) to a Kafka topic partitioned by userId (32+ partitions), and returns 202 Accepted in <3 ms. Partitioning by userId guarantees all updates for a given player arrive in strict causal order.
Consumer workers pull batches of 100–250 events and flush them to each Redis shard using Redis pipelining—cutting network round-trips by 100x while keeping per-batch latency under 5 ms.
Why Kafka WAL + Pipelined Idempotent ZADD Survives Failovers
Partitioning Kafka by userId preserves per-player order while pipelined ZADD GT makes consumer replays idempotent.
Interactive Visual Simulation
Score Update Pipeline & Failover Replay
Game Server
Score Emitter
Kafka Partition 7
Ordered WAL
Pipeline Worker
Batch 100 ZADD
Redis Shard 7
875 MB ZSET
user
u42
score
9850
kafka_offset
41020
- Problem
- How to implement Design a 100M-Player Distributed Leaderboard at 200K Writes/Sec without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When a single sorted set hits its single-core CPU ceiling and stalls on 14 GB memory snapshots, shard players by user ID across 16 instances, serve Top-100 from a 500 ms merged cache, and estimate tail ranks in O(1) from a score-range histogram instead of scanning all shards.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Design a 100M-Player Distributed Leaderboard at 200K Writes/Sec experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Scatter-Gather Top-100 via Min-Heap + 500 ms Singleflight Cache.
Why this matters: Prevent 100K read RPS from hitting all 16 Redis shards by merging Top-100 in a K-way Min-Heap behind a 500 ms cache.
If 100,000 players open the leaderboard tab simultaneously and each request fans out ZREVRANGE 0 99 to all 16 shards, Redis receives 1.6M range queries/sec and melts down.
Instead, a single background refresher (or Singleflight-guarded cache-aside) queries ZREVRANGE lb:shard_i 0 99 WITHSCORES across the 16 shards once every 500 ms (~50 KB total payload). A size-100 Min-Heap merges the 1,600 candidates in operations (<0.3 ms) and writes the serialized Top-100 JSON to a read cache/CDN.
100K RPS Served from 500 ms Cache via Background Min-Heap Merge
Decoupling 100K RPS client reads from a 500 ms background Min-Heap merge caps shard read overhead at 2 QPS/shard.
Exact Top-10K Snapshot vs. O(1) Score-Range Histogram for 99.99M Players.
Why this matters: Explain why global ZREVRANK cannot work across 16 shards and how a tiered Top-10K + Score Histogram serves all 100M players in O(1).
On a single Redis ZSET, ZREVRANK computes exact rank in . Across 16 shards, your local rank on Shard 3 tells you nothing about how many players on Shards 0–2 and 4–15 have a higher score—computing exact global rank for player #45,120,000 would require running ZCOUNT shard_i (score, +inf) on all 16 shards on every profile view!
Notice the product asymmetry: players in the Top 10,000 care deeply about exact #42 vs #43, while player #45,120,000 only needs an accurate percentile/bracket (~#45.1M).
- Tier 1 (Top 10,000): Background refresher merges
ZREVRANGE 0 9999across 16 shards every 2s into a fast lookup hash map (O(1)exact rank). - Tier 2 (Remaining 99.99M): Maintain a Score-Range Prefix Histogram (e.g., 10,000 fixed/log-width score buckets) updated asynchronously by Kafka consumers (
HINCRBY bucket_new +1,HINCRBY bucket_old -1). Global rank =sum(buckets > my_bucket) + linear_interpin O(1)!
Exact Top-10K Map + O(1) Score-Range Prefix Histogram
Tiering an exact Top-10K map with an O(1) Score-Range Prefix Histogram eliminates 16-shard ZCOUNT storms.
53-Bit IEEE-754 Composite Tie-Breaking & Server-Signed Score Guards.
Why this matters: Pack score + inverted timestamp cleanly inside Redis float64's 53-bit exact integer mantissa without silent rounding corruption.
Redis stores ZSET scores as IEEE-754 64-bit floating-point (double), which only represents integers exactly up to . Packing a 40-bit score + 32-bit timestamp (72 bits) silently drops low-order bits and breaks tie-breaking!
Fit the composite score strictly within 53 bits:
This gives 33 bits for score (up to $8.58 \times 10^9$) and 20 bits for inverted relative timestamp (~12 days at 1-second resolution, or ~17 minutes at 1-ms resolution within a match). Earlier achievers get a larger inverted timestamp and rank higher on ties!
Packing Score + Inverted Timestamp Inside IEEE-754 Exact Mantissa
Keeping composite scores within 53 bits preserves exact tie-breaking without floating-point rounding.
- Never exceed 2^53 - 1 (9.007e15) in Redis ZSET composite scores, or IEEE-754 rounding will corrupt tie-breaker bits.
- Never trust client-submitted absolute scores without server-signed match telemetry or delta-velocity checks.
Versioned Season Cutovers & Non-Blocking Redis UNLINK.
Why this matters: Prevent multi-second midnight Redis freezes during season resets by switching versioned keys and freeing old ZSETs asynchronously.
Calling Redis DEL lb:shard_0 on a 6.25M-entry ZSET frees 6.25 million heap nodes synchronously on the single main thread—freezing the entire Redis shard for 2–4 seconds right at midnight UTC!
Namespace every ZSET by season ID (lb:s42:shard_0..15, lb:s43:shard_0..15). Pre-warm empty s43 keys and histogram buckets 5 minutes before midnight. At 00:00:00 UTC, flip the active season pointer atomically in config/API.
Zero-Downtime Season Switch with Async UNLINK Reclamation
Versioned season namespaces and background UNLINK eliminate midnight reset stalls.
10 ms Shard Timeouts, Replica Isolation & Stale-While-Revalidate.
Why this matters: Keep Top-100 p99 under 20 ms even when a Redis shard fails over or a consumer lags.
In a 16-shard scatter-gather, tail latency is governed by the slowest of the 16 shards. If Shard 7 stalls for 3 seconds during a Sentinel/Cluster primary promotion, synchronous retries would stall 100% of Top-100 refreshes.
Route read-heavy ZREVRANGE refreshes to per-shard read replicas, enforce a strict 10 ms per-shard timeout, and on any shard timeout serve the last good cached Top-100 (Stale-While-Revalidate) while incrementing leaderboard_stale_serve_total.
Replica Reads + 10 ms Timeout + SWR Fallback During Shard 7 Failover
Per-shard 10 ms timeouts and SWR caching shield readers while Kafka replays missed writes onto promoted replicas.
Pause & reason: where would you draw the boundary?▼
- Why does a 10 ms per-shard timeout + Stale-While-Revalidate outperform synchronous retries on a 16-shard scatter-gather?
- How would your histogram update logic handle a player whose score decreases (if penalties exist) vs. monotonically increasing scores?
Practice: Make the trade-off yourself.
At 100M players (~14 GB total ZSET RAM) and 200k ZADD/sec, why is K = 16 sharding (`userId % 16`) effective?