Sharded Counters & Real-Time Leaderboards at Scale
Counting and ranking seem deceptively simple until they collide with extreme write concurrency. A viral tweet receiving 500,000 likes per second, an e-commerce flash sale tracking inventory, or a global gaming leaderboard ranking 100 million players cannot rely on naive SQL transactions or single-key Redis increments.
High-throughput systems scale counting and ranking through Sharded Counters, CRDT Convergent Counters, Probabilistic Data Structures (HyperLogLog, Count-Min Sketch), and Redis Sorted Set (ZSET) Skip Lists.
1. Why Single-Key Counters Melt Under Load
In relational databases and key-value caches, incrementing a counter is a read-modify-write operation:
-- PostgreSQL / MySQL:
UPDATE post_metrics SET like_count = like_count + 1 WHERE post_id = 99824;
-- Redis:
INCR post:99824:likes
The Two Bottlenecks:
-
Relational Row-Lock Contention: In PostgreSQL or MySQL (InnoDB), updating a row acquires an Exclusive (X) Row Lock. When 10,000 requests arrive concurrently for the same viral post, 9,999 transactions block waiting in a lock queue. Connection pools exhaust within milliseconds, database CPU spikes to 100% due to thread context-switching, and queries fail with
Lock wait timeout exceeded. -
Redis Single-Threaded Core Saturation: While Redis executes in-memory with non-blocking I/O, a single Redis master core executes commands sequentially. A single CPU core caps out at approximately 100,000 to 120,000 commands per second. A viral event exceeding 200,000 operations/second completely saturates the core, causing request buffering and cascading gateway timeouts.
2. Sharded Counters Architecture
The standard engineering solution for hot-key write contention is Counter Sharding: dividing a single logical counter into distinct physical sub-keys.
Incoming Writes (500k/s) βββΊ rand(0, 3) βββ¬βββΊ Shard 0: INCR post:99:like:0
ββββΊ Shard 1: INCR post:99:like:1
ββββΊ Shard 2: INCR post:99:like:2
ββββΊ Shard 3: INCR post:99:like:3
Write Path: Random Scatter
When a user likes a post:
- The client or API server selects a random shard index:
- The increment is routed to that sub-key:
INCR post:99:like:2
- Throughput Multiplier: Write throughput scales linearly with . If 1 shard handles 100,000 writes/sec, 10 shards across a Redis cluster handle 1,000,000 writes/sec with zero lock contention!
Read Path: Scatter-Gather & Rollup Caching
To read the total count:
- Low-Latency / Exact: Issue a multi-key fetch in a single network round-trip:
Sum the integers in memory on the API gateway ( operations).MGET post:99:like:0 post:99:like:1 post:99:like:2 post:99:like:3
- Hyperscale / Eventual Consistency: For high-read workloads (millions of users viewing a tweet), reading and summing 20 shards on every HTTP request wastes CPU. A lightweight background worker aggregates the shards every 1 to 3 seconds into a cached
total_likeskey.
3. CRDT Counters: G-Counters & PN-Counters
In multi-region active-active architectures (e.g. AWS US-East and EU-West), sharded keys cannot synchronize synchronously over transatlantic networks without latency penalties. We use Conflict-Free Replicated Data Type (CRDT) counters.
1. Grow-Only Counter (G-Counter)
A G-Counter only supports increments. It is modeled as a vector of integers of size , where is the number of participating datacenter nodes:
- Node only increments its own slot .
- Value: The total counter value is the sum of all elements:
- Merge: Replicas exchange vectors asynchronously. The merge function computes the element-wise maximum (forming a join-semilattice):
2. Positive-Negative Counter (PN-Counter)
To support both increments (likes) and decrements (unlikes), a PN-Counter pairs two G-Counters: (tracks increments) and (tracks decrements):
- Increment: Increments local node slot in .
- Decrement: Increments local node slot in .
- Both and grow monotonically, preserving commutativity and associativity across multi-region datacenters without locks!
4. Probabilistic Counting Primitives
When exact counts are not required (e.g. estimating unique visitor counts or detecting trending hashtags), storing exact IDs in sets wastes gigabytes of memory.
PROBABILISTIC DATA STRUCTURES
β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ
βΌ βΌ
HYPERLOGLOG (HLL) COUNT-MIN SKETCH (CMS)
β’ Unique Cardinality (Distinct Count) β’ Frequency Estimation (Item Counts)
β’ O(log log N) space (~12 KB memory) β’ Fixed 2D hash matrix
β’ Standard error β€ 0.81% β’ Ideal for Top-K trending & DDoS detection
β’ Redis: PFADD / PFCOUNT β’ Redis: CMS.INCRBY / CMS.QUERY
1. HyperLogLog (HLL)
- Problem: Counting distinct visitors (DAU) across 100 million users using a standard Redis
SETrequires storing 100M user IDs ( of RAM). - HLL Magic: HyperLogLog estimates the number of leading zeros in hashed bit patterns across 16,384 internal registers ().
- The Memory Feat: Counts from 1 up to unique items using a fixed 12 KB of RAM, with a bounded statistical error rate of 0.81%.
- Redis Commands:
PFADD daily_active_users:2026-05-01 "user_892" "user_104"PFCOUNT daily_active_users:2026-05-01
2. Count-Min Sketch (CMS)
- Problem: Determining which songs or hashtags are trending in real-time streams without storing billions of event strings.
- CMS Mechanism: A 2D array of columns and rows with independent hash functions. An item is hashed and its corresponding cells incremented. The estimated frequency is the minimum value across the hashed cells:
- Guaranteed never to underestimate; overestimation is bounded by matrix width and depth .
5. Real-Time Leaderboards on Redis Sorted Sets (ZSET)
Building a gaming or competitive leaderboard with millions of players requires three capabilities:
- Update player score in real-time ()
- Retrieve a player's exact rank ()
- Fetch the top 100 players or friends around a player ()
Relational databases fail because computing rank requires SELECT COUNT(*) FROM scores WHERE score > my_score, which degrades into a full table scan under continuous writes.
Redis ZSET Dual Architecture
Redis implements Sorted Sets using two coordinated data structures pointing to the same elements:
REDIS ZSET INTERNALS
β
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββ
βΌ βΌ
HASH TABLE SKIP LIST
β’ Maps: member β score β’ Multi-level linked list
β’ Provides O(1) score lookup (ZSCORE) β’ Keeps members ordered by score
β’ O(1) existence checks β’ Provides O(log N) rank & range
The Skip List Mechanism:β
A Skip List is a probabilistic alternative to balanced trees (AVL/Red-Black). Nodes have random geometric heights (promoted with probability ). Forward pointers allow the search traversal to skip over hundreds of nodes in time, avoiding complex tree rebalancing rotations during concurrent score updates.
6. Leaderboard Engineering Nuances
Nuance 1: Tie-Breaking via Timestamp Bit-Packing
If Player A and Player B both achieve 1,000 points, Player A who reached the score first should rank higher. By default, Redis ZSET breaks score ties lexicographically by username string!
The Solution: Decimal Timestamp Packingβ
Encode the inverted timestamp into the fractional component of the 64-bit IEEE double score:
- Player A scores 1,000 at :
- Player B scores 1,000 at (500 seconds later):
- : Player A deterministically ranks ahead without custom tie-break queries!
Nuance 2: Scaling Beyond a Single Redis Instance
A single Redis ZSET can hold millions of members, but memory capacity and network egress limit throughput.
For massive leaderboards (100 million players):
- Score-Range Partitioning:
Partition across multiple Redis instances based on score tiers:
- Node 1: Scores 0 β 999 (Long tail)
- Node 2: Scores 1,000 β 4,999 (Intermediate)
- Node 3: Scores 5,000+ (Elite / Top Tier)
- Approximate Ranking for the Long Tail:
At scale, players only care about their exact rank if they are in the Top 1,000. For a player ranked #4,582,104, displaying
"Rank: Top 5%"using bucketed histogram counters saves massive cluster coordination overhead.
7. Senior Interview Scenarios
Q1: How do you determine the optimal number of shards for a sharded counter?
Answer: Sizing is a balance between write capacity and read latency: If peak writes are 300,000 QPS and a single Redis instance safely handles 75,000 QPS, shards. Avoid over-sharding: setting when suffices increases
MGETpacket size and CPU scatter-gather overhead for read requests.
Q2: Why is a Skip List preferred over a B-Tree or Red-Black Tree in Redis ZSET?
Answer:
- Memory Efficiency: Skip lists consume less pointer overhead per node on average than balanced binary search trees.
- Simpler Range Queries: The bottom level of a skip list is a continuous sorted singly-linked list, allowing range streaming (
ZREVRANGE) once the start node is located in .- Concurrency & Lock-Free Simplicity: Balancing trees (AVL / Red-Black) requires complex rotational cascade rebalancing that can touch nodes near the root. Skip list insertions only modify local forward pointers of adjacent nodes, making future concurrent or partitioned implementations significantly simpler.
8. Advanced Deep Dives: Adaptive Sharding, Write-Behind Batching & ZSET Span Internals
References: Sujeet Pro β Sharded Counters | Sujeet Pro β Leaderboard Design
1. Why Single-Row SQL Updates Cap at ~1kβ5k Writes/Sec (Physical Engine Truth)
When executing UPDATE counters SET count = count + 1 WHERE counter_id = 'post_99' in PostgreSQL or MySQL:
- Row-Level Exclusive Lock Serialization (
X-Lock): Even if the server has 64 CPU cores, all concurrent transactions targeting'post_99'must serialize sequentially behind a single row lock. If a transaction takes0.2msβ1ms(including network round-trip and WALfsyncgroup commit), the physical ceiling for a single row is . - PostgreSQL MVCC Tuple Bloat: In PostgreSQL, every
UPDATEwrites a brand-new row version (dead tuple) on the heap page. Updating a single row 5,000 times per second generates 300,000 dead tuples per minute, causing severe B+Tree and heap bloat beforeautovacuumcan reclaim space.
2. Adaptive Dynamic Shard Splitting & Write-Behind Delta Aggregation
Static sharding (e.g., allocating shards for every post in the database) wastes the metadata rows when 99% of posts receive fewer than 10 likes. Production systems combine Adaptive Dynamic Shard Splitting with In-Memory Write-Behind Batching:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ADAPTIVE SHARD SPLITTING + WRITE-BEHIND DELTA AGGREGATION β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. Cold/Normal Key (QPS < 100/s): β
β β’ Uses N = 1 shard (counter_id:shard_0) β
β β
β 2. Hot-Key Detection (Sliding-Window Count-Min Sketch / Local Rate Tracker): β
β β’ Detects QPS > 1,000/s on 'post_99' β
β β’ Dynamically expands shard metadata in ZooKeeper/Redis config: N = 1 β N = 32 β
β β’ Writers immediately scatter across post_99:shard_0 .. post_99:shard_31 β
β β
β 3. Two-Tier Write-Behind Aggregation (Coalescing 500k/s into 1 DB Write/s): β
β β’ Tier 1 (App Node Memory): JVM LongAdder (striped 64-bit cells) accumulates β
β deltas for 200ms β flushes single INCRBY +4820 to Redis β
β β’ Tier 2 (Redis to RDBMS/Cassandra): Background worker atomically reads & resets β
β delta (GETSET key 0 / Lua script) every 5s β single SQL UPDATE count = count + Ξ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Why LongAdder Inside the Application Node?β
Even in Java memory, a single AtomicLong.incrementAndGet() suffers from CPU L1/L3 cache-line bouncing (MESI protocol invalidations) when 64 threads execute LOCK CMPXCHG on the same memory address. Java's LongAdder automatically stripes contention across an internal Cell[] array (padded to avoid false sharing), summing them only when .sum() or .sumThenReset() is called every 200ms!
3. Under the Hood of Redis ZSET: How ZREVRANK Achieves via span Pointers
A standard Skip List only allows search by score; finding a node's ordinal rank (#1, #4,592) would normally require walking the bottom linked list in time! How does Redis compute ZANK / ZREVRANK in ?
Level 3: [HEAD] βββββββββββββββ (span: 5) ββββββββββββββββΊ [Node E: 950] ββ (span: 2) βββΊ NULL
Level 2: [HEAD] ββ (span: 2) βββΊ [Node B: 400] β(span: 3)ββΊ [Node E: 950] ββ (span: 2) βββΊ NULL
Level 1: [HEAD] βββΊ [A: 100] βββΊ [B: 400] βββΊ [C: 600] βββΊ [D: 800] βββΊ [E: 950] βββΊ [F: 990]
Rank: 0 1 2 3 4 5 6
- The
zskiplistLevel.spanField: In Redis (server.h), every forward pointer at level of a skip list node stores an unsigned integerspanβthe exact number of level-1 nodes skipped over by that pointer. - Computing
ZRANKin : As Redis traverses from the top level down toward the target member, it simply adds thespanvalues of every forward pointer it traverses. By the time it lands on[Node E: 950]in hops, the accumulated sum of spans (2 + 3 = 5, or5directly at Level 3) equals the exact 0-based rank! - Precision Caveat with 64-Bit IEEE-754 Double Tie-Breaking:
In Redis,
ZSETscores are 64-bit IEEE-754 floating-point numbers, which have 53 bits of mantissa precision (exact integers up to ).- If you bit-pack a 32-bit Unix timestamp () into the lower bits or fractional decimal of the score, you have
53 - 32 = 21 bits() of exact integer score headroom before floating-point rounding causes two different timestamps to collide! - When Primary Scores Exceed : Either store the inverted timestamp in the member string (
score = 1000,member = "inv_ts:8299999500:user_42") to leverage Redis's native lexicographical tie-breaking on identical scores, or use a custom 64-bit integer skiplist service.
- If you bit-pack a 32-bit Unix timestamp () into the lower bits or fractional decimal of the score, you have
4. Scaling Leaderboards Past 100M+ Users: Scatter-Gather vs. Score-Range Sharding
When a leaderboard outgrows a single Redis instance's RAM (e.g., 250M users 100 bytes plus replication buffer) or write throughput (>100k ZINCRBY/sec), there are two primary sharding architectures:
| Sharding Strategy | How ZINCRBY (Write) Works | How ZREVRANGE 0 99 (Top 100) Works | How ZREVRANK user_x (Exact Rank) Works | Best Use Case |
|---|---|---|---|---|
1. Hash Partitioning by user_id ( Shards) | on 1 shard: Route directly to Shard[hash(user_id) % K]. | Scatter-Gather: Fetch Top 100 from all shards and merge-sort in memory on the API gateway (). | Expensive Scatter-Gather: First lookup user_x score on its home shard, then query ZCOUNT shard_i (score +inf across all shards and sum! | High write throughput where Top-K is cached and exact global rank is rarely queried. |
| 2. Score-Range (Tier) Partitioning + Histogram Approximation | Check user's old score bucket; if new score crosses bucket boundary (e.g. 990 -> 1010), move from Bucket_[0..999] to Bucket_[1000..4999] and update bucket total count. | on 1 shard: Top 100 always lives exclusively in the highest score-tier ZSET shard! | Instant (): Sum total counts of all higher score buckets + ZREVRANK within the user's current score bucket! | Massive global gaming leaderboards (100M+ users) requiring both fast Top-K and fast global rank. |
Senior/Staff Interview Playbook: How to Ace Sharded Counters & Leaderboard Interviews
1. The Senior Framing Strategy (First 60 Seconds)
When asked to "Design a Real-Time Like Counter for Viral Posts" or "Design a Global Gaming Leaderboard for 100M Players", immediately establish four physical invariants:
- Identify the Contention Boundary (Single-Key Serialization):
- A single SQL row (
UPDATE ... SET count = count + 1) caps at ~1kβ5k writes/sec due to row-lock queuing and WALfsync. A single Redis key (INCR/ZINCRBY) caps at ~100k ops/sec due to single-threaded event-loop serialization. Any design exceeding these numbers must distribute writes across shards or batch deltas in memory.
- A single SQL row (
- Consistency vs. Latency Trade-Off (PACELC):
- Ask upfront whether the counter requires Strict Linearizability (e.g., flash-sale inventory where overselling is forbiddenβrequiring atomic Lua scripts or partitioned reservation tokens) or Eventual / Monotonic Read Consistency (e.g., video views or tweet likesβwhere 1β3 seconds of write-behind batching and CRDT convergence is ideal).
- Exact vs. Probabilistic Cardinality:
- Distinguish between counting events (
INCRBY/ Sharded Counters) and counting unique entities (DAU, unique video viewers). If a user can view a video 50 times but only counts as 1 unique viewer, simple sharded counters failβyou need HyperLogLog (PFADD, 12 KB per key, 0.81% error) paired with a deduplication Bloom Filter or Kafka stream processor.
- Distinguish between counting events (
- Data Structure Mechanical Sympathy:
- Explain why Redis
ZSETachieves for both range queries and rank lookups (HashMapfor member-to-score lookup + Skip List with levelspancounters for rank summation).
- Explain why Redis
2. Classic Interviewer Traps & Principal Rebuttals
Trap 1: "To prevent a user from liking a post twice, we just increment our sharded counter when they click Like. What if their network retries the POST request?"β
- Junior/Mid Answer: "We can check
SELECT 1 FROM likes WHERE user_id = ? AND post_id = ?before incrementing the sharded counter." - Principal Rebuttal: "A non-atomic check-then-increment (
SELECTthenINCR) suffers from a classic Time-of-Check to Time-of-Use (TOCTOU) race condition under concurrent retries, resulting in double-counts. Worse, sharded counters (INCR post:99:shard_3) are non-idempotent by themselves. To guarantee idempotent counting:- Write the deduplication record
(post_id, user_id)to a partitioned primary store (e.g., Cassandra/DynamoDB or sharded PostgreSQL withINSERT ... ON CONFLICT DO NOTHING). - Only if the insert returns
inserted = true(or via a Change Data Capture (CDC) / Kafka stream off the likes table) do we increment the sharded counter or localLongAdderwrite-behind buffer."
- Write the deduplication record
Trap 2: "We packed score + (1 - timestamp / 10^10) into a Redis ZSET float score so earlier players win ties. In our game, players can earn up to 100,000,000 points. Does your tie-breaker work?"β
- Junior/Mid Answer: "Yes, Redis scores are 64-bit doubles (
double), which can store huge numbers up to , so100,000,000.8300000000fits easily." - Principal Rebuttal: "While a 64-bit IEEE-754
doublehas a massive exponent range (), it only has 53 bits of mantissa (significand) precisionβwhich translates to 15 to 17 significant decimal digits total!- If the integer part of the score is
100,000,000(, ), and the Unix timestamp in seconds/milliseconds needs (), ! - The lowest bits of the timestamp are silently truncated by IEEE-754 floating-point rounding, destroying tie-breaker determinism!
The Principal Fix: Keep the Redis ZSET
scoreas the pure integer score (which is exact up to ), or pack into a 64-bit integer where30 bits= score (up to 1B) and34 bits= epoch seconds delta; alternatively, leverage Redis ZSET's native lexicographical member tie-breaking by prefixing the member key with the zero-padded inverted timestamp."
- If the integer part of the score is
Trap 3: "How does ZREVRANK find that a player is ranked #842,109 out of 10,000,000 players in 0.1 milliseconds without counting 842,109 nodes?"β
- Junior/Mid Answer: "Redis uses a Skip List, so it binary-searches the list in time to find the player's node."
- Principal Rebuttal: "Finding the node in a standard Skip List or B-Tree takes , but knowing which node you landed on doesn't tell you how many nodes precede it unless the structure is an Order-Statistic Tree / Augmented Skip List! Redis augments every forward pointer at every level of the Skip List with a
spancounter recording how many bottom-level nodes that pointer jumps over. During the top-down search path (~20 pointer hops for 10M items), Redis sums thespanof every traversed edge to compute the exact rank#842,109in ~20 integer additions."
Trap 4: "We need to display exact unique view counts on 50 million YouTube videos. Should we use HyperLogLog for every video?"β
- Junior/Mid Answer: "Yes! HyperLogLog uses only 12 KB per video regardless of how many millions of views it gets."
- Principal Rebuttal: "Multiply
12 KB Γ 50,000,000 videosβthat's 600 GB of RAM even if 95% of those videos only have 5 views! A naive dense HLL allocation wastes massive memory on the long tail. Redis solves this internally via Hybrid Sparse-to-Dense HLL Encoding (and we should mirror this in system design):- For low-cardinality keys (
< ~3,000unique viewers), use an exact or sparse run-length encoded representation (hl_sparse_max_bytes, taking only100β500 bytes). - Automatically promote the key to a dense
12 KB16,384-register HLL only when cardinality crosses the threshold."
- For low-cardinality keys (
3. Quick Reference β Mid-Level vs. Principal Candidate Cheat Sheet
| Concept / Scenario | Mid-Level Candidate Says | Principal Candidate Demonstrates |
|---|---|---|
| Hot-Key Counter Writes | "Use UPDATE counters SET v = v + 1 or a single Redis INCR key." | "Use Adaptive Dynamic Sharded Counters (shard_0..N-1) + in-memory LongAdder write-behind batching to coalesce 500k/s increments into periodic delta flushes." |
| Multi-Region Counting | "Replicate increments across regions with last-write-wins (LWW)." | "LWW drops concurrent increments! Use State-based CRDT PN-Counters ( and per-datacenter vectors merged via element-wise max())." |
| Unique Visitor Counting | "Store user_id in a Redis SET and call SCARD." | "Use HyperLogLog (PFADD/PFCOUNT) with sparse-to-dense representation (12 KB max, 0.81% standard error) + PFMERGE for daily-to-monthly rollups." |
| ZSET Rank Internals | "Redis ZSET uses a Skip List to find rank in ." | "Redis ZSET pairs a Hash Table ( ZSCORE) with an Augmented Skip List carrying span counts on forward pointers to accumulate rank in ." |
| 100M+ User Leaderboard | "Put all 100M users in one Redis ZSET and pack timestamp into a float." | "Guard against IEEE-754 53-bit mantissa truncation; scale past 1 node via Score-Tier Range Partitioning (exact ZSET for Top Tiers + bucketed histograms for the long tail)." |
