System Design: HLD + LLD
The complete HLD and LLD sheets in one scrollable reference, with the shared design map and interview playbooks up front.
00Full system design map & decision flows
Translate product needs into interfaces, state, traffic paths, failure handling, and an operable design.
System design topic atlas#
HLD interview route#
flowchart TD
S[Clarify users and core use cases] --> N[Set functional scope and invariants]
N --> Q[Quantify QPS, read/write mix, payload, retention, regions]
Q --> A[Define APIs and core entities]
A --> W{{Dominant workload?}}
W -->|read-heavy| R[Cache, CDN, replicas, precompute]
W -->|write-heavy| X[Partition, append log, async workers]
W -->|long-running| J[Queue, workers, status/progress API]
W -->|real-time| RT[WebSocket / SSE / streaming log]
W -->|search or media| SI[Index or object store + CDN]
R --> D[Draw end-to-end request and data flows]
X --> D
J --> D
RT --> D
SI --> D
D --> H[Deep-dive bottlenecks, consistency, and failure modes]
H --> G[Check security, SLO, recovery, and cost]
G --> F[State trade-offs and evolution path]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class W decKeep the first diagram small. Deep-dive into the design choice that dominates the workload or correctness risk.
Check yourself 2 questions
What do you quantify before APIs?
Show answer
QPS, read/write mix, payload, retention and regions.
What decides the architecture branch?
Show answer
The dominant workload (read-heavy, write-heavy, real-time and so on).
Takeaway Clarify users and use cases, set scope and invariants, quantify the workload, define APIs, then design for the dominant workload.
Choose storage by access pattern#
flowchart LR
S[What must the data do?] --> Q{{Primary access}}
Q -->|transactions, joins, constraints| SQL[Relational database]
Q -->|lookup by key, very high throughput| KV[Key-value store]
Q -->|large write volume, known query shapes| WC[Wide-column / distributed NoSQL]
Q -->|full-text retrieval| IDX[Inverted search index]
Q -->|semantic nearest neighbors| VEC[Vector index]
Q -->|large immutable blobs| OBJ[Object store + CDN]
Q -->|append, replay, multiple consumers| LOG[Durable event log]
Q -->|relationship traversal| GR[Graph store or adjacency model]
Q -->|metrics over time| TS[Time-series store]
SQL --> B{{Need low-latency reads?}}
KV --> B
WC --> B
B -->|yes| C[Cache with explicit freshness and invalidation]
B -->|no| Z[Measure before adding another store]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,B decCheck yourself 2 questions
Transactions, joins and constraints?
Show answer
A relational database.
Large write volume with known query patterns?
Show answer
A wide-column store.
Takeaway Transactions → relational; key lookups → key-value; heavy writes with known queries → wide-column; search → index; blobs → object store.
Reliability and write-path flow#
flowchart TD C[Client request] --> V[Authenticate · authorize · validate] V --> I[Idempotency key + service transaction] I --> O[Outbox committed with state] O --> Q[Queue / event log] Q --> W[Idempotent consumer] W --> T[Retry with backoff + jitter] T -->|success| D[Downstream effect] T -->|exhausted| DLQ[DLQ + alert / replay] C -. timeout .-> CB[Circuit breaker / bounded retry] CB -.-> C I --> M[Metrics · logs · traces · audit] W --> M DLQ --> M
Retries are safe only when the operation is idempotent or deduplicated. Budget timeouts across the full call chain.
Check yourself 2 questions
Why commit the outbox with the state change?
Show answer
So the event is published if and only if the state changed.
What must consumers be?
Show answer
Idempotent.
Takeaway Validate, idempotency key and transaction, outbox with state, queue, idempotent consumers, retries and dead letters.
Pick consistency and recovery per operation#
| Requirement | Design direction | Check |
|---|---|---|
| Atomic invariant across rows | Database transaction / unique constraint | Keep the invariant in the authoritative store. |
| Read-after-write required | Leader read, session consistency, or quorum | State the consistency boundary and failover behavior. |
| Stale reads acceptable | Async replication, cache, eventual convergence | Define freshness and reconciliation limits. |
| External multi-service workflow | Saga with idempotent steps and compensations | Model timeout as unknown outcome; reconcile. |
| Regional outage | Failover / cells / active-active where justified | Set RTO, RPO, data residency, and conflict policy. |
| Network partition | Choose per operation whether to preserve invariants or accept availability | CAP applies during partition; avoid one global answer for every API. |
Check yourself 2 questions
Atomic invariant across rows?
Show answer
A database transaction or unique constraint in the authoritative store.
Read-after-write required?
Show answer
Leader reads, session consistency or quorum reads.
Takeaway Choose consistency per operation: transactions for invariants, leader or session reads for read-after-write, eventual elsewhere.
LLD flow: requirements to safe code#
flowchart TD S[Use cases and edge cases] --> I[Identify invariants and ownership] I --> M[Model entities and immutable value objects] M --> API[Define small public interfaces] API --> P[Add a pattern only for a real variation or workflow] P --> C[Choose synchronization and transaction boundaries] C --> T[Test state transitions, races, and failures] T --> R[Review SOLID, complexity, and extension points]
Write the core path early. State which component owns each mutable value and how concurrent calls stay correct.
Checklist before you write code
- Every mutable field has exactly one owning class.
- Invariants are checked inside constructors and methods, not by callers.
- Interfaces sit at the seams you will swap or fake: clock, ID generator, payment, storage.
- For each shared object, name the lock or atomic that guards it.
- Expected failures are domain exceptions; programming errors fail fast.
Check yourself 2 questions
When should you add a pattern?
Show answer
Only for a real variation point.
What do you identify right after use cases?
Show answer
Invariants and ownership.
Takeaway Use cases, invariants and ownership, entities and values, small interfaces, patterns only for real variation, then concurrency.
Coverage map — detailed references below#
| Area | Topics and patterns | Jump |
|---|---|---|
| Interview method | Requirements, estimates, APIs, diagrams, deep dives, LLD coding flow | Playbooks |
| Capacity and trade-offs | Latency math, QPS/storage, CAP, store choice, cache, scale | Numbers · Trade-offs |
| HLD patterns | Feeds, chat, booking, search, media, payments, queues, schedulers | HLD problems |
| LLD patterns | SOLID, object modeling, concurrency, common design patterns | LLD problems |
| Distributed systems | Replication, consensus, messaging, transactions, APIs, edge | Distributed concepts |
| Security, operations, evolution | Identity, privacy, observability, SLO, migration, recovery | §0 atlas · Distributed concepts · Last-minute |
Check yourself 2 questions
What does the coverage map help with?
Show answer
Jumping to the detailed section for an area.
Name one area listed.
Show answer
Any of: interview method, capacity and trade-offs, data, distributed systems, LLD.
Takeaway The coverage map points each area of system design to its detailed section.
Reusable design review#
Requirements → workload math → API and invariants → data model → read/write flows → scale bottleneck → failure and security paths → SLO and cost → migration and rollback. For each important choice, name the alternative, the reason for choosing, and the failure mode it creates.
Check yourself 2 questions
For each important choice, what should you name?
Show answer
The alternative and why you rejected it.
Last step of the review?
Show answer
Migration and rollback.
Takeaway Requirements, workload, API and invariants, data model, flows, bottleneck, failure and security, SLO and cost, migration and rollback.
01Interview playbooks (HLD + LLD)
SystemDesign/07-interview-templates HLD_Interview_Cheatsheet.md, 06-lld/LLD_Interview_Cheatsheet.md
HLD 60-min playbook#
| Min | Step |
|---|---|
| 0–5 | Functional reqs (3–5 core), non-functional (scale, latency, consistency, availability) |
| 5–10 | Estimation: QPS, storage, bandwidth (only what drives design) |
| 10–15 | Core entities + API (REST/WebSocket) |
| 15–30 | High-level design: client → LB → services → stores/caches/queues |
| 30–50 | 2–3 deep dives (the hard part of THIS problem) |
| 50–60 | Bottlenecks, failure modes, trade-offs, wrap-up |
Check yourself 2 questions
How many deep dives?
Show answer
Two or three.
Which estimates to make?
Show answer
Only those that drive the design.
Takeaway Requirements, estimates, entities and APIs, a high-level diagram, two or three deep dives, then trade-offs.
LLD 60-min playbook#
| Min | Step |
|---|---|
| 0–6 | Scope questions; list use cases |
| 6–12 | Entities vs value objects vs services |
| 12–18 | Public API (method signatures) |
| 18–24 | Class model / relationships |
| 24–44 | Write real code by minute 25: enums → value objects → entities → interfaces → service |
| 44–50 | Concurrency: ConcurrentHashMap.computeIfAbsent, minimal synchronized, ReentrantLock, AtomicInteger |
| 50–55 | Edge cases, validation, errors |
| 55–60 | Extensions / Q&A |
Check yourself 2 questions
When should real code start?
Show answer
By about minute 25.
What comes before the class model?
Show answer
Public method signatures.
Takeaway Scope, entities, method signatures, class model, then real code by minute 25.
Flow#
flowchart LR R[Requirements] --> E[Estimate] --> A[API + Entities] --> H[High-level diagram] --> D[Deep dives] --> W[Trade-offs and failures]
Check yourself 2 questions
What follows the high-level diagram?
Show answer
Deep dives.
What closes the flow?
Show answer
Trade-offs and failures.
Takeaway Requirements → estimate → API and entities → high-level diagram → deep dives → trade-offs and failures.
02HLD: 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.
03Numbers 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.
04Trade-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.
05Building 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.
06Databases 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.
07HLD 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.
08Worked 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.
09Distributed 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.
10Consistency, 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.
11Scalability, 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.
12Probabilistic 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.
13APIs 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.
14Security, 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.
15Follow-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.
16LLD: model behavior, state, and boundaries
60-minute interview route#
| Time | Focus |
|---|---|
| 0–6 | Use cases, constraints, edge cases |
| 6–12 | Entities, value objects, invariants |
| 12–18 | Public method signatures and ownership |
| 18–24 | Relationships and state transitions |
| 24–44 | Implement core path; extend only as needed |
| 44–50 | Concurrency and atomicity |
| 50–60 | Errors, races, tests, extension points |
What interviewers score
- Entities with one job each, and invariants enforced inside them rather than by callers.
- Patterns used for a real variation point, and named only after the code needs them.
- A working core path early, then extensions.
- Thread safety reasoned out loud: what is shared, and what guards it.
- Testability: injected clock and ID generator, small interfaces, edge cases named.
- Readable names, small methods, and no dead abstractions.
Check yourself 2 questions
What comes right after use cases?
Show answer
Entities, value objects and invariants.
When do you write method signatures?
Show answer
Before relationships and code, around minutes 12–18.
Takeaway Use cases, entities and invariants, method signatures, relationships and states, code the core, then concurrency and extensions.
Object design flow#
flowchart TD U[Use cases + edge cases] --> I[Invariants and state ownership] I --> M[Entities + immutable values] M --> A[Small public interfaces] A --> S[Services orchestrate behavior] S --> P[Pattern for real variation] P --> C[Concurrency / transaction boundaries] C --> T[Test transitions, races, failures]
Check yourself 2 questions
Where should invariant-preserving operations live?
Show answer
Near the state they protect, on the entity.
What do services do?
Show answer
Orchestrate behaviour across entities.
Takeaway Use cases → invariants and state ownership → entities and values → small interfaces → orchestrating services.
Responsibility guide#
| Building block | Owns | Design cue |
|---|---|---|
| Entity | Identity and lifecycle state | Keep invariant-preserving operations near state. |
| Value object | Immutable values such as Money or Address | Validate once; compare by value. |
| Service | Use-case orchestration | Coordinate collaborators; avoid god classes. |
| Repository / gateway | Persistence or external boundary | Depend on an interface for testability. |
| Strategy / state | Replaceable rule or legal transitions | Use when the variation is visible. |
Check yourself 2 questions
Give an example of a value object.
Show answer
Money or Address.
What does a repository hide?
Show answer
Storage details behind a collection-like interface.
Takeaway Entities own identity and lifecycle, value objects are immutable, services orchestrate, repositories hide storage.
17Object-oriented foundations
The vocabulary interviewers expect you to use while modeling. Name the principle when you apply it.
Four pillars of OOP#
| Pillar | What it means | Interview cue |
|---|---|---|
| Encapsulation | State is private; change it only through methods that keep invariants | No public setters on balance; expose deposit() / withdraw() |
| Abstraction | Callers depend on what an object does, not how | PaymentGateway interface hides Stripe/Razorpay details |
| Inheritance | "is-a" reuse of type and behaviour | Use for true subtypes only; prefer composition for reuse |
| Polymorphism | One call, many implementations (runtime dispatch / overloading) | Replace if type == … chains with subclasses or strategies |
Check yourself 2 questions
Encapsulation interview cue?
Show answer
No public setter on balance; expose deposit() and withdraw().
What does polymorphism let you do?
Show answer
Call the same interface with different behaviours.
Takeaway Encapsulation, abstraction, inheritance and polymorphism; protect invariants with methods, not public setters.
UML class relationships#
| Relation | Notation | Lifetime | Code shape |
|---|---|---|---|
| Dependency | dashed arrow | temporary use | parameter or local variable |
| Association | solid line | independent | field holding a reference |
| Aggregation | hollow diamond | part outlives whole | Team has Players passed in |
| Composition | filled diamond | part dies with whole | Order creates its OrderLines |
| Inheritance | hollow triangle, solid | — | class Car extends Vehicle |
| Realization | hollow triangle, dashed | — | class Card implements Payment |
Check yourself 2 questions
Composition versus aggregation?
Show answer
In composition the part's lifetime is owned by the whole; in aggregation it's independent.
Code shape of a dependency?
Show answer
A parameter or local variable.
Takeaway Dependency, association, aggregation, composition, inheritance and realisation differ in lifetime and code shape.
SOLID with the smell and the fix#
| Principle | Rule | Smell you'll see | Fix | LLD example |
|---|---|---|---|---|
| S · Single responsibility | One reason to change | Invoice computes, prints and saves itself | Split into calculator, printer, repository | ParkingLot doesn't compute fees; FeeCalculator does |
| O · Open/closed | Extend without editing | Growing switch(paymentType) | Interface + new class per variant | Add UpiPayment without touching checkout |
| L · Liskov substitution | Subtypes honour the parent's contract | Square extends Rectangle breaks setWidth; Penguin.fly() throws | Re-model the hierarchy; split capabilities | Flyable as a separate interface |
| I · Interface segregation | Small, client-specific interfaces | Classes implementing methods with throw UnsupportedOperation | Split fat interface into roles | Printer, Scanner, Fax instead of Machine |
| D · Dependency inversion | Depend on abstractions; inject them | new MySqlRepo() inside a service | Constructor injection of an interface | Swap in-memory repo for tests |
Check yourself 2 questions
SRP smell?
Show answer
One class that computes, prints and saves (several reasons to change).
DIP fix?
Show answer
Depend on abstractions; inject implementations.
Takeaway Each SOLID principle has a recognisable smell and a standard fix.
Design principles beyond SOLID#
- Composition over inheritance: assemble behaviour from parts; avoids fragile base classes.
- Tell, don't ask:
account.withdraw(x)rather than reading balance and deciding outside. - Law of Demeter: talk to direct collaborators only; avoid
a.getB().getC().do(). - DRY · KISS · YAGNI: no duplicated knowledge, simplest design that works, no speculative features.
- High cohesion, low coupling: related behaviour together; few, narrow dependencies.
- Program to interfaces; keep the domain free of framework and I/O code.
- Immutability for value objects and anything shared across threads.
- Fail fast: validate at construction; make illegal states unrepresentable (enums, types).
Check yourself 2 questions
Tell, don't ask example?
Show answer
account.withdraw(x) rather than reading the balance and deciding outside.
Why prefer composition?
Show answer
It avoids fragile base classes and allows swapping parts.
Takeaway Composition over inheritance, tell don't ask, Law of Demeter, DRY, KISS and YAGNI.
GRASP: who should own this responsibility?#
| Principle | Assign the responsibility to… |
|---|---|
| Information expert | the class that has the data needed |
| Creator | the class that contains or aggregates the created object |
| Controller | a use-case/facade object, not the UI |
| Polymorphism | the types that vary, not a conditional |
| Pure fabrication | a made-up service class when no domain object fits (repository, notifier) |
| Indirection | an intermediary that decouples two classes |
| Protected variations | an interface wrapped around whatever is likely to change |
Check yourself 2 questions
Information expert rule?
Show answer
Give the responsibility to the class with the needed data.
Creator rule?
Show answer
The class that contains or aggregates an object creates it.
Takeaway Information expert, creator, controller, low coupling, high cohesion and more decide ownership.
Language essentials for LLD: Java and Python#
| Topic | Java | Python | Interview cue |
|---|---|---|---|
| Interface vs abstract class | Interface: a contract, multiple inheritance, default methods. Abstract class: shared state and code, single inheritance | abc.ABC with @abstractmethod; typing.Protocol for structural typing | Interface for a capability or strategy; abstract class when subclasses share real state |
| Immutability | final fields, no setters, defensive copies; record for value objects | @dataclass(frozen=True), tuples | Value objects (Money, Address) and anything shared across threads |
| Equality and hashing | Override equals and hashCode together; equal objects must have equal hashes | __eq__ and __hash__; frozen dataclasses generate both | Mutating a field used in the hash after inserting into a HashMap/set loses the entry |
| Enums | Enums can hold fields and per-constant behaviour | enum.Enum; add methods on the class | Model statuses and types as enums, not strings |
| Generics | Bounded types; PECS rule: producer extends, consumer super | TypeVar, Generic[T] (hints only) | Repository<T, ID>, Cache<K, V> |
| Exceptions | Checked (recoverable, declared) vs unchecked (programming errors); custom domain exceptions | All unchecked; subclass Exception per domain error | SeatUnavailableException beats returning null or -1 |
| Visibility and encapsulation | private by default; package-private for tests | Leading underscore by convention; @property for computed or read-only attributes | No public mutable fields on entities |
| Composition helpers | Constructor injection; Optional for absent values | Pass collaborators to __init__; None checks or Optional[T] | Makes swapping and testing collaborators trivial |
Check yourself 2 questions
Interface versus abstract class in Java?
Show answer
Interfaces are contracts with multiple inheritance; abstract classes share state and code with single inheritance.
Python's equivalent of an abstract class?
Show answer
abc.ABC with @abstractmethod.
Takeaway Interfaces versus abstract classes, generics, enums, records and dataclasses, and equality and hashing.
18Design patterns catalogue
All 23 Gang of Four patterns plus the modern ones that show up in machine-coding rounds. In an interview, use one or two that the requirements actually call for, and say why.
Creational (5)#
| Pattern | Intent | Use when |
|---|---|---|
| Singleton | One shared instance | Config, registry, ID generator; make it thread-safe and injectable |
| Factory Method | Subclass decides which product to create | Create Vehicle by type; hide new |
| Abstract Factory | Families of related products | UI themes, DB driver families (connection + command) |
| Builder | Step-by-step construction | Many optional params; immutable result (Pizza, HTTP request) |
| Prototype | Clone an existing object | Expensive setup; templates (documents, game units) |
Check yourself 2 questions
When use Builder?
Show answer
For objects with many optional parameters.
What should a Singleton be, in modern practice?
Show answer
Thread-safe and injectable.
Takeaway Singleton, Factory Method, Abstract Factory, Builder and Prototype manage object creation.
Structural (7)#
| Pattern | Intent | Use when |
|---|---|---|
| Adapter | Convert one interface to another | Wrap a third-party payment SDK |
| Bridge | Split abstraction from implementation | Shape × renderer, Remote × device |
| Composite | Tree of parts treated uniformly | File system, nested comments, menu |
| Decorator | Add behaviour by wrapping | Pizza toppings, stream compression, logging |
| Facade | Simple front for a subsystem | BookingService over seats, payments, notifications |
| Flyweight | Share intrinsic state | Chess piece types, text glyphs, map tiles |
| Proxy | Stand-in that controls access | Lazy loading, caching, auth, remote stub |
Check yourself 2 questions
Wrap a third-party payment SDK?
Show answer
Adapter.
Tree of items treated uniformly?
Show answer
Composite.
Takeaway Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy shape how objects compose.
Behavioral (11)#
| Pattern | Intent | Use when |
|---|---|---|
| Strategy | Swap algorithms | Pricing, matching, split types, eviction |
| State | Behaviour changes with state | Vending machine, ATM, order lifecycle |
| Observer | Notify subscribers of change | Stock alerts, order status, UI events |
| Command | Request as an object | Undo/redo, job queues, macro recording |
| Chain of Responsibility | Pass along handlers | Log levels, approval flows, middleware, ATM notes |
| Template Method | Fixed skeleton, overridable steps | Game turn, report generation, data import |
| Iterator | Traverse without exposing internals | Custom collections, paginated results |
| Mediator | Central hub for interactions | Chat room, air-traffic control, UI dialogs |
| Memento | Snapshot and restore state | Editor undo, game save points |
| Visitor | New operations over a fixed structure | AST evaluation, tax/export over shapes |
| Interpreter | Grammar evaluation | Rule engines, simple expression parsers |
Check yourself 2 questions
Vending machine behaviour changes with state?
Show answer
State pattern.
Swap pricing algorithms?
Show answer
Strategy.
Takeaway Strategy, State, Observer, Command, Chain of Responsibility, Template Method and others organise behaviour.
Modern and enterprise patterns#
| Pattern | Use when |
|---|---|
| Dependency injection | Always: pass collaborators in; enables tests and swaps |
| Repository | Hide storage behind a collection-like interface |
| Unit of Work | Commit several changes atomically |
| Specification | Composable business rules (eligibility, filters) |
| Null Object | Avoid null checks (NoDiscount) |
| Object Pool | Reuse expensive objects (connections, threads) |
| Producer–Consumer | Decouple work creation from execution |
| Event bus / Pub-Sub | Many-to-many async notifications |
| Circuit breaker | Stop calling a failing dependency |
| Rule engine | Coupons, fraud rules, pricing stored as data |
Check yourself 2 questions
When use dependency injection?
Show answer
Always: pass collaborators in for testability and swaps.
Unit of Work?
Show answer
Commits several changes as one transaction.
Takeaway Dependency injection, repository, unit of work, CQRS, event sourcing and outbox appear in modern systems.
Patterns people confuse#
| Pair | Difference |
|---|---|
| Strategy vs State | Client picks the strategy; a state object switches itself to the next state |
| Decorator vs Proxy | Decorator adds behaviour and stacks; proxy controls access to the same interface |
| Adapter vs Facade | Adapter converts one interface; facade simplifies many |
| Factory Method vs Abstract Factory | One product via inheritance vs a family via composition |
| Builder vs Factory | Builder assembles step by step; factory picks a type in one call |
| Observer vs Pub-Sub | Observer: subject knows observers. Pub-sub: broker in between, often async |
| Template vs Strategy | Inheritance fills steps vs composition swaps the whole algorithm |
| Composite vs Decorator | Both wrap the same interface; composite has many children, decorator one |
| Mediator vs Observer | Mediator coordinates two-way logic; observer only broadcasts |
| Bridge vs Adapter | Bridge is designed up front so abstraction and implementation vary independently; adapter retrofits a mismatch |
| Command vs Strategy | Command is a request object you can queue, log or undo; strategy is an interchangeable algorithm |
| Flyweight vs Singleton | Flyweight shares many immutable instances by key; singleton has exactly one instance |
| Chain of Responsibility vs Decorator | A chain link may stop the request; a decorator always delegates and adds behaviour |
Check yourself 2 questions
Strategy versus State?
Show answer
The client picks a strategy; a state object switches itself to the next state.
Decorator versus Proxy?
Show answer
Decorator adds behaviour and stacks; Proxy controls access.
Takeaway Strategy vs State, Decorator vs Proxy, Adapter vs Facade and Factory vs Builder differ in intent.
Trigger phrase → pattern#
| Requirement says… | Reach for |
|---|---|
| "support multiple … types, add more later" | Strategy + Factory |
| "behaves differently when idle / running / out of stock" | State |
| "notify users when…" | Observer |
| "undo", "replay", "queue requests" | Command (+ Memento) |
| "escalate", "levels", "fall through" | Chain of Responsibility |
| "folders contain files and folders" | Composite |
| "add-ons", "toppings", "wrap with logging" | Decorator |
| "integrate legacy / external API" | Adapter |
| "exactly one …" | Singleton, but prefer DI |
| "object with many optional fields" | Builder |
Check yourself 2 questions
'Support multiple types, add more later'?
Show answer
Strategy + Factory.
'Notify users when…'?
Show answer
Observer.
Takeaway Requirement phrases map to patterns: multiple types → Strategy + Factory, state-dependent behaviour → State, notify → Observer.
Which pattern? A quick picker#
Check yourself 2 questions
Behaviour depends on state?
Show answer
State.
Create objects by type?
Show answer
Factory.
Takeaway Varying algorithm → Strategy; state-dependent → State; reactions → Observer; creation by type → Factory.
Vending machine state diagram#
stateDiagram-v2 direction LR [*] --> Idle Idle --> HasMoney: insertCoin HasMoney --> HasMoney: insertCoin HasMoney --> Dispensing: select, stock and funds ok HasMoney --> Idle: refund Dispensing --> Idle: dispense and return change
Check yourself 2 questions
What moves HasMoney to Dispensing?
Show answer
A selection with stock and enough funds.
How do you return from HasMoney to Idle?
Show answer
Refund.
Takeaway Idle → HasMoney on coins → Dispensing on a valid selection → Idle; refunds return to Idle.
Code smells and the refactoring that fixes them#
| Smell | Looks like | Refactoring |
|---|---|---|
| God class | One class with dozens of methods and fields across concerns | Extract class by responsibility; introduce a facade that delegates |
| Long method | A method that needs comments to explain its sections | Extract method per step; name the steps |
| Switch on type | if type == CAR … elif type == BIKE … repeated in several places | Replace conditional with polymorphism (Strategy or subclasses) |
| Primitive obsession | Money as double, IDs as raw strings, status as int | Introduce value objects and enums |
| Feature envy | A method mostly reads another object's data | Move the method to the class that owns the data |
| Data clumps / long parameter lists | The same 4–5 arguments passed together everywhere | Introduce a parameter object or builder |
| Shotgun surgery | One change requires edits in many classes | Move related behaviour together; one place per decision |
| Anemic domain model | Entities are bags of getters/setters; all logic in services | Move invariant-protecting behaviour into the entity |
| Hidden dependencies | new or singletons called deep inside methods | Constructor injection behind interfaces |
| Speculative generality | Abstract layers and patterns with a single implementation | Inline them until a second variation appears (YAGNI) |
Check yourself 2 questions
Fix for a god class?
Show answer
Extract classes by responsibility, with a facade delegating.
Fix for switch-on-type?
Show answer
Replace conditional with polymorphism (Strategy or State).
Takeaway God classes, long methods, switch-on-type and feature envy each have a standard refactoring.
Strategy + Factory (Java)#
interface PricingStrategy { Money price(Ride r); } class StandardPricing implements PricingStrategy { public Money price(Ride r){ return r.km().times(12); } } class SurgePricing implements PricingStrategy { private final double mult; SurgePricing(double m){ mult = m; } public Money price(Ride r){ return r.km().times(12 * mult); } } final class PricingFactory { static PricingStrategy forDemand(double ratio){ return ratio > 1.5 ? new SurgePricing(ratio) : new StandardPricing(); } } // RideService depends on PricingStrategy only (DIP); new rule = new class (OCP)
Check yourself 2 questions
What does the factory return?
Show answer
The right PricingStrategy implementation for the context.
Adding a new pricing rule needs what?
Show answer
A new class, without editing existing ones.
Takeaway An interface per algorithm, implementations per type, and a factory choosing one.
State machine (vending machine)#
interface State { default void insertCoin(Machine m, int c){ throw new IllegalStateException(); } default void select(Machine m, String code){ throw new IllegalStateException(); } default void dispense(Machine m){ throw new IllegalStateException(); } } class Idle implements State { public void insertCoin(Machine m, int c){ m.addBalance(c); m.setState(new HasMoney()); } } class HasMoney implements State { public void insertCoin(Machine m, int c){ m.addBalance(c); } public void select(Machine m, String code){ if (!m.inventory().available(code)) throw new OutOfStock(code); if (m.balance() < m.price(code)) throw new InsufficientFunds(); m.setSelection(code); m.setState(new Dispensing()); } } class Dispensing implements State { public void dispense(Machine m){ m.release(); m.returnChange(); m.setState(new Idle()); } } // Illegal transitions fail loudly; no if/else on a status enum
Check yourself 2 questions
What do default methods do in the State interface?
Show answer
Throw IllegalStateException for invalid actions.
Who switches the current state?
Show answer
The state objects, via the machine.
Takeaway Each state implements only valid actions; defaults throw for invalid ones.
Observer#
interface Subscriber { void onEvent(OrderEvent e); } class OrderPublisher { private final List<Subscriber> subs = new CopyOnWriteArrayList<>(); void subscribe(Subscriber s){ subs.add(s); } void publish(OrderEvent e){ for (Subscriber s : subs) s.onEvent(e); } } // CopyOnWriteArrayList: safe iteration while others subscribe. // Async delivery? hand events to an ExecutorService or a BlockingQueue.
Check yourself 2 questions
Why CopyOnWriteArrayList for subscribers?
Show answer
Safe iteration while subscribers are added or removed.
What does a subscriber implement?
Show answer
An onEvent method.
Takeaway Publishers hold a thread-safe list of subscribers and notify each on events.
Thread-safe Singleton#
// 1) Holder idiom: lazy, thread-safe, no locks final class IdGenerator { private IdGenerator() {} private static class Holder { static final IdGenerator I = new IdGenerator(); } static IdGenerator get(){ return Holder.I; } } // 2) Enum singleton: also safe against reflection/serialization enum Registry { INSTANCE; } // 3) Double-checked locking needs a volatile field // Python: a module-level instance is already a singleton.
Check yourself 2 questions
Why is the holder idiom thread-safe?
Show answer
Class loading initialises the holder once, safely.
Alternative Java singleton?
Show answer
An enum with one instance.
Takeaway The holder idiom gives lazy, lock-free, thread-safe initialisation; an enum also works.
19LLD problem breakdowns & patterns
SystemDesign/06-lld/06-problems/* (Key takeaways), LLD_Interview_Cheatsheet.md, 03-design-patterns
LLD problems: pattern + the gotcha#
| Problem | Patterns | Gotcha / key insight |
|---|---|---|
| Parking lot | Strategy (spot allocation), Factory, Singleton | ParkingLot → ParkingFloor → ParkingSpot; delegate, don't god-class |
| Rate limiter | Strategy | token bucket w/ lazy refill; ConcurrentHashMap per user |
| Tic-tac-toe | — | O(1) win check with row/col/diag counters |
| Vending machine | State | no if-else state; polymorphic states |
| Splitwise | Strategy (split types) | + minimise cash flow greedy on net balances |
| BookMyShow | Strategy, Observer | Seat vs ShowSeat; lock ShowSeat with TTL |
| Chess | Template, Factory | pieces validate geometry; Board validates path/check |
| Snake & ladder | — | single Jumper(start→end) class |
| Elevator | Strategy, State | SCAN/LOOK sweep with sorted sets, not FIFO |
| Comment system | Composite | materialised path for O(1) thread fetch |
| Hotel management | Strategy (pricing) | date-range overlap in availability |
| ATM | State, Chain (cash dispenser) | external BankService does atomic debit |
| LRU cache | — | HashMap + DLL with dummy head/tail; know the wiring cold |
| Food delivery | Strategy (dispatch), Observer (status) | focus on core models |
| Locker | Strategy | size ordering: S fits S/M/L/XL, L fits L/XL |
| Notification | Strategy, Observer, Factory | add WhatsAppStrategy without touching core |
| Coupon system | Strategy / Rule engine | coupons as DB rows → strategy, never hardcode |
| Logger | Chain of Responsibility, Strategy, Producer-Consumer | BlockingQueue for async |
| Library | — | Book vs BookItem (copies) |
| Order management | Saga / Command | OrderOrchestrator with compensating steps |
| Ride sharing | Strategy (match, price), State (ride) | black-box LocationService |
| Pub-sub | Observer | BlockingQueue per topic + worker |
| Inventory | — | available vs reserved vs purchased quantity |
Check yourself 2 questions
Parking lot gotcha?
Show answer
Delegate through Lot → Floor → Spot; don't build a god class.
Patterns for a parking lot?
Show answer
Strategy for spot allocation, Factory, Singleton.
Takeaway Each classic LLD problem has signature patterns and one gotcha.
Pattern trigger map (use at most 2)#
| Trigger phrase | Pattern |
|---|---|
| multiple algorithms / pricing / payment types | Strategy |
| create objects by type | Factory |
| notify on change / subscribe | Observer |
| single shared instance (config, registry) | Singleton (thread-safe) |
| many optional params | Builder |
| add behaviour dynamically (toppings, filters) | Decorator |
| behaviour depends on state (vending, ATM, order) | State |
| undo / queue requests | Command |
| pass through handlers (log levels, approvals) | Chain of Responsibility |
| tree of parts (folders, comments) | Composite |
Check yourself 2 questions
Why use at most two patterns?
Show answer
Over-patterning adds complexity without value.
Single shared instance trigger?
Show answer
Singleton.
Takeaway Map trigger phrases to patterns, and use at most two per problem.
SOLID + scoring signals#
- SRP one reason to change · OCP extend via new class · LSP subtypes substitutable · ISP small interfaces · DIP depend on abstractions
- Composition over inheritance; facade service as the entry point
- Value objects immutable (Money, Address); enums for statuses
- Thread-safety stated explicitly; no global mutable state
- Recovery line: "Let me simplify — I'll get the core flow working, then extend.
Check yourself 2 questions
ISP in one line?
Show answer
Small, focused interfaces.
What's the typical entry point to the design?
Show answer
A facade service.
Takeaway SOLID, composition over inheritance and a facade service as the entry point score well.
Class sketch: parking lot#
classDiagram
class ParkingLot{+park(v) Ticket +unpark(t) Fee}
class ParkingFloor{+findSpot(type) Spot}
class ParkingSpot{+type +isFree()}
class Ticket{+id +entryTime}
class PricingStrategy{+fee(t)}
ParkingLot "1" --> "*" ParkingFloor
ParkingFloor "1" --> "*" ParkingSpot
ParkingLot --> PricingStrategy
ParkingLot --> TicketCheck yourself 2 questions
Who finds a free spot?
Show answer
ParkingFloor.findSpot(type).
How is the fee computed?
Show answer
By a PricingStrategy.
Takeaway ParkingLot parks and unparks, floors find spots, tickets record entry, a pricing strategy computes fees.
20LLD problems: entities, APIs and the core move
For each classic problem: the classes to draw first, the methods to write first, and the part interviewers probe.
Problem playbook#
| Problem | Core entities | Key methods | Patterns | What they probe |
|---|---|---|---|---|
| Parking lot | ParkingLot, Floor, Spot(type), Vehicle, Ticket, FeeCalculator, Gate | park(vehicle) → Ticket, unpark(ticket) → Receipt | Strategy (allocation, fees), Factory, Singleton | Concurrent spot allocation; per-type free lists |
| Elevator | ElevatorSystem, Elevator, Request, Direction, Dispatcher, Door | request(floor, dir), step() | Strategy (dispatch), State (moving/idle/maintenance) | SCAN/LOOK scheduling, choosing the nearest same-direction car |
| BookMyShow / movie booking | Movie, Theatre, Screen, Show, Seat, ShowSeat, Booking, Payment | holdSeats(show, seats), confirm(bookingId) | Strategy (pricing), Observer | Seat hold with TTL; no double booking |
| Splitwise | User, Group, Expense, Split (Equal/Exact/Percent), BalanceSheet | addExpense(), balances(user), settle() | Strategy, Factory | Validate splits sum; simplify debts with heaps on net balance |
| Vending machine | Machine, State, Inventory, Product, Coin | insertCoin(), select(), dispense(), refund() | State | Illegal transitions; change-making |
| ATM | ATM, Card, Account, Transaction, CashDispenser, BankService | authenticate(), withdraw(amount) | State, Chain (note denominations) | Atomic debit + dispense; reversal on failure |
| Library management | Book, BookItem(copy), Member, Loan, Reservation, Fine | checkout(), return(), reserve() | Observer (availability), Strategy (fines) | Book vs BookItem; limits per member |
| Chess | Game, Board, Cell, Piece(subtypes), Move, Player | makeMove(from, to), isCheckmate() | Template, Factory, Command (undo) | Piece validates shape; board validates path and check |
| Tic-tac-toe (n×n) | Game, Board, Player, Move | move(r, c) → result | — | O(1) win check using row/col/diagonal counters |
| Snake & ladder | Game, Board, Jumper(start→end), Player, Dice | playTurn() | Strategy (dice) | One Jumper class covers snakes and ladders |
| LRU / LFU cache | Cache, Node, DoublyLinkedList, (freq buckets) | get(k), put(k, v) in O(1) | Strategy (eviction) | Map + DLL wiring; LFU min-freq tracking; thread safety |
| Rate limiter | RateLimiter, Bucket, Rule, Clock | allow(clientId) → bool | Strategy (algorithm) | Lazy refill; per-key locking; injectable clock |
| Logger | Logger, Level, Appender(console/file), Formatter | log(level, msg) | Chain, Strategy, Singleton, Producer-Consumer | Async appender with bounded queue; level filtering |
| Pub-sub / message queue | Broker, Topic, Partition, Message, Publisher, Subscriber, Offset | publish(topic, msg), subscribe(topic, s) | Observer | Per-subscriber offsets; ordering; back-pressure |
| Hotel booking | Hotel, Room(type), Booking, Guest, DateRange, Invoice | search(range, type), book(), cancel() | Strategy (pricing) | Date-range overlap check; holds |
| Ride sharing | Rider, Driver, Trip(state), Location, Matcher, Pricing | requestRide(), accept(), complete() | Strategy, State, Observer | Matching nearest available driver atomically |
| Food delivery | Restaurant, Menu, Order(state), Cart, DeliveryAgent, Dispatcher | placeOrder(), assignAgent(), track() | State, Strategy, Observer | Order lifecycle; reassignment on reject |
| File system | Entry (File / Directory), Path, Permissions | mkdir, ls, find(filter) | Composite, Specification | Recursive size; search filters composed with AND/OR |
| Task scheduler | Task, Trigger(once/cron), Scheduler, Worker, DelayQueue | schedule(task, at), cancel(id) | Command, Strategy | Min-heap by next run time; worker pool; retries |
| Shopping cart / inventory | Product, Cart, CartItem, Inventory, Order, Coupon | add(), checkout(), applyCoupon() | Strategy, Specification | Reserve vs purchased stock; coupon stacking rules |
| Notification service | Notification, Channel(Email/SMS/Push), Template, Preference | send(userId, event) | Strategy, Factory, Observer | Add a channel without touching core; retries, dedup |
| Stack Overflow | User, Question, Answer, Comment, Vote, Tag, Reputation | post(), vote(), accept() | Observer, Composite | One vote per user; reputation updates |
| Cricket scoreboard | Match, Innings, Over, Ball, Player, Scorecard | recordBall(event) | Observer, Command | Extras, wickets and strike rotation rules |
Check yourself 2 questions
Parking lot key methods?
Show answer
park(vehicle) → Ticket; unpark(ticket) → Receipt.
What do interviewers probe in a rate limiter?
Show answer
Algorithm choice, concurrency and per-key state.
Takeaway For each problem know the core entities, key methods, patterns and what the interviewer is probing.
LRU cache, O(1) (Python)#
class Node: __slots__ = ("k", "v", "prev", "next") def __init__(self, k=0, v=0): self.k, self.v, self.prev, self.next = k, v, None, None class LRUCache: def __init__(self, cap): self.cap, self.map = cap, {} self.head, self.tail = Node(), Node() # sentinels self.head.next, self.tail.prev = self.tail, self.head def _remove(self, n): n.prev.next, n.next.prev = n.next, n.prev def _add_front(self, n): n.next, n.prev = self.head.next, self.head self.head.next.prev = n; self.head.next = n def get(self, k): if k not in self.map: return -1 n = self.map[k]; self._remove(n); self._add_front(n); return n.v def put(self, k, v): if k in self.map: self._remove(self.map[k]) n = self.map[k] = Node(k, v); self._add_front(n) if len(self.map) > self.cap: lru = self.tail.prev; self._remove(lru); del self.map[lru.k] # Thread-safe: guard get/put with one lock (or striped locks per shard)
Check yourself 2 questions
Data structures for an O(1) LRU?
Show answer
A hash map plus a doubly linked list.
What happens on get?
Show answer
Move the node to the front (most recent).
Takeaway A hash map to nodes plus a doubly linked list with sentinels gives O(1) get and put.
Token-bucket rate limiter (Java, thread-safe)#
final class TokenBucket { private final long capacity; private final double refillPerNano; private double tokens; private long last; private final Clock clock; // injectable for tests TokenBucket(long cap, double perSec, Clock c){ capacity = cap; refillPerNano = perSec / 1e9; tokens = cap; clock = c; last = c.nanos(); } synchronized boolean tryAcquire(){ long now = clock.nanos(); tokens = Math.min(capacity, tokens + (now - last) * refillPerNano); // lazy refill last = now; if (tokens < 1) return false; tokens -= 1; return true; } } class RateLimiter { private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>(); boolean allow(String client){ return buckets.computeIfAbsent(client, k -> new TokenBucket(10, 5, Clock.SYSTEM)).tryAcquire(); } }
Variants and follow-ups
- Leaky bucket smooths output to a fixed rate; fixed window is simple but bursts at window edges.
- Sliding log is exact but stores every timestamp; sliding window counter approximates it with two counters.
- Distributed: keep the bucket in Redis and refill-and-take in one Lua script so it stays atomic.
- Memory: per-client buckets need eviction (expire idle keys).
- Response: return 429 with
Retry-Aftercomputed from the token deficit.
Check yourself 2 questions
How are tokens refilled?
Show answer
By elapsed time × refill rate, capped at capacity.
Why inject a Clock?
Show answer
So tests can control time.
Takeaway Refill tokens by elapsed time, take one per request, synchronise access and inject a clock for tests.
Parking lot class sketch (Java)#
enum SpotType { MOTORBIKE, COMPACT, LARGE } enum VehicleType { BIKE, CAR, TRUCK } record Ticket(String id, String spotId, VehicleType type, Instant in) {} interface SpotAllocator { Optional<Spot> allocate(VehicleType t); void release(Spot s); } interface FeePolicy { Money fee(Ticket t, Instant out); } final class ParkingLot { // facade private final SpotAllocator allocator; private final FeePolicy fees; private final Map<String, Ticket> active = new ConcurrentHashMap<>(); Ticket park(Vehicle v){ Spot s = allocator.allocate(v.type()).orElseThrow(LotFull::new); // atomic inside Ticket t = new Ticket(UUID.randomUUID().toString(), s.id(), v.type(), Instant.now()); active.put(t.id(), t); return t; } Receipt unpark(String ticketId){ Ticket t = Optional.ofNullable(active.remove(ticketId)).orElseThrow(InvalidTicket::new); allocator.release(spotOf(t)); return new Receipt(t, fees.fee(t, Instant.now())); } }
Check yourself 2 questions
Why use a record for Ticket?
Show answer
It's an immutable value.
What returns Optional in the sketch?
Show answer
The SpotAllocator, when no spot is free.
Takeaway Enums for spot and vehicle types, records for tickets, and an injectable SpotAllocator.
Tic-tac-toe with O(1) win check (Java)#
final class TicTacToe { private final int n; private final int[] rows, cols; private int diag, anti; TicTacToe(int n) { this.n = n; rows = new int[n]; cols = new int[n]; } /** player 1 or 2; returns the winner or 0. */ int move(int r, int c, int player) { int d = player == 1 ? 1 : -1; rows[r] += d; cols[c] += d; if (r == c) diag += d; if (r + c == n - 1) anti += d; int target = d * n; return (rows[r] == target || cols[c] == target || diag == target || anti == target) ? player : 0; } } // Validation (occupied cell, wrong turn, game over) lives in a Game class around this.
Check yourself 2 questions
How does the O(1) win check work?
Show answer
Add ±1 to the move's row, column and diagonals; |sum| = n means a win.
Space needed?
Show answer
O(n): row and column arrays plus two diagonals.
Takeaway Track row, column and diagonal sums per player: a sum of ±n means a win, checked in O(1).
Logger with chain of responsibility (Java)#
enum Level { DEBUG, INFO, WARN, ERROR } abstract class Handler { private Handler next; Handler then(Handler n) { this.next = n; return n; } void handle(Level lvl, String msg) { if (accepts(lvl)) write(lvl, msg); if (next != null) next.handle(lvl, msg); } abstract boolean accepts(Level lvl); abstract void write(Level lvl, String msg); } final class ConsoleHandler extends Handler { boolean accepts(Level l) { return l.compareTo(Level.INFO) >= 0; } void write(Level l, String m) { System.out.println(l + " " + m); } } final class AlertHandler extends Handler { boolean accepts(Level l) { return l == Level.ERROR; } void write(Level l, String m) { /* page on-call */ } } // chain: Handler root = new ConsoleHandler(); root.then(new AlertHandler()); // For throughput, put a BlockingQueue + writer thread in front (async appender).
Follow-ups
- Async appender: a bounded queue plus one writer thread; decide whether to block or drop when it is full.
- Configuration: levels per package, changeable at runtime without a restart.
- Formatting is a Strategy; extra sinks (file, network) are more handlers in the chain.
- Thread safety: a single writer thread, or synchronise each sink's write.
Check yourself 2 questions
Which pattern routes log levels?
Show answer
Chain of Responsibility.
How do handlers link?
Show answer
Each holds a next handler.
Takeaway Handlers handle levels they care about and pass messages down the chain.
In-memory pub-sub with per-subscriber offsets (Java)#
final class Topic { private final List<String> log = new CopyOnWriteArrayList<>(); // append-only void publish(String msg) { log.add(msg); } String read(int offset) { return offset < log.size() ? log.get(offset) : null; } } final class Subscriber implements Runnable { private final Topic topic; private final Consumer<String> handler; private final AtomicInteger offset = new AtomicInteger(); // own position private volatile boolean running = true; Subscriber(Topic t, Consumer<String> h) { topic = t; handler = h; } public void run() { while (running) { String m = topic.read(offset.get()); if (m == null) { LockSupport.parkNanos(1_000_000); continue; } // or wait/notify handler.accept(m); offset.incrementAndGet(); // commit after handling } } void resetOffset(int o) { offset.set(o); } // replay void stop() { running = false; } } // Each subscriber has its own offset, so slow ones don't block fast ones and can replay.
Check yourself 2 questions
Why per-subscriber offsets?
Show answer
Each subscriber reads independently and can replay.
What structure holds messages?
Show answer
An append-only list per topic.
Takeaway An append-only log per topic with per-subscriber offsets lets each consumer read at its own pace.
21Worked LLD designs: three walkthroughs and a booking flow
Requirements, class diagram, the code that interviewers actually probe, and the extensions to mention. Java, since most machine-coding rounds expect it.
Elevator system#
The core is a per-car scheduler (LOOK: keep going in one direction while stops remain) and a dispatcher that picks the cheapest car.
classDiagram
class ElevatorSystem {
+requestPickup(floor, dir)
+requestStop(carId, floor)
+tick()
}
class Dispatcher {
<<interface>>
+choose(cars, floor, dir) Elevator
}
class LeastCostDispatcher
class Elevator {
-int floor
-Direction dir
-TreeSet up
-TreeSet down
+addStop(floor)
+step()
+cost(floor, dir) int
}
class Direction {
<<enumeration>>
UP
DOWN
IDLE
}
ElevatorSystem "1" --> "*" Elevator
ElevatorSystem --> Dispatcher
Dispatcher <|.. LeastCostDispatcher
Elevator --> Direction
Requirements to confirm
- N cars, M floors; hall calls (floor + direction) and car calls (destination).
- Minimise wait time; no starvation; doors, capacity and maintenance mode as extensions.
- Single controller process; simulation driven by
tick().
Key decisions
- Two sorted sets per car (stops above, stops below) give O(log n) next-stop lookup.
- Dispatcher is a Strategy: nearest car, least cost, zoning.
- Car state (moving, doors open, maintenance) can become a State pattern.
Edge cases to test
- A call for the current floor while the doors are open.
- An opposite-direction hall call on the car's path: serve it only after the car turns.
- Every car busy or in maintenance: queue the call, never drop it.
- Repeated presses of the same button are idempotent.
- Emergency stop or overweight: hold the car and re-dispatch its hall calls.
Follow-ups to expect
- 100 floors and 8 cars: zone the building or add express cars.
- Testing the scheduler: drive it with a fake clock and
tick()so runs are deterministic. - Destination dispatch: riders enter the floor in the lobby, so you can group them by destination.
Elevator scheduling (LOOK)
enum Direction { UP, DOWN, IDLE } final class Elevator { private int floor = 0; private Direction dir = Direction.IDLE; private final TreeSet<Integer> up = new TreeSet<>(), down = new TreeSet<>(); synchronized void addStop(int f) { if (f > floor) up.add(f); else if (f < floor) down.add(f); if (dir == Direction.IDLE && f != floor) dir = f > floor ? Direction.UP : Direction.DOWN; } synchronized void step() { // one tick = one floor if (dir == Direction.UP) { if (up.isEmpty()) { dir = down.isEmpty() ? Direction.IDLE : Direction.DOWN; return; } floor++; if (up.remove(floor)) openDoors(); } else if (dir == Direction.DOWN) { if (down.isEmpty()) { dir = up.isEmpty() ? Direction.IDLE : Direction.UP; return; } floor--; if (down.remove(floor)) openDoors(); } } synchronized int cost(int f, Direction d) { // lower is better int dist = Math.abs(floor - f); if (dir == Direction.IDLE) return dist; boolean onTheWay = (dir == Direction.UP && d == Direction.UP && f >= floor) || (dir == Direction.DOWN && d == Direction.DOWN && f <= floor); return onTheWay ? dist : dist + 100; // penalise turning around } private void openDoors() { /* notify observers, start door timer */ } }
Dispatcher
interface Dispatcher { Elevator choose(List<Elevator> cars, int floor, Direction d); } final class LeastCostDispatcher implements Dispatcher { public Elevator choose(List<Elevator> cars, int floor, Direction d) { return cars.stream().min(Comparator.comparingInt(c -> c.cost(floor, d))).orElseThrow(); } }
Extensions to mention
- Capacity: skip hall calls when the car is full.
- Peak modes: park idle cars at the lobby in the morning.
- Fairness: age requests so far floors aren't starved.
- Concurrency: requests arrive on many threads; each car's state is guarded by its own lock.
Check yourself 2 questions
What does the LOOK algorithm do?
Show answer
Keeps moving in one direction while stops remain, then reverses.
What does the dispatcher choose?
Show answer
The cheapest car for each pickup request.
Takeaway A per-car LOOK scheduler plus a dispatcher that picks the cheapest car.
Movie ticket booking (BookMyShow)#
Model a seat per show separately from the physical seat, and make "hold these seats" all-or-nothing with an expiry.
classDiagram
class Show {
+String id
+Movie movie
+Screen screen
+Instant start
}
class Seat {
+String id
+SeatType type
}
class ShowSeat {
+Seat seat
+SeatStatus status
+Money price
}
class Booking {
+String id
+String userId
+List seats
+BookingStatus status
}
class BookingService {
+hold(showId, seatIds, userId) Hold
+confirm(holdId, payment) Booking
}
class SeatLockProvider {
<<interface>>
+lock(showId, seatIds, userId) bool
+unlock(showId, seatIds, userId)
}
Show "1" --> "*" ShowSeat
ShowSeat --> Seat
BookingService --> SeatLockProvider
BookingService --> Booking
Booking --> ShowSeat
Requirements to confirm
- Search shows by city/movie; view seat layout; select up to N seats; hold for 10 minutes; pay; confirm or release.
- No double booking under concurrent requests; price by seat type and show.
Key decisions
- Seat vs ShowSeat: the physical seat is shared across shows; status lives on ShowSeat.
- Locking behind an interface: in-memory for the interview, Redis or DB in production.
- Pricing as a Strategy (weekday, premium, surge); notifications via Observer.
- Money as integer minor units, never
double.
All-or-nothing seat lock with expiry
final class InMemorySeatLock implements SeatLockProvider { private record Lock(String user, Instant expiry) {} private final Map<String, Map<String, Lock>> locks = new ConcurrentHashMap<>(); private final Duration ttl; private final Clock clock; InMemorySeatLock(Duration ttl, Clock clock) { this.ttl = ttl; this.clock = clock; } public boolean lock(String show, List<String> seats, String user) { Map<String, Lock> m = locks.computeIfAbsent(show, k -> new HashMap<>()); synchronized (m) { // serialise per show only Instant now = clock.instant(); for (String s : seats) { Lock l = m.get(s); if (l != null && l.expiry().isAfter(now) && !l.user().equals(user)) return false; } for (String s : seats) m.put(s, new Lock(user, now.plus(ttl))); return true; } } public void unlock(String show, List<String> seats, String user) { Map<String, Lock> m = locks.get(show); if (m == null) return; synchronized (m) { seats.forEach(s -> m.computeIfPresent(s, (k, l) -> l.user().equals(user) ? null : l)); } } }
Confirm flow
- Check every seat is still locked by this user (not expired).
- Charge with an idempotency key.
- Mark ShowSeats BOOKED and save the booking in one transaction.
- Unlock; publish a BookingConfirmed event.
- On payment failure or timeout, release the lock and mark the booking FAILED.
Extensions to mention
- Distributed lock: Redis
SET key NX PXper seat, with the DB unique constraint as a safety net. - Waitlist via Observer when seats free up.
- Coupons as a rule engine.
Check yourself 2 questions
Why model ShowSeat separately from Seat?
Show answer
Availability is per show, not per physical seat.
How are holds made safe?
Show answer
All-or-nothing locking with an expiry.
Takeaway Model seat-per-show separately from the physical seat; holds are all-or-nothing with expiry.
Splitwise (expense sharing)#
Different split types are a Strategy with validation, balances are a ledger, and "settle up" is a greedy matching of debtors and creditors.
classDiagram
class ExpenseService {
+addExpense(groupId, paidBy, amount, splitType, details)
+balances(userId) Map
+settlePlan(groupId) List
}
class Expense {
+String id
+String paidBy
+long amountCents
+List splits
}
class Split {
<<abstract>>
+String userId
+long amountCents
}
class SplitStrategy {
<<interface>>
+compute(amount, users, details) List
}
class EqualSplit
class ExactSplit
class PercentSplit
class BalanceSheet {
+apply(Expense)
+net(userId) long
}
ExpenseService --> SplitStrategy
ExpenseService --> BalanceSheet
Expense "1" --> "*" Split
SplitStrategy <|.. EqualSplit
SplitStrategy <|.. ExactSplit
SplitStrategy <|.. PercentSplit
Requirements to confirm
- Users, groups, expenses paid by one user split equally, by exact amounts or by percentages.
- Show who owes whom; simplify debts to few transfers; record settlements.
Key decisions
- Store money as
longcents; give rounding remainders to the first participants deterministically. - Each strategy validates its input (exact amounts sum to the total; percentages sum to 100).
- Balances as net amount per user per group: positive is owed money, negative owes.
- Expenses are immutable; edits are reversal plus a new expense (audit trail).
Equal split with fair rounding
final class EqualSplit implements SplitStrategy { public List<Split> compute(long amount, List<String> users, Map<String, Long> ignored) { long base = amount / users.size(), rem = amount % users.size(); List<Split> out = new ArrayList<>(); for (int i = 0; i < users.size(); i++) out.add(new Split(users.get(i), base + (i < rem ? 1 : 0))); return out; // sums exactly to amount } }
Simplify debts
record Transfer(String from, String to, long cents) {} static List<Transfer> simplify(Map<String, Long> net) { // + owed, − owes PriorityQueue<long[]> cred = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1])); PriorityQueue<long[]> debt = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1])); List<String> ids = new ArrayList<>(net.keySet()); for (int i = 0; i < ids.size(); i++) { long v = net.get(ids.get(i)); if (v > 0) cred.add(new long[]{i, v}); else if (v < 0) debt.add(new long[]{i, -v}); } List<Transfer> out = new ArrayList<>(); while (!cred.isEmpty() && !debt.isEmpty()) { long[] c = cred.poll(), d = debt.poll(); long amt = Math.min(c[1], d[1]); out.add(new Transfer(ids.get((int) d[0]), ids.get((int) c[0]), amt)); if (c[1] > amt) cred.add(new long[]{c[0], c[1] - amt}); if (d[1] > amt) debt.add(new long[]{d[0], d[1] - amt}); } return out; // at most n − 1 transfers; the true minimum is NP-hard }
Check yourself 2 questions
Pattern for equal, exact and percent splits?
Show answer
Strategy, each with validation.
How does settle-up minimise transactions?
Show answer
Greedily match largest debtors with largest creditors.
Takeaway Split types are strategies with validation, balances are a ledger, and settle-up greedily matches debtors and creditors.
Booking flow as a sequence diagram#
sequenceDiagram participant U as User participant BS as BookingService participant L as SeatLockProvider participant P as PaymentGateway participant R as BookingRepository U->>BS: hold(showId, seats) BS->>L: lock(showId, seats, userId) L-->>BS: locked until T + 10 min BS-->>U: holdId U->>BS: confirm(holdId, paymentToken) BS->>L: still locked by this user? BS->>P: charge(amount, idempotencyKey) P-->>BS: success BS->>R: save booking and mark seats BOOKED BS->>L: unlock(showId, seats) BS-->>U: booking confirmed
Draw this after the class diagram: it proves the classes can actually carry out the use case and shows where the concurrency risk sits (between lock and confirm).
Check yourself 2 questions
What happens if payment fails?
Show answer
Release the seat locks.
When is the booking saved?
Show answer
After successful payment, via the repository.
Takeaway Hold seats with a lock provider, pay, then confirm and save; release locks on failure.
22Concurrency, atomicity & error paths
Correctness boundary#
| Problem | Mechanism | Invariant |
|---|---|---|
| Concurrent map update | Atomic map op / lock | Check-and-set is one operation. |
| Shared counter | Atomic integer / synchronized allocator | No lost or duplicate increments. |
| Multi-field transition | Lock or database transaction | No partial state visible. |
| Work queue | BlockingQueue / bounded channel | Backpressure and shutdown are defined. |
| Retryable command | Idempotency key + stored result | Retry returns same logical outcome. |
| External side effect | Outbox / saga boundary | Failure can be retried or compensated. |
Check yourself 2 questions
Concurrent map update mechanism?
Show answer
An atomic map operation (e.g. computeIfAbsent) or a lock.
Shared counter mechanism?
Show answer
An atomic integer or a synchronised allocator.
Takeaway Make check-and-set one operation: atomic map ops, atomic counters, locks or transactions.
Review questions#
- Who owns each mutable field?
- Can two requests race on the same object?
- What makes each method atomic?
- Can a retry duplicate an operation?
- Are terminal and invalid states explicit?
- Can dependencies be replaced in a unit test?
Check yourself 2 questions
Name a concurrency review question.
Show answer
Any of: who owns each mutable field, can two requests race, what makes the method atomic.
Why ask whether retries duplicate operations?
Show answer
Retries without idempotency cause double effects.
Takeaway Ask who owns each field, what races, what makes methods atomic, whether retries duplicate, and which states are terminal.
Optimistic vs pessimistic locking in code#
// Pessimistic: hold a lock for the whole read-modify-write synchronized (account) { account.debit(amount); } // Optimistic in memory: compare-and-swap loop AtomicReference<Balance> ref = new AtomicReference<>(start); while (true) { Balance cur = ref.get(); Balance next = cur.minus(amount); // immutable value if (ref.compareAndSet(cur, next)) break; // retry if someone else won } // Optimistic in the database: version column // UPDATE accounts SET balance = ?, version = version + 1 // WHERE id = ? AND version = ? -- 0 rows updated means retry
- Optimistic wins when conflicts are rare; pessimistic when contention is high or retries are expensive.
- Avoid deadlock under pessimistic locking: acquire locks in a global order (for example by account ID) or use
tryLockwith a timeout. - CAS can suffer the ABA problem; use a versioned reference such as
AtomicStampedReference.
Check yourself 2 questions
When prefer optimistic locking?
Show answer
Low contention.
What does the optimistic loop use?
Show answer
Compare-and-swap, retrying on conflict.
Takeaway Pessimistic holds a lock for the whole read-modify-write; optimistic retries a compare-and-swap.
23Concurrency toolkit
Machine-coding rounds increasingly ask "make it thread-safe". Know the primitive, the hazard it prevents, and the classic exercises.
Primitives: Java and Python#
| Need | Java | Python |
|---|---|---|
| Mutual exclusion | synchronized, ReentrantLock (tryLock, fairness) | threading.Lock / RLock |
| Many readers, one writer | ReentrantReadWriteLock, StampedLock | Lock + Condition (no built-in RW lock) |
| Limit concurrent access | Semaphore | threading.Semaphore |
| Wait for a condition | Condition.await/signal, wait/notifyAll | threading.Condition, Event |
| Lock-free counter | AtomicInteger, LongAdder (CAS) | Lock (GIL doesn't make += atomic) |
| Visibility | volatile, happens-before | — |
| Concurrent map | ConcurrentHashMap.compute/merge | dict + Lock |
| Hand-off queue | BlockingQueue (Array/Linked), DelayQueue | queue.Queue, PriorityQueue |
| Wait for N tasks | CountDownLatch, CyclicBarrier, Phaser | Barrier, concurrent.futures.wait |
| Thread pool | ExecutorService, CompletableFuture, virtual threads (21+) | ThreadPoolExecutor, ProcessPoolExecutor, asyncio |
Check yourself 2 questions
Many readers, one writer in Java?
Show answer
ReentrantReadWriteLock or StampedLock.
Mutual exclusion in Python?
Show answer
threading.Lock or RLock.
Takeaway Locks, read-write locks, conditions, semaphores, atomics and concurrent collections in both languages.
Hazards and how to prevent them#
| Hazard | Looks like | Prevention |
|---|---|---|
| Race condition | check-then-act, read-modify-write | Atomic op (CAS, computeIfAbsent) or one lock around both steps |
| Deadlock | Two threads hold locks the other needs | Global lock ordering, tryLock with timeout, fewer locks |
| Livelock | Threads keep yielding to each other | Randomised back-off |
| Starvation | A thread never gets the lock | Fair locks, bounded priorities |
| Visibility bug | Thread never sees a flag change | volatile, locks, atomics |
| Lost update | Two writers overwrite each other | Optimistic version check or row lock |
| ABA | CAS succeeds on a recycled value | Versioned/stamped references |
| Priority inversion | Low-priority holder blocks high priority | Priority inheritance, short critical sections |
Check yourself 2 questions
How do you prevent deadlock?
Show answer
Acquire locks in a global order, or use tryLock with timeouts.
Fix a check-then-act race?
Show answer
An atomic operation or one lock around both steps.
Takeaway Races, deadlocks, livelocks, starvation and visibility bugs each have a prevention.
Classic concurrency exercises#
| Problem | Core idea |
|---|---|
| Producer–consumer / bounded blocking queue | Lock + two conditions (notFull, notEmpty); loop on the predicate |
| Readers–writers | RW lock; decide reader vs writer preference |
| Dining philosophers | Order the forks or limit diners with a semaphore of N−1 |
| Print in order / FooBar / ZeroEvenOdd | Semaphores or condition hand-off between threads |
| Building H₂O | Semaphores (2 H, 1 O) + barrier |
| Multithreaded web crawler | Concurrent visited set + work queue + pool; stop when queue empty and no task in flight |
| Thread-safe LRU cache | One lock, or segment the key space into shards |
| Delayed task scheduler | Priority queue + condition wait until the earliest deadline |
Check yourself 2 questions
Producer–consumer core idea?
Show answer
A lock with two conditions (notFull, notEmpty), looping on the predicate.
Why loop on the predicate, not if?
Show answer
Spurious wakeups.
Takeaway Producer–consumer, readers–writers, dining philosophers and ordered printing are the classics.
Bounded blocking queue (Python)#
import threading from collections import deque class BoundedBlockingQueue: def __init__(self, capacity): self.q, self.cap = deque(), capacity self.lock = threading.Lock() self.not_full = threading.Condition(self.lock) self.not_empty = threading.Condition(self.lock) def enqueue(self, x): with self.not_full: while len(self.q) == self.cap: # while, not if: spurious wake-ups self.not_full.wait() self.q.append(x) self.not_empty.notify() def dequeue(self): with self.not_empty: while not self.q: self.not_empty.wait() x = self.q.popleft() self.not_full.notify() return x
Check yourself 2 questions
When does put() wait?
Show answer
While the queue is full.
What does take() signal after removing?
Show answer
notFull, waking a producer.
Takeaway A deque, a lock and two conditions; producers wait when full, consumers when empty.
Producer–consumer with a bounded queue#
flowchart TD P1["Producer 1"] --> Q[["Bounded blocking queue<br/>capacity N"]] P2["Producer 2"] --> Q Q --> W1["Consumer 1"] Q --> W2["Consumer 2"] Q -.->|"full: producers block"| P1 W1 -.->|"empty: consumers wait"| Q
The bound gives back-pressure; a poison pill or shutdown flag stops consumers cleanly.
Check yourself 2 questions
What happens when the queue is full?
Show answer
Producers block.
Why bound the queue?
Show answer
Backpressure, to cap memory and slow producers.
Takeaway A bounded queue gives backpressure: producers block when full, consumers when empty.
24Machine-coding round: structure, APIs, errors, tests
Machine-coding rounds (90–120 minutes, runnable code) reward a clean package layout, a working demo and easy extension more than clever algorithms.
Time plan (90 min)#
| Min | Do |
|---|---|
| 0–10 | Clarify scope; write the 4–6 must-have commands |
| 10–20 | Models (enums, value objects, entities) and interfaces |
| 20–65 | Services for the happy path; in-memory repositories |
| 65–80 | Driver/demo with the sample input; validation and exceptions |
| 80–90 | Extension point demo, concurrency note, cleanup |
Check yourself 2 questions
What happens in minutes 0–10?
Show answer
Clarify scope and write the 4–6 must-have commands.
Where does most time go?
Show answer
Services for the happy path, about minutes 20–65.
Takeaway Clarify and list commands, models and interfaces, happy-path services, then edge cases, tests and demo.
Package layout#
app/ model/ # entities, value objects, enums repository/ # interfaces + in-memory impls service/ # use cases (facade per aggregate) strategy/ # pluggable rules (pricing, matching) exception/ # domain exceptions Main # driver: parses commands, prints output
- Keep I/O in the driver only; services return values.
- One public method per use case.
Check yourself 2 questions
Where do pluggable rules go?
Show answer
The strategy package.
Where do in-memory implementations live?
Show answer
Under repository.
Takeaway model, repository, service, strategy, exception and a main or demo package.
Evaluation rubric#
- Runs end-to-end on the sample input
- Separation of concerns; no god class
- Extensible: a new type means a new class
- Meaningful names, small methods, no dead code
- Edge cases and errors handled explicitly
- Thread-safety called out where state is shared
- Tests or a demo that proves behaviour
Check yourself 2 questions
What shows extensibility?
Show answer
A new type means a new class, not edits.
First thing on the rubric?
Show answer
It runs end to end on the sample input.
Takeaway Runs end to end, separated concerns, extensible, clean names, edge cases and tests.
API and method design#
- Methods are verbs in domain language:
reserve(),settle(). - Return domain objects or results, never raw maps.
- Validate inputs at the boundary; constructors enforce invariants.
- Prefer immutable inputs and outputs (records, frozen dataclasses).
- Idempotent where retries are possible: pass a request ID.
- Pagination and filtering for list methods.
Check yourself 2 questions
What should methods return?
Show answer
Domain objects or results, never raw maps.
Where should inputs be validated?
Show answer
At the boundary; constructors enforce invariants.
Takeaway Verb methods in domain language, domain return types, validation at boundaries, immutable values.
Errors and edge cases#
- Domain exceptions (
SeatUnavailable,InsufficientFunds) over generic ones. - Decide: exception,
Optional, or result type. Be consistent. - Check: empty input, duplicates, not found, capacity full, invalid transition, concurrent conflict, partial failure.
- Roll back or compensate on partial failure; never leave half-updated state.
Check yourself 2 questions
Domain exception examples?
Show answer
SeatUnavailable, InsufficientFunds.
Name three edge cases to check.
Show answer
Any three of: empty input, duplicates, not found, capacity limits, concurrent access.
Takeaway Domain exceptions, a consistent error style, and checks for empty, duplicate, missing and capacity cases.
Testing the design#
- DIP pays off here: inject fakes for clock, repository, payment gateway.
- Unit-test each strategy and each state transition.
- Table-driven tests for rules (fees, splits, discounts).
- Concurrency test: N threads booking one seat → exactly one succeeds.
- Say which tests you would write even if time runs out.
Check yourself 2 questions
How does DIP help testing?
Show answer
You can inject fakes for clock, repository and payment gateway.
What suits fee or split rules?
Show answer
Table-driven tests.
Takeaway Inject fakes, unit-test strategies and transitions, use table-driven tests, and test concurrency.
25Last-minute checklist
Last-minute revision#
- Always: requirements → estimate → API → diagram → 2–3 deep dives → trade-offs
- Say the numbers: 1M/day ≈ 12 QPS; RAM 100 ns, SSD 1 ms, cross-continent 150 ms
- Every write path: idempotency key; every read path: cache + CDN
- Celebrity / hot key: hybrid fan-out, local cache, key sharding
- Booking: HOLD with TTL → CONFIRM; DB unique constraint as safety net
- Counters at scale: Redis INCR / sharded counters, batch flush
- Payments: double-entry ledger, timeout ≠ failure
- LLD: code by minute 25; ≤2 patterns; state thread-safety
Check yourself 2 questions
1M requests a day is roughly how many QPS?
Show answer
About 12.
What should every write path have?
Show answer
An idempotency key.
Takeaway Requirements to trade-offs, key numbers, idempotency on writes, caching on reads, and a failure story.
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.
LLD last-minute checklist#
- Confirm use cases before drawing classes.
- State invariants and who owns each piece of state.
- Separate entities, immutable values, services, and gateways.
- Define method signatures before implementation details.
- Use composition; choose at most two useful patterns.
- Make state transitions and invalid transitions explicit.
- State thread-safety and transaction boundaries.
- Dry-run normal, duplicate, invalid, concurrent, and failure cases.
Check yourself 2 questions
What comes before drawing classes?
Show answer
Confirming use cases.
What should be stated for each piece of state?
Show answer
Its invariants and owner.
Takeaway Confirm use cases, state invariants and ownership, separate building blocks, define signatures, then code.