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
Start here: the concepts every design uses, each told as a story you'll remember.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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.
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.
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).
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.