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

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

TL;DR30-second simplified summary
▾

Core Mechanics & Why Single-Node ZSETs Hit a Wall: A single Redis ZSET holding 100M players consumes 12–16 GB of RAM and saturates Redis's single-threaded event loop at ~100k ZADD/sec—dropping 50% of writes during 200k/sec tournament peaks. Relational SQL ORDER BY queries degrade even faster into O(N log N) sorts.

K-Sharded ZSETs + Min-Heap Merge: Partitioning by userId % K (e.g., K = 16 shards) spreads writes uniformly to 12,500 ZADD/sec and ~6.25M entries per shard. To serve getTopK(T = 100), a coordinator runs parallel ZREVRANGE 0 99 calls across all K shards and merges the K sorted lists with a T-element Min-Heap in O(K * T log K) time, fronted by a 500 ms read-through cache.

O(1) Rank Queries via Score-Range Histograms: Because sharding by userId splits scores across all K nodes, ZREVRANK on one shard no longer gives global rank. Maintaining a Score-Range Histogram (atomic bucket counters per score band plus a prefix-sum array) computes global rank in O(1) time without scanning all K shards.

From patterns to decisions.

Sustain 200,000+ score updates/sec and sub-15ms p99 Top-K and rank queries across 100M+ active players without single-node RAM or CPU saturation.

Full walkthrough · 7 stages
01
Stage 1 · Foundationfoundation

Single-Node Bottlenecks: SQL Sorts & Single-Thread Redis ZSETs.

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.

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.

03
Stage 3 · Intermediateintermediate

Parallel Scatter-Gather + Min-Heap Top-K Merge.

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

def merge_top_k(shard_top_lists: list[list[tuple[int, str]]], t: int = 100) -> list[tuple[int, str]]:
    if t <= 0:
        return []
    merged = heapq.merge(*shard_top_lists, key=lambda item: -item[0])
    out: list[tuple[int, str]] = []
    for item in merged:
        out.append(item)
        if len(out) == t:
            break
    return out
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.

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. Summing counts of buckets strictly above the player's bucket gives an instant O(1) global rank!

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.

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.

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. If Shard 7 crashes and loses RAM, a warm replica promotes immediately or a recovery job streams Shard 7's Kafka/DB partition to rebuild the ZSET.

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.

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