← All posts

Series

System Design Mastermind

Real products reverse-engineered for Senior system-design interviews. Start with Foundations (the core concepts, told as stories), then three tracks: the classics, platform and infrastructure, and AI/ML systems. Each one walks the flow, the numbers, the APIs, the databases and what happens when each piece fails, with every claim tagged as seen, inferred or unknown.

Start here: F01
Foundations
18/18
Classics
6/10
Platform & Infra
5/12
AI / ML systems
8/9
Published
37 · 12 coming
Classics30 min01Uber system design, reverse-engineered: from tap to pickupFoundations20 minF01How a request travels: DNS, load balancers, gateways and open connectionsFoundations22 minF02The interview framework: requirements, numbers and scope before boxesFoundations20 minF03Back-of-envelope estimation: from users to servers in one minuteFoundations22 minF04APIs and real-time communication: REST, gRPC, retries, webhooks and live updatesFoundations24 minF05Databases: data models, indexes and transactionsFoundations25 minF06Replication and sharding: copying and splitting your dataFoundations24 minF07Caching: hit ratios, invalidation and stampedesFoundations25 minF08Consistency, CAP and quorums: what replicas promiseFoundations25 minF09Coordination: clocks, leaders, locks and consensusFoundations25 minF10Queues and event streamsClassics30 min12Rate limiter system design: fair limits at a million requests a secondFoundations25 minF11Idempotency, exactly-once and sagasFoundations24 minF12Scaling and performanceFoundations25 minF13Reliability and disaster recoveryFoundations25 minF14Observability and safe deploymentsFoundations26 minF15Security essentials for system designFoundations27 minF16Search, feeds and geo building blocksPlatform & Infra32 min19Distributed job scheduler system design: on time, at least once, never lostFoundations28 minF17Data pipelines: batch and streamFoundations30 minF18AI foundations: inference, RAG and agentsAI / ML34 min22LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changesClassics32 min23WhatsApp system design: chat, offline delivery and the three ticksPlatform & Infra32 min24Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trustAI / ML34 min25RAG assistant over company docs system design: retrieval, permissions and answers you can trustClassics32 min26Ticketmaster system design: selling seats without double-bookingPlatform & Infra33 min27Kafka system design: a distributed log that never loses an acknowledged messageAI / ML35 min28AI agent platform system design: tools, durable runs, approvals and agents you can trustClassics32 min29News feed system design: fan-out, celebrities and rankingPlatform & Infra32 min30Ad click aggregator system design: exactly-once counts, late clicks and hot adsAI / ML34 min31Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanishClassics32 min32Notification system design: push, email and SMS without spam, drops or duplicatesPlatform & Infra33 min33Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliationAI / ML34 min34Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a dayAI / ML34 min35Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B testsAI / ML33 min36LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rolloutsAI / ML34 min37AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals

Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

Classics

6 published · 4 comingThe problems almost every loop draws from.

01

Uber system design, reverse-engineered: from tap to pickup

In-memory geo index sharded by map cell → rank nearby drivers by road ETA → offer to one driver with a 15 s timeout → accept with compare-and-set → push updates to both apps.

30 min · interactive Preview
12

Rate limiter system design: fair limits at a million requests a second

Check every request once in the API gateway → one atomic Lua script per request on the caller's shard of a sharded Redis (token bucket for per-second, window for per-day) → 429 + Retry-After, or forward with RateLimit headers → local cache for keys already over → each rule fails open or closed on purpose.

30 min · interactive Preview
23

WhatsApp system design: chat, offline delivery and the three ticks

One long-lived encrypted connection per device → the chat server stores a copy per recipient device in a replicated offline queue, then acks (✓) → session lookup, forward or push → the device saves and acks, the copy is deleted (✓✓) → a read receipt when opened. Client-made ids and dedupe at both ends, backoff with jitter on reconnect, Sender Keys for groups.

32 min · interactive Preview
26

Ticketmaster system design: selling seats without double-booking

Cached reads for browsing → a seat inventory with one row per seat, sharded by event → a hold is one conditional UPDATE (only if free or expired) with a 10-minute timer → pay with a client-made idempotency key → confirm only if the hold is still yours, plus an outbox for tickets. A waiting room admits fans at the rate booking can serve.

32 min · interactive Preview
29

News feed system design: fan-out, celebrities and ranking

Write each post once → fan-out workers push its id into active followers' capped Redis timelines → accounts above ~1M followers are merged at read time instead → the feed service gathers ~1,500 candidates, a light model trims them, a heavy model predicts actions, a weighted sum orders them → deletes and blocks are checked at read time, pages use a cursor.

32 min · interactive Preview
32

Notification system design: push, email and SMS without spam, drops or duplicates

One Notify API with an idempotency key → a router checks dedupe, preferences, caps and quiet hours, picks live devices → per-channel queues with a transactional lane apart from bulk → workers call APNs, FCM, email and SMS with priority, expiry and a collapse id, retry 429s with backoff and delete dead tokens → campaigns paced below the provider quota, OTPs fall back to SMS.

32 min · interactive Preview
··

Video streaming (YouTube / Netflix)

Coming next
··

URL shortener

Coming next
··

Typeahead / autocomplete

Coming next

Platform & Infra

5 published · 7 comingWhat Senior platform loops lean on.

19

Distributed job scheduler system design: on time, at least once, never lost

Jobs in a sharded store with a precomputed next_run_at → one scheduler per shard (lease + fencing token) claims due jobs every second: insert run (unique job_id + time) and advance next_run_at in one transaction → durable queue with deliver-at, enqueued a little early → workers lease runs, heartbeat, call the target with the run id as idempotency key → backoff, then a DLQ. At-least-once, made safe by idempotency.

32 min · interactive Preview
24

Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trust

Agents add up metrics for 10 s and batch them with logs → intake checks key and quotas, appends to a durable log, then 202 → writers map tags to series ids in an inverted index and store compressed points with roll-ups → logs: index a slice, archive all → monitors evaluate a window that ends in the past, and the whole stack is watched from outside.

32 min · interactive Preview
27

Kafka system design: a distributed log that never loses an acknowledged message

Topics split into partitions; the producer hashes the key, batches and sends to the partition leader → the leader appends to the page cache, followers in other zones pull, acks=all waits for every in-sync copy (RF 3, min ISR 2) → consumer groups pull from offsets and commit them → KRaft controllers move leaders; tiered storage keeps history.

33 min · interactive Preview
30

Ad click aggregator system design: exactly-once counts, late clicks and hot ads

Signed click URL → click service appends to Kafka and 302s → Flink dedupes by click id, counts per ad in 1-minute event-time windows, upserts (ad, minute) rows into an OLAP store → a per-click counter paces budgets → a nightly recount from raw clicks is what billing reads.

32 min · interactive Preview
33

Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

Card → vault → token; confirm with an Idempotency-Key → attempt row written before the bank call → gateway with timeouts and breakers → result + outbox in one commit → event log → append-only double-entry ledger and signed webhooks → a timeout is 'unknown', resolved by status check and the next day's settlement file → payouts from balances.

33 min · interactive Preview
··

Web crawler

Coming next
··

File sync (Dropbox)

Coming next
··

Google Docs: real-time collaboration

Coming next

AI / ML systems

8 published · 1 comingLLM and ML systems, where interviews are heading.

22

LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes

Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.

34 min · interactive Preview
25

RAG assistant over company docs system design: retrieval, permissions and answers you can trust

Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.

34 min · interactive Preview
28

AI agent platform system design: tools, durable runs, approvals and agents you can trust

A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.

35 min · interactive Preview
31

Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish

Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.

34 min · interactive Preview
34

Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day

Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.

34 min · interactive Preview
35

Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests

Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.

34 min · interactive Preview
36

LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts

Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.

33 min · interactive Preview
37

AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals

Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.

34 min · interactive Preview
··

Feature store and training platform

Coming next