Interview Study Guide

Guide / System design Most asked

11. Top asked system design questions

Created · Updated · 16 min read

For each: the core challenge, the key components, and the deep dive interviewers push on. Practise each end to end with the 45-minute framework.

1. URL shortener (TinyURL, bit.ly). Read-heavy (100:1). Base62 of a Snowflake/counter ID or pre-generated key pool (avoid hash collisions). KV store (DynamoDB/Cassandra) short → long, Redis cache, 301 (cacheable) vs 302 (trackable) redirects. Deep dive: ID generation without collisions, analytics via async click events to Kafka, custom aliases, expiry.

2. Rate limiter. Token bucket in Redis with Lua; where it runs (gateway vs service vs sidecar); per-user/IP/tenant keys; fail-open vs fail-closed when Redis is down; multi-region (local limits + async sync).

3. News feed (Twitter/Instagram). Fan-out on write vs read vs hybrid for celebrities; feed cache per user in Redis (list of post IDs); ranking service; media on S3 + CDN. Deep dive: the celebrity problem, pagination with cursors, freshness.

4. Chat system (WhatsApp/Slack). WebSocket gateways, connection registry, message store in Cassandra partitioned by conversation_id + time bucket, per-conversation sequence numbers for ordering, sent/delivered/read receipts, offline delivery via push, group fan-out. Deep dive: reconnection and missed-message sync, ordering, end-to-end encryption at a high level.

5. Notification system. Ingestion API → Kafka → per-channel workers (push/SMS/email) → third-party providers; preferences, templates, dedupe keys, rate limits per user, retries + DLQ, priority queues (OTP before marketing).

6. Distributed cache (design Redis/Memcached). Consistent hashing, replication, eviction (LRU), hot keys, write policies, client-side vs proxy routing.

7. Typeahead / autocomplete. Trie or prefix index of top-K completions per prefix, precomputed offline from query logs, served from memory/Redis; updates batched; latency < 100 ms; personalization layered on top.

8. Web crawler. URL frontier (priority + politeness queues per host), DNS cache, fetchers, robots.txt, dedupe via Bloom filter + content hashing (SimHash for near-duplicates), distributed workers, recrawl scheduling.

9. Ride-hailing (Uber/Ola). Driver location updates every ~4 s into a geospatial index (geohash/H3 in Redis), matching service, trip state machine, surge pricing, WebSocket updates to riders. Deep dive: write-heavy location stream, matching consistency (one driver, one ride → conditional update/lock).

10. Video streaming (YouTube/Netflix). Upload → S3 → transcoding pipeline (DAG of jobs, multiple resolutions) → HLS/DASH segments → CDN; adaptive bitrate; metadata DB; view counts approximate and async.

11. E-commerce checkout and inventory (Amazon/Nykaa/Flipkart). Cart service, inventory reservation with TTL (reserve on checkout, release on timeout), order service state machine, payment with idempotency, saga across inventory → payment → shipping, outbox events. Deep dive: no overselling, idempotent payments, flash-sale load.

12. Payment system. Idempotency keys, ledger with double-entry, payment state machine, gateway integration, webhooks, reconciliation, PCI scope reduction via tokenization, retries with unknown outcome.

13. Ticket booking (BookMyShow). Seat map, temporary hold with expiry (Redis SET NX EX or DB row with held_until), confirm on payment, contention on popular shows (queue/virtual waiting room), consistency — never double-book.

14. Distributed job scheduler (cron at scale). Job store, scheduler partitions jobs by time buckets, workers pull with leases, at-least-once execution + idempotent jobs, retries, leader election for the scheduler.

15. Leaderboard / gaming scores. Redis sorted sets (ZINCRBY, ZREVRANGE), sharding by game/region, top-K merge across shards, periodic persistence, approximate ranks for huge sets.

16. Search system (product search). Inverted index in Elasticsearch fed by CDC, analyzers, ranking (BM25 + business signals), faceting, typo tolerance, sharding/replicas, reindex with alias swap.

17. Metrics/logging platform. Agents → Kafka → stream processing → time-series DB (hot) + object storage (cold), downsampling, retention tiers, high-cardinality labels as the main danger.

18. File storage and sync (Dropbox/Google Drive). Chunking (4 MB blocks), content hashes for dedupe, metadata DB, block store on S3, sync via change notifications, conflict copies.

19. Feature flag / A/B testing platform. Flag config store, SDKs cache rules locally and stream updates, deterministic bucketing (hash(user_id + experiment) % 100), exposure logging to analytics, kill switches.

20. Multi-tenant SaaS (payroll/HR/CRM). Tenant isolation model (shared schema with tenant_id vs schema per tenant vs DB per tenant), noisy neighbours, per-tenant config, audit logs, batch jobs (monthly payroll run) with idempotency and checkpoints.

Others worth one practice pass each: Google Docs (collaborative editing: OT vs CRDTs), Proximity service (Yelp), Stock exchange / order matching, Distributed message queue (design Kafka), Pastebin, API gateway, Unique ID generator, Ad click aggregation, Hotel reservation, Email service.

11.1 Full walkthrough — E-commerce checkout with flash-sale inventory#

1. Requirements. Functional: add to cart, checkout, reserve stock, pay, create order, notify. Non-functional: never oversell, never double-charge, checkout p99 < 1 s (excluding the payment gateway), survive a 10-minute flash sale at 50× normal traffic, 99.95% availability for browsing, 99.9% for checkout. Out of scope: search, recommendations, returns.

2. Estimates. 10M DAU, 2% convert → 200K orders/day ≈ 2.3 orders/s average. A flash sale: 1M users chasing 10K units in 10 minutes → bursts of ~20K checkout attempts/s on a few SKUs. Lesson: the average is trivial; the hot SKU under contention is the whole problem.

3. APIs.

  • POST /cart/items · POST /checkout (returns checkout_id, reserves stock) · POST /orders with Idempotency-Key (pays and confirms) · GET /orders/{id} · webhook POST /payments/webhook.

4. Data model.

  • inventory(sku, available, reserved, version) in Postgres (source of truth).
  • reservations(id, sku, user_id, qty, expires_at, status) — holds stock for ~10 minutes.
  • orders(id, user_id, idempotency_key UNIQUE, status, total, created_at) — state machine.
  • payments(id, order_id, gateway_ref, status, amount) and an append-only ledger.
  • outbox(id, aggregate_id, event_type, payload, published_at).

5. High-level design. Client → CDN (product pages cached) → API gateway (auth, rate limit) → Cart service (Redis, user-keyed) → Checkout/Order service → Inventory service → Payment service → gateway (Razorpay/Stripe). Order events leave via outbox → Kafka → notifications, fulfilment, analytics.

Happy path: checkout reserves stock (atomic decrement of available, insert reservation) → user pays → payment service calls the gateway with order_id as its idempotency key → webhook confirms → order PAID, reservation CONFIRMED, outbox event OrderPaid → fulfilment.

[embedded content: Checkout architecture · saga, outbox, idempotent payment]

The order service drives the saga; the outbox makes events as durable as the order row, and the webhook closes the payment loop.

6. Deep dive A — never oversell.

  • Normal traffic: UPDATE inventory SET available = available - :q, reserved = reserved + :q WHERE sku = :s AND available >= :q; 1 row updated = success, 0 = out of stock. One atomic statement, no read-then-write race.
  • Flash sale: one Postgres row taking 20K updates/s becomes a lock-contention hot spot. Move the hot SKU’s counter to Redis: preload stock:sku = 10000; a Lua script does check-and-decrement atomically and records the user (SADD buyers:sku user to enforce one per user). Winners get a reservation token; losers get “sold out” instantly. Persist reservations to Postgres asynchronously via a queue, and reconcile Redis vs DB counts after the sale.
  • Put a virtual waiting room (queue with a position) in front if even Redis plus app servers can’t absorb the burst; admit users at a rate the backend handles.
  • Reservation expiry: a sweeper (or Redis keyspace expiry + DB job) returns stock for reservations past expires_at that weren’t paid. The release must be idempotent and conditional (WHERE status = 'HELD') so it can’t race a late payment.

7. Deep dive B — charge exactly once. Idempotency key on POST /orders with a unique constraint; guarded transitions (WHERE status = 'PAYMENT_PENDING'); gateway idempotency key = order_id; webhook dedupe by gateway event ID; PAYMENT_UNKNOWN state on timeout resolved by polling the gateway; nightly reconciliation against the settlement report; auto-refund if payment succeeded but the reservation had already expired (or honour it if stock remains). Details in section 7.

8. Deep dive C — the saga. Orchestrated saga in the order service: reserve inventory → authorize payment → confirm order → capture payment → request shipment. Compensations: payment fails → release reservation; shipment creation fails → retry, then flag for ops (don’t refund automatically for a transient error). Use a workflow engine (Temporal) or a persisted state machine so a crash resumes mid-saga.

9. Failure modes.

FailureHandling
User double-clicks “Pay”Same idempotency key → second request returns the first result
Gateway timeoutPAYMENT_UNKNOWN, show “processing”, resolve via webhook/poll
Order service crashes after DB commitOutbox relay publishes the event on restart
Redis fails during flash salePause sale (fail closed) rather than oversell; Redis with AOF + replica; reconcile from DB
Kafka downOutbox rows accumulate; published when Kafka returns; checkout unaffected
Inventory DB primary failsFailover; in-flight checkouts retry idempotently

10. Scaling and evolution. Shard orders by user_id; inventory by sku (or by warehouse); read replicas and CDN for catalogue; separate flash-sale path from normal checkout; multi-warehouse inventory adds an allocation service.

Follow-ups to rehearse: How long should a reservation last? (Long enough to pay, short enough to avoid hoarding: ~10 min, shorter in flash sales.) How do you stop bots? (Rate limits per user/device, CAPTCHA at queue entry, one-per-user rule, purchase limits.) What if price changes during checkout? (Lock the price in the checkout record, with expiry.)

11.2 Full walkthrough — Chat system (WhatsApp)#

1. Requirements. 1:1 and group chat (up to ~500 members), online presence, sent/delivered/read receipts, offline delivery, message history on multiple devices, media attachments. Non-functional: delivery latency < 200 ms when both users are online, no message loss, per-conversation ordering, high availability.

2. Estimates. 500M DAU × 40 messages/day = 20B messages/day ≈ 230K messages/s average, ~700K/s peak. 100 bytes average text → ~2 TB/day raw (×3 replication). Concurrent connections: maybe 200M → at ~100K connections per gateway node, ~2,000+ gateway servers.

3. Connections. Clients keep a persistent WebSocket (or MQTT on mobile) to a stateless-logic but connection-stateful gateway node. On connect, the gateway writes user:device → gateway_id to a connection registry (Redis, with TTL refreshed by heartbeats every ~30 s).

4. Send path.

  1. Client generates a client_msg_id (UUID) and sends {conversation_id, client_msg_id, body}.
  2. Gateway forwards to the chat service, which assigns a per-conversation sequence number (from a counter per conversation — Redis INCR or the DB partition), stores the message, and acks the sender (“sent” ✓). Dedupe on (conversation_id, client_msg_id) so client retries don’t duplicate.
  3. Chat service publishes to a fan-out queue (Kafka, partitioned by conversation_id to keep order).
  4. Delivery workers look up each recipient’s gateways in the registry and push via internal pub/sub to those gateways → WebSocket to devices.
  5. Recipient device acks → “delivered” (✓✓) receipt flows back the same way; opening the chat sends “read”.
  6. Offline recipients: message stays stored; a push notification (APNs/FCM) is sent; on reconnect the device syncs.

[embedded content: Chat send path · sequence, store, fan out, deliver or push]

The chat service is the single point that assigns order and acks the sender; delivery reaches the recipient’s current gateway or falls back to push.

5. Storage. Messages in Cassandra/ScyllaDB: partition key (conversation_id, month_bucket), clustering key seq DESC. Fits the access pattern (latest messages of one conversation, append-heavy, huge volume) and keeps partitions bounded. User→conversations index in a separate table. Media goes to S3 via pre-signed upload URLs; the message stores only the media key; CDN serves downloads.

6. Deep dive A — ordering. Wall clocks differ between devices, so order by the server-assigned per-conversation sequence. Kafka partitioning by conversation_id keeps order through the pipeline. Clients display by seq and can detect gaps (got 41, then 43 → fetch 42).

7. Deep dive B — connection drops and sync. Each device tracks the last seq it has per conversation (or a global per-user inbox cursor). On reconnect: exponential backoff + jitter, re-authenticate, send cursors; server returns messages after them (paged), or a snapshot if the gap is huge. The client resends any unacked outgoing messages with the same client_msg_id (deduped server-side). Reconnecting to a different gateway is fine because the registry updates. This is exactly the “what if the connection drops?” follow-up.

8. Deep dive C — group chat fan-out. For groups up to a few hundred members, fan-out on write to each member’s delivery queue is fine. For very large channels (thousands+), store once and let clients pull (fan-out on read), push only notifications.

9. Presence. Heartbeats update last_seen in Redis; presence changes are published only to users who have that contact’s chat open or are in the contact list (subscribe on demand) — broadcasting every status change to every contact would dwarf message traffic.

10. Failure modes. Gateway node dies → clients reconnect elsewhere and sync by cursor; chat service crash after storing but before publishing → outbox or a retry sweep of undelivered messages; Cassandra node down → replication factor 3 with QUORUM writes; registry stale entry → delivery fails, worker treats the user as offline and sends push.

11. End-to-end encryption (high level). Signal protocol: keys live on devices; the server stores and forwards ciphertext only, so it can’t search or moderate content; multi-device means encrypting per device.

Follow-ups: “How do you store ‘delivered/read’ for a 500-person group?” (aggregate counts, or per-member receipts only on request). “How do you search message history?” (on-device search if E2EE; otherwise an index in Elasticsearch). “How would you rate-limit spam?” (per-user send limits, new-account limits, reports).

11.3 Full walkthrough — Distributed rate limiter#

1. Requirements. Limit requests per client (user ID, API key, IP, tenant) with configurable rules (e.g. 100 req/min per user, 10 logins/min per IP, 10K req/min per tenant). Return 429 with Retry-After. Non-functional: adds < 2 ms p99, works across hundreds of API servers, highly available, approximately accurate is acceptable (± a few %).

2. Estimates. 1M requests/s across the fleet, each needing a limit check → 1M+ counter operations/s. A Redis cluster handles that with sharding (~100K ops/s per node → 10+ shards, more for headroom).

3. Where it runs. Options: client-side (untrustworthy), API gateway / edge (central, protects everything behind it — usual choice), sidecar or middleware in each service (finer-grained rules). Answer: gateway for global per-client limits, plus per-service limits for expensive endpoints.

4. Algorithm choice. Token bucket: allows controlled bursts, two numbers per key (tokens, last_refill_ts), easy to explain. Alternative: sliding window counter for smoother limits. (Full comparison in section 10.1.)

5. Implementation.

  • Key: rl:{rule}:{client_id}. Redis hash with tokens and ts.
  • A Lua script runs atomically: read tokens and ts, refill min(capacity, tokens + (now − ts) × rate), if tokens ≥ 1 decrement and allow, else deny; set TTL so idle keys disappear.
  • Use Redis server time (or pass a monotonic timestamp) to avoid clock skew between API servers.
  • Rules stored in a config service/DB, cached in each gateway, hot-reloaded on change.
  • Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After.

[embedded content: Rate limiter · gateway, Redis token bucket, 429 path]

The gateway runs one atomic Lua check per request against Redis; the local bucket cache (deep dive A) cuts most of those round trips.

6. Deep dive A — latency and Redis load. One round trip per request is ~0.5 ms in the same zone. To cut load: local + global hybrid — each gateway keeps a local token bucket with a share of the limit and syncs with Redis periodically (or fetches tokens in batches of, say, 10). Trades exactness for far fewer Redis calls.

7. Deep dive B — Redis is down. Choose deliberately: fail open (allow traffic; protects availability, risks overload/abuse) for general API limits, fail closed (deny) for security-sensitive limits like login attempts or OTP sends. Fall back to local in-memory limits during the outage. Use Redis replicas + Sentinel/Cluster failover.

8. Deep dive C — hot keys. One tenant hammering the API makes its key hot on one shard. Local pre-limiting at gateways absorbs most of it; shard a tenant’s bucket into N sub-buckets each with limit/N.

9. Multi-region. Per-region limits (limit/regions) are simple and fast; true global limits need cross-region sync (async counter replication, accepting brief overshoot).

10. Beyond counting. Different tiers (free vs paid), cost-based limits (an expensive search endpoint costs 10 tokens), concurrency limits (max in-flight requests), and adaptive load shedding that lowers limits when backend latency rises.

Follow-ups: “Why not fixed windows?” (2× burst at the boundary). “How do you rate-limit by IP behind NAT/mobile carriers?” (IP limits are coarse and generous; prefer user/device/API key). “How do you test it?” (unit-test the algorithm with a fake clock; load-test concurrency for races).

11.4 Full walkthrough — News feed with the celebrity problem#

1. Requirements. Users post (text + media), follow others, and see a home feed of followed users’ posts, newest or ranked, with infinite scroll. Non-functional: feed loads p99 < 300 ms, a new post appears in followers’ feeds within seconds (eventual consistency is fine), read-heavy (~100 reads per write).

2. Estimates. 300M DAU, 10 feed loads/day → 3B feed reads/day ≈ 35K/s (peak ~100K/s). 1 post/user/day → ~3.5K posts/s. Average 200 followers; some accounts have 50M+.

3. Data model. users, follows(follower_id, followee_id) (sharded by follower and also stored by followee for fan-out), posts(post_id, author_id, created_at, body, media_keys) sharded by author_id, media in S3 + CDN. Feed cache: Redis list/sorted set per user of the latest ~800 post IDs (not full posts).

4. Fan-out on write (push). On a post: write to posts, publish PostCreated to Kafka; fan-out workers read the author’s followers and push the post_id into each follower’s feed cache. Reads are then one Redis call + a batched post hydration (multi-get from a post cache). Fast reads, but writes multiply by follower count.

5. Deep dive A — the celebrity problem. A 50M-follower account posting triggers 50M cache writes — slow and wasteful (most followers won’t open the app soon). Hybrid: push for normal authors; for authors above a threshold (say 100K followers), don’t fan out. At read time, merge the user’s precomputed feed with recent posts pulled from the few celebrities they follow (each celebrity’s recent posts are hot in cache anyway). Also skip fan-out to inactive users; build their feed on demand when they return.

[embedded content: Hybrid feed · push for normal authors, pull for celebrities]

Normal posts are pushed into followers’ Redis feeds; celebrity posts skip fan-out and are merged in by the feed service when a reader opens the app.

6. Deep dive B — ranking. Chronological is simple. Ranked feed: candidate generation (feed cache + celebrity posts + recommended posts) → feature fetch (author affinity, engagement, recency) → ML ranking model → rerank for diversity and policy filters. Cache the ranked page briefly per user so scrolling is stable.

7. Deep dive C — pagination. Cursor-based: cursor = (score or created_at, post_id) of the last item; never offset (new posts shift offsets and cause duplicates). For ranked feeds, store the ranked list snapshot for the session.

8. Writes and consistency. The author should see their own post immediately (read-your-writes: insert into their own feed synchronously or merge locally on the client). Deleting a post: mark deleted in posts; hydration filters it out, so no need to purge 50M caches; a lazy cleanup job trims stale IDs.

9. Failure modes. Fan-out lag during spikes (Kafka absorbs; feeds are just slightly stale); Redis feed cache lost (rebuild on read from the follow graph + recent posts, rate-limited); hot celebrity post (cached in local in-process caches on the read tier); a viral post’s like counter (sharded counters or approximate counts aggregated asynchronously).

10. Storage growth. Keep feed caches bounded (~800 IDs); older pages come from a fallback query over followees’ post tables; archive old posts to cheaper storage.

Follow-ups: “How do you pick the celebrity threshold?” (cost model: fan-out writes vs read-time merge latency; tune with metrics). “How do you handle a user following 5,000 accounts?” (cap pull-merge sources, rely on push for most). “How do you insert ads?” (ad service merges ad slots at read time with frequency caps).

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes