Skip to content

Interview PrepCase studies · Advanced

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.

write pathnew postpost servicefan-out workerskip celebritiesfollow graphfeed lists in Redisfeed:{user} → post IDsread pathopen feedfeed serviceIDs + celebrity postsrank, paginatepost cache and store
Do the work when posting, not when reading. Most users read far more than they post, so each post is copied into followers' feeds once. Celebrity posts are the exception: they are fetched and merged at read time to avoid millions of writes.

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 diveDesign
Hybrid fan-outPush for authors under, say, 100,000 followers; pull for the rest (fan-out)
Feed sizeKeep the newest 500 IDs per user; older pages come from the post store
Inactive usersSkip fan-out to users not seen for 30 days; rebuild their feed on next visit
RankingA second pass scores candidates by recency, affinity and engagement
Deletes and privacyFilter at read time against a deleted-posts set and blocks
PaginationCursor 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".

laptop clientchunk + hash4 MB piecesmetadata servicefiles, versions, chunksobject storagechunks by hashnotificationslong poll, WebSocketphone clientpulls changed chunks① which missing?② upload new③ version④ fetch
Move only what changed. Editing one paragraph of a 200 MB file changes one chunk, so one 4 MB piece is uploaded, not 200 MB. The new version is just an updated list of chunk hashes.
Deep diveDesign
DeduplicationChunks named by hash; a chunk shared by many files is stored once, with a reference count
Large uploadsResumable: each chunk is its own upload; retry only the failed ones
ConsistencyMetadata in PostgreSQL with transactions; commit a version only when all chunks exist
ConflictsTwo devices edit offline: keep both, name one "conflicted copy"
SharingAccess control lists on folders; signed download URLs
CostOld 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.

creatororiginal uploadtranscode queuemany workersrenditions240p · 480p · 1080p · 4K4 s segments + manifestCDN edgenear the viewerplayeradaptive bitratesegments
Encode once into many qualities, then serve from the edge. Splitting into short segments lets the player change quality every few seconds and lets the CDN cache small pieces efficiently.
Deep diveDesign
Transcoding scaleSplit the video into chunks and encode them in parallel on many workers
Adaptive bitrateThe player measures download speed and picks the next segment's quality
Storage costKeep popular titles at every quality; rarely watched ones at fewer, in cheaper tiers
CDNPre-warm the edge before a big release; most traffic never reaches the origin
View countsEvents to a stream; approximate counts per minute; exact counts later
ProtectionSigned 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.

driversGPS every 4 slocation servicegeo indexavailable driversby grid cellrider requestmatching servicenearby, rank by ETAoffer, 10 s timeouttrip servicestates, pricerider applive mapquery nearby
A live map plus a careful handshake. Locations are written constantly and kept only in memory. Matching reads that map, then offers the trip to one driver at a time, so no driver is double-booked.

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 diveDesign
Finding nearby driversGrid cells: look up the rider's cell and its neighbours, not the whole city
Double bookingDriver state changes available → offered → on_trip with a conditional update; only one offer at a time
Offer timeoutNo answer in 10 seconds: release and offer to the next driver
Surge pricingDemand and supply per cell, recomputed each minute
Trip statesrequested, matched, arriving, in_progress, completed, cancelled, each change recorded
PartitioningBy 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 holds

Reading 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 diveDesign
ContentionConditional updates per seat; hot events partitioned by event ID
HoldsExpiry timestamp; a sweeper releases them; checking the expiry on read covers sweeper lag
PaymentBooking and seat status sold in one transaction after payment succeeds; idempotency key
Payment slow or failsHold remains until expiry; then seats return to sale
Seat map trafficCached and pushed to viewers; may be a second stale, but the hold step is exact
Huge on-salesWaiting 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.

1M usersat 10:00CDN +waiting room5,000 / s inRedis stockDECR stock:sku9atomicbelow zero: "sold out"queueordersdatabasemost users are answered from memory; only winners reach the database
Turn a flood into a trickle. The waiting room limits how many get in. The Redis counter decides instantly who gets stock. The queue writes orders at a pace the database can handle.
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 }
}
  1. Atomic decrement. 10,000 units means exactly 10,000 callers see a value of zero or more.
  2. Below zero means sold out; put the unit back so the counter does not drift negative.
  3. 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.

ComponentJob
FrontierPriority queues per domain, so popular and stale pages come first and no site is hammered
FetchersDownload with timeouts; obey robots.txt; one request per domain every few seconds
DNS cacheAvoid a DNS lookup for every page
Content storeRaw HTML in object storage, keyed by URL hash and fetch time
ParserExtract links and text; detect near-duplicate pages with content fingerprints
Seen setBloom filter for "probably seen", database for certainty (Bloom filters)
RecrawlRevisit 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 diveDesign
Data structureTrie, or a map prefix → [top 10 completions]; each lookup is one read
FreshnessBatch job recomputes counts from logs; trending terms added from a streaming counter
PersonalisationMerge global suggestions with the user's own recent searches on the client
ClientDebounce keystrokes; cancel outdated requests with AbortController (debounce)
ScaleSmall prefixes are very hot: cache them at the CDN and in memory
SafetyFilter 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)
  1. Add 120 points to the player's monthly score.
  2. The top 10, highest first, with scores.
  3. 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 diveDesign
Exactly one claimUPDATE jobs SET status = 'queued' WHERE id = $1 AND status = 'scheduled', or SKIP LOCKED (locking)
Scheduler failureSeveral schedulers, each claiming with locks; or one leader with a lease (leader election)
ScaleIndex on next_run_at; partition jobs by hash across scheduler shards
Worker crash mid-jobVisibility timeout returns the job to the queue; the job is idempotent
Missed runs after downtimePolicy per job: run once now, run all missed, or skip
Long jobsHeartbeats from the worker; checkpoints so a retry resumes
VisibilityExecution history, durations, failure alerts per job

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
System Design
The method
Case studies
Auth designs
Scenarios
Other topics
Nothing picked yet