When traffic spikes expose hidden coupling, never funnel 100M-player writes into a single Redis ZSET; shard by userId % K for uniform write scaling and decouple global Top-K and rank reads.
TL;DR30-second simplified summary▾
Sharding by userId % 16 balances 200k ZADD/sec across 16 nodes; parallel ZREVRANGE + Min-Heap serves Top-100 in <15 ms p99, while score-bucket prefix sums answer arbitrary player ranks in O(1).
Single-Node Bottlenecks: SQL Sorts & Single-Thread Redis ZSETs.
Why this matters: Quantify why 100M entries and 200k ZADD/sec overwhelm both relational indexes and a single Redis instance.
Think of Single-Node Bottlenecks: SQL Sorts & Single-Thread Redis ZSETs as the intuition layer for Sharded ZSETs & Score-Range Histogram Ranking: Quantify why 100M entries and 200k ZADD/sec overwhelm both relational indexes and a single Redis instance.
In PostgreSQL, SELECT COUNT(*) + 1 FROM leaderboard WHERE score > ? triggers an O(N) index scan at 100M rows. Moving to a single Redis ZSET (skip list + hash table) speeds up individual ops to O(log N), but 100M members burn ~12–16 GB RAM and Redis's single-threaded command loop caps out near ~100k ZADD/sec.
Single-Thread Redis Saturation at 200K ZADD/s
1.Memory Footprint: Each ZSET entry costs ~120–160 bytes (SDS key + dictEntry + zskiplistNode).
2.Why Not Shard by Score?: Range-sharding by score creates extreme hot-spots on the top-score shard.
Caption: Funneling 200k writes/sec into one Redis ZSET saturates its single-threaded event loop.
Hash Sharding by userId % K for Linear Write Scaling.
Why this matters: Distribute 100M players and 200k ZADD/sec evenly across K = 16 independent Redis shards.
Think of Hash Sharding by userId % K for Linear Write Scaling as the intuition layer for Sharded ZSETs & Score-Range Histogram Ranking: Distribute 100M players and 200k ZADD/sec evenly across K = 16 independent Redis shards.
Routing ZADD leaderboard:{userId % 16} score userId splits 100M users into 6.25M users/shard (~1 GB RAM/shard) and 12,500 writes/sec/shard (~12% of single-node capacity). Because userId is uniform, no single shard suffers hot-key skew even when top players battle for #1.
Uniform userId % 16 Sharding Across 16 ZSETs
1.Consistent Hashing: Use virtual-node consistent hashing or fixed logical buckets if K will resize later.
2.Read Trade-Off: Sharding by userId makes writes fast, but scatters global Top-K and global rank across all K shards.
Caption: Hash-partitioning by userId % K scales writes linearly across K shards without score hot-spots.
- Problem
- How to implement Sharded ZSETs & Score-Range Histogram Ranking 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 traffic spikes expose hidden coupling, never funnel 100M-player writes into a single Redis ZSET; shard by userId % K for uniform write scaling and decouple global Top-K and rank reads.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Sharded ZSETs & Score-Range Histogram Ranking experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Parallel Scatter-Gather + Min-Heap Top-K Merge.
Why this matters: Reconstruct the exact global Top-T (e.g., Top-100) across K shards in O(K * T log K) time.
Because the global Top-100 must be a subset of the union of each shard's local Top-100, the API queries ZREVRANGE 0 99 WITHSCORES on all 16 shards in parallel (~2–5 ms) and merges the 16 sorted lists using a k-way merge (heapq.merge).
import heapqParallel ZREVRANGE + K-Way Min-Heap Merge
1.500ms Cache Shield: Caching global Top-100 for 500ms cuts scatter-gather QPS from 100k/s to 2 QPS.
2.Exactness Guarantee: No player outside every shard's local Top-T can ever appear in the global Top-T.
Caption: Parallel scatter-gather with a k-way heap merge computes exact global Top-100 in under 15ms.
Score-Range Prefix Histograms for O(1) Global Rank.
Why this matters: Answer getRank(userId) in O(1) without running K-way ZCOUNT scatter-gathers on every request.
If a user is at rank #4,512,300, you cannot use Top-K merge.
Instead, maintain a Score-Range Histogram dividing the score space into B buckets (e.g., [0..999], [1000..1999], ..., or log-spaced buckets). When a player's score moves from bucket old_b to new_b, decrement old_b and increment new_b asynchronously.
Score-Range Histogram + Prefix Sum Array
1.Exact Inside Top-K: Top 10,000 players use exact ZSET merge; ranks 10k..100M use histogram prefix sums.
2.Adaptive Buckets: Use narrower buckets in dense score bands (e.g., 1,000–2,000 Elo) to keep error < 0.1%.
Caption: Score-range prefix histograms compute global rank for 100M players in O(1) time.
Tie-Breaking & Score Encoding in IEEE-754 Doubles.
Why this matters: Ensure deterministic ranking when two players share the same integer score without overflowing Redis's 53-bit mantissa.
Think of Tie-Breaking & Score Encoding in IEEE-754 Doubles as the intuition layer for Sharded ZSETs & Score-Range Histogram Ranking: Ensure deterministic ranking when two players share the same integer score without overflowing Redis's 53-bit mantissa.
Redis ZSET scores are IEEE-754 64-bit floats (53 bits of exact integer precision = 9e15). To break ties by earliest achievement time, pack (score << 20) | ((MAX_TS - relative_ts) & 0xFFFFF) as long as total bits stay <= 53, or store a secondary tie-break key.
Packing Score + Timestamp Within 53-Bit Float Precision
1.53-Bit Ceiling: Exceeding 2^53 causes silent rounding in Redis ZSETs, breaking tie-order.
2.Lexicographical Alternative: If scores exceed 32 bits, use ZADD with score=0 and lexicographical member strings.
Caption: Packing score and inverted timestamp within 53 bits gives deterministic tie-breaking in Redis ZSETs.
Durability: Write-Behind WAL & Cold-Start Rebuild.
Why this matters: Recover a lost Redis shard in seconds without losing player scores.
Redis is an in-memory serving layer.
Every score update is first appended to a durable Kafka topic / PostgreSQL ledger (partitioned by userId), and asynchronously applied to Redis.
Kafka / DB Source of Truth + Redis Serving Shards
1.Idempotent Updates: Prefer absolute ZADD score over ZINCRBY delta, or include monotonic event_id dedup.
2.Zero RDB Stalls: Offload persistence to Kafka/DB so Redis never forks huge 10 GB RDB snapshots on primary.
Caption: Backing Redis ZSET shards with a partitioned Kafka/DB log enables clean recovery without RDB fork stalls.
Tournament Reset, Hot-Shard Isolation & Partial Degradation.
Why this matters: Handle seasonal leaderboard resets and single-shard timeouts gracefully.
Think of Tournament Reset, Hot-Shard Isolation & Partial Degradation as the intuition layer for Sharded ZSETs & Score-Range Histogram Ranking: Handle seasonal leaderboard resets and single-shard timeouts gracefully.
Never run DEL on a 6M-entry ZSET synchronously (it blocks Redis for seconds); use UNLINK or dual-key season suffixes (lb:season_42:shard_0). During getTopK(100), set a 10 ms per-shard timeout—if 1 of 16 shards is slow, serve the cached Top-100 (stale-while-revalidate) rather than failing the whole API.
Versioned Season Keys & Stale-While-Revalidate
1.Non-Blocking UNLINK: DEL blocks Redis's single thread while freeing 6M nodes; UNLINK frees memory in a background bio thread.
2.Tail-Latency Shield: Stale-while-revalidate keeps p99 under 15ms even during a shard failover.
Caption: Versioned season keys, UNLINK cleanup, and stale-while-revalidate keep tail latency flat.
Practice: Make the trade-off yourself.
Why should a 100M-player distributed leaderboard shard Redis ZSETs by `userId % K` rather than by score range?