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

Design a Real-Time Concurrent Gaming Leaderboard
with Range & Rank Queries.

Pair an in-memory HashMap + span-indexed Skip List for O(log N) rank/neighbor queries with composite (score DESC, ts ASC) keys, shard/partition routing for >200K RPS, and async WAL/snapshot persistence.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, A HashMap gives O(1) current-score lookup while an indexed Skip List gives O(log N) exact rank and neighbor-window scans—and sharding by score-bucket or regional-tier scales beyond single-core limits.

TL;DR30-second simplified summary
▾

Each leaderboard shard combines a HashMap (player_id -> (score, ts)) and a span-indexed Skip List ordered by (-score, ts, player_id) for O(log⁡N)O(\log N) updates, exact ranks, and neighbor-window queries.

Score-range buckets scale writes beyond a single core while an async WAL + CoW snapshots provide <5s crash recovery, guarded by match-level idempotency keys and a DLQ.

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.
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Full walkthrough · 7 stages
01
STAGE 01 · REQUIREMENTS & TIE-BREAKINGfoundation

Scale Math & Deterministic Composite Sort Keys.

Why this matters: Define the composite sort key and memory budget for 50M players before picking data structures.

  • Scale: 50M players × ~96 bytes (node + HashMap entry) ≈ 4.8 GB RAM—fits easily across a small cluster of memory-optimized nodes.
  • Deterministic Tie-Breaking: Store ( -score, achieved_at_ms, player_id ) as the sort key.
Lifecycle & Failure Recovery

Scale Math & Deterministic Composite Sort Keys

election timeoutmajority voteshigher term seenFollowerCandidate ElectionElected LeaderMinority Isolated
02
STAGE 02 · CORE ENGINEfoundation

HashMap + Span-Indexed Skip List for O(log N) Rank & Neighbors.

Why this matters: Combine O(1) player lookup with O(log N) rank computation and ±5 neighbor windowing.

A Skip List alone cannot find a player's old score in O(1) when updating score += delta. Pairing it with a HashMap solves both halves:

  1. Update(player_id, delta): Look up (old_score, old_ts) in HashMap in O(1)O(1) -> remove (old_score, old_ts, player_id) from Skip List in O(log⁡N)O(\log N) -> insert (new_score, now_ts, player_id) in O(log⁡N)O(\log N).
  2. GetNeighbors(player_id, k=5): Find rank rr in O(log⁡N)O(\log N), seek to max(1, r - 5) via span pointers in O(log⁡N)O(\log N), and walk 11 Level-0 pointers forward.

Score Update & Neighbor-Rank Query Flow

HashMap LookupSkip List DeleteSkip List InsertSpan Rank Seek
Engineering Decision Framework
Problem
How to implement Design a Real-Time Concurrent Gaming Leaderboard with Range & Rank Queries 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 bottleneck threatens end-to-end availability, a HashMap gives O(1) current-score lookup while an indexed Skip List gives O(log N) exact rank and neighbor-window scans—and sharding by score-bucket or regional-tier scales beyond single-core limits.
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 Real-Time Concurrent Gaming Leaderboard with Range & Rank Queries experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · HORIZONTAL SCALINGintermediate

Scaling Past Single-Node Throughput with Score-Range Buckets.

Why this matters: Partition 200K writes/sec and 500K reads/sec across shards without losing global rank accuracy.

A single-threaded Redis ZSET tops out around ~100K ops/sec and holds ~5 GB on one core. To scale:

  • Score-Range Partitioning: Split the score space into dynamic buckets (e.g., [0–1000), [1000–5000), [5000+)), each with its own Skip List shard and an atomic total_players counter.
  • Global Rank: global_rank = sum(counts of higher score buckets) + local_rank_in_bucket.
  • Top-K Cache: Serve Top 100 from the highest bucket (cached for 200 ms at edge) so 80%+ of read traffic never hits the core engine.
Design Trade-Off

Scaling Past Single-Node Throughput with Score-Range Buckets

Before · Async Primary / Split-Brain
  • Stale leader overwrites state
  • Clock skew breaks lease order
  • Full-table sync on reboot
After · Quorum + Monotonic Fencing
  • Majority quorum prevents split-brain
  • Fencing tokens reject zombies
  • Merkle/WAL catch-up in O(log N)
04
STAGE 04 · SAFE ENGINE CODEintermediate

Idempotent Score Update with WAL Append & Bounded Retry/DLQ.

Why this matters: Prevent duplicate +delta score inflation on RPC retries and persist updates safely to an async WAL.

Game servers frequently retry timed-out RPCs; applying +delta twice corrupts rankings. Gate updates with a short-TTL idempotency key (match_id:player_id) and route failed WAL flushes through bounded retries to a DLQ:

import time, random

def apply_score_update(dedup_cache, hashmap, skiplist, wal, dlq, event, max_retries=3):
    idem_key = f"{event['match_id']}:{event['player_id']}"
    if not dedup_cache.set_if_absent(idem_key, ttl_sec=3600):
        return hashmap.get(event['player_id'])  # Idempotent no-op on retry

old = hashmap.get(event['player_id'])
    new_score = (old.score if old else 0) + event['delta']
    new_key = (-new_score, event['ts_ms'], event['player_id'])

if old:
        skiplist.delete((-old.score, old.ts_ms, event['player_id']))
    skiplist.insert(new_key, new_score)
    hashmap[event['player_id']] = new_key
05
STAGE 05 · DURABILITYintermediate

Async WAL, Periodic Snapshots & Fast Node Recovery.

Why this matters: Recover 50M in-memory leaderboard entries in seconds after a node crash without blocking live writes.

Think of Async WAL, Periodic Snapshots & Fast Node Recovery as the intuition layer for Design a Real-Time Concurrent Gaming Leaderboard with Range & Rank Queries: Recover 50M in-memory leaderboard entries in seconds after a node crash without blocking live writes.

  • Periodic Snapshots (fork/CoW): Every 5–10 minutes, write a compact binary snapshot (player_id, score, ts_ms) to object storage.
  • WAL Replay: On restart, load the latest snapshot and replay only the trailing WAL segments in sequential order—restoring 10M entries per shard in < 5 seconds.
06
STAGE 06 · SKEW MITIGATIONadvanced

Handling Score-Bucket Skew (e.g., 80% of Players at Score 0–100).

Why this matters: Prevent a single low-score bucket from becoming a write hotspot when millions of casual players cluster near zero.

In real games, 70–80% of players sit in the lowest score bracket. Fix this with adaptive bucket splitting:

  • When a bucket exceeds 5M entries or 80K writes/sec, split it either by finer score sub-ranges or by hash(player_id) % sub_shards for the bottom 'unranked' tier (where exact rank isn't shown, only percentile/approximate rank).
Component Topology

Handling Score-Bucket Skew (e.g., 80% of Players at Score 0–100)

ClientingressQuorum LeadercomputeReplica 1storageReplica 2controlwrite(token)AppendEntriesquorum sync
07
STAGE 07 · GOTCHASadvanced

Floating-Point Precision Loss, Tie-Breaker Collisions & Cross-Bucket Moves.

Why this matters: Avoid subtle ranking bugs caused by packed IEEE-754 floats or non-atomic bucket migrations.

  • Float64 Bit-Packing Overflow: Packing (score, inverted_ts) into a 53-bit IEEE-754 float (common Redis ZSET hack) silently loses timestamp precision for large scores.

Use a native 128-bit composite key or separate (score, ts) comparator.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does a real-time leaderboard pair a HashMap with an indexed Skip List instead of using only a Skip List?

Recommended Learning Flow