← Interview prep

System Design interview questions

Scalable architecture, storage, and distributed design.

100 questions · Page 3 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 3 of 5

Questions 41–60 of 100 · 0 of 20 on this page marked learned

41.system-design-0041Mediummid

Design a search autocomplete (typeahead) service that suggests the top 10 completions as users type.

Precompute, offline, the top 10 popular queries for every prefix from search logs, store them in a sharded in-memory prefix map or trie, and serve lookups in a few milliseconds; refresh the data hourly or daily, with a streaming layer for trending terms. Clients debounce keystrokes and cache responses, and short prefixes are cached at the CDN. About 3 billion suggestion requests per day means roughly 35,000 per second on average.

Full answer

Requirements

Functional:

  • As the user types "pyth", return up to 10 suggestions such as "python tutorial", "python interview questions".
  • Rank by popularity, with recent trends reflected; filter offensive or blocked terms.
  • Support several languages.

Non-functional:

  • Very low latency: the full round trip should feel instant, so the server target is a few milliseconds and p99 under about 50 ms.
  • Highly available; slightly stale suggestions are fine.
  • Read-heavy; updates can lag by minutes or hours.

Capacity estimates

Assumptions: 100M DAU, 5 searches per user per day, 6 suggestion requests per search after client debouncing (about 150 ms), peak factor 2, 100M distinct popular queries, 500M distinct prefixes kept, 100 bytes per prefix entry (prefix plus 10 query IDs).

  • Requests: 100M x 5 x 6 = 3B per day = about 34,700 per second; about 69,000 per second at peak.
  • Data: 500M prefixes x 100 B = 50 GB, plus the query strings (100M x about 25 bytes = 2.5 GB). Fits in memory across a small sharded cluster, or even on one large machine per replica.
  • Caching: a large share of requests are for 1 to 3 character prefixes, which are few in number and cache perfectly at the CDN and in the browser.

API

GET /v1/suggest?q=pyth&lang=en&limit=10 200 Cache-Control: public, max-age=300 {"q":"pyth","suggestions":["python tutorial","python interview questions", ...]}

Data model

  • Serving: map prefix -> [query_id x 10] plus query_id -> text. A trie with top-k stored at each node is the textbook form; a flat hash map keyed by prefix is simpler to shard and serves the same lookups.
  • Offline: query_counts(query, window, count) aggregated from logs.

High-level design

mermaid
flowchart LR
  U[Browser / app] --> CDN[CDN cache]
  CDN --> SS[Suggest service]
  SS --> SH[(Prefix shards in memory)]
  SL[Search logs] --> K[Kafka]
  K --> AGG[Batch aggregation: Spark]
  K --> TR[Streaming trends: Flink]
  AGG --> BUILD[Index builder]
  TR --> BUILD
  BUILD --> SNAP[(Snapshot in object storage)]
  SNAP --> SH

Building the index

  1. Search logs go into Kafka.
  2. A batch job counts queries over a window (for example the last 30 days) with time decay so old popularity fades, removes blocked terms and very rare queries.
  3. For each query, add it as a candidate to every prefix of it (up to a limit like 20 characters), keep the top 10 per prefix by score.
  4. Write a versioned snapshot; serving nodes load it and switch atomically. Rollback means loading the previous snapshot.
  5. A streaming job detects sudden spikes ("exam results 2026") and pushes small overrides that merge into results until the next batch build.

Serving and scaling

Shard by hash of the prefix so load spreads evenly; sharding by first letter would make "s" and "a" shards hot. Replicate each shard for throughput and availability. Each lookup is one in-memory read, so a modest number of replicas handles about 69,000 requests per second, and the CDN absorbs much of it.

Personalisation (a user's own recent searches) is merged on the client or by a thin layer on top, rather than precomputed per user.

Bottlenecks and trade-offs

  • The bottleneck is not storage but peak read rate on short prefixes and the size of the offline build; the CDN and browser cache take the first, incremental builds the second.
  • Precomputed top-k per prefix gives constant-time reads but needs large offline builds and lags behind reality; the streaming layer reduces lag at extra complexity.
  • Storing top-k at every prefix uses more memory than computing it at query time from a trie, but query-time traversal would be too slow for popular short prefixes.
  • Aggressive caching makes blocked-term removal slower to take effect; keep short TTLs and a blocklist check at the service so a removal applies within minutes.

By level

Fresher: Explain a trie, how prefixes map to top suggestions, and why the client waits a little between keystrokes before sending. A fresher can describe a trie and top suggestions per prefix.

Mid: Estimate traffic and memory, design the offline pipeline and snapshot loading, shard by prefix hash and cache at the edge. Expect an estimate of requests and memory with stated assumptions.

Senior: Add streaming trends, multilingual and personalised layers, safe rollout and rollback of snapshots, abuse and manipulation of popularity, and cost of rebuilding at scale. Expect safe rollout and rollback of index snapshots.

Key points

  • Precompute top-k per prefix offline from query logs
  • Serve from sharded in-memory maps or tries in milliseconds
  • About 3B requests per day, roughly 35k per second average
  • Debounce on the client and cache short prefixes at the CDN
  • Streaming layer adds trending terms between batch builds

Common mistakes

  • Computing suggestions by scanning a database with LIKE 'prefix%' per keystroke
  • Sharding by first letter and creating hot shards
  • Sending a request for every keystroke without debouncing
  • Forgetting filtering of offensive or blocked terms

Follow-ups

  • How would you add personalised suggestions?
  • How do you handle typos in the prefix?
  • How would you remove a harmful suggestion within minutes?

Tips

  • Ask about freshness needs; they decide batch versus streaming
  • Mention client debounce and CDN caching early
  • Explain why top-k is stored per prefix

Evaluation rubric

  • Requirements emphasise latency and freshness
  • Request and memory estimates with assumptions
  • Offline build plus online serving design
  • Sharding, caching and freshness trade-offs
42.system-design-0042Hardsenior

Design a video streaming platform like YouTube that supports uploads, transcoding and adaptive playback worldwide.

Accept resumable uploads into object storage, run a transcoding pipeline that splits each video into segments and produces several resolutions and bitrates, package them as HLS or DASH, and serve segments from a CDN so players can switch quality as bandwidth changes. Egress dominates: 1 billion views per day of 5 minutes at 3 Mbps is about 112.5 PB per day, roughly 10.4 Tbps on average, which only a CDN can serve.

Full answer

Requirements

Functional:

  • Creators upload videos (up to several GB); viewers watch them on web, mobile and TV.
  • Playback adapts to network speed; seeking is quick.
  • Video metadata (title, description, thumbnails), view counts, likes. Search and recommendations exist but are out of scope here.

Non-functional:

  • Playback starts fast (target under about 2 seconds) and rarely rebuffers.
  • Uploaded videos are never lost; processing can take minutes.
  • Global reach and very high read volume; cost of storage and bandwidth matters a lot.

Capacity estimates

Assumptions: 1M uploads per day; average length 5 minutes; average raw upload 300 MB; all renditions together about 150 MB per video; 1B views per day; average 5 minutes watched at an average 3 Mbps; transcoding the full ladder costs 2 CPU-minutes per minute of video; peak factor 2.

  • Upload ingest: 1M x 300 MB = 300 TB per day of originals (kept in a cold tier).
  • Transcoded output: 1M x 150 MB = 150 TB per day; with 3 copies, 450 TB per day; about 164 PB per year.
  • Egress per view: 300 s x 3 Mbps = 900 megabits = 112.5 MB. Per day: 1B x 112.5 MB = 112.5 PB. Average bandwidth: 112.5 PB x 8 / 86,400 s = about 10.4 Tbps; about 21 Tbps at peak.
  • Transcoding compute: 1M x 5 min x 2 = 10M CPU-minutes per day = about 167,000 CPU-hours per day, about 6,900 cores busy around the clock.
  • Watch page metadata reads: about 1B per day = about 11,600 per second; easily cached.

API

POST /v1/uploads {"filename": "...", "size": 3221225472} -> {"upload_id", "upload_url"} PUT <upload_url> (resumable chunks, Content-Range) POST /v1/videos {"upload_id", "title", "description"} -> {"video_id", "status": "processing"} GET /v1/videos/{id} metadata, status, manifest URL GET https://cdn.example.com/v/{id}/master.m3u8 HLS master playlist (renditions) GET https://cdn.example.com/v/{id}/720p/seg_00042.ts

Data model

  • videos: video_id, owner_id, title, status (uploading, processing, ready, failed), duration, created_at.
  • renditions: video_id, resolution, bitrate, codec, manifest_path.
  • processing_jobs: video_id, step, segment_index, state, attempts.
  • Counters for views and likes in a separate counter service.
  • Bytes (originals, segments, thumbnails) in object storage; only paths in the database.

High-level design

mermaid
flowchart LR
  CR[Creator] --> UP[Upload service] --> RAW[(Object storage: originals)]
  UP --> Q[Job queue]
  Q --> SPLIT[Splitter]
  SPLIT --> TX[Transcode workers x N]
  TX --> PKG[Packager: HLS / DASH + thumbnails]
  PKG --> OUT[(Object storage: segments)]
  PKG --> META[(Video metadata DB)]
  OUT --> CDN[Global CDN]
  V[Viewer] --> API[Watch API] --> META
  V --> CDN

Processing pipeline

  1. Upload is resumable: the client sends chunks with offsets, so a dropped connection resumes rather than restarts.
  2. A job validates the file, then splits it into short pieces (for example 10 seconds at keyframes).
  3. Transcode workers convert pieces in parallel to a bitrate ladder (for example 240p to 1080p, and 4K where uploaded) in one or more codecs. Parallel segments turn a 1-hour video into many small jobs.
  4. The packager produces HLS and DASH manifests and segments, generates thumbnails, and marks the video ready.
  5. Each step is idempotent and retried from the job table; a failed piece is retried alone.

Playback

The player downloads the master manifest, picks a starting rendition, and requests segments from the CDN. It measures download speed and buffer level and switches rendition between segments (adaptive bitrate). Popular videos stay hot in edge caches; long-tail videos are fetched from origin on demand, with an origin shield layer to protect object storage.

Bottlenecks and trade-offs

  • Bandwidth cost dominates. Better codecs (AV1, VP9, HEVC) reduce bytes per view at the cost of much more transcoding CPU; apply them first to popular videos, where savings are largest.
  • Storage: keep every rendition for popular videos, fewer renditions or on-demand transcoding for videos that are rarely watched; move originals to archive storage.
  • Transcoding spikes are absorbed by the queue and autoscaled or spot workers; a creator waits longer, but nothing breaks.
  • View counts are aggregated asynchronously from playback events, with fraud filtering; exact real-time counts are not required.
  • Segment length: shorter segments switch quality faster and start sooner but add request overhead and slightly worse compression.

By level

Fresher: Explain upload to storage, converting video into several qualities, and serving it from a CDN so the player can switch quality. A fresher should know why video is served from a CDN.

Mid: Estimate storage, egress and transcoding compute, design the job pipeline and data model, and explain manifests and segments. Expect careful egress math with bits and bytes kept apart.

Senior: Address cost optimisation with codecs and storage tiers, origin shielding, multi-CDN, live streaming differences, failure recovery in the pipeline and global capacity planning. The senior answer treats bandwidth and storage cost as first-class design inputs.

Key points

  • Resumable uploads into object storage, then an asynchronous, parallel transcoding pipeline
  • Bitrate ladder packaged as HLS or DASH segments for adaptive playback
  • Egress of about 112.5 PB per day (about 10.4 Tbps) requires a CDN
  • Metadata in a database, bytes in object storage
  • Codec and storage tiering choices trade CPU against bandwidth and storage cost

Common mistakes

  • Streaming video bytes from application servers
  • Transcoding whole long videos on one machine
  • Confusing megabits and megabytes in bandwidth math
  • Keeping every rendition of every video in the hot tier forever

Follow-ups

  • How would you support live streaming instead of uploads?
  • How do you decide which videos get the expensive codec?
  • How would you prevent a single viral video from overloading the origin?

Tips

  • Do the egress arithmetic carefully with bits and bytes
  • Split the design into upload, processing and playback paths
  • Explain adaptive bitrate in one clear sentence

Evaluation rubric

  • Requirements separate upload, processing and playback
  • Correct storage, egress and compute math
  • Pipeline design with parallel, idempotent steps
  • CDN, adaptive bitrate and cost trade-offs discussed
43.system-design-0043Hardsenior

Design a distributed in-memory cache like Memcached or Redis Cluster that stores 1 TB of hot data and serves 1 million operations per second.

Partition keys across nodes with consistent hashing or fixed hash slots, keep each partition in an in-memory hash table with approximate LRU eviction and TTLs, and replicate each partition to a standby for fast failover. Clients route directly using a cluster map. With about 50 GB usable per node, 1 TB needs about 20 primaries, each serving about 50,000 operations per second.

Full answer

Requirements

Functional:

  • get, set with TTL, delete, multi-get, and compare-and-set.
  • Evict entries when memory is full.

Non-functional:

  • p99 latency around 1 ms inside a data centre.
  • Scale out by adding nodes without remapping most keys.
  • Survive a node failure with a short window of reduced hit ratio, not an outage. The cache is not the source of truth; losing some data is acceptable.

Capacity estimates

Assumptions: 1 TB of hot data; average value 1 KB; 1M operations per second at peak, 90% reads; servers with 64 GB RAM of which 50 GB holds data (the rest for the OS, connection buffers, fragmentation); one replica per primary.

  • Primaries: 1 TB / 50 GB = 20 nodes; with one replica each, 40 nodes.
  • Operations per primary: 1M / 20 = 50,000 per second; well within the range a tuned in-memory server can handle, leaving headroom.
  • Network: 1M x 1 KB = about 1 GB/s across the cluster, about 50 MB/s per primary.
  • Item count: 1 TB / 1 KB = 1 billion keys; per-key overhead (pointers, expiry, LRU fields) of about 50 to 100 bytes adds 50 to 100 GB, which must be included in sizing.

API

GET key -> value | miss SET key value [EX seconds] [NX | XX] DEL key MGET k1 k2 k3 ... batched read CAS key expected_version new_value

Data model on each node

  • A hash table from key to entry: value, expires_at, version, LRU or LFU metadata.
  • Memory allocated in size classes (slab allocation) to limit fragmentation.
  • Expiry: lazily on access plus a background sampler that removes expired keys.
  • Eviction: approximate LRU by sampling a few keys and evicting the oldest, avoiding a global linked list.

High-level design

mermaid
flowchart LR
  A[App server + cache client] -->|"hash of key, then slot, then node"| N1[Primary 1]
  A --> N2[Primary 2]
  A --> N3[Primary ...20]
  N1 --> R1[Replica 1]
  N2 --> R2[Replica 2]
  CM[(Cluster map / config service)] -. updates .-> A
  CM -. health, failover .-> N1

Partitioning

Use 16,384 fixed hash slots (as Redis Cluster does): slot = CRC16(key) mod 16384, and assign slot ranges to nodes. Adding a node moves some slots, not individual keys by recomputation, and migration can proceed slot by slot. Consistent hashing with virtual nodes gives the same property and is common in client-side Memcached setups.

Clients cache the slot map and send requests straight to the right node (one network hop, no proxy). If a slot moved, the node replies with a redirect and the client refreshes its map. A proxy layer (Twemproxy or Envoy) is an alternative that keeps clients simple at the cost of an extra hop.

Replication and failover

Each primary streams writes asynchronously to its replica. A failure detector (gossip among nodes, or a separate coordinator) marks a primary down after missing heartbeats, promotes the replica and updates the cluster map. Asynchronous replication means the last few writes can be lost; for a cache that is acceptable. Require agreement from a majority of observers before failover to avoid split brain on a network blip.

Bottlenecks and trade-offs

  • Hot keys: one key on one node can exceed its capacity. Use client-side local caching for a few seconds or replicate the key under several names.
  • Big values: a 5 MB value blocks a single-threaded server and saturates the network; cap value size and store big objects elsewhere.
  • Thundering herd after failover: a cold replacement causes misses that hit the database. Keep replicas warm (they already are, with replication) and add request coalescing in clients.
  • Multi-get fan-out: an MGET of 100 keys may touch 20 nodes; the slowest node decides latency. Group keys that are read together using hash tags ({user:77}:profile, {user:77}:settings share a slot).
  • Consistency: the cache can serve stale data after the database changes; invalidation is the application's job (TTL plus delete on write).
  • Replication vs memory: a replica doubles memory cost. Some teams skip replicas for pure caches and accept a hit-ratio dip; that is fine only if the database can absorb the extra misses.

By level

Fresher: Explain splitting keys across several cache servers by hashing, LRU eviction and TTL, and what happens when one server fails. A fresher should say that a cache is not the source of truth.

Mid: Size the cluster, choose hash slots or consistent hashing, describe client routing, replication and failover, and per-node memory layout. Expect memory sizing that includes per-key overhead.

Senior: Cover slot migration, split-brain protection, hot keys, big values, cross-zone placement, warm-up after failure, cost of replicas versus database headroom, and operational tooling. Expect protection against split brain during failover.

Key points

  • Partition with hash slots or consistent hashing; clients route with a cached map
  • Size by memory including per-key overhead, then check ops per node
  • 1 TB at 50 GB usable per node needs about 20 primaries at about 50k ops/s each
  • Async replicas plus majority-based failure detection for fast failover
  • Hot keys, big values and multi-get fan-out are the main bottlenecks

Common mistakes

  • Ignoring per-key memory overhead and fragmentation in sizing
  • Treating the cache as durable storage
  • Using hash mod N and remapping most keys on scale-out
  • Allowing very large values on a single-threaded engine

Follow-ups

  • How would you migrate a slot to a new node without errors?
  • What happens to in-flight writes during failover?
  • How would you support a 2 TB working set next year?

Tips

  • Size memory first, then operations, then network
  • Explain how a client finds the right node
  • State clearly that the cache is not the source of truth

Evaluation rubric

  • Requirements with latency and failure behaviour
  • Correct sizing math with overhead
  • Partitioning, routing, replication and eviction designed coherently
  • Bottlenecks and trade-offs covered
44.system-design-0044Hardsenior

Design a web-scale search engine: crawling, indexing and answering queries over 10 billion pages.

A crawler with a polite URL frontier fetches pages, deduplicates them and stores their text; an indexing pipeline builds a compressed inverted index split into document-partitioned shards; a query service sends each query to all shards, each returns its local top results, and an aggregator merges and re-ranks them. Recrawling 10 billion pages every 30 days means about 3,900 fetches per second, and a result cache in front of the index absorbs repeat queries.

Full answer

Requirements

Functional:

  • Crawl the web, respecting robots.txt and per-site politeness.
  • Index page text, titles and links; answer keyword queries with ranked results and snippets.
  • Refresh pages; popular or fast-changing pages more often.

Non-functional:

  • Query latency target around 200 ms at p99.
  • High availability for queries; indexing can lag by hours or days.
  • Scale to tens of billions of documents and high query volume.

Capacity estimates

Assumptions: 10B pages; average 100 KB of HTML and 10 KB of extracted text per page; compressed inverted index about 30% of text size; full recrawl every 30 days; 5B queries per day with peak factor 2; 50M documents per index shard.

  • Raw HTML: 10B x 100 KB = 1 PB (keep compressed, or only the latest copy).
  • Extracted text: 10B x 10 KB = 100 TB; index: about 30 TB.
  • Crawl rate: 10B / 30 days = about 333M pages per day = about 3,900 per second; bandwidth 3,900 x 100 KB = about 390 MB/s, about 3.1 Gbps.
  • Queries: 5B / 86,400 = about 58,000 per second; about 116,000 at peak.
  • Shards: 10B / 50M = 200 shards; each query fans out to all 200, so total shard lookups are 200 x the queries that miss the result cache. Each shard is replicated many times to carry that load.

API

GET /search?q=binary+search+tree&lang=en&cursor=... 200 {"results": [{"url", "title", "snippet", "score"}], "next_cursor": "...", "took_ms": 84}

Data model

  • Document store: doc_id -> url, title, extracted text, fetch time, content hash, quality signals.
  • Inverted index per shard: term -> postings list [(doc_id, term frequency, positions)], sorted by doc_id and compressed with delta encoding.
  • Link graph: doc_id -> outlinks, used for link-based authority scores.
  • URL frontier: queue of URLs to crawl, with priority and next allowed fetch time per host.

High-level design

mermaid
flowchart LR
  F[URL frontier] --> CR[Crawler fleet]
  CR --> DED[Dedup: URL Bloom filter + content hash]
  DED --> DS[(Document store)]
  DS --> IDX[Indexing pipeline]
  IDX --> SH[(Index shards x 200, replicated)]
  CR --> LX[Link extractor] --> F
  U[User] --> QS[Query service]
  QS --> RC[(Result cache)]
  QS --> AGG[Aggregator]
  AGG --> SH
  AGG --> RR[Re-ranker + snippets]

Crawling

The frontier holds billions of URLs, partitioned by host so one crawler owns each host and can enforce a delay between requests. Seen URLs are checked against a Bloom filter (billions of entries in a few GB) before enqueueing. Near-duplicate pages are detected with a similarity hash (for example SimHash) so mirrors are not indexed twice. Recrawl frequency is set per URL from how often it has changed and how important it is.

Indexing

Tokenise text (lowercase, language-specific stemming), build postings per batch of documents, and merge batches into shard segments. New documents land in small fresh segments merged in the background, which is how near-real-time indexing works in Lucene-based engines.

Document partitioning (each shard holds all terms for a subset of documents) is the usual choice: shards are independent and balanced. Term partitioning (each shard holds some terms for all documents) makes multi-term queries cross shards and creates hot shards for common words.

Query path

  1. Check the result cache; popular queries are answered directly.
  2. Parse and normalise the query, then send it to one replica of every shard.
  3. Each shard intersects postings lists for the terms, scores matches cheaply (BM25 plus static quality scores), and returns its top 100 or so.
  4. The aggregator merges, then a more expensive learned ranking model re-ranks the top few hundred.
  5. Snippets are generated from the document store for the final page.

Bottlenecks and trade-offs

  • Tail latency: with 200 shards, the slowest shard sets query latency. Use hedged requests (send to a second replica if the first is slow) and return partial results after a deadline.
  • Index tiers: keep a smaller, heavily replicated tier with the most important documents; query the full tier only when the first tier gives too few good results. This cuts cost a lot.
  • Freshness vs cost: frequent recrawls and segment merges cost bandwidth and CPU; prioritise by change rate and importance.
  • Two-phase ranking balances quality and latency: cheap scoring for millions of candidates, expensive models for hundreds.
  • Spam and quality: link farms and duplicate content need dedicated signals; without them, ranking quality collapses regardless of infrastructure.

By level

Fresher: Explain what an inverted index is, how a crawler finds pages, and how a query looks up terms and ranks pages. A fresher should be able to describe a postings list for one word.

Mid: Estimate crawl, storage and query load, design the frontier, index shards and query fan-out, and describe two-phase ranking. Expect the reason document partitioning is preferred.

Senior: Address tail latency at high fan-out, index tiering, freshness strategies, spam resistance, ranking evaluation, and the cost of replicas across regions. The senior answer manages tail latency across hundreds of shards.

Key points

  • Crawler with a host-partitioned, polite frontier and Bloom-filter URL dedup
  • Document-partitioned inverted index shards with compressed postings
  • Scatter-gather query: every shard returns local top-k, aggregator merges and re-ranks
  • 10B pages every 30 days is about 3,900 fetches per second
  • Tail latency, index tiers and two-phase ranking manage cost and speed

Common mistakes

  • Proposing a SQL LIKE query for search
  • Term-partitioning the index without discussing hot terms
  • Ignoring robots.txt and per-host politeness
  • Forgetting that fan-out to many shards makes tail latency the bottleneck

Follow-ups

  • How would you add a news section that must index within a minute?
  • How do you generate snippets quickly?
  • How would you evaluate whether a ranking change is better?

Tips

  • Split the answer into crawl, index and serve
  • Explain why document partitioning is preferred
  • Mention the result cache and hedged requests

Evaluation rubric

  • Requirements for all three subsystems
  • Correct estimates for storage, crawl rate and queries
  • Correct inverted index and scatter-gather design
  • Discusses tail latency, freshness, ranking and cost trade-offs
45.system-design-0045Hardsenior

Design a distributed lock service. How do you guarantee safety when a lock holder pauses or crashes?

Build the lock service on a consensus store such as etcd or ZooKeeper: a lock is a key created only if absent and tied to a lease that expires unless the holder renews it. Every grant returns a monotonically increasing fencing token, and the protected resource rejects requests carrying an older token, which keeps things safe even if a paused holder wakes up after its lease expired.

Full answer

Requirements

Functional:

  • acquire(name, ttl), renew, release; optional blocking acquire with a wait timeout.
  • Only one holder per lock name at a time.

Non-functional:

  • Safety: two clients must never both act as the holder in a way that corrupts data.
  • Liveness: a crashed holder's lock is released automatically.
  • Highly available; acquire latency of a few milliseconds inside a region.

Capacity estimates

Assumptions: 20,000 lock acquisitions per second at peak (for example, per-student job locks in a grading pipeline); each lock lives 2 seconds on average with one renewal; a 3-node consensus cluster sustains about 10,000 writes per second (an assumption that depends heavily on disks and network; benchmark it).

  • Writes per lock lifecycle: acquire + renew + release = 3 consensus writes.
  • Total: 20,000 x 3 = 60,000 writes per second.
  • At 10,000 per cluster: 6 clusters minimum; plan 8 for headroom. Partition lock names across clusters by hash. A single lock always lives on one cluster, so safety is unaffected by partitioning.
  • Storage is tiny: active locks at any moment = 20,000 x 2 s = 40,000 keys (Little's Law), a few MB.

These numbers show that consensus throughput, not storage, is the limiting resource, and that heavy lock users should consider partitioning work so fewer locks are needed.

API

POST /v1/locks/{name}/acquire {"ttl_ms": 5000, "wait_ms": 1000} -> 200 {"lease_id": "L77", "fencing_token": 918273} or 409 if not acquired in time POST /v1/locks/{name}/renew {"lease_id": "L77"} -> 200 | 410 (lease expired) POST /v1/locks/{name}/release {"lease_id": "L77"} -> 204

Most teams use the client libraries of etcd or ZooKeeper directly rather than wrapping them in a service; the design is the same.

Data model

  • Key /locks/{name} -> {owner_id, lease_id}.
  • The fencing token is the store's revision number at creation (etcd's mod_revision or ZooKeeper's zxid), which increases with every write in the cluster.
  • Waiters: in ZooKeeper, each waiter creates a sequential ephemeral node under /locks/{name}/ and watches only the node just before it; in etcd, waiters watch the key before theirs by revision. This gives a fair queue and avoids waking all waiters at once.

High-level design

mermaid
flowchart LR
  C1[Client A] --> LS[Lock client library]
  C2[Client B] --> LS
  LS -->|"hash of lock name"| E1[(Consensus cluster 1: 3 nodes)]
  LS --> E2[(Consensus cluster 2)]
  LS --> EN[(Cluster ...8)]
  C1 -- write + fencing token --> RES[(Protected resource)]
  RES -. rejects older tokens .-> C2

Why fencing tokens matter

Client A acquires the lock with token 33, then suffers a 10-second garbage collection pause. Its 5-second lease expires; client B acquires with token 34 and writes to the storage. A wakes up, still believing it holds the lock, and sends a write. Without fencing, A overwrites B's work. With fencing, the storage remembers the highest token it has seen (34) and rejects A's write carrying 33. The lock service alone cannot prevent this because A's pause happened outside its control.

Redis-based locks

SET lock:name <random-value> NX PX 5000 on a single Redis node is simple and fast, and release must use a script that deletes only if the value matches. It is fine when the lock is an efficiency optimisation (avoid doing the same work twice) and an occasional double holder is harmless. With asynchronous replication, a failover can lose the lock and grant it again. The multi-node Redlock algorithm is debated because it relies on timing assumptions and provides no fencing token; for correctness-critical locks, use a consensus store plus fencing.

Bottlenecks and trade-offs

  • The bottleneck is consensus write throughput and latency, shown in the estimate above; renewals are a large share of it, so longer leases with fencing reduce load.
  • Short TTLs release crashed holders quickly but risk expiry during long pauses; long TTLs are safer for the holder but delay recovery. Renew at about one third of the TTL.
  • Consensus stores give safety at the cost of write throughput and a few milliseconds per operation.
  • Often the best lock is no lock: partition work by key so only one worker owns each partition, or use database row locks and conditional updates where the data already lives.

By level

Fresher: Explain why a lock needs an expiry, what happens if a holder crashes, and that only one client should hold it at a time. A fresher should know that releasing someone else's lock is a bug.

Mid: Design acquire, renew and release on etcd or ZooKeeper with leases and fair waiting, and estimate consensus write load. Expect the consensus write estimate to set the cluster count.

Senior: Explain fencing tokens and the pause problem, critique Redlock, partition across clusters, discuss cross-region locks and recommend designs that avoid locks altogether. Expect the pause scenario to be explained with fencing token numbers.

Key points

  • Locks need leases so crashed holders release automatically
  • Use a consensus store (etcd, ZooKeeper) for correctness-critical locks
  • Fencing tokens let the resource reject stale holders after pauses
  • Consensus write throughput is the scaling limit; partition lock names across clusters
  • Single-node Redis locks suit efficiency locks, not safety-critical ones

Common mistakes

  • Assuming a lease guarantees the holder has not been paused past expiry
  • Releasing a lock without checking ownership
  • Using Redis with async replication for correctness-critical locks
  • Having all waiters watch the same key and wake together

Follow-ups

  • Walk through the GC-pause scenario with and without fencing
  • How would the storage system check fencing tokens?
  • How would you design a lock that spans two regions?

Tips

  • Separate safety from liveness in the requirements
  • Tell the pause story with concrete token numbers
  • Suggest avoiding locks through partitioning where possible

Evaluation rubric

  • Safety and liveness requirements explicit
  • Throughput estimate drives cluster count
  • Correct use of leases, consensus and fencing tokens
  • Balanced discussion of Redis locks and TTL trade-offs
46.system-design-0046Hardsenior

Design a recommendation system for a learning platform that suggests courses and videos to 100 million users.

Use a multi-stage pipeline: candidate generation pulls a few hundred items from several sources (embedding nearest neighbours, co-viewed items, popular in the user's segment), a ranking model scores them with user, item and context features from a feature store, and a re-ranking step applies diversity and business rules. Models train offline on interaction logs; features update in near real time. At about 23,000 requests per second, ranking 500 candidates each means about 11.5 million item scores per second on average.

Full answer

Requirements

Functional:

  • Personalised rows on the home page ("Continue learning", "Recommended for you", "Because you watched Python basics").
  • Similar items on a course page.
  • React within minutes to what the user just did.

Non-functional:

  • Server latency under about 200 ms at p99 for a recommendation call.
  • High availability with graceful fallback to popular items.
  • Measurable: every change is A/B tested on engagement and completion, not just clicks.

Capacity estimates

Assumptions: 100M users, 50M DAU; 10M items (courses, lessons, videos); 2B recommendation requests per day (several surfaces per session); 50 interaction events per active user per day at 200 bytes each; 256-dimensional float32 embeddings; 500 candidates ranked per request; peak factor 2.

  • Requests: 2B / 86,400 = about 23,000 per second; about 46,000 at peak.
  • Ranking load: 23,000 x 500 = 11.5M scored items per second on average; 23M at peak. This sets the size of the ranking fleet and is why the ranking model must be cheap or batched on accelerators.
  • Embeddings: items 10M x 256 x 4 B = 10.24 GB; users 100M x 256 x 4 B = 102.4 GB. Item embeddings fit in memory for an approximate nearest neighbour (ANN) index on each candidate server.
  • Events: 50M x 50 x 200 B = 500 GB per day into the log.

API

GET /v1/recommendations?user_id=77&surface=home&limit=20&context=mobile 200 {"items": [{"item_id": "c-310", "reason": "because_you_watched", "score": 0.82}], "request_id": "r-5a1", "model_version": "rank-2026-12-01"} POST /v1/events {"user_id": 77, "item_id": "v-88", "type": "completed", "ts": "..."}

request_id links later clicks back to what was shown, which training needs.

Data model

  • Interaction log (Kafka, then a data lake): user, item, event type, timestamp, surface, request ID.
  • Feature store: offline tables for training, plus an online key-value store for serving (user: recent topics, skill level, language; item: popularity, completion rate, freshness; cross features).
  • Item catalogue: metadata, topics, difficulty, language, availability.
  • Model registry: versioned models and embedding tables.

High-level design

mermaid
flowchart LR
  APP[App] --> RS[Recommendation service]
  RS --> CG1[ANN over item embeddings]
  RS --> CG2[Co-view / co-enrol lists]
  RS --> CG3[Popular in segment]
  RS --> FS[(Online feature store)]
  RS --> RK[Ranking model servers]
  RS --> RR[Re-rank: diversity, rules]
  APP --> EV[Event API] --> K[Kafka]
  K --> STR[Stream features] --> FS
  K --> DL[(Data lake)] --> TR[Daily training] --> MR[(Model registry)]
  MR --> RK
  MR --> CG1

Request path

  1. Candidate generation (about 30 ms budget): look up the user's embedding (or compute it from recent activity), query the ANN index for the nearest few hundred items, add co-viewed items for the last few things watched, add popular items for the user's language and level. Deduplicate; remove items already completed.
  2. Ranking (about 50 ms): fetch features in one batched call, score all candidates with a model that predicts, for example, probability of starting and completing.
  3. Re-ranking (about 10 ms): enforce diversity (not ten Python videos), freshness, and rules (do not recommend paid content to users in regions where it is unavailable).
  4. Log what was shown with the request ID.

Cold start

New users: use onboarding choices, language and device to choose segment-popular items, then adapt quickly from first clicks via streaming features. New items: use content embeddings from title, description and transcript, and give them controlled exploration traffic.

Bottlenecks and trade-offs

  • Ranking cost grows with candidates x requests; reduce candidates, distil the model, or precompute recommendations for less active users in a nightly batch and serve from a cache.
  • Freshness vs stability: streaming features react within minutes; full retraining daily keeps models stable. Real-time retraining adds complexity for modest gains in most products.
  • Feedback loops: recommending only what is already popular hides new content; reserve a share of slots for exploration.
  • Fallbacks: if the ranking service times out, return candidate-stage results or precomputed popular lists rather than an error.
  • Metrics: optimise for long-term value (course completion, return visits), since pure click-through optimisation tends to favour clickbait titles.

By level

Fresher: Explain recommending items based on what similar users watched, and the idea of first finding candidates then sorting them. A fresher can describe the funnel from many items to a short list.

Mid: Design candidate generation, feature store and ranking with latency budgets, estimate load and embedding size, and handle cold start. Expect latency budgets per stage.

Senior: Cover training-serving skew, feedback loops and exploration, model rollout and A/B testing, cost of ranking at scale, fallbacks and long-term metric choice. The senior answer explains how impressions are logged for unbiased training.

Key points

  • Multi-stage: candidate generation, ranking, re-ranking
  • Several candidate sources including ANN over embeddings and co-occurrence
  • Online feature store for serving, offline tables for training
  • Ranking load = requests x candidates, about 11.5M scores per second here
  • Handle cold start, feedback loops and fallbacks explicitly

Common mistakes

  • Scoring the entire catalogue for every request
  • Ignoring cold start for new users and items
  • Not logging impressions with a request ID, so training data is biased
  • Optimising only for clicks

Follow-ups

  • How would you evaluate a new ranking model offline and online?
  • How would you make recommendations react to a video the user finished a minute ago?
  • How would you avoid recommending content the user cannot access?

Tips

  • Draw the funnel with candidate counts at each stage
  • Give latency budgets per stage
  • Mention cold start and exploration unprompted

Evaluation rubric

  • Requirements include latency, fallback and measurement
  • Capacity math for requests, ranking load and embeddings
  • Multi-stage architecture with offline and online parts
  • Trade-offs on cost, freshness, feedback loops and metrics
47.system-design-0047Mediummid

Design a distributed task queue like Celery, Sidekiq or Amazon SQS for background jobs with retries, delays and priorities.

Producers enqueue tasks into a durable, partitioned store; workers lease tasks with a visibility timeout, process them and acknowledge; tasks whose lease expires become visible again, so delivery is at least once and handlers must be idempotent. Failed tasks retry with exponential backoff and move to a dead-letter queue after a limit. Delays and priorities are handled with an available-at time and priority ordering. 100M tasks per day averages about 1,200 per second, with bursts to around 10,000.

Full answer

Requirements

Functional:

  • Enqueue a task (type, payload) to a named queue, optionally delayed ("send reminder in 2 hours") or with a priority.
  • Workers fetch, process and acknowledge tasks; failed tasks retry with backoff.
  • Dead-letter queue (DLQ) for tasks that keep failing; operators can inspect and replay them.
  • Visibility into queue depth, age of the oldest task and failure rates.

Non-functional:

  • Durable: an accepted task is never lost.
  • At-least-once execution; duplicates are rare but possible.
  • Scales horizontally for bursts (for example, end-of-term report generation).

Capacity estimates

Assumptions: 100M tasks per day; bursts up to 10,000 enqueues per second; average payload 2 KB; completed tasks kept 7 days for debugging; average processing time 500 ms.

  • Average rate: 100M / 86,400 = about 1,160 per second; bursts are about 9x the average, so the queue must buffer them.
  • Storage: 100M x 2 KB = 200 GB per day; 7 days = 1.4 TB.
  • Workers: by Little's Law, sustaining 1,160 tasks per second at 0.5 s each needs about 580 tasks running at once; at 10 concurrent tasks per worker process, about 58 workers on average. During a burst the backlog grows and drains as workers autoscale.

API

enqueue(queue="reports", type="build_report_card", payload={...}, delay_s=0, priority=5, idempotency_key="term2-student-77") -> task_id lease(queue="reports", max_tasks=10, visibility_timeout_s=60) -> [{task_id, lease_token, payload, attempt}] ack(task_id, lease_token) nack(task_id, lease_token, retry_after_s) # explicit failure extend(task_id, lease_token, visibility_timeout_s) # long-running task heartbeat

Data model

tasks: task_id, queue, partition, state (ready, leased, done, dead), priority, available_at, lease_owner, lease_until, attempts, max_attempts, payload, idempotency_key (unique per queue), last_error. Index on (queue, partition, state, priority, available_at) so the next ready task is an index seek.

High-level design

mermaid
flowchart LR
  P[Producers] --> API[Queue API]
  API --> ST[(Partitioned task store)]
  W1[Worker pool A] -->|lease / ack| API
  W2[Worker pool B] -->|lease / ack| API
  REAP[Lease reaper] --> ST
  API --> DLQ[(Dead-letter queue)]
  API --> MET[Metrics: depth, oldest age, failures]

Leasing safely

With a relational store, a lease is one statement (PostgreSQL syntax, shown for illustration, not run here):

sql
UPDATE tasks
SET state = 'leased', lease_owner = $1,
    lease_until = now() + interval '60 seconds', attempts = attempts + 1
WHERE task_id IN (
  SELECT task_id FROM tasks
  WHERE queue = $2 AND state = 'ready' AND available_at <= now()
  ORDER BY priority DESC, available_at
  LIMIT 10
  FOR UPDATE SKIP LOCKED
)
RETURNING task_id, payload, attempts;

SKIP LOCKED lets many workers lease concurrently without blocking on each other's rows. A reaper sets expired leases (lease_until < now()) back to ready. Ack checks the lease_token so a slow worker whose lease already expired cannot acknowledge a task that another worker now holds.

For higher throughput than one database can give, split each queue into partitions on different shards (workers lease from partitions in rotation), or build on a broker such as SQS, RabbitMQ or Kafka and keep only scheduling and DLQ logic in your own service.

Retries, delays and priorities

  • Retry: on failure set available_at = now() + backoff(attempt) with exponential backoff and jitter; after max_attempts, state becomes dead and the task is copied to the DLQ with its last error.
  • Delay: just a future available_at. For very long delays, a separate timer store (time-bucketed) moves tasks into the ready set when due.
  • Priority: ordering by priority within a queue, or separate queues per priority with workers weighted toward high priority so low priority is not starved forever.

Bottlenecks and trade-offs

  • Poison tasks that crash workers are caught by the attempt limit.
  • Visibility timeout too short causes duplicate processing of slow tasks; too long delays recovery after a worker crash. Use extend heartbeats for long tasks.
  • Exactly-once is not offered; use idempotency keys and idempotent handlers (for example, "generate report card for term 2 if not already generated").
  • Strict FIFO across many workers conflicts with throughput; offer ordering only within a partition key when needed.
  • Database-backed vs broker-backed: a database queue is transactional with your business data (enqueue in the same transaction as the change) but limited in throughput; a broker scales further but needs the outbox pattern for the same guarantee.

By level

Fresher: Explain producers, a queue and workers, why tasks are acknowledged after processing, and why failed tasks are retried. A fresher should explain what a dead-letter queue is for.

Mid: Design leasing with visibility timeouts, retries with backoff, DLQ, delays and priorities, and estimate worker count and storage. Expect Little's Law to size the worker pool.

Senior: Address partitioning for throughput, fairness across tenants, transactional enqueue with the outbox, observability and autoscaling on queue age, and choosing between database and broker backends. Expect a fairness plan so one tenant cannot starve others.

Key points

  • Lease with visibility timeout; expired leases become visible again
  • At-least-once delivery, so handlers must be idempotent
  • Retries with exponential backoff and jitter, then a dead-letter queue
  • Delays via available_at; priorities via ordering or separate queues
  • Little's Law sizes the worker pool

Common mistakes

  • Deleting tasks on fetch, which loses them if the worker crashes
  • Letting an expired lease holder acknowledge the task
  • Retrying forever without a DLQ
  • Promising exactly-once execution

Follow-ups

  • How would you guarantee a task is enqueued only if the database transaction commits?
  • How would you support cron-style recurring tasks?
  • How do you keep one tenant from starving others?

Tips

  • Explain the lease and visibility timeout clearly
  • Size workers with Little's Law
  • Mention idempotency as the consumer's responsibility

Evaluation rubric

  • Requirements include durability, retries, delays and observability
  • Correct throughput, storage and worker math
  • Correct leasing mechanics and failure handling
  • Trade-offs on timeouts, ordering and storage choice
48.system-design-0048Mediummid

Design a centralised logging system that collects, stores and searches logs from 5,000 servers.

Run an agent on each server that tails logs, adds metadata and ships batches to a durable buffer such as Kafka; stream processors parse and enrich them, then write recent logs to a search index for fast queries and all logs in compressed form to object storage for long retention. At 500,000 lines per second of 300 bytes, raw volume is about 150 MB/s or 13 TB per day, so retention tiers and sampling decide the cost.

Full answer

Requirements

Functional:

  • Collect application and system logs from every server and container.
  • Search by time range, service, host, level, request ID and free text; live tail.
  • Alerts on patterns (error rate spikes); retention of 7 days hot and 90 days cold.

Non-functional:

  • Logging must never slow down or crash the applications.
  • Ingestion survives spikes and backend outages without losing data (or with clearly bounded loss).
  • Searches over recent data return in seconds.

Capacity estimates

Assumptions: 5,000 servers; 100 lines per second each on average; 300 bytes per line; compression ratio about 10x for cold storage; hot index size roughly equal to raw size per replica, with 2 replicas.

  • Lines: 5,000 x 100 = 500,000 per second.
  • Raw bytes: 500,000 x 300 B = 150 MB/s; per day 150 MB/s x 86,400 = about 12.96 TB.
  • Hot index: 12.96 TB x 7 days x 2 replicas = about 181 TB.
  • Cold archive: about 1.3 TB per day compressed; 90 days = about 117 TB in object storage.
  • Spikes: an incident can multiply error logs 5 to 10x; the buffer must hold that for hours.

181 TB of hot index is the expensive part, which is why many teams index fewer fields or use a label-indexed store such as Grafana Loki that keeps logs compressed and only indexes labels.

API

Ingestion (agent to collector): batched, compressed, over HTTP or gRPC.

POST /v1/logs:batch (gzip) [{"ts":"2026-12-04T10:15:02.118Z","service":"payments","host":"pay-17","level":"ERROR", "trace_id":"7f3a...","msg":"provider timeout","attrs":{"provider":"x","latency_ms":3021}}]

Query:

GET /v1/search?q=level:ERROR AND service:payments AND msg:"timeout"&from=...&to=...&limit=200 GET /v1/tail?service=payments (server-sent events)

Data model

  • Structured JSON log events with required fields (ts, service, env, host, level, trace_id, msg) and free-form attrs.
  • Hot store: one index per day per environment (time-based indices make deletion cheap: drop the whole index).
  • Cold store: compressed files partitioned by date/service/hour in object storage, readable by batch query engines.

High-level design

mermaid
flowchart LR
  APP[App writes stdout / file] --> AG[Agent on host: Fluent Bit / Vector]
  AG --> K[Kafka: logs topic, partitioned]
  K --> PR[Stream processors: parse, enrich, redact]
  PR --> ES[(Search index: 7 days)]
  PR --> OS[(Object storage: 90 days)]
  PR --> AL[Alerting rules]
  UI[Log UI / query API] --> ES
  UI --> OS

Key design points

  • Agents write to a local disk buffer and send asynchronously in batches. If the pipeline is down, they buffer up to a limit, then drop the lowest-priority logs (debug first) rather than block the application.
  • Kafka decouples producers from the indexers. With replication factor 3 and producer compression, it holds a few hours to a day of logs so an index outage does not lose data.
  • Processing parses unstructured lines, adds Kubernetes or host metadata, and redacts secrets and personal data (card numbers, passwords, emails) before anything is stored.
  • Indexing writes in bulk; time-based indices roll over daily; old indices are deleted or moved to cheaper nodes.
  • Correlation: a trace_id in every log line links logs to distributed traces.

Bottlenecks and trade-offs

  • Cost vs searchability: full-text indexing of everything is fast to query but expensive; label-only indexing is cheap but slower for free-text search. Many teams index errors and key services fully and archive the rest.
  • Sampling: keep all errors, sample a percentage of debug and info logs from high-volume services.
  • Noisy neighbours: one service logging in a loop can flood the pipeline; enforce per-service quotas at the agent or collector.
  • Ordering: logs from different hosts arrive out of order; sort by event timestamp at query time and accept clock skew of a few milliseconds.
  • Reliability: logs are best-effort compared with business data; state the acceptable loss under extreme overload (for example, debug logs may be dropped) rather than promising zero loss at any cost.

By level

Fresher: Describe agents collecting logs from servers, a central store, and searching by time and service. A fresher should know that logging must not slow the application.

Mid: Estimate volume and storage, add a Kafka buffer, design time-based indices, retention and structured log format. Expect volume math in MB per second and TB per day.

Senior: Optimise cost with tiering, sampling and label indexing, enforce quotas, handle incident spikes, ensure privacy and compliance, and integrate with traces and metrics. The senior answer cuts cost without losing error visibility.

Key points

  • Agent with local buffer, then Kafka, then processors, then hot index and cold object storage
  • 500k lines per second of 300 B is 150 MB/s, about 13 TB per day
  • Hot index size dominates cost; tier, sample and index selectively
  • Redact secrets and personal data before storage
  • Logging must never block the application

Common mistakes

  • Sending logs synchronously from the request path
  • Indexing every field of every log for 90 days
  • Storing passwords or personal data in logs
  • No per-service quotas, so one noisy service floods the pipeline

Follow-ups

  • How would you find all logs for one failed checkout across 12 services?
  • How would you cut cost by half without losing error visibility?
  • How do you handle a 10x log spike during an incident?

Tips

  • Size the pipeline in MB/s and TB per day first
  • Separate hot and cold paths
  • Mention redaction and trace IDs

Evaluation rubric

  • Requirements include safety for applications and retention
  • Correct volume and storage math
  • Buffered, decoupled pipeline with hot and cold tiers
  • Cost, sampling, quotas and reliability trade-offs
49.system-design-0049Mediummid

Design a distributed counter service for likes and view counts that handles viral spikes of a million increments per minute on one item.

Separate exact counts that come from unique facts (a like is a row keyed by user and post) from high-volume approximate counts (views). Absorb increments as events, aggregate them in memory per key for a second, and apply batched increments to a counter store; for very hot keys, split the counter into sub-counters summed on read. Serve reads from a cache, and use HyperLogLog for approximate unique counts at about 12 KB per counter.

Full answer

Requirements

Functional:

  • Increment and read counters: views, likes, shares per post or video.
  • Unique viewers per video (approximate is fine).
  • Likes are per user: a user can like once and unlike.

Non-functional:

  • Handle 10 billion increments per day overall and a viral item receiving 1M increments per minute.
  • Reads are fast and frequent (every time a post is shown).
  • View counts may lag a few seconds and be slightly approximate; like state for a user must be correct.

Capacity estimates

Assumptions: 10B increments per day overall; one viral item at 1M increments per minute; 1B counters; about 50 bytes per counter row; a single Redis key handles in the order of tens of thousands of increments per second on one core (an assumption; it shares that core with other keys).

  • Overall rate: 10B / 86,400 = about 116,000 increments per second.
  • Viral item: 1M / 60 = about 16,700 per second on one key, which would be the dominant load on its shard.
  • Counter storage: 1B x 50 B = 50 GB, small.
  • Unique counts: a Redis HyperLogLog uses up to 12 KB per key with a standard error of 0.81%; for 10M videos that is up to 120 GB, so keep HLLs only for items that need them, or merge per day.

API

POST /v1/counters/{entity}/{id}/increment {"field": "views", "by": 1} -> 202 GET /v1/counters/{entity}/{id} -> {"views": 1048576, "likes": 20311} PUT /v1/posts/{id}/likes/me -> 200 (idempotent like) DELETE /v1/posts/{id}/likes/me -> 204 (unlike)

Data model

  • likes(post_id, user_id, created_at), primary key (post_id, user_id): the uniqueness makes like and unlike idempotent. The like count is maintained from changes to this table, not from raw button taps.
  • counters(entity, id, field, value) in a store that supports atomic increments (Redis, Cassandra counters, or a SQL table updated in batches).
  • Optional counter_shards(entity, id, field, shard_no, value) for hot keys.

High-level design

mermaid
flowchart LR
  C[Clients] --> API[Counter API]
  API --> K[Kafka: increment events, keyed by item]
  K --> AGG[Aggregators: sum per key per second]
  AGG --> CS[(Counter store)]
  CS --> RC[(Read cache)]
  API --> RC
  API --> LK[(Likes table)]
  LK -. change events .-> K

Write path

  1. The API publishes an increment event, keyed by item ID so all events for one item go to one Kafka partition and one aggregator.
  2. Each aggregator keeps an in-memory map {key: pending_count} and every second (or every 10,000 events) writes one INCRBY key n per key, then commits its Kafka offsets.
  3. A viral item at 16,700 increments per second becomes one write per second to the store.

If the aggregator crashes after writing but before committing offsets, some events are replayed and counted twice. For views that small error is acceptable; to remove it, store the last applied offset per partition together with the counts.

Hot counters without a log

Where increments must go straight to Redis, split the key into N sub-counters (views:v42:0 to views:v42:15). Each increment picks a random sub-counter; a read sums all of them (one MGET) and caches the result for a second. Sixteen sub-counters cut per-key load by 16x, and spreading them across slots spreads load across nodes.

Read path

Counts are read far more than written. Serve from a cache with a short TTL (1 to 5 seconds). Show rounded numbers for large values ("1.2M"), which also hides small lag.

Bottlenecks and trade-offs

  • Bottleneck: the hot key on one shard or one Kafka partition; aggregation fixes the store side, and an extremely hot item can be split across several partitions with a salted key.
  • Exact vs approximate: likes come from a unique table and are exact; views tolerate small error in return for much cheaper writes.
  • Freshness vs cost: a 1-second aggregation window means counts lag by about a second but cut writes by orders of magnitude for hot items.
  • Sub-counters spread writes but make reads more expensive; use them only for keys detected as hot.
  • Fraud: view counts that matter (monetisation) need filtering of bots and repeated views before counting, usually in the stream processor.

By level

Fresher: Explain why updating one row for every view is slow for popular posts, and the idea of adding up increments and writing them together. A fresher should know that likes need uniqueness per user.

Mid: Design the event pipeline with per-key aggregation, sub-counters for hot keys, idempotent likes, and caching of reads. Expect the per-minute spike converted into per-second load on one key.

Senior: Cover exactly-once options with offset storage, reconciliation from raw events, fraud filtering, multi-region counting and memory cost of unique counting at scale. Expect an option for exactly-once counting and its cost.

Key points

  • Exact counts come from unique facts (a likes table); approximate counts can be aggregated
  • Key events by item, aggregate in memory, write batched increments
  • Sub-counters spread load for hot keys and are summed on read
  • HyperLogLog gives unique counts at up to 12 KB with about 0.81% error
  • Cache reads with short TTLs and accept slight lag

Common mistakes

  • Doing one database UPDATE per view on a viral item
  • Counting likes by incrementing on every tap without uniqueness
  • Claiming exact counts while replaying events at least once
  • Storing a set of all viewer IDs to count unique views

Follow-ups

  • How would you make view counts exactly once?
  • How would you show a live counter during a live stream?
  • How do you reconcile counters if the aggregator had a bug?

Tips

  • Ask which counts must be exact
  • Convert per-minute spikes into per-second load on one key
  • Mention HyperLogLog for uniques

Evaluation rubric

  • Requirements distinguish exact and approximate counts
  • Correct capacity math including the hot key
  • Batched aggregation and hot key strategy
  • Trade-offs on accuracy, freshness and read cost
50.system-design-0050Mediummid

Design a distributed configuration management service that pushes configuration and feature flags to 50,000 service instances.

Keep versioned configuration in a strongly consistent store with validation, audit history and approval for changes. Distribute it through a read-only fan-out tier that clients watch with long polling, so changes reach instances within seconds, and have each client cache the last known good version on disk so instances still start if the service is down. Roll out risky changes gradually and roll back by version.

Full answer

Requirements

Functional:

  • Store key-value configuration and feature flags per service and environment (dev, staging, prod).
  • Every change is versioned, validated against a schema, attributed to a person, and can be rolled back.
  • Instances receive changes without redeploying; gradual rollout (1%, 10%, 100%) and targeting rules for flags.

Non-functional:

  • Changes reach all instances within about 10 seconds.
  • Reads must keep working if the config service is down: an outage of the config system must not stop the applications.
  • Strong consistency for writes (no lost updates); reads may be briefly behind.

Capacity estimates

Assumptions: 50,000 instances; 10,000 config keys averaging 2 KB; each instance subscribes to its own service's config, about 100 keys or 200 KB; about 500 changes per day.

  • Total config data: 10,000 x 2 KB = 20 MB. Tiny; it fits in memory on every config server.
  • Polling every 30 s would be 50,000 / 30 = about 1,700 requests per second, mostly returning "no change".
  • Long-poll watches instead: 50,000 open connections spread across, say, 10 fan-out servers is 5,000 connections each.
  • Change fan-out: one change to a shared key used by all instances means 50,000 notifications x 2 KB = 100 MB of traffic, fine if spread over a few seconds.

The scaling problem is fan-out and connection count, not storage.

API

PUT /v1/configs/{service}/{env}/{key} {"value": ..., "expected_version": 41, "comment": "raise timeout"} -> 200 {"version": 42} or 409 if someone else changed it first GET /v1/configs/{service}/{env}?since_version=41&wait_s=30 long-poll, returns changes or 304 POST /v1/configs/{service}/{env}/rollback {"to_version": 40} GET /v1/configs/{service}/{env}/history

Data model

  • config_entries: service, env, key, value, version, schema_id.
  • config_versions: append-only history with version, full diff, author, approved_by, comment, created_at (the audit trail).
  • flags: flag_key, rules (targeting by region, plan, user ID hash), rollout_percentage.
  • Secrets are not stored here; configs hold references to a secrets manager.

High-level design

mermaid
flowchart LR
  ADM[Admin UI / CLI / Git] --> API[Config write API: validate, approve]
  API --> DB[(Consistent store: etcd or PostgreSQL)]
  DB --> CH[Change stream]
  CH --> FO1[Fan-out server]
  CH --> FO2[Fan-out server]
  FO1 --> I1[Instance SDK + disk cache]
  FO2 --> I2[Instance SDK + disk cache]

How it works

  1. A change goes through the write API: schema validation (type, ranges), optional approval for production, and an optimistic concurrency check on expected_version.
  2. The store commits the new version; the change stream notifies fan-out servers, which keep the full current config in memory.
  3. Each instance's SDK holds a long-poll with its current version. When the version moves, it receives the changed keys, applies them atomically in memory, and writes them to a local disk cache.
  4. On startup, the SDK loads the disk cache first, then syncs. If the service is unreachable, the instance runs with the last known good config.

Safe rollout

Bad config is a common cause of outages, so treat config like code:

  • Validate before saving; reject a timeout of "30s" where an integer is expected.
  • Roll out progressively: a canary group of instances or a percentage gets the new version, health metrics are compared, then it widens.
  • One-click rollback to any previous version.
  • Feature flags evaluate locally in the SDK (a hash of user ID decides the rollout bucket), so evaluation adds no network call.

Bottlenecks and trade-offs

  • Push vs pull: long-poll or streaming gives seconds of latency with few wasted requests; plain polling is simpler but slower and wasteful. Push-based systems need connection management.
  • Consistency across instances: during rollout, instances run different versions for a short time; code must tolerate both old and new values.
  • Central store choice: etcd or ZooKeeper give watches natively but are not designed for tens of thousands of direct watchers with large values; the fan-out tier protects them.
  • Git-based config (config as code, changes through pull requests) adds review and history for free, at the cost of slower emergency changes; many teams combine Git for structure with a fast path for flags.

By level

Fresher: Explain storing settings centrally, versioning each change, and services picking up changes without redeploying. A fresher should explain why every change needs a version number.

Mid: Design versioned storage, watches through long polling, client caching, validation and rollback, and estimate connection and request load. Expect the polling versus watch arithmetic.

Senior: Cover progressive rollout with health checks, feature flag evaluation, multi-region replication, protecting the consensus store with a fan-out tier, secrets separation, and change governance. The senior answer makes sure a config outage cannot stop the applications.

Key points

  • Versioned, validated, audited writes with optimistic concurrency
  • Fan-out tier with long-poll watches; clients apply changes atomically
  • Clients cache last known good config on disk to survive outages
  • Progressive rollout and versioned rollback treat config like code
  • Data is tiny; fan-out and connection count are the scaling problem

Common mistakes

  • Making application startup depend on the config service being up
  • Storing secrets in plain configuration
  • Pushing changes to all instances at once without validation or canary
  • Polling every second from 50,000 instances

Follow-ups

  • How would you roll back a bad config within a minute?
  • How do you evaluate a feature flag for 5% of users consistently?
  • How would you keep configs in sync across three regions?

Tips

  • State that config outages must not cause app outages
  • Do the polling versus watch arithmetic
  • Mention validation and canary rollout as safety features

Evaluation rubric

  • Requirements cover versioning, audit, rollout and failure behaviour
  • Capacity math identifies fan-out as the challenge
  • Write path, distribution and client caching designed
  • Rollout safety and trade-offs discussed
51.system-design-0051Hardsenior

Design a ride-hailing service like Uber or Ola that matches riders with nearby drivers in a few seconds for 20 million rides per day.

Drivers stream their location every few seconds into an in-memory geospatial index partitioned by city and cell; a matching service queries nearby cells, ranks candidate drivers by ETA and offers the trip to one driver at a time with a short timeout. Trips are a state machine stored durably. The hard part is the write rate of location updates (about 250,000 per second for 1 million online drivers), not the ride requests (about 230 per second on average).

Full answer

Requirements

Functional:

  • A rider requests a ride from a pickup point and sees an estimated fare and arrival time.
  • The system finds a nearby available driver, offers the trip, and the driver accepts or declines.
  • Both sides see each other's live location until the trip ends; the trip is priced and paid.

Non-functional:

  • Matching completes in a few seconds; location on the map lags by no more than a few seconds.
  • A driver is never assigned two trips at once; a trip is never lost once accepted.
  • Each city keeps working if another region has problems.

Capacity estimates

Assumptions: 20M rides per day, 1M drivers online at peak, one location update every 4 seconds, 100 bytes per update, 2 KB per stored trip record.

  • Ride requests: 20M / 86,400 = about 230 per second on average; a few thousand per second at city rush hours.
  • Location updates: 1M / 4 = 250,000 per second, about 25 MB per second of incoming data.
  • Trip storage: 20M x 2 KB = 40 GB per day, about 14.6 TB per year before replication.
  • Current driver positions: 1M x 100 bytes = 100 MB, which fits in memory many times over.

Location updates dominate, so they must not go to a relational database one row at a time.

API

POST /v1/rides {"pickup": {"lat": 12.97, "lng": 77.59}, "dropoff": {...}, "product": "economy"} -> 202 {"ride_id": "r_81f", "status": "SEARCHING"} GET /v1/rides/{ride_id} -> {"status": "DRIVER_ASSIGNED", "driver": {...}, "eta_s": 240} WS /v1/drivers/stream driver sends {"lat", "lng", "heading", "ts"} every 4 s; server pushes trip offers POST /v1/offers/{offer_id}/accept

Data model

  • driver_location (in memory, per city shard): driver_id, cell_id, lat, lng, status (available, on_trip, offline), updated_at.
  • trips (durable, partitioned by city then trip_id): trip_id, rider_id, driver_id, status, pickup, dropoff, fare, timestamps.
  • location_history (append-only, for disputes and route replay): written in batches to a log or column store.

High-level design

mermaid
flowchart LR
  D[Driver app] -- "WebSocket, every 4 s" --> GW[Connection gateway]
  GW --> LOC[Location service]
  LOC --> GEO[(Geo index per city)]
  LOC --> K[(Location log)]
  R[Rider app] --> API[Ride API]
  API --> M[Matching service]
  M --> GEO
  M --> ETA[ETA service]
  M --> T[(Trips DB)]
  M -- "offer" --> GW

Matching

  1. The ride API creates a trip in SEARCHING.
  2. The matching service looks up the pickup's cell and its neighbours (a geohash or H3 cell of about 1 km) and gets available drivers.
  3. It ranks the top candidates by road ETA, not straight-line distance, because a river or highway can make a close driver far away.
  4. It offers the trip to the best driver with a 10 to 15 second timeout. To prevent double booking, it sets the driver's status from available to offered with a conditional write; only one trip can win.
  5. On accept, the trip moves to DRIVER_ASSIGNED in the durable store. On decline or timeout, the next driver gets the offer.

Partitioning by city keeps each match local: a match in Mumbai never needs data from Delhi.

Bottlenecks and trade-offs

  • Location write rate. Updates go to memory first and to a log in batches. Losing a few seconds of positions is acceptable; losing a trip is not, so the two have different durability.
  • Hot cells. An airport or stadium can hold thousands of drivers. Smaller cells or a cap on candidates per query keep lookups cheap.
  • Offer one driver at a time or several? One at a time is fair and avoids races but adds seconds per decline. Offering to two or three with "first accept wins" is faster but wastes driver attention.
  • Connection gateways hold long-lived WebSockets; a gateway crash means drivers reconnect, so gateways stay stateless apart from the socket and route by driver_id.
  • Surge pricing reads supply and demand per cell from the same index and runs as a separate service so pricing bugs cannot block matching.

By level

Fresher: List the rider and driver flows, sketch the APIs and explain that drivers send their location often. A fresher should be able to explain why nearby drivers are found by grid cell instead of scanning all drivers.

Mid: Do the update-rate math, design the geo index and the matching flow with timeouts, and show how a conditional write stops double booking. Partitioning by city should come up naturally.

Senior: Cover hot cells, ETA-based ranking, connection gateway failure, durability trade-offs between positions and trips, and surge pricing as an isolated service. Expect a view on single versus parallel offers and on regional failure.

Key points

  • Location updates (250,000 per second) dominate, not ride requests
  • Keep current positions in an in-memory geo index partitioned by city
  • Rank by road ETA, not straight-line distance
  • Conditional write on driver status prevents double assignment
  • Trips are durable state machines; positions can tolerate small loss

Common mistakes

  • Writing every location update as a row in a relational database
  • Matching by straight-line distance only
  • Offering one driver to two riders at the same time
  • Treating positions and trips with the same durability requirements

Follow-ups

  • How would you implement surge pricing per area?
  • How do you handle a driver who loses network mid-trip?
  • How would you support shared rides with several pickups?

Tips

  • Separate the high-rate location path from the low-rate trip path early
  • Show the conditional write that prevents double booking
  • Mention city-level partitioning

Evaluation rubric

  • Correct capacity math showing location updates dominate
  • Sensible geo index and matching flow
  • Prevents double assignment
  • Discusses durability differences and hot cells
52.system-design-0052Mediummid

Design a food delivery platform like Swiggy, Zomato or DoorDash that handles 10 million orders per day across restaurants, customers and delivery partners.

Split the platform into restaurant discovery (search with a cache, read-heavy), ordering (a durable order state machine with payments) and dispatch (assigning delivery partners using live locations and predicted food-ready time). Orders peak sharply at lunch and dinner, so plan for about 3 times the average rate. Dispatch is the interesting part: assign a partner so they arrive when the food is ready, not as early as possible.

Full answer

Requirements

Functional:

  • Customers browse restaurants near them, see menus and delivery time, place and pay for an order.
  • Restaurants accept the order and mark it ready.
  • A delivery partner is assigned, picks up and delivers; the customer tracks the order live.

Non-functional:

  • Browsing is fast and can be slightly stale (a menu price a minute old is fine).
  • Orders and payments are never lost or duplicated.
  • Dispatch decisions within about 30 seconds of the restaurant accepting.

Capacity estimates

Assumptions: 10M orders per day, peak factor 3 at meal times, 300,000 delivery partners online at peak sending a location every 5 seconds, 20 browse requests per order.

  • Orders: 10M / 86,400 = about 116 per second on average, about 350 per second at peak.
  • Browse and search: 20 x 350 = about 7,000 requests per second at peak, mostly cacheable.
  • Partner locations: 300,000 / 5 = 60,000 updates per second.

The order rate is modest; the location stream and the browse traffic need the scaling work.

API

GET /v1/restaurants?lat=..&lng=..&q=biryani&cursor=.. -> list with ETA and rating GET /v1/restaurants/{id}/menu POST /v1/orders (Idempotency-Key header) {"restaurant_id", "items": [...], "address_id", "payment_method"} GET /v1/orders/{id} -> status, partner location, ETA POST /v1/partner/orders/{id}/pickup | /deliver

Data model

  • restaurants and menus in a relational store, copied into a search index (geo field, cuisine, open hours) for discovery.
  • orders: order_id, customer_id, restaurant_id, items, amount, status, partner_id, timestamps. Partitioned by order_id; secondary indexes by customer and restaurant.
  • order_events: append-only history of each status change, used for support and analytics.
  • Partner locations: in-memory geo index, as in ride-hailing.

High-level design

mermaid
flowchart LR
  C[Customer app] --> API[API gateway]
  API --> S[Search service]
  S --> IDX[(Search index with geo)]
  API --> O[Order service]
  O --> DB[(Orders DB)]
  O --> PAY[Payment service]
  O -- "order events" --> BUS[(Event bus)]
  BUS --> DIS[Dispatch service]
  BUS --> N[Notifications]
  P[Partner app] --> LOC[Location service] --> GEO[(Partner geo index)]
  DIS --> GEO
  BUS --> REST[Restaurant tablet app]

Order state machine

CREATED -> PAID -> ACCEPTED_BY_RESTAURANT -> PARTNER_ASSIGNED -> PICKED_UP -> DELIVERED, with CANCELLED and REFUNDED branches. Each transition is a conditional update ("set ACCEPTED only if status is PAID") and emits an event. The idempotency key on order creation stops a double tap from creating two orders.

Dispatch

The dispatcher predicts when food will be ready (from the restaurant's history and current load) and the travel time of candidate partners. It assigns a partner whose arrival matches the ready time, so partners do not wait at the counter and food does not go cold. Every few seconds it solves a small batch assignment per zone (orders and partners in that zone), which gives better results than greedy one-by-one matching and allows batching two orders from the same restaurant.

Bottlenecks and trade-offs

  • Meal-time peaks. Autoscale stateless services ahead of known peaks; the search cache absorbs most browse traffic.
  • Restaurant tablets may be offline. If an order is not accepted within a few minutes, call the restaurant or cancel and refund automatically.
  • Batch dispatch versus instant dispatch. Batching every few seconds gives better assignments at the cost of a small delay.
  • Search freshness. Restaurant open or closed status must update quickly (seconds), while ratings can refresh hourly; use separate update paths.
  • Payment and order consistency uses the outbox pattern: the order row and an outgoing event are written in one local transaction, so no payment succeeds without an order record.

By level

Fresher: Describe the customer, restaurant and partner flows and the main tables. A fresher should explain the order status steps and why the menu can be cached.

Mid: Do the peak math, design the state machine with conditional updates and idempotency, and describe event-driven dispatch. Mention search for discovery with geo filters.

Senior: Discuss batch assignment, ready-time prediction, offline restaurants, freshness of different data, and the outbox for payment consistency. Expect capacity planning for meal peaks.

Key points

  • Three subsystems: discovery, ordering, dispatch
  • Orders are a durable state machine with conditional transitions
  • Idempotency key on order creation
  • Dispatch targets food-ready time, not earliest arrival
  • Plan for meal-time peaks about 3 times the average

Common mistakes

  • Treating the order rate as the scaling problem while ignoring browse and location traffic
  • Assigning the nearest partner immediately so they wait at the restaurant
  • Updating order status without conditional checks
  • Coupling payment success and order creation without an outbox or saga

Follow-ups

  • How would you batch two orders from the same restaurant?
  • How do you estimate food preparation time?
  • What happens if the restaurant never accepts?

Tips

  • Draw the order state machine
  • Explain why dispatch waits for the ready time
  • Show the event bus between services

Evaluation rubric

  • Clear split into discovery, ordering and dispatch
  • Correct capacity math with peaks
  • Order state machine with idempotency
  • Thoughtful dispatch design and trade-offs
53.system-design-0053Mediumfresher

Design a movie or concert ticket booking system like BookMyShow or Ticketmaster where users pick specific seats and seats are held while they pay.

Store each seat of each show as a row with a status. When a user selects seats, hold them with a short-lived lock (for example 8 minutes) using a conditional update or a Redis key with a TTL, so no one else can take them. Payment confirms the booking in a transaction; if the hold expires first, the seats return to the pool. The key requirement is that one seat is never sold twice.

Full answer

Requirements

Functional:

  • Browse shows by city, see a seat map with live availability.
  • Select seats, hold them while paying, confirm the booking and get a ticket.
  • Holds that are not paid in time are released automatically.

Non-functional:

  • A seat is never sold to two people (strong consistency for seat status).
  • The seat map can be a few seconds stale; booking itself cannot.
  • Handle bursts when popular shows open (10 times the normal rate).

Capacity estimates

Assumptions: 10M bookings per day, peak factor 10 at big releases, about 4 seats per booking, 20 seat-map views per booking.

  • Bookings: 10M / 86,400 = about 116 per second on average, about 1,160 per second at peak.
  • Seat-map reads: 20 x 1,160 = about 23,000 per second at peak; serve them from a cache.
  • Seat rows: a hall of 300 seats with 5 shows per day across 10,000 screens is 15M seat rows per day, which a sharded relational database handles easily.

API

GET /v1/shows/{show_id}/seats -> [{"seat_id": "F12", "status": "AVAILABLE"}, ...] POST /v1/holds {"show_id", "seat_ids": ["F12", "F13"]} -> 201 {"hold_id", "expires_at"} or 409 POST /v1/bookings {"hold_id", "payment_token"} (Idempotency-Key header) -> 201 {"booking_id"} DELETE /v1/holds/{hold_id}

Data model

sql
CREATE TABLE show_seats (
  show_id     BIGINT,
  seat_id     VARCHAR(8),
  status      VARCHAR(10),   -- AVAILABLE, HELD, BOOKED
  hold_id     UUID NULL,
  held_until  TIMESTAMP NULL,
  booking_id  UUID NULL,
  PRIMARY KEY (show_id, seat_id)
);

bookings: booking_id, user_id, show_id, seats, amount, payment_id, created_at. Shard by show_id so all seats of a show live together.

High-level design

mermaid
flowchart LR
  U[User] --> API[Booking API]
  API --> C[(Seat map cache)]
  API --> DB[(Shows and seats DB)]
  API --> PAY[Payment gateway]
  SW[Hold expiry worker] --> DB
  DB -- "change events" --> C

Holding seats safely

A hold is one atomic statement:

sql
UPDATE show_seats
SET status = 'HELD', hold_id = :hold, held_until = now() + interval '8 minutes'
WHERE show_id = :show AND seat_id IN ('F12', 'F13')
  AND (status = 'AVAILABLE' OR (status = 'HELD' AND held_until < now()));

If the number of updated rows is less than the number of requested seats, roll back and return 409. Because the check and the update happen in one statement inside a transaction, two users can never hold the same seat. Expired holds are treated as available, so a crashed client cannot lock seats forever; a background worker also clears them for a clean seat map.

Confirming the booking checks the hold is still valid, charges the payment with an idempotency key, and sets status to BOOKED in one transaction.

An alternative is a Redis key per seat (SET seat:show:F12 hold NX EX 480), which is fast but must still be reconciled with the database before final confirmation.

Bottlenecks and trade-offs

  • Hot shows. All seats of one show are on one shard, which becomes hot when tickets open. A virtual waiting room in front of the booking API admits users at a steady rate.
  • Hold length. Longer holds are kinder to slow payers but leave seats unavailable; 5 to 10 minutes is common.
  • Payment succeeds after the hold expired. Detect it at confirmation and refund automatically, or extend holds while a payment is in progress.
  • Seat-map cache may show a seat as free that was just held; the hold call is the source of truth and returns 409 with a fresh map.

By level

Fresher: Describe the flow from seat map to hold to payment, and the seat table with a status column. A fresher should explain why the hold must expire.

Mid: Write the atomic hold, explain the race it prevents, size the peak and add a cache for the seat map. Cover idempotent confirmation.

Senior: Address hot shards, waiting rooms, bot defence, late payment refunds and Redis versus database holds. Expect clear reasoning about which data must be strongly consistent.

Key points

  • One row per seat per show with a status
  • Hold seats with an atomic conditional update and an expiry time
  • Expired holds count as available
  • Confirm payment and booking with an idempotency key
  • Shard by show and use a waiting room for hot shows

Common mistakes

  • Checking availability in one query and updating in another without a transaction
  • Holds with no expiry
  • Trusting the cached seat map for the final decision
  • Ignoring the case where payment succeeds after the hold expired

Follow-ups

  • How would you add a virtual waiting room?
  • How do you handle general admission tickets without seat numbers?
  • How would you prevent bots from holding all seats?

Tips

  • Write the conditional update; it is the heart of the design
  • Say what happens when a hold expires
  • Separate the cached seat map from the source of truth

Evaluation rubric

  • Correct seat-level data model
  • Atomic hold with expiry
  • Idempotent confirmation with payment
  • Handles hot shows and late payments
54.system-design-0054Hardsenior

Design a payment system with a digital wallet that processes 50 million payments per day without losing or double-charging money.

Model money with a double-entry ledger: every payment writes balanced debit and credit entries in one database transaction, and balances are derived from or checked against those entries. Every external call uses an idempotency key, payment states move through a strict state machine, and a daily reconciliation compares the ledger with bank and card network reports. At 50 million payments per day the rate is only about 580 per second, so correctness, not throughput, drives the design.

Full answer

Requirements

Functional:

  • Users top up a wallet from a card or bank, pay merchants from the wallet or directly, and withdraw.
  • Merchants see settlements; users see a history of transactions.
  • Refunds and chargebacks.

Non-functional:

  • No money is created or lost; every movement is auditable.
  • A retried request never charges twice.
  • High availability for payment acceptance; strong consistency for balances.

Capacity estimates

Assumptions: 50M payments per day, peak factor 5, two ledger entries per payment at about 1 KB each including metadata.

  • Payments: 50M / 86,400 = about 580 per second; about 2,900 per second at peak.
  • Ledger growth: 50M x 2 x 1 KB = 100 GB per day, about 36.5 TB per year before replication.
  • A well-indexed relational database cluster sharded by account handles this; the challenge is correctness and retention (financial records are kept for years).

API

POST /v1/payments Idempotency-Key: 6f1c... {"payer_account": "acc_1", "payee_account": "acc_9", "amount": {"value": 49900, "currency": "INR"}} -> 201 {"payment_id": "pay_77", "status": "SUCCEEDED"} (same response if retried) GET /v1/accounts/{id}/balance GET /v1/accounts/{id}/entries?cursor=.. POST /v1/payments/{id}/refunds Idempotency-Key: ...

Amounts are integers in the smallest unit (paise, cents), never floating point.

Data model

  • accounts: account_id, owner_id, type (user_wallet, merchant, bank_clearing, fees), currency, balance, version.
  • ledger_entries: entry_id, payment_id, account_id, direction (debit or credit), amount, created_at. Insert only; never updated.
  • payments: payment_id, idempotency_key (unique), status, amount, created_at.

The rule: for every payment, total debits equal total credits.

High-level design

mermaid
flowchart LR
  C[Client] --> API[Payment API]
  API --> IK[(Idempotency store)]
  API --> PS[Payment service]
  PS --> L[(Ledger DB)]
  PS --> PSP[Card and bank adapters]
  PSP --> EXT[External networks]
  PS -- "outbox events" --> BUS[(Event bus)]
  BUS --> N[Notifications]
  REC[Reconciliation job] --> L
  REC --> EXT

Moving money

Wallet to merchant (internal):

  1. Look up the idempotency key; if it exists, return the stored result.
  2. In one transaction: lock the payer account row (SELECT ... FOR UPDATE) and check the balance; insert a debit entry for the payer and a credit entry for the merchant; update both balances; mark the payment SUCCEEDED; write an outbox event.
  3. Store the response under the idempotency key.

Card top-up (external): the payment goes CREATED -> PENDING -> SUCCEEDED or FAILED. The call to the card network carries our payment_id as its idempotency key. If the call times out, the status stays PENDING and a worker queries the provider until it gets a final answer. The wallet is credited only after a confirmed success.

Reconciliation

Every day, compare the ledger with settlement files from banks and card networks. Each mismatch (money received but no ledger entry, or the reverse) creates a case for automatic fixing or manual review. Also verify that all ledger entries sum to zero across accounts.

Bottlenecks and trade-offs

  • Hot merchant accounts. A big merchant receives thousands of credits per second; locking one row serialises them. Split the merchant's balance into several sub-accounts, or credit merchants asynchronously from a queue, since merchants do not need real-time balances.
  • Cross-shard transfers. If payer and payee are on different shards, use a saga with a clearing account: debit the payer into clearing, then credit the payee from clearing, each step idempotent.
  • Timeouts are not failures. Treating an unknown result as failed and retrying with a new key is the classic double-charge bug.
  • Strong consistency is chosen over availability for balance updates; accepting a payment request can still be queued during a short outage.

By level

Fresher: Explain why money is stored as integers and why each payment needs a unique key so retries are safe. A fresher should describe a simple transfer inside one database transaction.

Mid: Design the double-entry ledger, the payment state machine and idempotency at both the API and the provider. Do the capacity math and note that it is small.

Senior: Cover reconciliation, hot merchant accounts, cross-shard sagas through clearing accounts, retention and audit, and the consistency versus availability choice. Expect the timeout double-charge trap to be named.

Key points

  • Double-entry ledger: debits equal credits for every payment
  • Integer amounts in the smallest currency unit
  • Idempotency keys on every API and external call
  • Unknown results stay pending until confirmed
  • Daily reconciliation against external reports

Common mistakes

  • Storing only a balance column with no entries
  • Using floating point for money
  • Retrying a timed-out card charge with a new idempotency key
  • Ignoring hot merchant accounts that serialise on one row lock

Follow-ups

  • How would you handle currency conversion?
  • How do refunds and chargebacks appear in the ledger?
  • How would you move money between shards?

Tips

  • Start with the ledger invariant
  • Explain the pending state for timeouts
  • Point out that throughput is small and correctness is the focus

Evaluation rubric

  • Double-entry ledger with append-only entries
  • Idempotency at API and provider level
  • Correct handling of timeouts and reconciliation
  • Addresses hot accounts and cross-shard transfers
55.system-design-0055Mediummid

Design a distributed web crawler that downloads 5 billion pages per month while staying polite to every website.

A URL frontier holds URLs to fetch, organised as per-host queues so each host is fetched at a polite rate. Fetchers download pages, a parser extracts links, and a deduplication step (a seen-URL set and content fingerprints) stops repeat work. Partition the frontier and fetchers by host hash so one host is always handled by one worker. The target is about 1,930 pages per second and 1.5 Gbps of download bandwidth.

Full answer

Requirements

Functional:

  • Start from seed URLs, fetch pages, extract links and keep crawling.
  • Respect robots.txt and per-host rate limits.
  • Store page content and metadata for an indexer; re-crawl pages based on how often they change.

Non-functional:

  • Scale to billions of pages; add machines to go faster.
  • Never overload a single website.
  • Survive worker crashes without losing the frontier.

Capacity estimates

Assumptions: 5B pages per 30-day month, average page 100 KB, compression to about a quarter for storage.

  • Fetch rate: 5B / (30 x 86,400) = about 1,930 pages per second.
  • Bandwidth: 1,930 x 100 KB x 8 = about 1.5 Gbps sustained.
  • Raw storage: 5B x 100 KB = 500 TB per month; about 125 TB compressed.
  • Seen-URL set: 10B URLs at 8-byte hashes is 80 GB; a Bloom filter at 1% false positives needs about 12 GB.

API

Internal interfaces rather than a public API:

frontier.add(urls, priority) # from parser or seed loader frontier.next(worker_id) -> url # returns a URL whose host is due store.put(url, content_hash, body, fetched_at, http_status)

Data model

  • Frontier: per-host FIFO queues plus a priority index, persisted to disk (for example in RocksDB or Kafka partitions).
  • host_state: host, next_allowed_fetch_time, crawl_delay, robots_rules, robots_fetched_at.
  • pages: url_hash, url, content_hash, fetched_at, status, change_rate estimate; bodies in object storage.

High-level design

mermaid
flowchart LR
  SEED[Seeds] --> F[URL frontier]
  F --> W[Fetcher workers]
  W --> DNS[DNS cache]
  W --> R[robots.txt cache]
  W --> OS[(Object storage)]
  W --> P[Parser]
  P --> D[Dedup: seen URLs and content hash]
  D --> F
  OS --> IX[Indexer]

Politeness and priority

The frontier has two layers. Front queues order URLs by priority (page importance, change rate). Back queues hold one host each. A heap keyed by next_allowed_fetch_time decides which host is due; after a fetch, the host's next time moves forward by its crawl delay (for example 1 second, or what robots.txt asks). This means even 10,000 URLs from one site are fetched one at a time with gaps.

Each host is assigned to one worker by hash(host) mod N (or consistent hashing), so politeness state is local and no locks are needed.

Deduplication and traps

  • Normalise URLs (lowercase host, remove default ports, sort query parameters, drop fragments) before checking the seen set.
  • Skip pages whose content fingerprint (SHA-256 for exact, SimHash for near-duplicates) was already stored.
  • Crawler traps such as endless calendar pages: limit depth per host and URL length, and cap pages per host per crawl.

Bottlenecks and trade-offs

  • DNS can become slow at 2,000 lookups per second; cache results per host with their TTL.
  • Bloom filter versus exact set: the Bloom filter saves memory but occasionally skips a new URL, which is acceptable for a crawler.
  • Freshness versus coverage: re-crawling news sites hourly uses budget that could discover new pages; schedule re-crawls by observed change rate.
  • Large hosts become a slow tail because of politeness; this is accepted by design.
  • Crashes: the frontier is persisted, and a URL is marked done only after its content is stored, so a crash causes a re-fetch, not a loss.

By level

Fresher: Describe the fetch, parse and add-links loop and explain why the crawler must wait between requests to the same site. A fresher should mention robots.txt and a set of visited URLs.

Mid: Design the two-layer frontier, partition by host, size the system and handle normalisation and duplicates. Mention DNS caching.

Senior: Discuss freshness scheduling, near-duplicate detection, traps, Bloom filter trade-offs, persistence and recovery. Expect thoughtful reasoning about large hosts and politeness limits.

Key points

  • Per-host back queues and a next-fetch-time heap enforce politeness
  • Partition hosts to workers by hash
  • Normalise URLs and deduplicate by URL and content
  • About 1,930 pages per second and 1.5 Gbps for 5 billion pages a month
  • Persist the frontier so crashes cause re-fetches, not losses

Common mistakes

  • Fetching from one host in parallel with many threads
  • Ignoring robots.txt and crawl delays
  • No URL normalisation, so duplicates explode
  • Forgetting crawler traps and DNS cost

Follow-ups

  • How do you decide when to re-crawl a page?
  • How would you crawl JavaScript-heavy sites?
  • How do you detect near-duplicate pages?

Tips

  • Explain front and back queues
  • State the politeness rule clearly
  • Size the seen-URL set and offer a Bloom filter

Evaluation rubric

  • Correct frontier design with politeness
  • Capacity math for rate, bandwidth and storage
  • Deduplication and trap handling
  • Partitioning and failure handling
56.system-design-0056Mediumfresher

Design a photo sharing app like Instagram where 100 million photos are uploaded per day and users scroll a feed of people they follow.

Upload photos directly to object storage with a pre-signed URL, create resized versions in background workers, and serve every image through a CDN. Metadata (posts, follows, likes) lives in a sharded database, and each user's feed is built mostly by fan-out on write into a per-user feed cache. Storage is the biggest number: about 300 TB per day with resized copies.

Full answer

Requirements

Functional:

  • Upload a photo with a caption; view a profile grid.
  • Follow other users; scroll a home feed of recent posts from people you follow.
  • Like and comment.

Non-functional:

  • Feed loads in under about 300 ms; images load quickly worldwide.
  • Uploads are never lost; feeds can be a few seconds behind.
  • Read-heavy: many more views than uploads.

Capacity estimates

Assumptions: 500M daily active users, 100M uploads per day, 3 MB stored per photo (2 MB original plus 1 MB of resized versions), 20 feed loads per user per day.

  • Uploads: 100M / 86,400 = about 1,160 per second.
  • Storage: 100M x 3 MB = 300 TB per day, about 109.5 PB per year before replication.
  • Feed loads: 500M x 20 / 86,400 = about 116,000 per second; each loads metadata for about 10 posts and their image URLs.
  • Image bandwidth is served by the CDN, not by origin servers.

API

POST /v1/uploads -> {"upload_url": "https://storage/...signed", "media_id": "m_91"} PUT {upload_url} (client uploads bytes directly) POST /v1/posts {"media_id": "m_91", "caption": "Campus sunrise"} GET /v1/feed?cursor=.. -> [{"post_id", "author", "image_urls": {"640": ..., "1080": ...}, "likes"}] POST /v1/posts/{id}/likes POST /v1/users/{id}/follow

Data model

  • users: user_id, name, avatar.
  • posts: post_id (time-sortable ID), author_id, media_id, caption, created_at. Shard by author_id so a profile grid is one shard read.
  • follows: (follower_id, followee_id) with an index in both directions.
  • likes: (post_id, user_id); a separate counter per post for display.
  • Images: object storage keys like media/m_91/1080.jpg.
  • Feed cache: per-user list of the latest few hundred post IDs in Redis.

High-level design

mermaid
flowchart LR
  A[App] --> API[API servers]
  A -- "upload bytes" --> S3[(Object storage)]
  S3 -- "upload event" --> IMG[Resize workers]
  IMG --> S3
  API --> DB[(Posts and follows DB)]
  API --> FC[(Feed cache)]
  DB -- "new post event" --> FO[Fan-out workers]
  FO --> FC
  A -- "images" --> CDN[CDN]
  CDN --> S3

Upload and feed flows

Upload: the app asks for a pre-signed URL, uploads directly to object storage (API servers never carry the bytes), then creates the post. A storage event triggers workers that make 3 to 4 sizes and strip location metadata.

Feed: when a user posts, fan-out workers push the post ID to the feed cache of each follower (fan-out on write). Reading a feed is then one cache read plus a batch fetch of post metadata. For accounts with millions of followers, skip fan-out and merge their recent posts at read time instead (a hybrid), because writing to 50M feed lists for one post is too slow.

Bottlenecks and trade-offs

  • Storage cost dominates. Move old originals to colder storage classes; keep popular sizes hot in the CDN.
  • Celebrity fan-out is handled by the hybrid model.
  • Like counts on viral posts: increment in a cache and flush to the database in batches, accepting a few seconds of lag.
  • Fan-out on write makes reads fast but uses more storage and work for inactive users; only fan out to users active in the last few weeks.
  • Chronological versus ranked feeds: ranking adds a scoring service on the read path, which costs latency but improves engagement.

By level

Fresher: Explain that photos go to object storage and a CDN while post details go to a database, and sketch the upload and feed APIs. A fresher should describe a simple way to build the feed from followed users.

Mid: Do the capacity math, design fan-out on write with a feed cache, and add background resizing. Explain the celebrity problem and the hybrid fix.

Senior: Discuss storage tiering and cost, ranking, counter scaling, deletion and privacy across caches, and fan-out only to active users. Expect numbers to guide each choice.

Key points

  • Upload directly to object storage with pre-signed URLs
  • Resize images asynchronously and serve through a CDN
  • Shard posts by author; keep a per-user feed cache
  • Fan-out on write, with read-time merge for celebrities
  • Storage, about 300 TB per day, is the largest cost

Common mistakes

  • Sending image bytes through API servers
  • Storing images in the database
  • Fanning out a celebrity's post to every follower
  • Updating like counts with a database write per like on viral posts

Follow-ups

  • How would you add Stories that expire after 24 hours?
  • How would you rank the feed?
  • How would you delete a user's photos everywhere, including the CDN?

Tips

  • Separate media from metadata at the start
  • Do the storage math; it is striking
  • Explain the hybrid fan-out

Evaluation rubric

  • Correct media path with object storage and CDN
  • Capacity math for uploads, storage and reads
  • Feed design with fan-out trade-offs
  • Handles celebrities and counters
57.system-design-0057Mediummid

Design the home timeline for a Twitter or X style service with 250 million daily users and 500 million posts per day, including accounts with tens of millions of followers.

Precompute each active user's home timeline as a list of post IDs in an in-memory store by fanning out new posts to followers' lists, but skip fan-out for accounts with very many followers and merge their recent posts at read time. Reads (about 87,000 per second) then cost one list read plus a hydration call, while fan-out writes reach about 1.16 million per second on average. The timeline cache holds IDs only, about 1.6 TB for 800 IDs per user.

Full answer

Requirements

Functional:

  • Post short messages; follow accounts.
  • The home timeline shows recent posts from followed accounts, newest first (ranking can be added later).
  • A user timeline shows one account's own posts.

Non-functional:

  • Home timeline loads in under about 200 ms at p99.
  • A new post appears in followers' timelines within a few seconds.
  • Availability over strict consistency: a post showing up a few seconds late is acceptable.

Capacity estimates

Assumptions: 250M daily users, 500M posts per day, 200 followers on average, 30 timeline loads per user per day, 800 post IDs cached per timeline at 8 bytes each.

  • Posts: 500M / 86,400 = about 5,800 per second.
  • Fan-out writes: 5,800 x 200 = about 1.16 million timeline inserts per second.
  • Timeline reads: 250M x 30 / 86,400 = about 87,000 per second.
  • Timeline cache: 250M x 800 x 8 bytes = 1.6 TB, spread over a Redis cluster (with replicas, about 3.2 TB of memory).

The average hides the real problem: one post from an account with 50M followers would be 50M inserts on its own.

API

POST /v1/posts {"text": "...", "media_ids": [...]} GET /v1/timelines/home?cursor=.. -> [{"post_id", "author", "text", "counts"}...], next_cursor GET /v1/users/{id}/posts?cursor=.. POST /v1/users/{id}/follow

The cursor is the last post ID seen; post IDs are time-ordered (Snowflake style), so "older than this ID" works without offsets.

Data model

  • posts: post_id, author_id, text, media, created_at. Stored in a sharded store keyed by post_id; a per-author index for user timelines.
  • follows: follower_id to followee_id and the reverse, in a graph or wide-column store.
  • home_timeline:{user_id}: Redis list of post IDs, trimmed to 800.
  • celebrity flag on accounts above a follower threshold (for example 1M).

High-level design

mermaid
flowchart LR
  U[Client] --> W[Post service]
  W --> PS[(Posts store)]
  W -- "new post" --> Q[(Queue)]
  Q --> FO[Fan-out workers]
  FO --> G[(Follow graph)]
  FO --> TL[(Timeline cache)]
  U --> R[Timeline service]
  R --> TL
  R --> CEL[Celebrity recent posts]
  R --> H[Hydration: posts and users cache]

Fan-out and the celebrity problem

Normal accounts: on a new post, fan-out workers read the follower list in pages and push the post ID onto each active follower's list, trimming it to 800 entries.

Celebrities: no fan-out. At read time, the timeline service fetches the user's precomputed list, plus the latest posts from the handful of celebrities they follow (each celebrity's recent posts are cached and read by millions), merges by post ID and returns the top page.

Inactive users (not seen in 30 days) get no fan-out; their timeline is rebuilt from the follow graph when they return.

Bottlenecks and trade-offs

  • Fan-out on write versus read. Write fan-out makes reads cheap but costs huge write volume; read fan-out is cheap to write but needs a scatter-gather over many authors on each read. The hybrid uses each where it is cheap.
  • Threshold choice. Too low a celebrity threshold makes reads slow; too high makes fan-out spikes. Tune it from measurements.
  • Deletions must remove IDs from many lists; instead, filter deleted posts during hydration.
  • Cache loss. If a Redis shard is lost, timelines are rebuilt on demand from posts and the follow graph, so the cache is not the source of truth.
  • Hydration batches post and user lookups so one timeline page costs a few cache calls, not 20.

By level

Fresher: Explain fan-out on write in simple terms and why a timeline cache makes reads fast. A fresher should notice that very popular accounts cause a problem.

Mid: Do the fan-out math, design the hybrid with a threshold, and use ID-based cursors. Explain hydration and trimming.

Senior: Discuss threshold tuning, inactive users, deletions, cache rebuild, ranking and the cost model that drives each choice. Expect a clear comparison with fan-out on read.

Key points

  • Precompute home timelines as lists of post IDs
  • About 1.16 million fan-out inserts per second on average
  • Skip fan-out for celebrities and merge at read time
  • Skip inactive users and rebuild their timeline on return
  • Store IDs only and hydrate from caches

Common mistakes

  • Pure fan-out on write including celebrities
  • Pure fan-out on read for every request
  • Storing full post bodies in every timeline
  • Offset pagination on a changing feed

Follow-ups

  • How would you add ranking to the timeline?
  • How do you handle a user who follows 5,000 accounts?
  • How would you show a "new posts" banner?

Tips

  • Show the averages, then the celebrity spike
  • Explain the hybrid clearly
  • Use ID cursors for pagination

Evaluation rubric

  • Correct capacity math
  • Fan-out design with clear trade-offs
  • Celebrity handling and inactive users
  • Cache rebuild and hydration discussed
58.system-design-0058Hardsenior

Design end-to-end encrypted messaging like WhatsApp or Signal, where the server delivers messages to all of a user's devices but can never read them.

Each device has its own identity key and uploads a batch of one-time prekeys to a key directory. A sender fetches the recipient's device keys, sets up a session with an X3DH-style handshake and encrypts each message with a ratchet that changes keys per message. The server only stores and forwards ciphertext per device. Multi-device means encrypting once per recipient device, so deliveries are about 580,000 per second for 290,000 messages per second.

Full answer

Requirements

Functional:

  • One-to-one and group messages delivered to every device a user owns (phone, laptop).
  • Offline devices receive messages when they reconnect.
  • Users can verify a contact's keys (safety numbers).

Non-functional:

  • The server cannot read message content, even if its database leaks.
  • Forward secrecy: stealing today's keys does not reveal past messages.
  • Low latency delivery and high availability.

Capacity estimates

Assumptions: 500M daily users, 50 messages each per day, 2 devices per user on average, 1 KB average ciphertext, 1B registered devices, 100 one-time prekeys per device at 32 bytes each.

  • Messages: 500M x 50 / 86,400 = about 290,000 per second.
  • Device deliveries: x 2 devices = about 580,000 encrypted copies per second.
  • Prekey storage: 1B x 100 x 32 bytes = 3.2 TB in the key directory.
  • Undelivered message queue: kept only until delivery (or 30 days), so storage stays small compared with a chat archive.

API

PUT /v1/keys/{device_id} {"identity_key", "signed_prekey", "signature", "one_time_prekeys": [...]} GET /v1/keys/{user_id} -> list of devices, each with identity key, signed prekey and one one-time prekey (consumed) WS /v1/messages send {"to_device": "...", "ciphertext": "base64", "msg_id"} ; receive same shape POST /v1/messages/ack {"msg_ids": [...]} -> server deletes delivered ciphertext

Data model

  • devices: user_id, device_id, identity_public_key, signed_prekey, registered_at.
  • one_time_prekeys: device_id, key_id, public_key (each handed out once, then deleted).
  • pending_messages: recipient_device_id, msg_id, sender_device_id, ciphertext, created_at. Deleted on ack.

The server never stores private keys or plaintext.

High-level design

mermaid
flowchart LR
  A[Sender device] -- "fetch keys" --> KD[(Key directory)]
  A -- "ciphertext per device" --> GW[Connection gateways]
  GW --> RT[Routing service]
  RT --> PRES[(Device presence)]
  RT --> PQ[(Pending messages)]
  RT --> GW2[Gateway of recipient]
  GW2 --> B1[Recipient phone]
  GW2 --> B2[Recipient laptop]
  RT --> PUSH[Push notification service]

How encryption works

  1. Session setup (X3DH idea). The sender combines its identity key and a fresh ephemeral key with the recipient device's identity key, signed prekey and one one-time prekey, using several Diffie-Hellman operations, to derive a shared secret. The recipient can compute the same secret from the first message even if it was offline.
  2. Double Ratchet. Every message advances a key chain, and every reply mixes in a new Diffie-Hellman result. Old keys are deleted, which gives forward secrecy and recovery after a compromise.
  3. Groups. Small groups can encrypt to each member device; large groups use sender keys: each sender shares a group key once with every member device, then encrypts each message once, which reduces work from one encryption per device to one per message.

The server routes by device ID and sees metadata (who talks to whom, when), but not content. Reducing metadata exposure (sealed sender) is an extra step.

Bottlenecks and trade-offs

  • Key directory trust. A malicious server could hand out fake keys. Safety numbers let users compare keys out of band; key transparency logs make substitution detectable.
  • Prekey exhaustion. If one-time prekeys run out, fall back to the signed prekey alone (slightly weaker) and ask the device to upload more.
  • Multi-device cost doubles delivery work and complicates adding a new device, which cannot read old history unless an existing device transfers it.
  • Server-side features such as search or spam filtering on content are impossible; they move to the device.
  • Backups must be encrypted with a user-held key, or they break the end-to-end promise.

By level

Fresher: Explain that messages are locked on the sender's phone and only the receiver's device holds the key to open them. A fresher should describe the server as a post office that cannot open envelopes.

Mid: Describe identity keys, prekeys and the handshake at a high level, plus per-device delivery and pending queues. Do the delivery math with multiple devices.

Senior: Cover the Double Ratchet, sender keys for groups, key transparency, prekey exhaustion, device linking, encrypted backups and metadata leakage. Expect clear reasoning about what the server can and cannot do.

Key points

  • Per-device identity keys and one-time prekeys in a key directory
  • X3DH-style handshake works even when the recipient is offline
  • Double Ratchet gives forward secrecy
  • Server stores and forwards ciphertext per device and deletes it on ack
  • Sender keys make large groups efficient

Common mistakes

  • Encrypting with one key per user instead of per device
  • Letting the server hold private keys "for backup"
  • Ignoring key substitution by the server
  • Assuming the server can still do content search or moderation

Follow-ups

  • How would you add a new device to an existing account?
  • How do encrypted backups work?
  • What metadata does the server still see and how can it be reduced?

Tips

  • Separate routing (server) from cryptography (devices)
  • Explain prekeys with the offline recipient case
  • Mention safety numbers for trust

Evaluation rubric

  • Correct key distribution model
  • Explains forward secrecy and session setup at a high level
  • Per-device delivery with capacity math
  • Discusses trust, groups and lost features
59.system-design-0059Hardsenior

Design real-time collaborative document editing like Google Docs, where many people edit the same document at once and see each other's changes within a second.

Clients send small operations (insert or delete at a position) over a WebSocket to a document session server that owns that document. The server orders operations, transforms concurrent ones with operational transformation (or merges them with a CRDT), appends them to an operation log and broadcasts them. Snapshots compact the log. The key design choices are one owner per document for ordering and a conflict-resolution method that makes every copy converge.

Full answer

Requirements

Functional:

  • Several users edit one document at the same time; everyone sees changes and cursors live.
  • Edits made offline merge when the user reconnects.
  • Version history and restore.

Non-functional:

  • Changes appear for others in under about 500 ms.
  • All copies converge to the same text; no edit is silently lost.
  • Documents are durable once the server acknowledges an edit.

Capacity estimates

Assumptions: 1M documents being edited at peak, 1 operation per second per active document on average (typing is bursty but small), 100 bytes per operation with metadata.

  • Operations: 1M per second at peak.
  • Operation log: 1M x 86,400 x 100 bytes = about 8.64 TB per day if every document were busy all day; in practice far less, and snapshots let old operations be compacted.
  • Connections: a few million WebSockets across gateway servers (around 50,000 to 100,000 per server).

API

GET /v1/docs/{id} -> {"snapshot": "...", "version": 1842} WS /v1/docs/{id}/session client -> {"base_version": 1842, "ops": [{"insert": "Hello", "pos": 120}], "client_op_id": "c7-55"} server -> {"ack": "c7-55", "version": 1843} server -> {"remote_ops": [...], "version": 1844, "author": "u_9"} GET /v1/docs/{id}/history?from=..

Data model

  • documents: doc_id, owner, title, latest_snapshot_version.
  • snapshots: doc_id, version, content (object storage for large docs).
  • operations: doc_id, version (monotonic), author, ops, created_at. Append only.
  • permissions: doc_id, principal, role.

High-level design

mermaid
flowchart LR
  C1[Editor A] -- "WebSocket" --> GW[Gateways]
  C2[Editor B] -- "WebSocket" --> GW
  GW --> RTR[Doc router]
  RTR --> DS[Doc session server owning the doc]
  DS --> OL[(Operation log)]
  DS --> SN[(Snapshots)]
  SNP[Snapshot worker] --> OL
  SNP --> SN

Ordering and conflict resolution

Each document has one session server at a time (chosen by consistent hashing or a lease in a coordination service). It assigns a version number to every accepted operation, which gives one global order per document.

With operational transformation (OT), a client sends operations against the version it last saw. If other operations were accepted since, the server transforms the new operation against them. Example: A inserts "X" at position 5 while B deletes position 2. After B's delete, A's position becomes 4. The server then broadcasts the transformed operation and clients apply the same transforms to their pending local edits.

With a CRDT, each character has a unique, ordered identifier, so inserts and deletes commute and any order of delivery converges. CRDTs suit offline and peer-to-peer editing but carry more metadata per character.

Bottlenecks and trade-offs

  • Single owner per document makes ordering simple but limits a single document's write rate; that is fine, since even 100 editors produce a small stream.
  • Session server failure: a new owner loads the latest snapshot plus later operations from the log; clients resend unacknowledged operations, and client_op_id makes that safe.
  • Snapshots every few hundred operations keep load time short; history views replay operations from a snapshot.
  • Cursors and presence are sent over the same socket but never stored, since they are temporary.
  • OT versus CRDT: OT needs a central server and careful transform functions; CRDTs avoid the central ordering but cost memory and make some operations (rich text formatting) harder.

By level

Fresher: Explain that each keystroke becomes a small operation sent to the server and broadcast to others. A fresher should see that two people editing at once can conflict.

Mid: Describe per-document ordering, a simple OT example and the operation log with snapshots. Handle reconnects with client operation IDs.

Senior: Compare OT and CRDTs in depth, cover owner failover, offline merges, rich text and comments anchoring. Expect a view on when to choose each method.

Key points

  • One session server owns each document and orders its operations
  • OT transforms concurrent operations; CRDTs make operations commute
  • Append operations to a log and compact with snapshots
  • client_op_id makes resending after reconnect safe
  • Presence is temporary and not stored

Common mistakes

  • Last-write-wins on whole documents, which loses edits
  • Locking paragraphs so only one person can type
  • Sending the whole document on every keystroke
  • Forgetting to transform pending local operations on the client

Follow-ups

  • How would you support offline editing for hours?
  • How do comments stay attached to text that moves?
  • How would you move a document to a new session server without a pause?

Tips

  • Give a small OT example with positions
  • Explain why one owner per document is enough
  • Mention snapshots for load time

Evaluation rubric

  • Per-document ordering design
  • Correct explanation of OT or CRDT
  • Durability with logs and snapshots
  • Handles failure and reconnect
60.system-design-0060Easyfresher

Design a real-time leaderboard for a game or coding contest with 10 million players that shows the top 100 and each player's own rank.

Keep scores in a Redis sorted set: updating a score and fetching a rank are both O(log n), and the top 100 is a single range read. Persist every score change in a database so the sorted set can be rebuilt. 10 million players fit in about 1 GB of memory. For far larger boards, shard by score range or keep exact ranks only near the top and approximate ranks elsewhere.

Full answer

Requirements

Functional:

  • Update a player's score when they finish a game or solve a problem.
  • Show the global top 100, a player's own rank and the players just above and below.
  • Separate boards per contest, per day or per week.

Non-functional:

  • Rank updates visible within a second or two.
  • Reads are much more frequent than writes.
  • Scores must not be lost.

Capacity estimates

Assumptions: 10M players on one board, 50M score updates per day, peak factor 5, about 100 bytes per sorted-set member including overhead.

  • Updates: 50M / 86,400 = about 580 per second; about 2,900 per second at peak.
  • Memory: 10M x 100 bytes = about 1 GB, which fits in one Redis instance with a replica.
  • Each update or rank query is O(log n): about 23 steps for 10M members.

API

POST /v1/boards/{board_id}/scores {"player_id": "p_42", "delta": 30} (or "score" for absolute) GET /v1/boards/{board_id}/top?limit=100 GET /v1/boards/{board_id}/players/{player_id} -> {"rank": 18234, "score": 1290, "neighbours": [...]}

Data model

  • Redis sorted set board:{board_id}: member = player_id, score = points.
  • Database table score_events: event_id, board_id, player_id, delta, created_at (source of truth, append only).
  • player_scores: board_id, player_id, total (for rebuilds and history).

High-level design

mermaid
flowchart LR
  G[Game or judge service] --> API[Leaderboard API]
  API --> DB[(Score events DB)]
  API --> Z[(Redis sorted sets)]
  C[Clients] --> API
  RB[Rebuild job] --> DB
  RB --> Z

How the operations work

  • Update: ZINCRBY board:contest-7 30 p_42 after the event is stored.
  • Top 100: ZREVRANGE board:contest-7 0 99 WITHSCORES.
  • Own rank: ZREVRANK board:contest-7 p_42 (0-based), then neighbours with ZREVRANGE around that rank.
  • Ties: sorted sets order equal scores by member name. To rank earlier achievers higher, encode the score as points x 10^10 + (MAX_TS - finish_time), so the same points with an earlier time sort first.

Bottlenecks and trade-offs

  • Single instance limits. One Redis node handles tens of thousands of operations per second, enough here. For boards of hundreds of millions, shard by score range (each shard knows how many players are above it) or compute exact ranks for the top and percentile ranks ("top 5%") for everyone else.
  • Durability. Redis is a cache of the database; if it is lost, rebuild from player_scores.
  • Time-based boards (daily, weekly) are separate keys with an expiry, so resets are just new keys.
  • Hot reads of the top 100 can be cached for one second at the API layer, since everyone requests the same page.
  • Cheating is outside the leaderboard: accept scores only from trusted game or judge services, never from clients.

By level

Fresher: Explain why a sorted set fits and show the top 100 and own-rank queries. A fresher should say why a SQL query that counts higher scores gets slow.

Mid: Do the memory math, persist events, rebuild the cache and handle ties. Add time-based boards with expiry.

Senior: Discuss sharding by score range, approximate ranks, friend boards, caching hot reads and anti-cheat boundaries. Expect a clear plan for growth beyond one node.

Key points

  • Redis sorted set gives O(log n) updates and rank queries
  • Top 100 is one range read
  • Database events are the source of truth; rebuild Redis from them
  • Encode tie-breaks into the score
  • Shard by score range or approximate ranks for huge boards

Common mistakes

  • Computing rank with ORDER BY and COUNT on every request
  • Trusting score updates sent by clients
  • Treating Redis as the only copy of scores
  • Ignoring ties

Follow-ups

  • How would you show a friends-only leaderboard?
  • How would you support 500 million players?
  • How do you reset weekly boards?

Tips

  • Name the sorted-set commands
  • Show the tie-break encoding
  • Say how you rebuild after a cache loss

Evaluation rubric

  • Correct use of a sorted structure for ranks
  • Capacity math for memory and updates
  • Durability and rebuild plan
  • Handles ties and scaling limits