High-Level Design
Requirements to architecture: estimation, building blocks, databases, consistency and consensus, resilience, APIs, security, 35 problem summaries and 8 full worked designs.
00HLD atlas: topics and routes
The whole sheet on one screen. Select an area or topic to jump to it; hover the boxes in any diagram below for explanations.
HLD topic atlas#
How to use this sheet#
- Learning: read Interview method, then Building blocks and Data and storage in order; they are the vocabulary for everything else.
- Going deeper: Distributed systems and Scale and resilience cover the senior-level follow-ups.
- Practising: pick a worked design, cover the page, design it out loud in 45 minutes, then compare.
- Interview tomorrow: numbers to know, the 35-problem table, follow-up questions, then the last-minute checklist.
The five questions behind every design#
| Question | Where it's covered |
|---|---|
| What load, and what must never break? | Estimates · Requirements |
| Where does the data live? | Data model · Store by access |
| How do reads stay fast? | Caching · Replicas |
| How do writes stay correct? | Transactions · Isolation |
| What happens when parts fail? | Resilience · Disaster recovery |
Check yourself 2 questions
First question behind every design?
Show answer
What load, and what must never break?
Which topics answer 'how do reads stay fast?'
Show answer
Caching and replication.
Takeaway What load and invariant, where data lives, how reads stay fast, how writes scale, and what happens on failure.
01HLD: requirements to architecture
60-minute interview route#
| Time | Focus |
|---|---|
| 0–5 | Core use cases, constraints, invariants |
| 5–10 | Peak QPS, storage, bandwidth, retention |
| 10–15 | APIs and entities |
| 15–30 | Client → edge → services → stores |
| 30–50 | Deep-dive 2–3 workload risks |
| 50–60 | Failures, trade-offs, security, cost |
What interviewers score
- Requirements: you ask before you draw, and write the numbers down.
- Trade-offs: every choice names its cost and the alternative you rejected.
- Bottlenecks: you find the hot path, hot key or fan-out before being asked.
- Failure thinking: retries, idempotency, degradation and data loss are covered.
- Communication: you drive the session, summarise and check in at each step.
Keep the last 3–5 minutes to walk the design back against the requirements.
Check yourself 2 questions
What happens in minutes 5–10?
Show answer
Peak QPS, storage, bandwidth and retention estimates.
Where does most time go?
Show answer
Deep dives, roughly minutes 30–50.
Takeaway Use cases and invariants, numbers, APIs and entities, the end-to-end path, deep dives, then failure and trade-offs.
Design flow#
flowchart TD R[Requirements + invariants] --> Q[Workload and capacity] Q --> A[APIs and entities] A --> D[Read and write paths] D --> B[Scale and correctness bottleneck] B --> F[Failure, security, recovery] F --> S[SLO, cost, rollout]
Check yourself 2 questions
What comes right after requirements?
Show answer
Workload and capacity estimates.
What should deep dives target?
Show answer
The scale and correctness bottleneck.
Takeaway Requirements and invariants, workload, APIs and entities, read and write paths, the bottleneck, then failure, security and operations.
Workload signal → architecture lever#
| Signal | Start with | Watch for |
|---|---|---|
| Read-heavy / global | CDN, cache, replicas, precompute | Freshness, invalidation, hot keys |
| Write-heavy / replay needed | Partitioned log, async consumers | Ordering, backpressure, duplicates |
| Long-running jobs | Queue + workers + status API | Retry safety, DLQ, progress |
| Real-time updates | WebSocket, SSE, or streaming log | Reconnects, fan-out, ownership |
| Media / search | Object store + CDN / search index | Access control, freshness, recall |
Check yourself 2 questions
Read-heavy global workload: first levers?
Show answer
CDN, cache, read replicas, precomputation.
Write-heavy with replay needs?
Show answer
A partitioned log with async consumers.
Takeaway Read-heavy → CDN, cache, replicas; write-heavy → partitioned log and async consumers; each lever has a watch-out.
Clarifying questions checklist#
| Area | Ask | Why it changes the design |
|---|---|---|
| Users and scope (functional requirements) | Who are the users? Which 3–5 actions matter? What is explicitly out of scope? | Prevents designing features nobody asked for |
| Scale | DAU, peak QPS, read:write ratio, data size today and in 3–5 years | Decides single DB vs sharding, caching, async processing |
| Latency | p50 and p99 targets for the main read and write paths | Decides caching, precomputation, regional deployment |
| Consistency | Must a user see their own write immediately? Can others see stale data, and for how long? | Strong vs eventual consistency per operation |
| Availability | Target SLO; single region or multi-region; what happens during an outage? | Replication, failover, degradation strategy |
| Durability | Can any data be lost? Retention period? | Synchronous replication, backups, storage tiering |
| Security and compliance | Authentication, sensitive data (PII, payments), data residency | Encryption, isolation, regional storage, audit logs |
| Clients and access | Web, mobile, third-party API? Offline support? Real-time updates? | Protocols (REST, WebSocket, SSE), sync design |
| Cost and constraints | Budget, team size, existing systems that must be reused | Managed services vs self-hosted; simplicity |
Every row after the first is a non-functional requirement (NFR): how well the system must do its job rather than what it does.
Check yourself 2 questions
Why ask what's out of scope?
Show answer
It prevents designing features nobody needs.
Name two non-functional areas to clarify.
Show answer
Any two of: scale, latency, availability, consistency, durability, security, cost.
Takeaway Ask about users and scope, scale, latency, consistency, data, security and constraints, because each answer changes the design.
02Numbers to know & estimation
SystemDesign/08-reference/numbers-to-know.md, 02-capacity-estimation
Latency numbers#
| Op | Time |
|---|---|
| L1 cache | 0.5 ns |
| Branch mispredict | 5 ns |
| L2 cache | 7 ns |
| Mutex lock/unlock | 25 ns |
| Main memory | 100 ns |
| Compress 1 KB (Snappy) | 3 µs |
| Send 2 KB over 1 Gbps | 20 µs |
| Read 1 MB from memory | 250 µs |
| DC round trip | 500 µs |
| Read 1 MB SSD | 1 ms |
| HDD seek | 10 ms |
| Read 1 MB disk | 20 ms |
| CA → Netherlands → CA | 150 ms |
Takeaways: memory is ~10× faster than SSD for sequential reads and ~106× faster than a cross-continent round trip. Avoid chatty cross-region calls; batch, cache, and keep hot data in memory.
Check yourself 2 questions
Main memory reference?
Show answer
About 100 ns.
Round trip within a datacentre?
Show answer
About 0.5 ms.
Takeaway Memory is about 100 ns, SSD reads tens of µs, a datacentre round trip about 0.5 ms, cross-continent about 150 ms.
Storage, availability, sizes#
| Item | Value |
|---|---|
| HDD IOPS | 100–200 |
| SATA SSD IOPS | ~90K |
| NVMe IOPS | 500K–1M |
| 99.9% | 8.76 h/yr · 43.8 min/mo |
| 99.99% | 52.6 min/yr · 4.4 min/mo |
| 99.999% | 5.26 min/yr |
| 2^10 / 2^20 / 2^30 / 2^40 | KB / MB / GB / TB |
| 1 day | ~86,400 s ≈ 10^5 s |
| 1M req/day | ≈ 12 QPS (peak ×2–3) |
| Snowflake ID | 41b ts + 10b machine + 12b seq = 4096 IDs/ms/node |
Check yourself 2 questions
Downtime per year at 99.99%?
Show answer
About 52.6 minutes.
NVMe IOPS roughly?
Show answer
500K–1M.
Takeaway HDD hundreds of IOPS, NVMe up to a million; 99.9% is 8.76 hours down a year, 99.99% about 53 minutes.
Estimation recipe#
- QPS = DAU × actions/day ÷ 86,400; peak = 2–3× (consumer flash ≈ 12×)
- Storage = writes/day × size × retention × replication (3×)
- Bandwidth = QPS × payload
- Cache = 20% of daily reads (80/20 rule)
- Servers = peak QPS ÷ per-server QPS (~1–10K simple API)
- State only the numbers that change a design choice
Example: URL shortener
- 100M new URLs/day → ~1.2K writes/s; 100:1 reads → ~120K reads/s
- 500 B/row × 100M × 365 × 5y ≈ 90 TB
- Base62, 7 chars → 62^7 ≈ 3.5 T keys
Shortcuts
- 1 day ≈ 105 s, so 1M requests/day ≈ 12 QPS and 100M/day ≈ 1.2K QPS.
- 210 ≈ 103: 1 billion rows × 1 KB ≈ 1 TB.
- One commodity server: ~10K simple QPS, 64–256 GB RAM, a few TB SSD.
Check yourself 2 questions
QPS formula?
Show answer
DAU × actions per day ÷ 86,400.
Typical replication factor in storage estimates?
Show answer
3×.
Takeaway QPS = DAU × actions ÷ 86,400, peak 2–3×; storage = writes × size × retention × replication.
03Trade-offs, stores, caching & scale
SystemDesign/07-interview-templates/02-cheat-sheets (trade-offs, architecture-by-scale, concept map), 02 building blocks
Core trade-offs#
| Choice | Pick A when… | Pick B when… |
|---|---|---|
| CAP during a partition | Reject or limit conflicting writes when invariants need strong consistency (e.g., balances, unique reservations) | Accept writes and reconcile later when stale or duplicate state is tolerable (e.g., presence, some feed signals) |
| SQL vs NoSQL | joins, transactions, ad-hoc queries | huge scale, simple access, flexible schema |
| Sync vs async | user waits for result | slow / fan-out / retryable work |
| Push vs pull | few followers, real-time | celebrities, inactive users |
| Horizontal vs vertical | unbounded growth, HA | simple, early stage |
| Monolith vs micro | small team, early | independent scaling / teams |
| Stateful vs stateless | WebSocket sessions | API tier (scale freely) |
| Normalise vs denormalise | write-heavy, consistency | read-heavy, avoid joins |
| Latency vs throughput | user-facing | batch / analytics |
Check yourself 2 questions
When reject writes during a partition?
Show answer
When invariants need strong consistency, such as balances or unique reservations.
Push versus pull for feeds?
Show answer
Push for normal users, pull for celebrities (hybrid).
Takeaway Consistency versus availability, latency versus throughput, normalise versus denormalise, push versus pull: pick by the invariant and workload.
Store by access pattern#
| Access pattern | Store |
|---|---|
| Relational, transactions | PostgreSQL / MySQL |
| Key lookup, hot data | Redis / Memcached |
| Huge write volume, wide rows | Cassandra / DynamoDB |
| Full-text search | Elasticsearch (inverted index) |
| Blobs: images, video, files | S3 + CDN |
| Time series / metrics | InfluxDB / Prometheus / TSDB |
| Graph relationships | Neo4j / adjacency in KV |
| Event log / streaming | Kafka |
| Geospatial | Redis GEO / geohash / H3 / S2 |
| Vectors | HNSW (pgvector, FAISS, Pinecone) |
Check yourself 2 questions
Huge write volume with wide rows?
Show answer
Cassandra or DynamoDB.
Full-text search?
Show answer
Elasticsearch.
Takeaway Relational for transactions, Redis for hot keys, Cassandra or DynamoDB for huge writes, Elasticsearch for search, S3 for blobs.
Caching strategies#
| Strategy | Note |
|---|---|
| Cache-aside | app reads cache, on miss loads DB; most common |
| Write-through | write cache+DB together; consistent, slower writes |
| Write-back | write cache, flush later; fast, risk of loss |
| Write-around | write DB only; avoids polluting cache |
| Eviction | LRU / LFU / TTL |
| Stampede | request coalescing, jittered TTL, origin shield |
| Hot key | local micro-cache + key sharding (key#n) |
Check yourself 2 questions
Most common caching strategy?
Show answer
Cache-aside.
Risk of write-back?
Show answer
Data loss if the cache fails before flushing.
Takeaway Cache-aside is most common; write-through is consistent but slower; write-back is fast but risks loss.
Architecture by scale#
| Users | What breaks first → fix |
|---|---|
| 1K | single server + DB is fine |
| 10K | DB load → read replicas, cache |
| 100K | single app server → LB + stateless app tier, CDN |
| 1M | DB writes → sharding, async queues, search index |
| 10M+ | multi-region, CDN everywhere, cell architecture, event-driven |
Check yourself 2 questions
What typically breaks first around 10K users?
Show answer
Database load: add read replicas and a cache.
At around 1M users?
Show answer
Database writes: shard and add async queues.
Takeaway Fix what breaks at each scale: replicas and cache at 10K, load-balanced stateless apps at 100K, sharding and queues at 1M.
Concept → problem map#
| Concept | Shows up in |
|---|---|
| Consistent hashing | KV store, distributed cache, GitHub storage |
| Trie | autocomplete, typeahead |
| Inverted index | search, tweets search |
| Geohash / H3 | ride sharing, maps, nearby |
| Snowflake | IDs, tweets, URL shortener |
| Token bucket | rate limiter, API gateway |
| Min-heap / timer wheel | job scheduler |
| Fan-out | twitter, instagram, notifications, chat |
| Distributed lock / SETNX | ticketmaster, booking |
| Bloom filter | web crawler, dedup |
Check yourself 2 questions
Which concept powers autocomplete?
Show answer
A trie.
Which concept powers 'drivers near me'?
Show answer
Geohash or H3 geo indexing.
Takeaway Consistent hashing, tries, inverted indexes and geohashes each show up in specific design problems.
Reliability toolkit#
- Idempotency keys on every retryable write
- Retries w/ exponential backoff + jitter; circuit breaker; timeouts
- Outbox pattern (avoid dual-write); saga with compensations
- Leader election (Raft / ZooKeeper); quorum R+W>N
- Back-pressure, DLQs, rate limits, graceful degradation
- Observability: metrics, logs, traces; SLO / error budgets
Check yourself 2 questions
What avoids dual-write inconsistency?
Show answer
The outbox pattern.
Why add jitter to retries?
Show answer
To avoid synchronized retry storms.
Takeaway Idempotency keys, retries with backoff and jitter, circuit breakers, timeouts, the outbox pattern and sagas.
Caching failure modes#
| Problem | What happens | Fix |
|---|---|---|
| Stampede (thundering herd) | A hot key expires; thousands of requests hit the database at once | Request coalescing or a per-key lock; refresh ahead of expiry; serve stale while revalidating |
| Penetration | Requests for keys that don't exist always miss and hit the database (often an attack) | Cache negative results with a short TTL; Bloom filter of valid keys; validate input |
| Avalanche | Many keys expire at the same moment, or the cache cluster restarts cold | Add random jitter to TTLs; warm the cache before traffic; replicate the cache |
| Hot key | One key's traffic exceeds a single cache node | Local in-process cache; split the key into copies (key#1..n); CDN for public data |
| Big key | A huge value blocks the node and the network | Split into pages or fields; compress; store the blob elsewhere and cache a pointer |
| Stale or inconsistent data | Cache and DB disagree after concurrent writes | Delete-on-write after the DB commit, short TTLs, versioned keys, CDC-driven invalidation |
| Cache pollution | One-off scans evict genuinely hot data | Admission policies (TinyLFU), don't cache bulk reads |
Check yourself 2 questions
Fix for a cache stampede?
Show answer
Request coalescing or a per-key lock, refresh-ahead, or serving stale.
What is cache penetration?
Show answer
Requests for keys that don't exist, hitting the database every time; cache negatives or use a Bloom filter.
Takeaway Stampedes, penetration, avalanches and hot keys each have a known fix.
04Building blocks catalogue
Each component you might draw, what it is for, the choice you have to make, and the number or failure mode to mention.
Components at a glance#
| Component | Role | Key choices | Say this |
|---|---|---|---|
| DNS | Name → IP; coarse geo routing | GeoDNS, latency routing, low TTL for failover | TTL caching delays failover by minutes |
| CDN | Edge cache for static, media, some API responses | Push vs pull; cache keys; signed URLs; origin shield | Offloads 80–95% of static bytes; invalidation is slow |
| Load balancer | Spread traffic, health-check, terminate TLS | L4 (TCP, fast) vs L7 (HTTP routing, headers); algorithm below | Make it redundant (active-passive pair or managed LB) |
| API gateway | Single entry: auth, rate limit, routing, aggregation | Managed vs Envoy/Kong; BFF per client | Keep business logic out of it |
| Stateless app tier | Business logic; scale horizontally | Session state in Redis/JWT, not memory | Autoscale on CPU or queue depth |
| Cache | Fast reads, hot data | Redis (structures, persistence) vs Memcached (simple, multithreaded) | Redis ~100K+ ops/s per node; sub-ms |
| Relational DB | Transactions, joins, constraints | Postgres/MySQL; replicas; partitioning; Spanner/CockroachDB for global SQL | One primary ≈ 5–20K writes/s depending on row size |
| Key-value / wide-column | Massive write throughput, simple access | DynamoDB, Cassandra, ScyllaDB; partition + clustering key | Design the table per query; no joins |
| Document DB | Flexible JSON per entity | MongoDB, Firestore | Embed what's read together; reference what grows unbounded |
| Search engine | Full-text, facets, fuzzy match | Elasticsearch/OpenSearch; fed by CDC | Near-real-time (~1 s refresh), not the source of truth |
| Object storage | Blobs: images, video, backups, data lake | S3/GCS; multipart upload; lifecycle tiers | 11 nines durability; upload direct via pre-signed URL |
| Message queue | Task distribution, decoupling | SQS, RabbitMQ; visibility timeout; DLQ | At-least-once → consumers must be idempotent |
| Event log | Ordered, replayable stream | Kafka, Pulsar, Kinesis; partitions, retention | Ordering only within a partition |
| Stream processor | Stateful real-time aggregation | Flink, Kafka Streams, Spark Structured Streaming | Windows, watermarks, checkpointing |
| Batch / warehouse | Analytics over history | Spark; BigQuery, Snowflake, Redshift; lakehouse (Delta, Iceberg) | Columnar formats (Parquet) for scans |
| Coordination | Leader election, config, locks | ZooKeeper, etcd, Consul | Small, strongly consistent; don't store data there |
| Workflow engine | Durable multi-step processes | Temporal, Step Functions, Airflow (batch) | Retries and timers survive crashes |
| Service discovery / mesh | Find instances; mTLS, retries, telemetry | Consul, Kubernetes DNS; Istio/Linkerd sidecars | Adds latency hop; centralises policy |
Check yourself 2 questions
Why do low DNS TTLs matter?
Show answer
TTL caching delays failover by minutes.
What does a CDN cache?
Show answer
Static content and media at the edge.
Takeaway DNS, CDN, load balancers, gateways, caches, queues, databases and object stores each have a role and key choices.
Load-balancing algorithms#
| Algorithm | Use when |
|---|---|
| Round robin / weighted | Uniform, short requests |
| Least connections / least outstanding | Variable request duration |
| Power of two choices | Large fleets; near-optimal with little state |
| IP / consistent hash | Session affinity, cache locality |
| Latency-aware (EWMA) | Heterogeneous backends |
Check yourself 2 questions
Variable request durations: which algorithm?
Show answer
Least connections or least outstanding requests.
Why power of two choices?
Show answer
Near-optimal balance with little coordination in large fleets.
Takeaway Round robin for uniform requests, least connections for variable ones, power of two choices for large fleets, consistent hashing for affinity.
Data processing styles#
| Style | Fit |
|---|---|
| OLTP vs OLAP | Row store for transactions; column store for analytics |
| ETL vs ELT | Transform before load vs load raw into warehouse then transform (dbt) |
| Lambda | Batch (correct) + speed layer (fresh); two codebases |
| Kappa | One streaming path; replay the log to recompute |
| CDC | Debezium reads the DB log → Kafka → search, cache, warehouse |
| File formats | Parquet/ORC columnar; Avro row-based with schema evolution |
Check yourself 2 questions
Row store or column store for analytics?
Show answer
Column store.
Lambda architecture?
Show answer
A batch layer for correctness plus a speed layer for freshness.
Takeaway OLTP versus OLAP, ETL versus ELT, Lambda versus Kappa, batch versus streaming.
Little's law and utilisation#
- Queueing delay grows sharply past ~70–80% utilisation; plan headroom.
- Fan-out multiplies tail latency: 100 calls each with 1% slow → 63% of requests hit a slow one.
- Thread-pool size ≈ throughput × latency (per instance).
Check yourself 2 questions
1,000 req/s at 0.2 s latency: concurrency?
Show answer
200 concurrent requests.
Why keep headroom below ~75% utilisation?
Show answer
Queueing delay grows sharply beyond it.
Takeaway In-flight requests = arrival rate × latency; keep utilisation below about 70–80% because queueing explodes beyond it.
Request path through a typical web system#
flowchart LR
U["Client"] --> CDN["CDN edge<br/>static, media"]
U --> LB["Load balancer<br/>L4 / L7"]
CDN -->|"miss"| LB
LB --> GW["API gateway<br/>auth · rate limit"]
GW --> SVC["Stateless services"]
SVC --> C[("Cache")]
SVC --> DB[("Primary DB")]
DB -.->|"replicate"| RR[("Read replicas")]
SVC --> Q[["Queue / log"]]
Q --> W["Async workers"]
W --> OBJ[("Object store")]
W --> IDX[("Search index")]Read path: CDN → cache → replica. Write path: primary DB plus an event on the log, so workers update the search index, notifications and analytics asynchronously.
Check yourself 2 questions
Where are auth and rate limiting usually enforced?
Show answer
At the API gateway.
What makes services horizontally scalable?
Show answer
Being stateless.
Takeaway Client, CDN, load balancer, gateway with auth and rate limits, stateless services, cache, database, queue.
Proxy, gateway, load balancer, mesh: who does what#
| Component | Sits | Main jobs |
|---|---|---|
| Forward proxy | In front of clients | Outbound filtering, caching, anonymity for clients |
| Reverse proxy | In front of servers | TLS termination, compression, caching, hiding backends (Nginx, Envoy) |
| Load balancer | In front of a server pool | Spread traffic, health checks, connection draining (L4 or L7) |
| API gateway | Edge of the service estate | Auth, rate limits, routing, request transformation, API keys, usage plans |
| Service mesh | Beside every service (sidecar) | Service-to-service mTLS, retries, timeouts, traffic shifting, telemetry |
Check yourself 2 questions
What does a reverse proxy do?
Show answer
TLS termination, compression, caching and hiding servers.
What does a service mesh add?
Show answer
mTLS, retries and telemetry between services via sidecars.
Takeaway Forward proxies serve clients, reverse proxies front servers, gateways handle API concerns, meshes handle service-to-service traffic.
05Databases and storage internals
What you need to justify a data-store choice and to answer "how does it scale" and "what anomalies can happen".
Index and storage engines#
| Structure | Good at | Cost | Seen in |
|---|---|---|---|
| B+ tree | Point and range reads; in-place updates | Random writes, page splits | Postgres, MySQL InnoDB |
| LSM tree (memtable → SSTables) | High write throughput; sequential I/O | Read and space amplification; compaction | Cassandra, RocksDB, LevelDB |
| Hash index | O(1) point lookup | No ranges | Redis, Bitcask |
| Inverted index | Full-text search | Index build and update lag | Elasticsearch, Lucene |
| Geo index | Nearby queries | Cell-size tuning | Geohash, quadtree, S2, H3, R-tree |
| Vector index | Approximate nearest neighbours | Recall vs memory vs latency | HNSW, IVF-PQ |
| Bitmap / columnar | Analytics filters and scans | Slow single-row updates | Druid, ClickHouse, Parquet |
Check yourself 2 questions
Which engine favours high write throughput?
Show answer
LSM trees.
Where are B+ trees used?
Show answer
Postgres and MySQL InnoDB.
Takeaway B+ trees suit reads and in-place updates; LSM trees suit heavy writes at the cost of compaction and read amplification.
Isolation levels and anomalies#
| Level | Prevents | Still allows |
|---|---|---|
| Read uncommitted | — | Dirty reads |
| Read committed (Postgres default) | Dirty reads | Non-repeatable reads, lost updates |
| Repeatable read / snapshot (MySQL default) | Non-repeatable reads | Write skew (phantoms depend on engine) |
| Serializable (2PL or SSI) | All of the above | Lower throughput, retries on conflict |
- Lost update fix:
SELECT … FOR UPDATE, atomicUPDATE … SET x = x - 1 WHERE x > 0, or optimistic version column. - Write skew (two doctors both go off call): needs serializable or a constraint/lock on the shared predicate.
- ACID vs BASE: atomicity, consistency, isolation, durability vs basically available, soft state, eventually consistent.
Check yourself 2 questions
Postgres default isolation?
Show answer
Read committed.
Which anomaly survives snapshot isolation?
Show answer
Write skew.
Takeaway Each isolation level prevents some anomalies; snapshot isolation still allows write skew; serializable prevents all.
Replication#
| Mode | Pros | Cons |
|---|---|---|
| Single leader | Simple; no write conflicts | Leader is the write bottleneck; failover risk |
| Multi-leader | Multi-region writes; offline clients | Conflict resolution (LWW, CRDT, app merge) |
| Leaderless (Dynamo) | High availability; tunable quorum | Read repair, hinted handoff, sloppy quorums |
| Synchronous | No data loss on failover | Latency; blocked by slow replica |
| Asynchronous | Fast writes | Replication lag; possible loss on failover |
Check yourself 2 questions
Main con of single-leader replication?
Show answer
The leader is the write bottleneck, with failover risk.
How does multi-leader resolve conflicts?
Show answer
LWW, CRDTs or application logic.
Takeaway Single-leader is simple, multi-leader needs conflict resolution, leaderless uses quorums.
Partitioning (sharding)#
| Strategy | Good for | Watch out |
|---|---|---|
| Range | Range scans, time series | Hot latest partition |
| Hash | Even spread | No range queries; resharding moves data |
| Consistent hash + vnodes | Elastic clusters | Only ~K/N keys move on change |
| Directory / lookup | Flexible placement, tenant moves | Lookup service is critical path |
| Geo / tenant | Data residency, isolation | Uneven tenant sizes |
- Hot key: add a random suffix (
key#0..n) and merge on read; or cache it locally. - Secondary index: local (scatter-gather reads) vs global (async, partitioned by term).
- Cross-shard transactions are expensive: choose the shard key so most transactions stay on one shard.
Check yourself 2 questions
Hot-spot risk of range sharding?
Show answer
The latest partition gets all new writes.
Downside of hash sharding?
Show answer
No range queries; resharding moves data.
Takeaway Range sharding suits scans but creates hot partitions; hash spreads evenly; consistent hashing with vnodes eases rebalancing.
Picking a data model#
| Question | If yes |
|---|---|
| Need multi-row transactions or strong constraints (money, inventory)? | Relational; keep the invariant in one DB |
| Access is always by a known key at huge scale? | Key-value / wide-column; model one table per query |
| Entity is a self-contained, evolving document? | Document store |
| Queries traverse relationships many hops deep? | Graph DB (or adjacency lists + cache if shallow) |
| Append-only measurements over time? | Time-series DB with downsampling and retention |
| Free-text relevance or facets? | Search index fed by CDC from the source of truth |
| Semantic similarity? | Vector index (pgvector to start; dedicated store at 10M+ vectors) |
Check yourself 2 questions
Money and inventory invariants: which model?
Show answer
Relational, keeping the invariant in one database.
Access always by a known key at huge scale?
Show answer
Key-value or wide-column.
Takeaway Transactions and constraints → relational; known-key lookups at scale → key-value; relationships → graph; search → index.
Cache-aside read and write#
sequenceDiagram participant A as App participant C as Cache participant D as Database A->>C: GET key C-->>A: miss A->>D: SELECT row D-->>A: row A->>C: SET key with TTL Note over A,D: On write: update DB first, then DELETE the cache key
Check yourself 2 questions
On a write, update or delete the cache entry?
Show answer
Delete (invalidate) after updating the database.
Why set a TTL?
Show answer
To bound staleness if an invalidation is missed.
Takeaway On read: check cache, on miss load from DB and set with TTL; on write: update DB then delete the cache key.
06HLD problem breakdowns (35 problems)
SystemDesign/05-hld-problems/{01-easy,02-medium,03-hard}/*.md — Deep Dive headings + Key takeaway
Every HLD problem: 3 deep dives + the one insight#
| Problem | Deep dives | Key takeaway |
|---|---|---|
| URL shortener | ID generation; redirect latency; custom aliases | 100:1 read-heavy → cache in Redis; 302 not 301 for analytics |
| Pastebin | large content; expiry; abuse | metadata in DB, content in S3, serve via CDN |
| Rate limiter | algorithms; distributed; rule hot paths | token bucket in Redis + Lua (atomic); fail open |
| Unique ID | Snowflake; alternatives; clock sync | 41b ts + 10b machine + 12b seq; no coordination, time-sortable |
| KV store | consistent hashing; vector clocks; failure detection | commit log → MemTable → SSTable; quorum R/W |
| Leaderboard | sorted-set internals; segments; percentile | ZADD + ZREVRANK, O(log N) |
| Autocomplete | trie storage; trending; personalisation | cache top-K for short prefixes in Redis; trie only for long tail |
| Booking | double-booking; availability search; refunds | HOLD → CONFIRM; idempotency keys |
| Web crawler | politeness; dedup; recrawl priority | URL frontier (PQ) + Bloom filter + per-domain rate limits |
| E-commerce | overselling; catalog search; orders | flash sale: Redis atomic DECR, DB eventually consistent |
| push vs pull feed; media upload; graph | hybrid fan-out (pull for celebrities) | |
| Twitter feed | celebrity fan-out; sharding; trending | answer the hotspot problem proactively |
| Notification | at-least-once; preferences / quiet hours; tokens | preference check + dedup before fan-out |
| Typeahead | trie vs ES; ranking; freshness | offline top-K + CDN for common prefixes + Kafka trending |
| WS routing; ordering / exactly-once; E2E Signal | registry user_id → server_id in Redis | |
| YouTube | transcoding; ABR; view counts | split upload path (async) from streaming (CDN + ABR) |
| Chat (Slack) | large-channel fan-out; ordering; search | user → gateway map is the core |
| Distributed cache | ring; replication; eviction | virtual nodes; hot keys → local cache + key sharding |
| Job scheduler | duplicate execution; 10M jobs; retries | CAS claim on status + idempotent jobs |
| Message queue | partition log; consumer groups; exactly-once | partitions + pull + ISR replication |
| Dropbox / Drive | CDC chunking; conflicts; dedup | SHA-256 content-addressed chunks → dedup + delta sync |
| GitHub | git storage; code search; merges | repo routing via consistent hashing + replica sets |
| Google Maps | routing; live traffic; ETA | Contraction Hierarchies: ms instead of seconds |
| Hotel booking | double booking; search; pricing | HOLD 10-min TTL; UNIQUE(room_id,date) as safety net |
| Ticketmaster | seat locking; flash sale; waitlist | Redis SETNX + 10-min TTL; virtual waiting room |
| Ride sharing | geo index; matching; surge | H3/S2 cells in Redis; avoid haversine full scans |
| Payment | idempotency; ledger; PCI | idempotency key + double-entry ledger; timeout ≠ failure |
| Stock exchange | order book; price-time matching; recovery | single-threaded matcher per symbol |
| Ad-click aggregator | dedup; Flink aggregation; fraud | lambda: Flink realtime + Spark batch for billing |
| Metrics | TSDB compression; queries; alerts | cardinality control at ingestion |
| CDN | anycast; cache tiers; invalidation | anycast + origin shield |
| Search | inverted index; PageRank; ranking | inverted index + BM25 is the core |
| LLM chat | SSE streaming; context window; GPU routing | SSE + KV-cache-aware routing |
| RAG | chunking; HNSW; hybrid + rerank | ANN for recall, cross-encoder for precision, BM25 for exact terms |
| Gaming leaderboard | ZSET; friends board; tournaments | friends: on-demand ZSCORE lookups |
Check yourself 2 questions
URL shortener key insight?
Show answer
100:1 read-heavy, so cache in Redis; use 302 not 301 to keep analytics.
Why 302 over 301?
Show answer
301 is cached by browsers, hiding clicks from analytics.
Takeaway Each classic problem has three deep dives and one key insight, such as a URL shortener's 100:1 read ratio.
Example: WhatsApp message flow#
flowchart TD A[Sender] -->|WebSocket| G1[Gateway 1] G1 --> MS[Message service] MS --> DB[(Cassandra: messages)] MS --> R[(Redis: user to gateway)] R --> G2[Gateway 2] G2 -->|WebSocket| B[Receiver] MS -->|offline| P[Push notification]
Check yourself 2 questions
How does the server find the recipient's connection?
Show answer
Redis maps each user to their gateway.
Where are messages stored?
Show answer
Cassandra.
Takeaway Sender's WebSocket gateway, message service, Cassandra for messages, Redis mapping user to gateway, recipient's gateway.
Example: hybrid feed fan-out#
flowchart LR
T[New post] --> Q{{Author followers}}
Q -->|normal| F[Fan-out on write to follower timelines]
Q -->|celebrity| S[Store only in author timeline]
U[Reader] --> TL[Precomputed timeline]
U --> M[Merge celebrity posts at read]
TL --> M
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q decCheck yourself 2 questions
Why not fan out a celebrity's post on write?
Show answer
Millions of follower timeline writes per post.
How do celebrity posts reach readers?
Show answer
Merged at read time with the precomputed timeline.
Takeaway Fan out on write for normal authors; store celebrity posts once and merge at read time.
07Worked designs: eight full walkthroughs
Five classic prompts carried through the 60-minute route: requirements, estimates, API and data model, architecture, deep dives and trade-offs. Use them as model answers to rehearse out loud.
URL shortener#
Read-heavy key lookup. The interesting parts are generating short unique codes and keeping redirects under ~50 ms at 100K+ QPS.
flowchart LR
C["Client"] --> CDN["CDN edge"]
CDN --> LB["Load balancer"]
LB --> R["Redirect service"]
LB --> W["Create service"]
R --> RC[("Redis<br/>code → URL")]
R --> DB[("KV store: urls")]
W --> IDG["ID range allocator"]
W --> DB
R -.->|"click event"| K[["Kafka"]]
K -.-> AN[("Analytics store")]
Requirements
- Shorten a URL to a 7-character code; redirect; optional custom alias and expiry; click analytics.
- 100M new URLs/day, 100:1 read:write, p99 redirect < 50 ms, highly available.
Back-of-envelope
API and data model
POST /v1/urls {long_url, alias?, ttl_days?} → 201 {code} GET /{code} → 302 Location: long_url urls(code PK, long_url, owner_id, created_at, expires_at) click events → Kafka → analytics (OLAP)
Deep dives
- Code generation: each server leases a counter range (e.g. 1M IDs) from a coordinator, base62-encodes, and scrambles with a bijection so codes aren't guessable. No collision checks needed.
- Read path: CDN caches popular redirects briefly; Redis LRU for hot codes; KV store partitioned by code hash.
- Custom alias: conditional put (insert if absent) gives uniqueness.
- Expiry: store TTL; check on read; background cleanup.
Trade-offs
- 301 is cached by browsers (less load, lost analytics); 302 keeps every click visible.
- Hash of URL + collision retry avoids coordination but costs extra reads.
- Abuse: scan destinations, rate-limit creators.
Check yourself 2 questions
Name a way to generate unique short codes.
Show answer
Any of: base62 of a distributed counter or ID ranges, hashing with collision checks, pre-generated keys.
Latency target for redirects?
Show answer
About 50 ms.
Takeaway A read-heavy key lookup: unique short codes plus CDN and cache to keep redirects under about 50 ms at 100K+ QPS.
News feed (home timeline)#
Write fan-out versus read fan-out. The celebrity problem decides the design, so raise it before the interviewer does.
flowchart LR
U["Client"] --> API["API gateway"]
API --> PS["Post service"]
PS --> PDB[("Posts DB")]
PS --> K[["Kafka: new posts"]]
K --> FO["Fan-out workers"]
FO --> G[("Social graph")]
FO --> FC[("Feed cache<br/>per-user list in Redis")]
API --> FS["Feed service"]
FS --> FC
FS -->|"celebrity posts at read time"| PDB
FS --> RK["Ranker"]
Requirements
- Post text/media, follow users, see a ranked or chronological home feed with infinite scroll.
- 300M DAU, feed p99 < 200 ms, eventual consistency acceptable.
Back-of-envelope
API and data model
POST /v1/posts {text, media_ids[]} GET /v1/feed?cursor=… → {items[], next_cursor} POST /v1/follows {followee_id} posts(post_id snowflake, author_id, body, media_ref, created_at) follows(follower_id, followee_id) + reverse index feed:{user_id} → Redis list of recent post_ids
Deep dives
- Hybrid fan-out: push post IDs into followers' caches for normal authors; for authors above ~10K followers, pull their recent posts at read time and merge.
- Ranking: candidates from cache + celebrity pull → features → lightweight model → diversity rules.
- Inactive users: skip fan-out; rebuild the feed on next login.
- Media: upload to object storage via pre-signed URL; serve through CDN.
Trade-offs
- Push = fast reads, write amplification. Pull = cheap writes, slow reads.
- Deletes and privacy changes need cache invalidation (tombstones).
- Cursor pagination on post_id keeps pages stable as new posts arrive.
Check yourself 2 questions
What decides feed design?
Show answer
The celebrity problem.
Where are precomputed timelines stored?
Show answer
In a cache such as Redis.
Takeaway Fan-out on write versus read; the celebrity problem decides the hybrid design.
Chat messaging (WhatsApp style)#
Long-lived connections, routing a message to whichever gateway holds the recipient, ordering per conversation, and offline delivery.
flowchart LR
A["Sender app"] -->|"WebSocket"| G1["Gateway A"]
G1 --> MS["Message service"]
MS --> SEQ["Per-conversation sequencer"]
MS --> DB[("Cassandra<br/>messages by conversation")]
MS --> REG[("Redis<br/>user → gateway")]
MS --> G2["Gateway B"]
G2 -->|"WebSocket"| B["Recipient app"]
MS -.->|"recipient offline"| PN["Push notification"]
Requirements
- 1:1 and group chat (≤ 500 members), sent/delivered/read receipts, presence, offline delivery, multi-device sync.
- 500M DAU × 40 messages/day; delivery < 500 ms when online.
Back-of-envelope
API and data model
WS send {conv_id, client_msg_id, body} WS ack {conv_id, seq} receipts flow back the same way GET /v1/conversations/{id}/messages?before_seq=… messages(conv_id PARTITION, seq CLUSTERING, msg_id, sender_id, body_ciphertext, created_at) presence:{user_id} → gateway_id, last_seen (Redis, TTL)
Deep dives
- Routing: gateways register user → gateway in Redis; message service looks it up and forwards.
- Ordering: sequence number per conversation from its owner shard; clients order by seq and dedupe by client_msg_id.
- Delivery: at-least-once with idempotent writes; receipts update per-recipient state.
- Groups: store once, fan out to online members' gateways; very large groups switch to pull.
- Security: end-to-end encryption (Signal protocol); server stores ciphertext.
Trade-offs
- Keep history server-side (multi-device sync) or delete after delivery (privacy, cost).
- Gateway crash: clients reconnect and resync from their last acknowledged seq.
- Presence is expensive; publish only to contacts who are viewing.
Check yourself 2 questions
How is ordering guaranteed?
Show answer
Per conversation, for example by partitioning on chat ID with sequence numbers.
How are offline users handled?
Show answer
Store messages and deliver on reconnect, plus push notifications.
Takeaway Long-lived connections, routing to the recipient's gateway, per-conversation ordering and offline delivery.
Ticket booking with flash sales#
The invariant is "a seat is sold at most once". Everything else (holds, payments, waiting room) protects that invariant under a traffic spike.
flowchart LR
U["User"] --> WR["Virtual waiting room"]
WR --> API["Booking API"]
API --> SM[("Seat map cache")]
API --> HOLD["Hold service"]
HOLD --> LOCK[("Redis SET NX + TTL")]
HOLD --> DB[("SQL: seats, bookings")]
API --> PAY["Payment provider"]
PAY -.->|"webhook"| API
API --> Q[["Expiry and notification queue"]]
Requirements
- Browse events, view seat map, hold seats for 10 minutes, pay, get a confirmed ticket.
- No double booking; survive 1M users arriving for 50K seats.
Back-of-envelope
API and data model
GET /v1/events/{id}/seats POST /v1/holds {event_id, seat_ids[]} → {hold_id, expires_at} POST /v1/bookings {hold_id, payment_token} Idempotency-Key: … seats(event_id, seat_id, status, hold_id, hold_expires_at, version) bookings(booking_id, user_id, event_id, seat_ids, status, payment_ref)
Deep dives
- Atomic hold:
UPDATE seats SET status='HELD', hold_id=? WHERE event_id=? AND seat_id IN (…) AND status='AVAILABLE'; success only if the row count matches. Redis SET NX can front it; the DB stays the source of truth. - Expiry: holds carry a deadline; a sweeper releases them, and reads treat expired holds as available.
- Payment: idempotency key; confirm on webhook; a timeout is "unknown", so reconcile before releasing seats.
- Flash sale: waiting room issues signed tokens at a fixed admit rate; pre-scale; serve the seat map from cache.
Trade-offs
- Optimistic (version check) vs pessimistic (row locks): optimistic scales better when contention is spread.
- Partition seats by event so each event's state lives on one primary.
- Fairness: queue order vs lottery for very hot events.
Check yourself 2 questions
How do you prevent double-selling a seat?
Show answer
Atomic holds with TTL (conditional update or lock), then confirm on payment.
What absorbs a flash-sale spike?
Show answer
A virtual waiting room.
Takeaway The invariant is a seat sold at most once; holds, payments and a waiting room protect it under spikes.
Ride hailing#
A firehose of location writes, a geo index for "who is near", and an atomic match so one driver isn't offered two rides.
flowchart LR
D["Driver app"] -->|"location every 4 s"| LS["Location service"]
LS --> GEO[("Geo index<br/>H3 cell → drivers")]
LS -.-> K[["Kafka: location stream"]]
R["Rider app"] --> RS["Ride service"]
RS --> MT["Matching service"]
MT --> GEO
MT -->|"offer"| D
RS --> TDB[("Trips DB<br/>state machine")]
K -.-> PR["Surge pricing"]
K -.-> ETA["ETA service"]
Requirements
- Request a ride, match a nearby driver within seconds, live tracking, fare estimate with surge, trip lifecycle.
- 5M active drivers; matching p99 < 5 s.
Back-of-envelope
API and data model
WS driver → {lat, lng, heading, ts} POST /v1/rides {pickup, dropoff} → {ride_id, eta, fare} GET /v1/rides/{id} (SSE or WS for live updates) geo: cell_id → set(driver_id) driver_id → (lat, lng, status) trips(ride_id, rider_id, driver_id, state, fare, timestamps)
Deep dives
- Geo index: H3 or geohash cells in memory, sharded by city; search the pickup cell plus neighbouring rings.
- Matching: rank candidates by ETA (road network), not straight-line distance; reserve the driver atomically before sending the offer; time out and move to the next.
- Write volume: keep only the latest point in the index; stream history to Kafka for analytics and ETA training.
- Surge: demand/supply ratio per cell per minute from the stream.
Trade-offs
- Update frequency vs battery and write load: adapt to speed and trip state.
- City-level sharding keeps queries local but complicates cross-boundary trips.
- Trip state changes need transactions; location data can be lossy.
Check yourself 2 questions
How often do drivers send location?
Show answer
About every 4 seconds.
How do you stop a driver being offered two rides?
Show answer
Atomic matching, such as a conditional update or lock on driver state.
Takeaway A firehose of location writes, a geo index for nearby drivers, and atomic matching so a driver gets one offer.
Payment system#
Money must never be created, lost or double-charged. Idempotency, a double-entry ledger and reconciliation carry the design.
flowchart LR
C["Checkout client"] --> API["Payment API<br/>idempotency key"]
API --> PS["Payment service<br/>state machine"]
PS --> DB[("Payments DB")]
PS --> PSP["External PSP<br/>card network"]
PSP -.->|"webhook"| PS
PS --> LED[("Double-entry ledger")]
PS --> OB[["Outbox events"]]
OB --> N["Order and notification services"]
REC["Daily reconciliation"] --> LED
REC --> PSP
Requirements
- Charge, refund and pay out; support retries safely; show payment status; never double-charge.
- Thousands of payments per second at peak; strong consistency for balances; full audit trail.
Payment state machine
API and data model
POST /v1/payments Idempotency-Key: … {order_id, amount_minor, currency, method_token} GET /v1/payments/{id} payments(id, order_id, amount_minor, currency, status, psp_ref, version) idempotency(key, request_hash, response, expires_at) ledger(entry_id, txn_id, account, debit_minor, credit_minor)
Deep dives
- Idempotency: store key + request hash + response atomically; a retry returns the saved response.
- Ledger: every movement is two entries that sum to zero; balances are derived, never updated in place.
- External calls: call the PSP outside the DB transaction, record intent first, update on webhook or polling.
- Reconciliation: compare ledger, PSP reports and bank statements daily; mismatches go to a queue for humans.
Trade-offs
- Synchronous authorisation for the user; asynchronous capture and settlement.
- Tokenise cards so raw card data never touches your systems (PCI scope).
Check yourself 2 questions
How do you prevent double charges on retries?
Show answer
Idempotency keys.
What is double-entry bookkeeping?
Show answer
Every movement debits one account and credits another, summing to zero.
Takeaway Idempotency, a double-entry ledger and reconciliation keep money from being created, lost or double-charged.
Video streaming platform#
Two separate paths: a slow, asynchronous upload and transcode pipeline, and a fast playback path served almost entirely by CDNs.
flowchart LR
U["Creator"] -->|"pre-signed multipart upload"| RAW[("Raw video store")]
RAW --> Q[["Transcode queue"]]
Q --> TW["Transcode workers<br/>bitrate ladder"]
TW --> SEG[("Segments + manifests<br/>HLS / DASH")]
TW --> META[("Video metadata DB")]
V["Viewer"] --> API["Playback API<br/>signed URLs"]
API --> META
V --> CDN["CDN edges"]
CDN -->|"miss"| SEG
V -.->|"watch events"| AN[["Analytics stream"]]
Requirements
- Upload large videos, watch with quick start and no buffering on varied networks, view counts, recommendations.
- Upload is rare relative to viewing (1:1000+); global audience.
Back-of-envelope
Pipeline
- Client uploads in chunks directly to object storage (resumable).
- An event enqueues a transcode job; split the video into chunks to transcode in parallel.
- Produce several resolutions and bitrates, segment into 2–6 s pieces, write HLS/DASH manifests.
- Mark the video ready; thumbnails and captions run as separate jobs.
Deep dives
- Adaptive bitrate: the player picks the rendition per segment from measured bandwidth.
- CDN: popular videos are pre-warmed; long-tail content is fetched from origin through a regional shield.
- View counts: stream events into aggregations; approximate counts in real time, exact counts in batch.
- Access control: short-lived signed URLs or tokens; DRM for premium content.
Check yourself 2 questions
How are large uploads handled?
Show answer
Pre-signed multipart uploads to object storage.
What serves playback?
Show answer
CDNs with adaptive bitrate segments.
Takeaway A slow async upload and transcode pipeline, and a fast playback path served mostly by CDNs.
Notification system#
Turn events into messages on many channels, respecting user preferences, without duplicates or floods.
flowchart LR
SRC["Services emit events"] --> K[["Event bus"]]
K --> NS["Notification service"]
NS --> PREF[("Preferences, quiet hours")]
NS --> TPL["Templates and localisation"]
NS --> DEDUP[("Dedup and rate limits")]
NS --> CQ[["Per-channel queues"]]
CQ --> PUSH["Push: APNs / FCM"]
CQ --> EMAIL["Email provider"]
CQ --> SMS["SMS provider"]
PUSH -.->|"delivery receipts"| LOG[("Delivery log")]
EMAIL -.-> LOG
SMS -.-> LOG
Requirements
- Push, email, SMS and in-app; user preferences and quiet hours; templates in many languages; delivery tracking.
- Bursts of millions (breaking news, campaigns); at-least-once delivery without visible duplicates.
Deep dives
- Preferences first: check opt-outs, channel choice and quiet hours before enqueueing.
- Dedup: idempotency key per (user, event); store recent keys with TTL.
- Per-channel queues: isolate slow providers; retry with backoff; dead-letter after N attempts.
- Rate limiting: per user (don't spam) and per provider (stay under their quotas).
Trade-offs
- Fan-out for campaigns is a batch job, separate from real-time transactional notifications.
- Priority lanes so one-time passwords never wait behind marketing.
- Track opens and clicks to tune frequency and relevance.
Check yourself 2 questions
How do you avoid duplicate notifications?
Show answer
Idempotency or dedup keys per event and user.
How do you avoid flooding users?
Show answer
Per-user rate limits, batching and quiet hours.
Takeaway Events become messages across channels, respecting preferences, with deduplication and rate limits.
08Distributed systems essentials
SystemDesign/02 building blocks, 09 patterns, 08-reference
Distributed systems core#
| Concept | One-liner |
|---|---|
| Consistent hashing | ring + virtual nodes; move only K/N keys |
| Replication | leader-follower, multi-leader, leaderless (quorum) |
| Quorum | Overlapping read/write quorums can support strong reads only with compatible replica/version guarantees; otherwise plan for stale reads and repair. Cassandra quorum notes |
| Sharding keys | hash (even) vs range (scans); avoid hot shards (salt) |
| Consensus | Raft: leader, log replication, majority commit |
| Vector clocks | detect concurrent writes; app resolves |
| Exactly-once effects | Usually require at-least-once delivery plus deduplication/idempotency and atomic state/offset updates; guarantees stop at system boundaries. |
| Outbox | write event in same DB txn; relay to Kafka |
| Saga | local txns + compensations (orchestrated / choreographed) |
| 2PC | blocking coordinator; avoid across services |
Check yourself 2 questions
Quorum condition for reading the latest write?
Show answer
R + W > N.
What does consistent hashing move when a node joins?
Show answer
Only about K/N keys.
Takeaway Consistent hashing, replication, quorums, consensus, idempotency and backpressure are the core vocabulary.
Messaging & streams#
- Kafka: topic → partitions (ordering per partition), consumer groups, offsets, ISR
- Choose partition key = ordering key (user_id, chat_id)
- Queue (SQS/RabbitMQ) for tasks; log (Kafka) for replayable events
- DLQ + retries with backoff; poison messages
- Flink for stateful realtime aggregates (windows, watermarks); Spark for batch
Check yourself 2 questions
How do you keep a user's events in order in Kafka?
Show answer
Use the user ID as the partition key.
Queue versus log?
Show answer
Queues for tasks consumed once; logs for replayable event streams.
Takeaway Kafka orders per partition with consumer groups and offsets; queues suit tasks, logs suit replayable streams.
API & edge#
- REST for CRUD; gRPC internal low-latency; GraphQL for client-shaped reads
- WebSocket bidirectional (chat); SSE server→client (LLM tokens); long-poll fallback
- Pagination: cursor > offset at scale
- API gateway: auth, rate limit, routing; LB L4 vs L7
- CDN for static + video; signed URLs for private blobs
Check yourself 2 questions
Server-to-client token streaming?
Show answer
SSE.
Cursor or offset pagination?
Show answer
Cursor.
Takeaway REST for CRUD, gRPC internally, GraphQL for client-shaped reads; WebSocket, SSE or long-poll for push; cursor pagination.
Kafka partitions and consumer groups#
flowchart LR P["Producers<br/>partition = hash(key)"] --> T0["Partition 0"] P --> T1["Partition 1"] P --> T2["Partition 2"] T0 --> C1["Group A: consumer 1"] T1 --> C1 T2 --> C2["Group A: consumer 2"] T0 -.-> X["Group B: analytics<br/>own offsets"] T1 -.-> X T2 -.-> X
Order holds within a partition. In a group, each partition goes to one consumer, so consumers beyond the partition count sit idle. Separate groups read independently.
- Partition count: size for peak throughput ÷ per-consumer throughput; adding partitions later moves keys to new partitions.
- Hot key: one key means one partition and one consumer. Salt the key or split the entity.
- Delivery: commit offsets after processing for at-least-once, so consumers must be idempotent.
- Exactly-once inside Kafka needs an idempotent producer plus transactions; side effects outside Kafka still need deduplication.
- Health: watch consumer lag per partition; rising lag means scale consumers or fix a slow handler.
Check yourself 2 questions
How many consumers in a group can read one partition?
Show answer
One.
What's the max useful consumers per group?
Show answer
The number of partitions.
Takeaway Partition = hash(key); each partition goes to one consumer per group; groups read independently.
09Consistency, consensus and time
The distributed-systems theory interviewers dig into at senior levels, condensed to what changes a design.
Consistency models, strongest first#
| Model | Guarantee | Example |
|---|---|---|
| Linearizable | Every read sees the latest write; real-time order | etcd, Spanner, single-leader sync reads |
| Sequential | One global order consistent with each client's order | ZooKeeper writes |
| Causal | Cause precedes effect everywhere | Comment shows after the post it replies to |
| Read-your-writes | You see your own updates | Profile edit visible immediately |
| Monotonic reads | Never go back in time | Pin session to a replica |
| Eventual | Replicas converge if writes stop | DNS, likes counters, Dynamo defaults |
Check yourself 2 questions
Strongest consistency model?
Show answer
Linearizable.
Give a system offering linearizable reads.
Show answer
etcd or Spanner.
Takeaway Linearizable, sequential, causal, read-your-writes, eventual: weaker models are cheaper and more available.
CAP and PACELC#
- CAP: during a network partition, choose consistency (reject some requests) or availability (serve possibly stale data). Partitions are not optional.
- PACELC: if Partition → A or C; Else → Latency or Consistency. Even without failures, strong consistency costs latency.
| System | PACELC |
|---|---|
| DynamoDB, Cassandra (default) | PA / EL |
| Spanner, CockroachDB, etcd | PC / EC |
| MongoDB (majority) | PC / EC (tunable) |
Check yourself 2 questions
What does PACELC add to CAP?
Show answer
Even without partitions, there's a latency versus consistency trade-off.
Are partitions optional?
Show answer
No.
Takeaway During a partition choose C or A; else choose latency or consistency.
Consensus and leadership#
- Raft: leader election with terms and randomised timeouts; leader appends entries; commit when a majority acknowledges; 2f+1 nodes tolerate f failures.
- Paxos / Multi-Paxos: same safety guarantees, harder to explain; ZAB in ZooKeeper.
- Leases give a leader time-bounded authority; require bounded clock drift.
- Fencing tokens: monotonically increasing token checked by storage, so a paused old leader can't write after losing its lock.
- Split brain: prevented by majority quorums; never run 2-node clusters without a tiebreaker.
- Use consensus for metadata (who is leader, config, locks), not for every data write.
Check yourself 2 questions
How many nodes tolerate 2 failures?
Show answer
5.
When is a Raft entry committed?
Show answer
When a majority has acknowledged it.
Takeaway Raft elects a leader with terms and commits on majority acknowledgement; 2f+1 nodes tolerate f failures.
Time, ordering and failure detection#
| Tool | Use |
|---|---|
| Physical clocks (NTP) | Drift ms–100s of ms; don't order events across machines with them |
| Lamport clock | Total order consistent with causality (counter max+1) |
| Vector clock | Detect concurrent writes (siblings) in leaderless stores |
| Hybrid logical clock | Physical time + logical counter (CockroachDB) |
| TrueTime | Bounded uncertainty; Spanner waits it out for external consistency |
| Heartbeats + timeouts | Simple failure detection; tune to avoid flapping |
| Gossip | Membership and state spread in O(log N) rounds |
| Phi-accrual detector | Suspicion level instead of binary up/down (Cassandra) |
Check yourself 2 questions
What can vector clocks detect that Lamport clocks can't?
Show answer
Concurrent (causally unrelated) events.
Why not order events with NTP timestamps?
Show answer
Clocks drift by milliseconds or more.
Takeaway Physical clocks drift; Lamport clocks give causal order; vector clocks detect concurrency; heartbeats detect failure.
Distributed transactions: choosing the tool#
| Approach | How | Use when | Downside |
|---|---|---|---|
| Single-DB transaction | Keep related data on one shard/DB | Always try first | Constrains data model |
| Two-phase commit | Coordinator: prepare → commit | Inside one database system (Spanner, XA) | Blocking if coordinator dies; latency |
| Saga (orchestrated) | Central workflow runs steps + compensations | Multi-service business flows (order → payment → shipping) | No isolation; design compensations |
| Saga (choreographed) | Services react to each other's events | Few steps, loosely coupled teams | Hard to trace the overall flow |
| Transactional outbox | Write row + event in one local txn; relay publishes | DB update must emit an event reliably | Relay adds delay; consumers dedupe |
| TCC (try-confirm-cancel) | Reserve resources, then confirm or cancel | Inventory, bookings, payments holds | Every service implements three APIs |
Check yourself 2 questions
What should you try first?
Show answer
Keep related data on one database or shard.
Downside of two-phase commit?
Show answer
Blocking on coordinator failure, and higher latency.
Takeaway Prefer one database; 2PC within a trusted boundary; sagas with compensation across services.
CRDTs and conflict resolution#
- Last-write-wins: simple, silently drops concurrent updates.
- CRDTs: merge automatically without coordination: G-counter, PN-counter, OR-set, LWW-register, RGA/sequence CRDTs for collaborative text.
- Operational transform: classic Google Docs approach; needs a central server to order operations.
- Application merge: keep siblings and let the domain decide (shopping cart union).
Check yourself 2 questions
Downside of last-write-wins?
Show answer
Silently drops concurrent updates.
Name a CRDT.
Show answer
Any of: G-counter, PN-counter, OR-set, LWW-register, RGA.
Takeaway LWW silently drops updates; CRDTs merge without coordination.
Saga with compensation#
sequenceDiagram participant O as Order orchestrator participant P as Payment participant I as Inventory O->>P: charge(order, idempotency key) P-->>O: charged O->>I: reserve(items) I-->>O: out of stock O->>P: refund(order) P-->>O: refunded Note over O: mark order FAILED and notify the user
Check yourself 2 questions
Inventory reservation fails after payment. What happens?
Show answer
The orchestrator refunds the payment (compensation).
Why idempotency keys on each step?
Show answer
Retries mustn't repeat side effects.
Takeaway An orchestrator calls each step with idempotency keys and runs compensations if a later step fails.
Raft: replicating one write#
sequenceDiagram participant C as Client participant L as Leader participant F1 as Follower 1 participant F2 as Follower 2 C->>L: write x = 5 L->>L: append to log (term 3, index 42) L->>F1: AppendEntries(42) L->>F2: AppendEntries(42) F1-->>L: ack Note over L: 2 of 3 have it, so commit index 42 L-->>C: ok F2-->>L: ack (late) L->>F1: heartbeat carrying commit index 42
Check yourself 2 questions
When does the leader reply to the client?
Show answer
After a majority acknowledges and the entry is committed.
What identifies a log entry?
Show answer
Its term and index.
Takeaway The leader appends, sends AppendEntries, commits on majority, applies and replies.
Distributed locks done right#
| Option | How | Caveat |
|---|---|---|
| Database lock | SELECT … FOR UPDATE, advisory locks, or a unique row as the lock | Simple and correct if you already depend on that database |
| Redis single node | SET key token NX PX 30000; release with a Lua script that checks the token | Lost on failover before replication; fine for efficiency, not for correctness |
| Redlock (several Redis nodes) | Acquire on a majority of independent nodes within a time limit | Relies on timing assumptions; disputed for correctness-critical use |
| ZooKeeper / etcd | Ephemeral (lease-backed) nodes; the lowest sequence number holds the lock | Consensus-backed and safe; more operational weight |
- Always use fencing tokens: the lock service hands out an increasing number and storage rejects writes with an older one, so a paused former holder can't corrupt data.
- Leases expire: GC pauses or network delays can outlast the lease; never assume you still hold it without fencing.
- Prefer avoiding locks: single-writer partitions, conditional writes (
UPDATE … WHERE version = ?), and idempotent operations often remove the need entirely.
Check yourself 2 questions
What prevents a paused lock-holder corrupting data?
Show answer
Fencing tokens checked by the resource.
Simplest correct lock if you already use a database?
Show answer
SELECT … FOR UPDATE or advisory locks.
Takeaway Use DB locks where possible; Redis locks need tokens and TTLs; protect resources with fencing tokens.
10Scalability, resilience and deployment patterns
The patterns that turn a box diagram into something that survives load spikes, dependency failures and bad deploys.
Rate-limiting algorithms#
| Algorithm | How | Pros | Cons |
|---|---|---|---|
| Fixed window | Counter per time bucket | Tiny, simple | 2× burst at window edges |
| Sliding log | Store each timestamp | Exact | Memory per request |
| Sliding window counter | Weighted current + previous window | Accurate, cheap | Approximation |
| Token bucket | Refill at rate r, capacity b | Allows bursts; most common | Two parameters to tune |
| Leaky bucket | Queue drains at fixed rate | Smooth output | Adds queueing delay |
Retry-After; decide fail-open vs fail-closed.Check yourself 2 questions
Flaw of fixed windows?
Show answer
Up to 2× bursts at window edges.
Which algorithm allows controlled bursts?
Show answer
Token bucket.
Takeaway Fixed window, sliding log, sliding window counter, token bucket and leaky bucket trade accuracy, memory and burstiness.
Resilience patterns#
| Pattern | Purpose |
|---|---|
| Timeouts | Never wait forever; budget across the call chain |
| Retries + exponential backoff + jitter | Recover from transient errors without thundering herds; cap attempts |
| Circuit breaker | Closed → open on failures → half-open probe; fail fast |
| Bulkhead | Separate pools per dependency so one can't exhaust all threads |
| Load shedding | Drop low-priority work when saturated |
| Back-pressure | Bounded queues; slow producers instead of crashing |
| Graceful degradation | Serve cached or partial results (hide recommendations, keep checkout) |
| Hedged requests | Send a duplicate after p95 to cut tail latency |
| Idempotency keys | Make retries safe for writes |
Check yourself 2 questions
What do bulkheads do?
Show answer
Isolate resources so one failure can't drain everything.
What does load shedding do?
Show answer
Rejects excess work to protect the system.
Takeaway Timeouts, retries with backoff and jitter, circuit breakers, bulkheads, load shedding and graceful degradation.
Microservice architecture patterns#
| Pattern | When |
|---|---|
| Database per service | Independent deploys; share data via APIs/events |
| API gateway / BFF | One entry per client type |
| Service mesh / sidecar | mTLS, retries, telemetry without app code |
| CQRS | Separate write model from read-optimised views |
| Event sourcing | Audit trail, temporal queries; state = fold over events |
| Strangler fig | Incrementally replace a monolith behind a router |
| Anti-corruption layer | Translate a legacy model at the boundary |
| Cell-based architecture | Independent copies of the stack per user shard; limits blast radius |
Check yourself 2 questions
Why database per service?
Show answer
Independent deploys; share data via APIs and events.
What's a BFF?
Show answer
A backend-for-frontend: one entry per client type.
Takeaway Database per service, API gateway or BFF, service mesh, events and sagas.
Deployment and release#
| Strategy | Trade-off |
|---|---|
| Rolling | No extra capacity; mixed versions during rollout |
| Blue-green | Instant switch and rollback; double capacity |
| Canary | Small % first, compare metrics, then ramp |
| Feature flags | Decouple deploy from release; kill switch |
| Shadow / dark launch | Mirror real traffic to the new path; no user impact |
| Expand–contract migration | Add new column → dual write → backfill → switch reads → drop old |
Check yourself 2 questions
Blue-green trade-off?
Show answer
Instant switch and rollback, at double capacity.
Canary?
Show answer
Release to a small percentage, compare metrics, then ramp.
Takeaway Rolling, blue-green, canary and feature flags trade capacity, speed and blast radius.
Multi-region and disaster recovery#
| Setup | RTO / RPO | Cost | Notes |
|---|---|---|---|
| Backup and restore | Hours / hours | Low | Test restores regularly |
| Pilot light | Tens of minutes / minutes | Low–medium | Data replicated, compute scaled to zero |
| Warm standby | Minutes / seconds | Medium | Scaled-down copy running |
| Active-passive | Minutes / near zero (sync) or seconds (async) | High | Failover via DNS or global LB |
| Active-active | ~0 / ~0 for local writes | Highest | Write conflicts; home-region per user; data residency |
Check yourself 2 questions
Which setup has the lowest RTO and RPO?
Show answer
Active-active multi-region.
Pilot light?
Show answer
Data replicated, compute scaled to zero until needed.
Takeaway Backup and restore, pilot light, warm standby and active-active trade RTO, RPO and cost.
Circuit breaker states#
stateDiagram-v2 direction LR [*] --> Closed Closed --> Open: failure rate over threshold Open --> HalfOpen: cool-down elapsed HalfOpen --> Closed: probe succeeds HalfOpen --> Open: probe fails
Closed passes calls through; Open fails fast without calling the dependency; Half-open lets a few probes test recovery.
Check yourself 2 questions
When does the breaker open?
Show answer
When the failure rate exceeds a threshold.
What happens in half-open?
Show answer
A probe request tests recovery; success closes, failure reopens.
Takeaway Closed → open on failures, half-open after cool-down, closed again if probes succeed.
11Probabilistic and specialised data structures
Small structures that make large systems cheap. Each one maps to recurring HLD problems.
Structure → use → numbers#
| Structure | Answers | Error / size | Used in |
|---|---|---|---|
| Bloom filter | "Definitely not" or "maybe" in set | ~10 bits/item → ~1% false positives; no deletes | Crawler seen-URLs, LSM read path, username check |
| Counting / cuckoo filter | Membership with deletes | Slightly more space than Bloom | Cache admission, dedup with expiry |
| HyperLogLog | Count distinct | ~12 KB for ~0.81% error at any cardinality | Unique visitors, distinct searches |
| Count-min sketch | Approximate frequency | Overestimates only; width × depth counters | Heavy hitters, trending topics, top-K |
| t-digest / KLL | Approximate percentiles | Accurate at tails | p99 latency over streams |
| Skip list | Sorted set with O(log n) ops | Probabilistic balancing | Redis sorted sets (leaderboards) |
| Merkle tree | Which ranges differ between replicas | O(log n) comparison | Anti-entropy (Cassandra), Git, blockchains |
| Consistent hash ring | Which node owns a key | Moves ~K/N keys on resize | Caches, KV stores, load balancers |
| Geohash / quadtree / S2 / H3 | What is near this point | Cell size vs precision | Ride matching, nearby search, maps |
| Trie | Prefix lookup | Store top-K per node for speed | Typeahead, routing tables |
| Inverted index | Which documents contain the term | Posting lists, compressed | Search engines |
| Timing wheel | Millions of timers in O(1) | Bucketed by tick | Schedulers, TTL expiry, Kafka delays |
| Ring buffer | Fixed-size FIFO, lock-free options | Overwrites oldest | Logging, metrics, LMAX disruptor |
| Reservoir sampling | Uniform sample of a stream | O(k) memory | Log sampling, analytics |
Check yourself 2 questions
Bloom filter answers?
Show answer
'Definitely not' or 'maybe' in the set.
Count distinct users cheaply?
Show answer
HyperLogLog.
Takeaway Bloom filters, count-min sketches, HyperLogLog and others trade accuracy for tiny memory.
12APIs and communication protocols
How clients and services talk, and the API conventions that prevent production incidents.
Protocol picker#
| Protocol | Pattern | Use for |
|---|---|---|
| REST over HTTP/1.1–2 | Request/response, resources | Public CRUD APIs; cache-friendly |
| gRPC (HTTP/2, protobuf) | Typed RPC, streaming | Internal low-latency service calls |
| GraphQL | Client-shaped queries | Many clients with different needs; watch N+1 and caching |
| WebSocket | Full-duplex, persistent | Chat, multiplayer, collaborative editing |
| Server-Sent Events | Server → client stream over HTTP | LLM token streaming, live feeds, notifications |
| Long polling | Held request | Fallback when sockets are blocked |
| Webhooks | Server → server callback | Payment status, integrations; sign and retry |
| HTTP/3 (QUIC) | UDP, no head-of-line blocking | Mobile and lossy networks |
| MQTT | Lightweight pub-sub | IoT devices |
Check yourself 2 questions
Internal low-latency typed RPC?
Show answer
gRPC.
Why REST for public APIs?
Show answer
Simple and cache-friendly.
Takeaway REST for public CRUD, gRPC for internal low-latency calls, GraphQL for client-shaped reads, WebSocket and SSE for push.
API design checklist#
- Nouns for resources, HTTP verbs for actions:
POST /orders,GET /orders/{id}. - Idempotency: GET/PUT/DELETE by definition; POST needs an
Idempotency-Keyheader. - Cursor pagination (
?after=…&limit=50) over offset at scale. - Versioning: URL (
/v2) or header; never break existing clients. - Consistent error body: code, message, details, request ID.
- Status codes: 400 bad input, 401 unauthenticated, 403 forbidden, 404, 409 conflict, 429 rate-limited, 5xx server.
- Rate-limit headers and
Retry-After. - Large uploads: pre-signed URL direct to object storage; resumable/multipart.
- Long jobs:
202 Accepted+ status endpoint or webhook. - ETags for caching and optimistic concurrency (
If-Match).
Check yourself 2 questions
How do you make POST safe to retry?
Show answer
An Idempotency-Key header.
Which methods are idempotent by definition?
Show answer
GET, PUT and DELETE.
Takeaway Resource nouns, idempotent methods, Idempotency-Key for POST, cursor pagination, versioning and clear errors.
13Security, observability and operations
The wrap-up topics that separate a complete design from a whiteboard sketch.
Identity and access#
| Mechanism | Note |
|---|---|
| Session cookie | Server-side state; easy revocation; CSRF protection needed |
| JWT | Stateless, signed; short expiry + refresh token; hard to revoke |
| OAuth 2.0 | Delegated authorisation; auth-code + PKCE for apps |
| OpenID Connect | Identity layer on OAuth (ID token) |
| mTLS | Service-to-service identity |
| API keys | Server-to-server; rotate, scope, hash at rest |
| RBAC / ABAC / ReBAC | Roles / attributes / relationships (Zanzibar) |
Check yourself 2 questions
Main drawback of JWTs?
Show answer
Hard to revoke; use short expiry plus refresh tokens.
What extra protection do session cookies need?
Show answer
CSRF protection.
Takeaway Sessions are easy to revoke, JWTs are stateless but hard to revoke, OAuth delegates authorisation.
Security checklist#
- TLS everywhere; encrypt at rest (KMS, envelope encryption).
- Secrets in a vault, never in code or images.
- Input validation; parameterised queries (SQL injection); output encoding (XSS).
- CSRF tokens; SSRF allow-lists for server-side fetches.
- WAF, rate limits and CDN absorb DDoS.
- Least privilege IAM; audit logs for sensitive access.
- PII: minimise, tokenise, regional storage, deletion workflows (GDPR/DPDP).
- Payments: tokenise cards; stay out of PCI scope.
Check yourself 2 questions
Defence against SQL injection?
Show answer
Parameterised queries.
Where should secrets live?
Show answer
In a vault, never in code or images.
Takeaway TLS everywhere, encryption at rest, secrets in a vault, input validation, least privilege and audit logs.
Observability#
| Concept | Meaning |
|---|---|
| Golden signals | Latency, traffic, errors, saturation |
| RED (services) | Rate, errors, duration |
| USE (resources) | Utilisation, saturation, errors |
| Logs · metrics · traces | Structured logs with request ID; metrics for alerting; distributed tracing (OpenTelemetry) for latency breakdown |
| SLI / SLO / SLA | Measured indicator / internal target / contractual promise |
| Error budget | 1 − SLO; spend it on releases, freeze when exhausted |
| Alerting | Page on user-facing symptoms (burn rate), not on every cause |
Check yourself 2 questions
The four golden signals?
Show answer
Latency, traffic, errors, saturation.
RED stands for?
Show answer
Rate, errors, duration.
Takeaway Golden signals, RED for services, USE for resources, with logs, metrics and traces correlated.
OAuth 2.0 authorization code with PKCE#
sequenceDiagram participant A as App participant AS as Auth server participant API as Resource API A->>A: make code_verifier and code_challenge = SHA256(verifier) A->>AS: /authorize with code_challenge Note over AS: user signs in and consents AS-->>A: redirect with authorization code A->>AS: /token with code + code_verifier AS-->>A: access token + refresh token A->>API: request with Bearer access token API-->>A: data
PKCE stops a stolen authorization code from being exchanged: only the app holding the verifier can redeem it.
Check yourself 2 questions
What does PKCE protect against?
Show answer
Interception of the authorization code.
What is the code_challenge?
Show answer
SHA-256 of the code_verifier.
Takeaway The app sends a code challenge, exchanges the code with the verifier, and the server checks they match.
Multi-tenancy#
| Model | Isolation | Cost and effort | Fits |
|---|---|---|---|
| Pool (shared everything) | tenant_id on every row, row-level security, per-tenant quotas | Cheapest, simplest to operate | Many small tenants |
| Bridge (shared app, separate schemas or databases) | Data separated per tenant; compute shared | Moderate; migrations run per schema | Mid-size tenants, compliance needs |
| Silo (dedicated stack or cell) | Full isolation per tenant | Most expensive | Large or regulated customers |
- Noisy neighbours: per-tenant rate limits, quotas, separate queues, and cell-based routing.
- Security: enforce the tenant in every query (row-level security), per-tenant encryption keys for sensitive customers.
- Operations: tenant-aware logging, metrics and billing; tenant-level backups and data export or deletion.
Check yourself 2 questions
Cheapest multi-tenancy model?
Show answer
Pool: shared everything with tenant_id and row-level security.
Strongest isolation?
Show answer
Silo: dedicated stack per tenant.
Takeaway Pool, bridge and silo models trade isolation against cost.
14Follow-up questions and strong answers
The curveballs asked after the main design. A good answer names the mechanism, the trade-off and the number.
Curveball → answer#
| They ask | Strong answer |
|---|---|
| Traffic grows 10×. What breaks first? | Walk the path: DB writes (shard or queue), cache hit ratio, hot keys, connection pools. Autoscale stateless tiers; add read replicas; precompute. |
| One key gets 1M QPS (celebrity, flash sale) | Local in-process cache with short TTL, key splitting with merge on read, request coalescing, CDN for public data. |
| A whole region goes down | Health checks + global LB/DNS failover; replicated data with known RPO; idempotent replays; degrade non-critical features. |
| How do you avoid double charging? | Idempotency key stored with the result; payment state machine; reconcile with the provider; treat timeout as "unknown", not failure. |
| Exactly-once processing? | At-least-once delivery + idempotent consumer or dedup table; Kafka transactions for read-process-write within Kafka. |
| Migrate a live database with no downtime | Expand–contract: dual write, backfill, verify with shadow reads, switch reads, stop old writes, remove. |
| Counts are wrong under concurrency (likes, views) | Atomic increments or sharded counters; batch flush to DB; HyperLogLog for unique counts. |
| Cache and DB disagree | Cache-aside with delete-on-write, short TTL, versioned keys, or CDC-driven invalidation. |
| Queue consumers fall behind | Scale consumers up to partition count; increase partitions; batch; DLQ poison messages; back-pressure producers. |
| Latency p99 is bad, p50 fine | Find fan-out and GC pauses; hedged requests; timeouts per hop; cache warmers; reduce payload size. |
| Schema change across many services | Backward-compatible changes (add optional fields), schema registry, consumers before producers. |
| How would you test this? | Load tests at 2× peak, chaos experiments (kill nodes, inject latency), game days, canaries with automatic rollback. |
| What does it cost? | Estimate the dominant item (storage, egress, GPU, DB IOPS); tiered storage; reserved capacity; cache to cut origin load. |
Check yourself 2 questions
Traffic grows 10×: how do you answer?
Show answer
Walk the path: DB writes, cache hit ratio, hot keys, connection pools; autoscale stateless tiers.
What's the general strategy?
Show answer
Find the first bottleneck and name a concrete fix.
Takeaway Answer curveballs by walking the request path to the first thing that breaks and naming the fix.
15HLD last-minute checklist
HLD last-minute checklist#
- State users, core actions, and the invariant to preserve.
- Estimate only numbers that change the architecture.
- Show read and write paths; mark sync and async boundaries.
- Explain cache freshness, shard key, hot-key plan, consistency.
- Make retries safe; treat timeouts as unknown outcomes.
- Cover overload, dependency failure, regional recovery, degradation.
- Name SLO, observability, security, rollout, and rollback.
- For each choice: alternative → reason → failure mode.
Check yourself 2 questions
Which numbers should you estimate?
Show answer
Only those that change the architecture.
What should you mark on the paths?
Show answer
Sync and async boundaries.
Takeaway Users, actions and invariant, numbers that matter, read and write paths, caching, data and failure plans.