Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a 100M-Player Distributed
Leaderboard at 200K Writes/Sec.

A single Redis ZSET holding 100M players consumes ~14 GB RAM and saturates one CPU core at ~80K ops/s, causing multi-second RDB fork pauses and dropped score updates. Sharding by userId % 16, buffering writes through a userId-partitioned Kafka WAL, caching a 16-shard Min-Heap Top-100 for 500 ms, and serving tail ranks from a Score-Range Prefix Histogram holds getTopK(100) and getPlayerRank(userId) under 20 ms p99.
Start the journey7 stages· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Sharded ZSETs & Score-Range Histogram Ranking
Partitioning players across K Redis ZSET shards by userId % K scales write throughput linearly, while a Min-Heap merges global Top-K slices in O(K * T log K) and Score-Range Histograms answer getRank(userId) in O(1).
Skip Lists & Probabilistic Multi-Level Indexing
A skip list layers probabilistic express lanes on top of a sorted linked list so searches, insertions, and range scans run in O(log N) expected time without global tree rebalancing.
Full walkthrough · 7 stages
01
STAGE 01 · HARDWARE & MEMORY LIMITSfoundation

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:

Total RAM=100×106×140 B≈14 GB\text{Total RAM} = 100\times 10^6 \times 140\text{ B} \approx 14\text{ GB}

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 log⁡2(108)≈27\log_2(10^8) \approx 27 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 ≤15K writes/sec\le 15\text{K writes/sec} and ≤1.5 GB\le 1.5\text{ GB} per shard) yields:

K=max⁡(⌈200K/15K⌉,⌈14 GB/1.5 GB⌉)=16 shardsK = \max\left(\lceil 200\text{K} / 15\text{K} \rceil, \lceil 14\text{ GB} / 1.5\text{ GB} \rceil\right) = 16\text{ shards}

At K=16K=16 (userId % 16), each shard holds 6.25M players (~875 MB RAM) and 12,500 writes/sec.

STAGE 01 · CAPACITY SCALING

Breaking the 1-Core Redis Ceiling with K=16 Hash Sharding

Single ZSET
100M Entries / 1 Core
14 GB RAM · 200K/s Overloaded
Partition Key
shard = hash(userId) % 16
Uniform Distribution · Zero Moves
16 Redis Shards
6.25M Players / Shard
875 MB RAM · 12.5K ZADD/s

Sharding 100M players across 16 Redis nodes drops per-shard load to 875 MB and 12.5K writes/sec.

ChoiceWhat it buysWhat it costs
Single 14 GB Redis ZSETO(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 ShardingTop-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).
02
STAGE 02 · INGESTION & PIPELININGfoundation

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.

STAGE 02 · ORDERED WRITE PIPELINE

Why Kafka WAL + Pipelined Idempotent ZADD Survives Failovers

Score APIKafka (userId Part)Batch ConsumerRedis Shard i1. Publish (userId, absScore, ts)2. Ordered batch (100 events)3. Pipeline 100x ZADD GT4. ACK -> Commit Kafka Offset

Partitioning Kafka by userId preserves per-player order while pipelined ZADD GT makes consumer replays idempotent.

Interactive Visual Simulation

Score Update Pipeline & Failover Replay

client

Game Server

Score Emitter

1. Produce (key=u42)
kafka

Kafka Partition 7

Ordered WAL

2. Poll batch
worker

Pipeline Worker

Batch 100 ZADD

3. Pipeline ZADD GT
redis

Redis Shard 7

875 MB ZSET

user

u42

score

9850

kafka_offset

41020

Ingest Score EventHealthy
Score API appends u42=9850 to Kafka Partition 7 and ACKs the game server in 2 ms without waiting on Redis.
Engineering Decision Framework
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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · GLOBAL TOP-K MERGEintermediate

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 O(16×100log⁡100)≈10,000O(16 \times 100 \log 100) \approx 10,000 operations (<0.3 ms) and writes the serialized Top-100 JSON to a read cache/CDN.

STAGE 03 · READ FAN-OUT SHIELD

100K RPS Served from 500 ms Cache via Background Min-Heap Merge

100K Read RPSLeaderboard Tab500 ms Edge/RedisCacheServes <2ms HitsSingleflightRefresher1x / 500ms Cron16x Redis ZREVRANGE0 991,600 CandidatesGET /top100 (<2ms)Every 500msWrite Min-Heap Top-100

Decoupling 100K RPS client reads from a 500 ms background Min-Heap merge caps shard read overhead at 2 QPS/shard.

04
STAGE 04 · O(1) GLOBAL RANKINGintermediate

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 O(log⁡N)O(\log N). 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 9999 across 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_interp in O(1)!
STAGE 04 · TIERED RANK LOOKUP

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.

05
STAGE 05 · PRECISION & ANTI-CHEATadvanced

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 253−1=9,007,199,254,740,9912^{53} - 1 = 9,007,199,254,740,991. 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:

composite=(score≪20)∣((MAX_TS−ts)  &  0xFFFFF)\text{composite} = (\text{score} \ll 20) \mid ((\text{MAX\_TS} - \text{ts}) \;\&\; \text{0xFFFFF})

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!

STAGE 05 · 53-BIT COMPOSITE LAYOUT

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.
06
STAGE 06 · ZERO-DOWNTIME RESETSadvanced

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.

STAGE 06 · SEASON CUTOVER LIFECYCLE

Zero-Downtime Season Switch with Async UNLINK Reclamation

23:55 UTC00:00 UTCAfter S3 archiveSeason s42 Activelb:s42:shard_0..15Pre-Warm s43T-5m Empty BucketsAtomic Flip -> s4300:00:00 UTC CutoverReplica Archive +UNLINKO(1) Async Free

Versioned season namespaces and background UNLINK eliminate midnight reset stalls.

07
STAGE 07 · FAILOVER & DEGRADATIONadvanced

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.

STAGE 07 · FAILOVER ISOLATION

Replica Reads + 10 ms Timeout + SWR Fallback During Shard 7 Failover

Shards 0..6, 8..15Replica ZREVRANGE <3msShard 7 PrimaryFailover (Timeout 10ms)SWR Top-100 CacheServe Last Good (<2ms)

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

At 100M players (~14 GB total ZSET RAM) and 200k ZADD/sec, why is K = 16 sharding (`userId % 16`) effective?

Recommended Learning Flow