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

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).
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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).

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Full walkthrough · 7 stages
01
Stage 1 · Foundationfoundation

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.

Naive Baseline

Single-Thread Redis Saturation at 200K ZADD/s

200K ZADD/s (100MUsers)source1 Redis ZSETwarning100K/s CeilingsinkStoreEvent loop saturated

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.

02
Stage 2 · Foundationfoundation

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.

Write Partitioning

Uniform userId % 16 Sharding Across 16 ZSETs

200K ZADD/ssourceshard = userId % 16process16 Redis ZSETShardsstoreStoreO(log(N/K)) ZADD

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.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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?

03
Stage 3 · Intermediateintermediate

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 heapq
Top-K Read Path

Parallel ZREVRANGE + K-Way Min-Heap Merge

16 Shards (LocalTop-100)sourceMin-Heap Mergeprocess500 ms Global CachestoreStoreTop-100 (<15ms p99)

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.

04
Stage 4 · Intermediateintermediate

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.

Rank Read Path

Score-Range Histogram + Prefix Sum Array

Score Delta EventsourceHistogram Buckets BprocessPrefix Sum LookupstoreStoreRefresh every 1s

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.

05
Stage 5 · Intermediateintermediate

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.

Tie-Breaking

Packing Score + Timestamp Within 53-Bit Float Precision

Integer Score (32bits)sourceInverted Delta TS(20 bits)process52-Bit CompositeDoublestoreStoreLower 20 bits

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.

06
Stage 6 · Advancedadvanced

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.

Durability

Kafka / DB Source of Truth + Redis Serving Shards

Kafka Score TopicsourceRedis ZSET ShardsprocessPartition ReplaystoreStoreOn total shard loss

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.

07
Stage 7 · Advancedadvanced

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.

SRE Operations

Versioned Season Keys & Stale-While-Revalidate

lb:s42:shard_isource10ms Shard TimeoutprocessUNLINK Old SeasonstoreStoreRetire s41 cleanly

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

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why should a 100M-player distributed leaderboard shard Redis ZSETs by `userId % K` rather than by score range?

Recommended Learning Flow