System Design Case Studies: 12 Step-by-Step Walkthroughs (URL Shortener, Chat, News Feed, Ride Sharing, Video Streaming and More)
Twelve complete system design walkthroughs, each solved step by step the way a strong candidate would in an interview: requirements, capacity estimates with real arithmetic, API, data model, a Mermaid architecture diagram, deep dives into the hard parts, and the trade-offs and follow-up questions interviewers ask. It is for software engineers preparing for system design interviews and for anyone who wants to see how real products like chat apps, feeds and ride-hailing services are built.
Last reviewed: December 2026. Traffic numbers in each case are assumptions chosen to make the math concrete, not figures for any real company.
Table of Contents
- The method used in every case study
- Estimation cheat sheet
- 1. URL shortener
- 2. Distributed rate limiter
- 3. Chat application
- 4. News feed
- 5. Ride sharing
- 6. Video streaming platform
- 7. Web crawler
- 8. Distributed key-value store
- 9. Search autocomplete
- 10. File storage and sync
- 11. Ticket booking
- 12. Real-time leaderboard
- Patterns that repeat across case studies
- How to practise
- FAQ
- Where to go next
- Contributing
- More free resources
The method used in every case study
| Step | Question to answer | Typical time in a 45-minute interview |
|---|---|---|
| 1. Requirements | What must it do (functional)? How well (non-functional: latency, availability, consistency, durability)? What is out of scope? | 5 min |
| 2. Estimates | Requests per second, storage, bandwidth, read/write ratio | 5 min |
| 3. API | The few endpoints or events that matter | 3 min |
| 4. Data model | Entities, keys, access patterns, choice of storage | 5 min |
| 5. High-level design | Boxes and arrows for the main flows | 10 min |
| 6. Deep dives | The two or three hardest parts | 12 min |
| 7. Wrap-up | Bottlenecks, failure modes, trade-offs, what you would do next | 5 min |
Estimation cheat sheet
| Fact | Value |
|---|---|
| Seconds per day | 86,400 ≈ 10^5 |
| Seconds per month (30 days) | 2,592,000 ≈ 2.6 × 10^6 |
| 1 million per day | ≈ 12 per second |
| 1 billion per day | ≈ 11,600 per second |
| Peak-to-average ratio | Assume 2-5x unless told otherwise |
| 1 KB × 1 billion | 1 TB |
| Characters in base62 alphabet | 62 (a-z, A-Z, 0-9) |
| 62^7 | ≈ 3.5 × 10^12 |
Approach: round aggressively, state assumptions out loud, and only compute numbers that change a design decision (for example whether data fits on one machine, or whether reads need caching).
1. URL shortener
Requirements
- Functional: create a short link for a long URL (optionally with a custom alias and expiry); redirect short links to the long URL; basic click analytics.
- Non-functional: redirects must be fast (p99 under ~50 ms server-side) and highly available; short codes must be unique and hard to guess if links are private.
Estimates
- 100 million new links per month → 100 × 10^6 / 2.6 × 10^6 ≈ 40 writes/s.
- Read:write ratio 100:1 → 4,000 redirects/s on average, perhaps 20,000/s at peak.
- 5 years of links: 100M × 60 = 6 billion links × ~500 bytes ≈ 3 TB.
- 7-character base62 codes give 62^7 ≈ 3.5 trillion combinations, far more than 6 billion.
API
POST /api/links {"url": "...", "alias": "optional", "expires_at": "optional"} -> {"code": "aZ3k9Qx"}
GET /{code} -> 302 redirect to the long URL
GET /api/links/{code}/stats
Data model
| Table | Key | Fields |
|---|---|---|
| links | code | long_url, owner_id, created_at, expires_at |
| clicks (or a stream) | code + time bucket | count, referrer, country |
A key-value or wide-column store fits the lookup-by-code access pattern; a relational database also works at this scale with the code as primary key.
High-level design
flowchart LR
U[User] --> LB[Load balancer]
LB --> API[Link service]
API --> IDG[ID generator]
API --> DB[(Links store)]
LB --> RD[Redirect service]
RD --> C[(Cache)]
C -. miss .-> DB
RD --> Q[[Click events queue]]
Q --> AN[Analytics workers] --> ADB[(Analytics store)]
Deep dives
Generating codes. Three common options:
| Option | How | Pros | Cons |
|---|---|---|---|
| Hash the URL | First 7 chars of base62(hash(url)) | Same URL gives same code | Collisions must be checked and resolved |
| Global counter + base62 | Encode an increasing integer | No collisions, short codes | Sequential codes are guessable; counter needs coordination |
| Pre-allocated ranges | Each server takes a block of IDs (for example 1,000,000 at a time) from a coordinator | No per-request coordination | Unused IDs are lost on restart (acceptable) |
To make sequential IDs unguessable, apply a reversible permutation (for example multiply by a large odd number modulo 62^7) before encoding.
Base62 encoding in Python:
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))
def decode(s: str) -> int:
n = 0
for ch in s:
n = n * 62 + ALPHABET.index(ch)
return n
assert decode(encode(125)) == 125 and encode(61) == "Z"
301 vs 302. A 301 (permanent) redirect lets browsers cache it, which reduces load but hides repeat clicks from analytics. A 302 (temporary) keeps every click visible. Most shorteners that offer analytics use 302 (or 307).
Caching. Link popularity is highly skewed, so an in-memory cache in front of the store absorbs most redirects. Cache misses for unknown codes should be cached too (negative caching) to block scans.
Analytics must not slow down redirects: emit a click event to a queue and aggregate asynchronously.
Trade-offs and follow-ups
- Custom aliases: check uniqueness in the same keyspace and reserve offensive words.
- Abuse: scan new URLs for malware and phishing, rate-limit creation per user and IP.
- Expiry: delete lazily on read plus a background cleanup job.
- Multi-region: replicate the links store; redirects can be served from the nearest region because links rarely change.
2. Distributed rate limiter
Requirements
- Limit requests per client (API key, user or IP) per time window, for example 100 requests per minute.
- Shared across all API servers; adds at most a few milliseconds; fails open or closed by policy.
- Return
429 Too Many Requestswith aRetry-Afterheader.
Estimates
- 50,000 requests/s across the API fleet → 50,000 limit checks/s.
- 10 million active keys × ~100 bytes of state ≈ 1 GB: fits in memory on a small in-memory cluster.
Design
flowchart LR
C[Clients] --> GW[API gateway or middleware]
GW --> RL{Rate limit check}
RL --> R[(In-memory store cluster<br/>counters per key)]
RL -->|allowed| S[Backend services]
RL -->|limited| E[429 + Retry-After]
CFG[(Rules config)] --> GW
Deep dives
Algorithm. Token bucket is the usual choice: each key has a bucket with capacity b that refills at r tokens per second; a request consumes a token or is rejected. It allows short bursts while enforcing the average rate. A minimal single-process version:
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float, now: float | None = None):
self.rate, self.capacity = rate, capacity
self.tokens = capacity
self.updated = time.monotonic() if now is None else now
def allow(self, now: float | None = None) -> bool:
now = time.monotonic() if now is None else now
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(rate=1, capacity=2, now=0.0)
assert [bucket.allow(0.0), bucket.allow(0.0), bucket.allow(0.0), bucket.allow(1.0)] == [True, True, False, True]
(The optional now arguments make the bucket testable with a fake clock, as in the assertion; in production omit them to use the real monotonic clock.)
Atomicity across servers. Two servers reading and writing the same counter can both allow a request. Run the read-modify-write as a single atomic operation on the store (for example a server-side script), or use atomic increment with expiry for fixed windows.
Latency and availability. Keep the store close to the gateways; on store failure, decide whether to fail open (allow traffic, protect availability) or fail closed (protect the backend). Many systems fail open with a local in-process fallback limiter.
Multiple rules. Combine per-user, per-IP and global limits; evaluate the cheapest first.
Follow-ups
- Different limits per plan tier: store rules in config, cache them in the gateway.
- Very hot keys: shard counters or use local token buckets with periodic synchronisation (allows slight overshoot).
- Distributed denial of service needs network-level protection; an application rate limiter is not enough.
3. Chat application
Requirements
- One-to-one and group chats (up to a few hundred members), text and media, delivery and read receipts, online presence, message history across devices, push notifications for offline users.
- Low latency delivery (under ~200 ms when both users are online); messages never lost; per-conversation ordering.
Estimates
- 50 million daily active users, 40 messages per user per day → 2 billion messages/day ≈ 23,000 messages/s, peaks around 70,000/s.
- ~100 bytes of text plus metadata per message → 200 GB/day ≈ 73 TB/year (media stored separately in object storage).
- Concurrent connections: if 20% of DAU are online at peak, 10 million open connections. At roughly 100,000 connections per gateway server, about 100 gateway servers.
API (over a persistent connection)
send_message {conversation_id, client_message_id, body}
ack {message_id} // delivered / read receipts
sync {conversation_id, after_message_id}
presence {user_id, status}
Data model
| Table | Partition key | Clustering | Notes |
|---|---|---|---|
| messages | conversation_id | message_id (time-ordered) | Wide-column store; reads are “latest N in a conversation” |
| conversations | conversation_id | Members, type, last message | |
| user_inbox | user_id | updated_at | Conversation list per user |
Message IDs should be sortable by time and unique without coordination (for example a Snowflake-style ID: timestamp + machine ID + sequence).
High-level design
flowchart LR
A[Client A] <-->|WebSocket| G1[Chat gateway 1]
B[Client B] <-->|WebSocket| G2[Chat gateway 2]
G1 --> CS[Chat service]
CS --> DB[(Messages store)]
CS --> SR[(Session registry<br/>user to gateway)]
CS --> BUS[[Message bus]]
BUS --> G2
CS --> PN[Push notification service]
PN --> APNS[Mobile push providers]
A --> MEDIA[Media upload to object storage + CDN]
Deep dives
Delivery flow. The sender’s gateway forwards the message to the chat service, which assigns an ID, persists it, acknowledges to the sender, then looks up the recipient’s gateway in the session registry and routes the message there. If the recipient is offline, the service sends a push notification; the client syncs missing messages on reconnect using the last message ID it has.
Exactly-once feel. Networks retry, so the client sends a client_message_id; the server deduplicates on it. Delivery is at-least-once with idempotent handling.
Ordering. Guarantee order per conversation, not globally: route all writes for a conversation through the same partition and order by message ID.
Groups. For small groups, fan out to each member’s gateway on send. For very large groups or channels, store once and let clients pull, with notifications only for mentions.
Presence. Heartbeats over the connection update a short-TTL entry; broadcast presence changes only to contacts who are online, and batch updates to avoid storms.
End-to-end encryption. If required, the server routes ciphertext it cannot read; keys live on devices. This affects search, moderation and multi-device sync, so raise it early.
4. News feed
Requirements
- Users follow others and see a feed of their posts, newest or ranked, with pagination.
- Feed loads in under ~300 ms; posting is fast; eventual consistency is fine (a post may appear a few seconds later).
Estimates
- 300 million daily active users, 10 feed loads each → 3 billion feed reads/day ≈ 35,000 reads/s.
- 10% of users post once a day → 30 million posts/day ≈ 350 posts/s.
- Average 200 followers; some accounts have tens of millions.
High-level design
flowchart LR
U[User] --> API[Feed API]
API --> FC[(Feed cache<br/>post IDs per user)]
API --> PS[Post service] --> PDB[(Posts store)]
PS --> Q[[New post events]]
Q --> FO[Fan-out workers]
FO --> SG[(Social graph)]
FO --> FC
API --> RK[Ranking service]
API --> HYD[Hydrate posts, authors, counts]
Deep dives
Fan-out on write vs on read.
| Approach | How | Good | Bad |
|---|---|---|---|
| Fan-out on write (push) | When a user posts, insert the post ID into every follower’s feed cache | Very fast reads | Celebrities with 50M followers create massive write spikes; wasted work for inactive users |
| Fan-out on read (pull) | On feed load, gather recent posts from everyone the user follows and merge | No write amplification | Slow reads for users who follow many accounts |
| Hybrid | Push for normal accounts; pull for celebrities at read time and merge | Balances both | More complex |
The hybrid model is the standard answer. Skip fan-out for users who have not been active recently; build their feed on demand when they return.
Feed storage. Keep only the latest few hundred post IDs per user in an in-memory store; hydrate post content, author info and counts from caches at read time. IDs are small, so 300M users × 500 IDs × 8 bytes ≈ 1.2 TB, spread across a cluster.
Ranking. Candidate generation (followed accounts’ recent posts, plus recommendations), then a model scores relevance; diversity and freshness rules adjust the final order. Cache the ranked page briefly.
Pagination. Use cursors (the last seen post ID or score) rather than offsets, since the feed changes constantly.
5. Ride sharing
Requirements
- Riders request rides; nearby available drivers are matched; both see live locations; trip lifecycle and pricing; payments after the trip.
- Matching in a few seconds; location updates every few seconds; high availability in each city.
Estimates
- 1 million drivers online at peak, sending location every 4 seconds → 250,000 location updates/s.
- 10 million trips per day ≈ 116 trip requests/s on average, much higher at peaks.
- Location updates are small (~100 bytes) but frequent: 25 MB/s ingest; only the latest position per driver needs to be hot.
High-level design
flowchart LR
D[Driver app] -->|location every 4s| LOC[Location service]
LOC --> GEO[(Geospatial index<br/>in memory, sharded by cell)]
R[Rider app] --> RQ[Ride request service]
RQ --> MATCH[Matching service]
MATCH --> GEO
MATCH -->|offer| D
MATCH --> TRIP[Trip service<br/>state machine]
TRIP --> TDB[(Trips store)]
TRIP --> PRICE[Pricing service]
TRIP --> PAY[Payments]
TRIP -->|live updates| R
Deep dives
Geospatial indexing. Divide the map into cells (geohash, a quadtree, or a hexagonal grid such as H3). Each driver is stored in the cell for their latest position. To find nearby drivers, search the rider’s cell and neighbouring rings until enough candidates are found. Keep this index in memory, sharded by region or cell, because it changes constantly.
Matching. Rank candidates by estimated time of arrival (from a routing engine, not straight-line distance), driver rating and other factors; offer to one driver at a time (or a few) with a short timeout. Use a lock or conditional update so a driver is never assigned two trips.
Trip state machine. requested → driver_assigned → driver_arrived → in_progress → completed (or cancelled). Persist each transition; make transitions idempotent so retries are safe.
Surge pricing. Compute supply and demand per cell over short windows; apply multipliers with smoothing to avoid oscillation.
Reliability. Cities are natural partitions: deploy per region so one region’s outage does not affect others. Location updates can be lossy (the next one arrives in seconds); trips and payments cannot.
6. Video streaming platform
Requirements
- Creators upload videos; viewers stream them on any device at the best quality their connection allows; search and recommendations; view counts.
- Playback starts in about two seconds; smooth playback with adaptive quality; uploads processed within minutes.
Estimates
- 500,000 uploads per day, average 10 minutes → 5 million minutes of new video per day.
- Each minute stored in about 5 renditions totalling ~100 MB → 500 TB of new storage per day (before replication).
- 100 million viewing hours per day at an average 3 Mbps → 100M × 3,600 s × 3 Mb ≈ 1.08 × 10^12 Mb ≈ 135 PB/day of egress, served almost entirely by CDNs.
High-level design
flowchart LR
CR[Creator] -->|resumable upload| UP[Upload service]
UP --> RAW[(Raw video storage)]
UP --> Q[[Processing queue]]
Q --> TR[Transcoding workers<br/>split into chunks, encode in parallel]
TR --> OUT[(Renditions + HLS/DASH manifests)]
OUT --> CDN[CDN]
V[Viewer] --> API[Playback API<br/>auth, manifest URL]
V --> CDN
TR --> META[(Video metadata)]
API --> META
Deep dives
Transcoding pipeline. Split the upload into segments, transcode segments in parallel into several resolutions and bitrates (a bitrate ladder), generate thumbnails, then assemble manifests. Model it as a DAG of tasks with retries; use spot or preemptible compute for cost.
Adaptive bitrate streaming. Videos are cut into short segments (a few seconds each) at each quality level and described by a manifest (HLS or DASH). The player measures throughput and buffer level and switches quality between segments.
CDN strategy. Popular videos are cached at the edge; long-tail videos are fetched from origin or a regional shield. Pre-position new videos from popular creators. Egress cost dominates, so codec choice (more efficient codecs mean fewer bytes) matters financially.
Uploads. Use resumable, chunked uploads directly to object storage with pre-signed URLs so large files survive flaky connections.
View counts. Count views asynchronously: client events → stream → aggregation → periodic updates to the counter store, with deduplication and fraud filtering.
7. Web crawler
Requirements
- Crawl billions of pages for a search index; respect robots.txt and per-site politeness; avoid duplicates; refresh pages based on how often they change.
Estimates
- 1 billion pages per month → 1 × 10^9 / 2.6 × 10^6 ≈ 385 pages/s average.
- 100 KB average page → 100 TB/month of raw HTML (compress before storing).
High-level design
flowchart LR
SEED[Seed URLs] --> FR[URL frontier<br/>priority + per-host queues]
FR --> FE[Fetchers]
FE --> DNS[(DNS cache)]
FE --> ROB[(robots.txt cache)]
FE --> ST[(Page store)]
FE --> PAR[Parser]
PAR --> DED{Seen URL?<br/>Seen content?}
DED -->|new URLs| FR
PAR --> IDX[Indexing pipeline]
Deep dives
URL frontier. Two layers: a priority layer (important or frequently changing pages first) and a politeness layer of per-host queues, so each host is fetched by one worker at a limited rate. Honour robots.txt rules, including crawl delays where specified (the robots exclusion protocol is standardised in RFC 9309).
Deduplication. Normalise URLs (lowercase host, remove fragments, sort known parameters) and check a seen-URL set; at billions of URLs, a Bloom filter in front of a persistent store saves memory. Detect duplicate content with a content hash for exact copies and SimHash-style fingerprints for near-duplicates.
Traps and failures. Limit URL depth and per-host page counts to avoid infinite calendars and session-ID loops; time out slow hosts; retry with backoff.
Freshness. Track how often each page changes and schedule recrawls adaptively: news front pages hourly, rarely changing pages monthly.
8. Distributed key-value store
Requirements
put(key, value)andget(key); scale horizontally to many nodes; highly available for writes even during failures; tunable consistency.
Design
flowchart LR
C[Client] --> CO[Coordinator node]
CO -->|N = 3 replicas| N1[(Node A)]
CO --> N2[(Node B)]
CO --> N3[(Node C)]
N1 <-. gossip membership .-> N2
N2 <-. gossip membership .-> N3
N1 <-. Merkle tree anti-entropy .-> N3
Deep dives
Partitioning. Consistent hashing places keys on a ring; each key is stored on the next N nodes clockwise. Virtual nodes spread load evenly and make adding nodes smooth.
Replication and quorums. With N replicas, a write waits for W acknowledgements and a read queries R replicas. If R + W > N, every read overlaps at least one replica with the latest acknowledged write. N = 3, W = 2, R = 2 is a common balance; W = 1 favours write availability and latency.
Conflicts. Concurrent writes to the same key on different replicas need resolution: last-write-wins by timestamp (simple, can lose updates), version vectors to detect concurrency and return siblings to the client, or CRDTs for data types that merge automatically.
Handling failures.
| Technique | Purpose |
|---|---|
| Hinted handoff | A healthy node temporarily stores writes for a down replica and forwards them later |
| Read repair | Reads that find stale replicas update them |
| Merkle trees | Replicas compare tree hashes to find and sync differing key ranges efficiently |
| Gossip | Nodes exchange membership and health information without a central coordinator |
Storage engine. An LSM-tree (write-ahead log, memtable, sorted files with compaction) gives fast writes; Bloom filters reduce disk reads for missing keys.
This design follows the ideas in Amazon’s Dynamo paper, the classic reference for leaderless key-value stores. For strongly consistent alternatives, read about consensus with Raft.
9. Search autocomplete
Requirements
- As the user types, return the top 5-10 suggestions for the prefix within ~100 ms; suggestions ranked by popularity and freshness; filter offensive terms.
Estimates
- 10 million searches per day with ~10 keystrokes each, debounced to about 5 requests per search → 50 million requests/day ≈ 580 requests/s, peaks of a few thousand.
- Unique queries worth suggesting: tens of millions, each short; the index fits in memory on a few machines.
Design
flowchart LR
U[Typing user] --> API[Autocomplete API]
API --> CACHE[(Prefix cache / CDN)]
API --> TS[Trie servers<br/>top-k stored at each node]
LOGS[(Query logs)] --> AGG[Batch or streaming aggregation]
AGG --> BUILD[Trie builder] --> TS
BUILD --> FILT[Blocklist filter]
Deep dives
Data structure. A trie where each node stores the precomputed top-k completions for its prefix makes a lookup O(length of prefix). Without the precomputed lists you would have to traverse the whole subtree.
Building it. Aggregate query logs over a sliding window (for example the last 7 days with decay) offline or in a streaming job, rebuild or update the trie, and swap it in atomically. Real-time trending terms can come from a separate short-window aggregator merged at query time.
Serving. Shard by prefix range (or replicate the whole trie if it fits), cache popular prefixes (one- and two-letter prefixes are requested constantly), and debounce requests on the client.
Personalisation and safety. Blend global suggestions with the user’s own history; apply blocklists before suggestions are published.
10. File storage and sync
Requirements
- Upload, download and sync files across devices; share with others; version history; handle large files and flaky networks; conflicts when two devices edit offline.
Estimates
- 50 million users with an average 10 GB stored → 500 PB before deduplication and compression.
- Most files rarely change; metadata operations far outnumber byte transfers.
High-level design
flowchart LR
CL[Desktop or mobile client] -->|chunked upload| BLK[Block service]
BLK --> OBJ[(Object storage<br/>blocks keyed by content hash)]
CL --> META[Metadata service]
META --> MDB[(Metadata DB<br/>files, versions, block lists)]
META --> NOTIFY[Notification service]
NOTIFY -->|long poll or push| CL2[Other devices]
CL2 -->|fetch changed blocks| BLK
Deep dives
Chunking and deduplication. Split files into blocks (for example 4 MB, or content-defined chunks so an insertion does not shift every block), hash each block, and upload only blocks the server does not have. A file version is a list of block hashes, so small edits upload little and identical files across users are stored once (subject to privacy and encryption design).
Metadata is the heart. The metadata DB holds the namespace (folders, files, versions, sharing permissions) and must be strongly consistent; it is relational and sharded by user or namespace. Each change increments a per-namespace cursor that clients use to sync.
Sync protocol. A client asks “what changed since cursor X?”, downloads changed block lists, and fetches missing blocks. Notifications (long polling or push) tell clients when to ask.
Conflicts. If two devices change the same file based on the same version, keep both: save the second as a “conflicted copy” and let the user resolve it. Collaborative editors use operational transforms or CRDTs instead.
11. Ticket booking
Requirements
- Browse events and seat maps; hold seats while the user pays; never sell the same seat twice; survive on-sale spikes when millions arrive at once.
Design
flowchart LR
U[Users] --> WR[Virtual waiting room]
WR -->|admitted at a controlled rate| WEB[Booking API]
WEB --> INV[Inventory service]
INV --> DB[(Seats table<br/>status, hold_expires_at, version)]
WEB --> PAY[Payment service]
PAY -->|success| INV
EXP[Hold expiry job] --> INV
Deep dives
No double booking. Seat state transitions must be atomic: available → held(user, expires_at) → sold. Use a conditional update so only one request wins:
UPDATE seats
SET status = 'held', held_by = :user, hold_expires_at = NOW() + INTERVAL 10 MINUTE, version = version + 1
WHERE seat_id = :seat AND status = 'available';
-- 1 row updated: you got the seat. 0 rows: someone else did.
(MySQL interval syntax; adapt for your database.) This optimistic approach scales better than long-held locks. Expired holds are released by a background job or treated as available when hold_expires_at has passed.
Spikes. A virtual waiting room admits users at a rate the booking system can handle and gives everyone a fair queue position. Serve event pages and seat maps from caches and CDNs; only seat holds and payments hit the database.
Payments. Use idempotency keys; if payment succeeds but confirmation fails, a reconciliation job completes the sale or refunds.
Bots. Rate limits per account and device, purchase limits per event, and verified-fan or lottery systems for high-demand events.
12. Real-time leaderboard
Requirements
- Update player scores in real time; show the top 100 and a player’s own rank with neighbours; millions of players per leaderboard; daily and all-time boards.
Design
flowchart LR
G[Game servers] -->|score events| Q[[Event stream]]
Q --> W[Score workers]
W --> Z[(Sorted sets<br/>per leaderboard)]
W --> DB[(Durable score store)]
API[Leaderboard API] --> Z
P[Players] --> API
Deep dives
Sorted sets. An in-memory sorted set (for example Redis sorted sets) supports updating a score, fetching the top N and getting a member’s rank in O(log n). One set per leaderboard and period (board:2026-12-01), with expiry for old periods.
Durability. The in-memory set is a fast view; the source of truth is the durable score store or the event stream, so the set can be rebuilt.
Very large boards. When one set is too big or too hot, shard players by score range, or compute exact ranks only for the top tiers and approximate ranks (percentiles from a histogram) for everyone else; players far down the board rarely need an exact number.
Ties. Encode a tiebreaker into the score, for example score × 10^10 + (MAX_TS - timestamp) so earlier achievers rank higher.
Patterns that repeat across case studies
| Pattern | Where it appeared |
|---|---|
| Cache the read path aggressively | URL shortener, news feed, autocomplete, leaderboard |
| Move slow work to queues | Analytics, fan-out, transcoding, crawling, view counts |
| Idempotency keys and deduplication | Chat messages, payments, ticket holds, webhooks |
| Partition by the main access key | Messages by conversation, feeds by user, drivers by cell |
| Precompute for fast reads | Feeds (fan-out on write), autocomplete (top-k per node) |
| Conditional updates instead of locks | Ticket holds, driver assignment |
| Consistent hashing | Key-value store, caches, sharded services |
| CDN for heavy static bytes | Video, media in chat, file downloads |
| Separate hot state from durable truth | Leaderboards, locations, presence |
How to practise
- Pick a case study and close this page. Set a 45-minute timer and design it out loud or on paper.
- Compare with the walkthrough here. Note what you missed: estimates, a failure mode, a data model detail.
- Redo the same system a week later, then change one requirement (10x traffic, strong consistency, multi-region) and adapt the design.
- Practise with a partner who asks “why?” and “what if this fails?” after every box you draw.
FAQ
Do interviewers expect these exact designs? No. They expect a reasonable design with justified trade-offs. Two candidates can draw different architectures and both do well if they explain their reasoning and handle follow-ups.
How precise should estimates be? Within an order of magnitude. The point is to decide whether something fits on one machine, whether you need caching or sharding, and where the bottleneck is.
Which databases should I name? Name categories first (relational, wide-column, key-value, object storage) and explain why the access pattern fits. Mention specific products only if you know their trade-offs.
What if I have never built a system at this scale? That is normal. Show structured thinking, use estimates to drive decisions, and be honest about uncertainty. Reading engineering blogs and papers like the ones below fills the experience gap.
How many case studies should I prepare? Work through all twelve once, then redo five or six deeply. Most interview questions are variations of these.
Where to go next
- Book: Designing Data-Intensive Applications (book site) for the theory behind replication, partitioning and consistency.
- Course: MIT 6.5840 Distributed Systems lectures and labs.
- Papers: Dynamo, Bigtable, and the Raft consensus site.
- Practice articles: Amazon Builders’ Library on timeouts, retries, caching and load shedding.
- Reliability: Google’s Site Reliability Engineering book.
Contributing
PRs are welcome. Keep entries accurate:
- New case studies follow the same seven steps and include estimates with visible arithmetic and a Mermaid diagram that renders.
- Corrections to numbers or claims should include a source or a worked calculation.
- Keep designs product-neutral: describe patterns, not a specific company’s private architecture.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.