Real-Time Ranking System for Competitive Programming Platform
System DesignModel answerLast updated
Design a leaderboard that tracks millions of users' scores and serves rankings with sub-100ms latency at 50K writes/sec.
Real-Time Ranking System for Competitive Programming Platform
You're building a ranking system for a competitive programming website with millions of active participants. Users accumulate points by completing challenges, and the platform displays their position relative to all other competitors worldwide.
What the System Must Support
Core Operations:
- Record score changes: When a user completes a challenge, their total points increase
- Fetch top performers: Show the 100 highest-ranked users
- Look up individual rank: Given a user ID, return their current position
- Show nearby competitors: For any user, display the 50 people ranked immediately above and below them
Scale and Performance Targets
- User base: 10 million people online at once; 100 million total with scores
- Write throughput: 50,000 score updates arriving every second during peak hours
- Read latency: Ranking queries must complete in under 100 milliseconds
- Consistency model: Score updates must be durable within seconds; rank calculations can tolerate brief eventual consistency
What to Cover in Your Design
- Overall architecture: which storage systems and caching strategies you'd use
- Schema and data structures for both persistent storage and the ranking layer
- How you'd prevent "hot spot" issues when many highly-ranked users update simultaneously
- Strategies to validate submissions without slowing down the ingestion pipeline
Assume the platform's judge service verifies solutions server-side before sending score updates, so clients never directly report their own points.
Hints
Hint 1
A sorted set data structure with O(log N) rank lookups can fit 100M users in ~10GB of memory
Hint 2
Batch and coalesce multiple updates for the same user before writing to the ranking store to reduce load
Hint 3
Precompute and cache the top 100 list separately with a 1-second refresh cycle to serve read traffic from CDN
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Ranking System
1. Clarifying the Problem Space
Begin by establishing concrete numbers and understanding the score semantics:
Scale parameters:
- 100 million users have earned points
- 50K score updates/second at peak
- Read traffic likely 5–10× higher than writes (~250K–500K queries/second)
- Each user's score only increases when they solve a new problem (first-time solve only)
Key clarification: The judge service computes points server-side after validating solutions. Clients never send point values directly. This design choice eliminates most fraud concerns from the critical path.
Tie-breaking rule: When two users have identical scores, rank by who reached that score first (earlier timestamp wins).
2. High-Level Architecture
Write path:
Client submissions → Judge Service → Score Ingest API
→ Message Queue (Kafka, partitioned by userId)
→ Database Writer (Postgres/DynamoDB) — durable record
→ Ranking Updater → Redis sorted set — fast lookups
Read path:
Client → CDN (top 100, cached 1s) → API Service → Redis read replicas
Why this layered approach:
- The message queue decouples ingestion from processing, providing durability and backpressure handling
- Database and Redis are updated in parallel from the queue, so slow database writes never delay rank freshness
- CDN and precomputed snapshots handle the majority of read traffic without touching the ranking store
3. Data Model
Persistent storage (Postgres, sharded by user_id):
user_scores (
user_id BIGINT PRIMARY KEY,
season_id INT,
total_points INT,
last_scored_at TIMESTAMP,
solve_count INT
)
solved_problems (
user_id BIGINT,
problem_id INT,
solved_at TIMESTAMP,
points_awarded INT,
PRIMARY KEY (user_id, problem_id)
)
score_events (append-only Kafka topic, 7-day retention)
{userId, problemId, submissionId, points, timestamp}
Ranking layer (Redis):
ZSET season:2026:ranks
member = userId
score = composite_score
HASH user:{userId}:profile
{displayName, avatar, country}
STRING season:2026:top100
(cached JSON payload, refreshed every second)
Composite score for tie-breaking:
- Formula:
(points × 2^32) + (MAX_TIMESTAMP - last_scored_at) - This encodes both points and recency into a single sortable number
- Higher scores naturally sort first; among ties, earlier timestamps produce higher composite values
Memory footprint: Redis sorted set entry ≈ 100 bytes. For 100M users: ~10GB, comfortably fitting on one large Redis instance with room to spare.
4. Handling Write Throughput and Hot Partitions
The hot partition challenge: If you shard by score range (e.g., top shard holds scores above 5000), the highest-ranked users—who are also the most active—concentrate all writes on one shard.
Solution: Batch and coalesce at the consumer level
- Windowed aggregation: Each Kafka consumer accumulates events for 100–500ms
- Per-user coalescing: Multiple updates for the same user within the window merge into one
- Batched write: Issue one Redis pipeline containing all updates for that window
- Use absolute scores: Send final computed scores (not increments) to make retries idempotent
This reduces Redis operations by 10–100×. A user solving five problems in one second becomes a single ZADD command.
Additional mitigations:
- Separate read and write hot spots: Nobody reads directly from the primary Redis instance. The top 100 snapshot is precomputed every second and served from CDN, so read load on the ranking store remains constant regardless of traffic spikes
- Read replicas: Deploy Redis replicas to absorb rank lookup queries. Slight replication lag (tens of milliseconds) is acceptable given the "within seconds" consistency requirement
- Tiered precision: Maintain exact sorted sets only for the top 1–10 million users. For the long tail, keep score histograms and return approximate ranks like "~42,130,000, top 15%"—users ranked in the millions rarely care about exact position
Sharding strategy:
For systems that outgrow a single Redis node, hash-shard by userId:
- Writes distribute evenly across shards
- Rank queries become scatter-gather: query each shard for
ZCOUNT(shard, (score, +inf))and sum results - Top 100 requires merging each shard's top 100 (K × 100 entries sorted)
- Cache per-shard user counts and refresh every second to avoid repeated ZCARD calls
5. API Implementation
POST /submit-score
- Called by judge service with signed token:
{userId, problemId, submissionId, judgeToken} - Validates HMAC signature binding the submission to server-generated timestamp
- Checks Redis
SETNX submissionIdfor idempotency - Publishes to Kafka partitioned by userId, returns 202 Accepted immediately
GET /leaderboard
- Returns precomputed top 100 from Redis string key, updated every ~1 second by background job
- Served through CDN with 1-second TTL
- Cost: effectively zero regardless of query volume
GET /rank/{userId}
ZREVRANKon Redis sorted set: O(log N) ≈ 26 comparisons for 100M users- Returns
{rank, score, totalUsers}
GET /neighbor-rank/{userId}
ZREVRANKto get position, thenZREVRANGE rank-50 rank+50- Total complexity: O(log N + 101)
- Returns 101 users centered on the requested user
6. Anti-Cheat Without Blocking Ingestion
Synchronous checks (ingestion path, <1ms each):
- mTLS authentication that caller is the authorized judge service
- HMAC signature on judge token proving server generated the result
- Redis-based idempotency check via
SETNX submissionId - Per-user rate limiting (token bucket)
- Timestamps originate from judge service clocks, never client-supplied
Asynchronous validation (separate consumer group):
- Solution time plausibility (e.g., complex problem solved in 15 seconds)
- Code similarity detection and plagiarism fingerprinting
- Velocity anomalies (impossible solve rate patterns)
- Multi-account correlation
- When fraud is detected, publish compensating "revoke" events that flow through the same pipeline
This keeps the hot path fast while still providing comprehensive fraud detection within seconds.
7. Failure Modes and Recovery
Redis failure:
- Rebuild from
user_scorestable with bulk insert, or replay recent Kafka history - During rebuild, serve stale top 100 from CDN and return degraded rank responses
Kafka partition lag:
- Monitor consumer lag; alert if it exceeds 5 seconds
- Add consumers or increase batch size to catch up
- Kafka retention allows reprocessing events from hours ago if needed
Database hot spot:
- Shard by userId (consistent hashing)
- Use write-optimized storage (e.g., Cassandra) if update rate exceeds RDBMS capacity per shard
8. Complexity Analysis
Time complexity:
- Score update (end-to-end): O(1) ingestion + O(log N) Redis ZADD ≈ 1–2 seconds total latency
- Top 100 fetch: O(1) from cache
- Rank lookup: O(log N) ≈ 50µs on modern Redis
- Neighbor fetch: O(log N + k) where k=101
Space complexity:
- Persistent storage: O(users + solutions) ≈ 100M users × 200 bytes = 20 GB
- Redis ranking: O(users) ≈ 10 GB
- Kafka buffer: O(write_rate × retention) ≈ 50K/s × 7 days × 200 bytes ≈ 6 TB
Common Mistakes to Avoid
- Calling Redis on every ingestion: This creates a synchronous bottleneck. Use async consumers with batching instead
- Using ZINCRBY: Increments aren't idempotent and complicate retries. Store absolute composite scores
- Reading top 100 from ZRANGE on every request: This becomes a bottleneck at high QPS. Precompute and cache
- Neglecting tie-breaking: Without deterministic tie resolution, ranks flap when scores are equal
- Putting fraud detection in the write path: Expensive checks will throttle ingestion. Move them to async pipelines