Appearance
Classic Designs, Part 2
21. How would you design a news feed?
The short answer
Users post; each user's feed shows recent posts from people they follow, ranked. Store posts once in a post store, the follow graph in a graph store, and a precomputed feed per user in Redis, a list of post IDs. When someone posts, a fan-out worker reads their followers and pushes the post ID into each follower's feed, which is fan-out on write. For accounts with millions of followers, skip the push and merge their recent posts at read time. Reading a feed fetches the ID list, loads post bodies from cache, ranks, and paginates with a cursor.
Estimates: 200 million daily users, 20 feed loads each = 4 billion reads a day, about 46,000 per second. 1 post per user per 5 days = 40 million posts a day, about 460 per second. With 300 followers on average, fan-out is about 140,000 feed inserts per second, which Redis handles across a cluster.
| Deep dive | Design |
|---|---|
| Hybrid fan-out | Push for authors under, say, 100,000 followers; pull for the rest (fan-out) |
| Feed size | Keep the newest 500 IDs per user; older pages come from the post store |
| Inactive users | Skip fan-out to users not seen for 30 days; rebuild their feed on next visit |
| Ranking | A second pass scores candidates by recency, affinity and engagement |
| Deletes and privacy | Filter at read time against a deleted-posts set and blocks |
| Pagination | Cursor of the last post ID, not page numbers, so new posts do not shift pages |
22. How would you design file storage and sync, like Dropbox?
The short answer
Split files into chunks, for example 4 MB, named by the hash of their content. The client uploads only chunks the server does not already have, straight to object storage with presigned URLs, then commits a file version: the ordered list of chunk hashes. A metadata service in a relational database stores folders, files, versions, chunk lists and sharing. Other devices learn about changes through a notification channel, a long poll or WebSocket, fetch the new metadata and download only the changed chunks. Identical chunks are stored once, which is deduplication. Conflicts create a "conflicted copy".
| Deep dive | Design |
|---|---|
| Deduplication | Chunks named by hash; a chunk shared by many files is stored once, with a reference count |
| Large uploads | Resumable: each chunk is its own upload; retry only the failed ones |
| Consistency | Metadata in PostgreSQL with transactions; commit a version only when all chunks exist |
| Conflicts | Two devices edit offline: keep both, name one "conflicted copy" |
| Sharing | Access control lists on folders; signed download URLs |
| Cost | Old versions and deleted files move to cheaper storage, then expire |
23. How would you design a video streaming service?
The short answer
Creators upload the original video to object storage through resumable uploads. A transcoding pipeline, a queue of jobs across many workers, converts it into several resolutions and bitrates, from 240p to 4K, split into short segments of a few seconds, with a manifest file, HLS or DASH, listing them. Viewers' players fetch the manifest and segments from a CDN, and adaptive bitrate streaming switches quality segment by segment as bandwidth changes. Metadata, search, recommendations and view counts are separate services. Nearly all the cost and scale is in storage and CDN bandwidth.
| Deep dive | Design |
|---|---|
| Transcoding scale | Split the video into chunks and encode them in parallel on many workers |
| Adaptive bitrate | The player measures download speed and picks the next segment's quality |
| Storage cost | Keep popular titles at every quality; rarely watched ones at fewer, in cheaper tiers |
| CDN | Pre-warm the edge before a big release; most traffic never reaches the origin |
| View counts | Events to a stream; approximate counts per minute; exact counts later |
| Protection | Signed URLs or tokens; DRM for licensed content |
24. How would you design a ride-hailing service?
The short answer
Drivers' apps send location updates every few seconds to a location service, which keeps each driver's latest position in an in-memory geospatial index, such as Redis geo commands or cells of a hexagonal grid like H3. When a rider requests a trip, the matching service finds nearby available drivers, ranks them by estimated arrival time, and offers the trip to one driver at a time with a short timeout, using an atomic state change so a driver can never accept two trips. The trip service then tracks the ride's states, pricing, and payment at the end; live positions stream to the rider over a WebSocket.
Estimates: 1 million active drivers × one update every 4 seconds = 250,000 location writes per second. Keep only the latest position in memory; send the stream to a log for analytics, not a transactional database.
| Deep dive | Design |
|---|---|
| Finding nearby drivers | Grid cells: look up the rider's cell and its neighbours, not the whole city |
| Double booking | Driver state changes available → offered → on_trip with a conditional update; only one offer at a time |
| Offer timeout | No answer in 10 seconds: release and offer to the next driver |
| Surge pricing | Demand and supply per cell, recomputed each minute |
| Trip states | requested, matched, arriving, in_progress, completed, cancelled, each change recorded |
| Partitioning | By city or region; each region runs its own matching |
25. How would you design a ticket booking system?
The short answer
The hard part is never selling the same seat twice while thousands try at once. When a user picks seats, hold them: an atomic conditional update sets each seat from available to held by this user with an expiry, such as 10 minutes, and fails if anyone else got there first. The user pays within the hold; on success, seats become sold in the same transaction that records the booking, using an idempotency key. Expired holds are released by a job or by checking the expiry on read. Seat maps are read from a cache; the authoritative state stays in the database.
sql
UPDATE seats
SET status = 'held', held_by = $1, held_until = now() + interval '10 minutes'
WHERE event_id = $2 AND seat_id = ANY($3)
AND (status = 'available' OR (status = 'held' AND held_until < now())); -- also reclaims expired holdsReading it: the update succeeds only for seats that are free or whose hold has expired. If the number of rows updated is less than the number of seats requested, someone else got at least one: roll back and tell the user which seats were taken. Two users can never both win, because the database checks and changes each row atomically.
| Deep dive | Design |
|---|---|
| Contention | Conditional updates per seat; hot events partitioned by event ID |
| Holds | Expiry timestamp; a sweeper releases them; checking the expiry on read covers sweeper lag |
| Payment | Booking and seat status sold in one transaction after payment succeeds; idempotency key |
| Payment slow or fails | Hold remains until expiry; then seats return to sale |
| Seat map traffic | Cached and pushed to viewers; may be a second stale, but the hold step is exact |
| Huge on-sales | Waiting room in front (question 26) |
26. How would you design a flash sale?
The short answer
A flash sale is a huge spike, say 1 million users in the first minute, for small stock, say 10,000 items. Protect the system in layers. Put a virtual waiting room in front that admits users at a controlled rate. Serve product pages from a CDN. Keep the remaining stock counter in Redis and decrement it atomically, so most users are turned away in memory without touching the database. Only users who got stock create an order, through a queue that writes to the database at a safe rate. Add rate limits and bot protection, and reconcile Redis with the database afterwards.
ts
async function tryReserve(sku: string, userId: string) {
const left = await redis.decr(`stock:${sku}`) // (1)
if (left < 0) { await redis.incr(`stock:${sku}`); return { ok: false } } // (2)
await orderQueue.add('create', { sku, userId }, { jobId: `${sku}:${userId}` }) // (3)
return { ok: true }
}- Atomic decrement. 10,000 units means exactly 10,000 callers see a value of zero or more.
- Below zero means sold out; put the unit back so the counter does not drift negative.
- One job per user per item, so double clicks do not create two orders. If payment later fails, the unit is returned with
INCR.
27. How would you design a web crawler?
The short answer
Start from seed URLs in a URL frontier, a set of queues of pages to visit. Fetcher workers take URLs, respect each site's robots.txt and a politeness delay per domain, download pages, and store the raw content. Parsers extract text and new links, normalise the links, and check a seen set, often a Bloom filter backed by a database, so each URL is crawled once. New URLs go back to the frontier, prioritised by importance and freshness. It scales by partitioning the frontier by domain, so one worker owns each domain's rate.
| Component | Job |
|---|---|
| Frontier | Priority queues per domain, so popular and stale pages come first and no site is hammered |
| Fetchers | Download with timeouts; obey robots.txt; one request per domain every few seconds |
| DNS cache | Avoid a DNS lookup for every page |
| Content store | Raw HTML in object storage, keyed by URL hash and fetch time |
| Parser | Extract links and text; detect near-duplicate pages with content fingerprints |
| Seen set | Bloom filter for "probably seen", database for certainty (Bloom filters) |
| Recrawl | Revisit often-changing pages sooner |
Estimates: 1 billion pages a month ≈ 400 pages per second; at 100 KB each, about 100 TB a month of raw HTML. Traps: infinite URL spaces such as calendars, so cap depth per site; spider traps; and duplicate content under different URLs.
28. How would you design typeahead autocomplete?
The short answer
As the user types, suggest the most popular completions of their prefix within about 100 ms. Precompute, offline, the top completions for every prefix from search logs, weighted by frequency and recency, and store them in a trie or simply a key-value map from prefix to its top 10 suggestions. Serve from memory or Redis, cache at the CDN for short popular prefixes, and debounce in the client so it asks at most every 150 ms or so. Rebuild the prefix data hourly or daily, and add a small real-time layer for trending terms.
| Deep dive | Design |
|---|---|
| Data structure | Trie, or a map prefix → [top 10 completions]; each lookup is one read |
| Freshness | Batch job recomputes counts from logs; trending terms added from a streaming counter |
| Personalisation | Merge global suggestions with the user's own recent searches on the client |
| Client | Debounce keystrokes; cancel outdated requests with AbortController (debounce) |
| Scale | Small prefixes are very hot: cache them at the CDN and in memory |
| Safety | Filter offensive and blocked terms before publishing |
29. How would you design a leaderboard?
The short answer
Use a Redis sorted set: each member is a player ID with their score, and Redis keeps them ordered. ZINCRBY updates a score, ZREVRANGE returns the top N, and ZREVRANK gives one player's rank, each in logarithmic time even with millions of players. Keep one sorted set per board and period, such as lb:global:2026-10. Persist scores in the database as the source of truth and rebuild Redis from it if needed. For huge boards, show exact ranks near the top and an approximate percentile further down.
ts
await redis.zIncrBy('lb:global:2026-10', 120, 'u_42') // (1)
const top10 = await redis.zRangeWithScores('lb:global:2026-10', 0, 9, { REV: true }) // (2)
const myRank = await redis.zRevRank('lb:global:2026-10', 'u_42') // (3)- Add 120 points to the player's monthly score.
- The top 10, highest first, with scores.
- The player's position, counting from 0.
Ties and fairness: encode the time into the score, such as score × 10^10 + (MAX_TIME − time), so the earlier achiever ranks higher among equal scores. Cheating: validate scores on the server; never trust a client-sent score.
30. How would you design a distributed job scheduler?
The short answer
Users define jobs to run at a time or on a cron schedule. Store job definitions and their next run time in a database. A scheduler loop, made safe for several instances with leader election or row locking, finds jobs whose next run time has passed, claims each one atomically with SELECT … FOR UPDATE SKIP LOCKED or a status update, pushes an execution to a queue, and computes the next run time. Workers run executions with timeouts, record results, retry with backoff, and send failures to a dead letter queue. Executions must be idempotent, because at-least-once delivery means a job can occasionally run twice.
| Deep dive | Design |
|---|---|
| Exactly one claim | UPDATE jobs SET status = 'queued' WHERE id = $1 AND status = 'scheduled', or SKIP LOCKED (locking) |
| Scheduler failure | Several schedulers, each claiming with locks; or one leader with a lease (leader election) |
| Scale | Index on next_run_at; partition jobs by hash across scheduler shards |
| Worker crash mid-job | Visibility timeout returns the job to the queue; the job is idempotent |
| Missed runs after downtime | Policy per job: run once now, run all missed, or skip |
| Long jobs | Heartbeats from the worker; checkpoints so a retry resumes |
| Visibility | Execution history, durations, failure alerts per job |