CSCheatsheets
Combined reference

System Design: HLD + LLD

The complete HLD and LLD sheets in one scrollable reference, with the shared design map and interview playbooks up front.

26sections
130cards
33diagrams
0%known

00Full system design map & decision flows

Translate product needs into interfaces, state, traffic paths, failure handling, and an operable design.

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 dec

Keep the first diagram small. Deep-dive into the design choice that dominates the workload or correctness risk.

Check yourself 2 questions
  1. What do you quantify before APIs?

    Show answer

    QPS, read/write mix, payload, retention and regions.

  2. 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 dec
Check yourself 2 questions
  1. Transactions, joins and constraints?

    Show answer

    A relational database.

  2. 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
  1. Why commit the outbox with the state change?

    Show answer

    So the event is published if and only if the state changed.

  2. 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#

RequirementDesign directionCheck
Atomic invariant across rowsDatabase transaction / unique constraintKeep the invariant in the authoritative store.
Read-after-write requiredLeader read, session consistency, or quorumState the consistency boundary and failover behavior.
Stale reads acceptableAsync replication, cache, eventual convergenceDefine freshness and reconciliation limits.
External multi-service workflowSaga with idempotent steps and compensationsModel timeout as unknown outcome; reconcile.
Regional outageFailover / cells / active-active where justifiedSet RTO, RPO, data residency, and conflict policy.
Network partitionChoose per operation whether to preserve invariants or accept availabilityCAP applies during partition; avoid one global answer for every API.
Check yourself 2 questions
  1. Atomic invariant across rows?

    Show answer

    A database transaction or unique constraint in the authoritative store.

  2. 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
  1. When should you add a pattern?

    Show answer

    Only for a real variation point.

  2. 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#

AreaTopics and patternsJump
Interview methodRequirements, estimates, APIs, diagrams, deep dives, LLD coding flowPlaybooks
Capacity and trade-offsLatency math, QPS/storage, CAP, store choice, cache, scaleNumbers · Trade-offs
HLD patternsFeeds, chat, booking, search, media, payments, queues, schedulersHLD problems
LLD patternsSOLID, object modeling, concurrency, common design patternsLLD problems
Distributed systemsReplication, consensus, messaging, transactions, APIs, edgeDistributed concepts
Security, operations, evolutionIdentity, privacy, observability, SLO, migration, recovery§0 atlas · Distributed concepts · Last-minute
Check yourself 2 questions
  1. What does the coverage map help with?

    Show answer

    Jumping to the detailed section for an area.

  2. 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
  1. For each important choice, what should you name?

    Show answer

    The alternative and why you rejected it.

  2. 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#

MinStep
0–5Functional reqs (3–5 core), non-functional (scale, latency, consistency, availability)
5–10Estimation: QPS, storage, bandwidth (only what drives design)
10–15Core entities + API (REST/WebSocket)
15–30High-level design: client → LB → services → stores/caches/queues
30–502–3 deep dives (the hard part of THIS problem)
50–60Bottlenecks, failure modes, trade-offs, wrap-up
Check yourself 2 questions
  1. How many deep dives?

    Show answer

    Two or three.

  2. 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#

MinStep
0–6Scope questions; list use cases
6–12Entities vs value objects vs services
12–18Public API (method signatures)
18–24Class model / relationships
24–44Write real code by minute 25: enums → value objects → entities → interfaces → service
44–50Concurrency: ConcurrentHashMap.computeIfAbsent, minimal synchronized, ReentrantLock, AtomicInteger
50–55Edge cases, validation, errors
55–60Extensions / Q&A
Check yourself 2 questions
  1. When should real code start?

    Show answer

    By about minute 25.

  2. 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
  1. What follows the high-level diagram?

    Show answer

    Deep dives.

  2. 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#

TimeFocus
0–5Core use cases, constraints, invariants
5–10Peak QPS, storage, bandwidth, retention
10–15APIs and entities
15–30Client → edge → services → stores
30–50Deep-dive 2–3 workload risks
50–60Failures, 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
  1. What happens in minutes 5–10?

    Show answer

    Peak QPS, storage, bandwidth and retention estimates.

  2. 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
  1. What comes right after requirements?

    Show answer

    Workload and capacity estimates.

  2. 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#

SignalStart withWatch for
Read-heavy / globalCDN, cache, replicas, precomputeFreshness, invalidation, hot keys
Write-heavy / replay neededPartitioned log, async consumersOrdering, backpressure, duplicates
Long-running jobsQueue + workers + status APIRetry safety, DLQ, progress
Real-time updatesWebSocket, SSE, or streaming logReconnects, fan-out, ownership
Media / searchObject store + CDN / search indexAccess control, freshness, recall
Check yourself 2 questions
  1. Read-heavy global workload: first levers?

    Show answer

    CDN, cache, read replicas, precomputation.

  2. 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#

AreaAskWhy 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
ScaleDAU, peak QPS, read:write ratio, data size today and in 3–5 yearsDecides single DB vs sharding, caching, async processing
Latencyp50 and p99 targets for the main read and write pathsDecides caching, precomputation, regional deployment
ConsistencyMust a user see their own write immediately? Can others see stale data, and for how long?Strong vs eventual consistency per operation
AvailabilityTarget SLO; single region or multi-region; what happens during an outage?Replication, failover, degradation strategy
DurabilityCan any data be lost? Retention period?Synchronous replication, backups, storage tiering
Security and complianceAuthentication, sensitive data (PII, payments), data residencyEncryption, isolation, regional storage, audit logs
Clients and accessWeb, mobile, third-party API? Offline support? Real-time updates?Protocols (REST, WebSocket, SSE), sync design
Cost and constraintsBudget, team size, existing systems that must be reusedManaged 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.

Interview tip: write the answers as a short list on the board, then refer back to them when you justify each decision.
Check yourself 2 questions
  1. Why ask what's out of scope?

    Show answer

    It prevents designing features nobody needs.

  2. 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#

OpTime
L1 cache0.5 ns
Branch mispredict5 ns
L2 cache7 ns
Mutex lock/unlock25 ns
Main memory100 ns
Compress 1 KB (Snappy)3 µs
Send 2 KB over 1 Gbps20 µs
Read 1 MB from memory250 µs
DC round trip500 µs
Read 1 MB SSD1 ms
HDD seek10 ms
Read 1 MB disk20 ms
CA → Netherlands → CA150 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
  1. Main memory reference?

    Show answer

    About 100 ns.

  2. 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#

ItemValue
HDD IOPS100–200
SATA SSD IOPS~90K
NVMe IOPS500K–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^40KB / MB / GB / TB
1 day~86,400 s ≈ 10^5 s
1M req/day≈ 12 QPS (peak ×2–3)
Snowflake ID41b ts + 10b machine + 12b seq = 4096 IDs/ms/node
Check yourself 2 questions
  1. Downtime per year at 99.99%?

    Show answer

    About 52.6 minutes.

  2. 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
  1. QPS formula?

    Show answer

    DAU × actions per day ÷ 86,400.

  2. 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#

ChoicePick A when…Pick B when…
CAP during a partitionReject 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 NoSQLjoins, transactions, ad-hoc querieshuge scale, simple access, flexible schema
Sync vs asyncuser waits for resultslow / fan-out / retryable work
Push vs pullfew followers, real-timecelebrities, inactive users
Horizontal vs verticalunbounded growth, HAsimple, early stage
Monolith vs microsmall team, earlyindependent scaling / teams
Stateful vs statelessWebSocket sessionsAPI tier (scale freely)
Normalise vs denormalisewrite-heavy, consistencyread-heavy, avoid joins
Latency vs throughputuser-facingbatch / analytics
Check yourself 2 questions
  1. When reject writes during a partition?

    Show answer

    When invariants need strong consistency, such as balances or unique reservations.

  2. 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 patternStore
Relational, transactionsPostgreSQL / MySQL
Key lookup, hot dataRedis / Memcached
Huge write volume, wide rowsCassandra / DynamoDB
Full-text searchElasticsearch (inverted index)
Blobs: images, video, filesS3 + CDN
Time series / metricsInfluxDB / Prometheus / TSDB
Graph relationshipsNeo4j / adjacency in KV
Event log / streamingKafka
GeospatialRedis GEO / geohash / H3 / S2
VectorsHNSW (pgvector, FAISS, Pinecone)
Check yourself 2 questions
  1. Huge write volume with wide rows?

    Show answer

    Cassandra or DynamoDB.

  2. 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#

StrategyNote
Cache-asideapp reads cache, on miss loads DB; most common
Write-throughwrite cache+DB together; consistent, slower writes
Write-backwrite cache, flush later; fast, risk of loss
Write-aroundwrite DB only; avoids polluting cache
EvictionLRU / LFU / TTL
Stampederequest coalescing, jittered TTL, origin shield
Hot keylocal micro-cache + key sharding (key#n)
Check yourself 2 questions
  1. Most common caching strategy?

    Show answer

    Cache-aside.

  2. 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#

UsersWhat breaks first → fix
1Ksingle server + DB is fine
10KDB load → read replicas, cache
100Ksingle app server → LB + stateless app tier, CDN
1MDB writes → sharding, async queues, search index
10M+multi-region, CDN everywhere, cell architecture, event-driven
Check yourself 2 questions
  1. What typically breaks first around 10K users?

    Show answer

    Database load: add read replicas and a cache.

  2. 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#

ConceptShows up in
Consistent hashingKV store, distributed cache, GitHub storage
Trieautocomplete, typeahead
Inverted indexsearch, tweets search
Geohash / H3ride sharing, maps, nearby
SnowflakeIDs, tweets, URL shortener
Token bucketrate limiter, API gateway
Min-heap / timer wheeljob scheduler
Fan-outtwitter, instagram, notifications, chat
Distributed lock / SETNXticketmaster, booking
Bloom filterweb crawler, dedup
Check yourself 2 questions
  1. Which concept powers autocomplete?

    Show answer

    A trie.

  2. 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
  1. What avoids dual-write inconsistency?

    Show answer

    The outbox pattern.

  2. 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#

ProblemWhat happensFix
Stampede (thundering herd)A hot key expires; thousands of requests hit the database at onceRequest coalescing or a per-key lock; refresh ahead of expiry; serve stale while revalidating
PenetrationRequests 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
AvalancheMany keys expire at the same moment, or the cache cluster restarts coldAdd random jitter to TTLs; warm the cache before traffic; replicate the cache
Hot keyOne key's traffic exceeds a single cache nodeLocal in-process cache; split the key into copies (key#1..n); CDN for public data
Big keyA huge value blocks the node and the networkSplit into pages or fields; compress; store the blob elsewhere and cache a pointer
Stale or inconsistent dataCache and DB disagree after concurrent writesDelete-on-write after the DB commit, short TTLs, versioned keys, CDC-driven invalidation
Cache pollutionOne-off scans evict genuinely hot dataAdmission policies (TinyLFU), don't cache bulk reads
Check yourself 2 questions
  1. Fix for a cache stampede?

    Show answer

    Request coalescing or a per-key lock, refresh-ahead, or serving stale.

  2. 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#

ComponentRoleKey choicesSay this
DNSName → IP; coarse geo routingGeoDNS, latency routing, low TTL for failoverTTL caching delays failover by minutes
CDNEdge cache for static, media, some API responsesPush vs pull; cache keys; signed URLs; origin shieldOffloads 80–95% of static bytes; invalidation is slow
Load balancerSpread traffic, health-check, terminate TLSL4 (TCP, fast) vs L7 (HTTP routing, headers); algorithm belowMake it redundant (active-passive pair or managed LB)
API gatewaySingle entry: auth, rate limit, routing, aggregationManaged vs Envoy/Kong; BFF per clientKeep business logic out of it
Stateless app tierBusiness logic; scale horizontallySession state in Redis/JWT, not memoryAutoscale on CPU or queue depth
CacheFast reads, hot dataRedis (structures, persistence) vs Memcached (simple, multithreaded)Redis ~100K+ ops/s per node; sub-ms
Relational DBTransactions, joins, constraintsPostgres/MySQL; replicas; partitioning; Spanner/CockroachDB for global SQLOne primary ≈ 5–20K writes/s depending on row size
Key-value / wide-columnMassive write throughput, simple accessDynamoDB, Cassandra, ScyllaDB; partition + clustering keyDesign the table per query; no joins
Document DBFlexible JSON per entityMongoDB, FirestoreEmbed what's read together; reference what grows unbounded
Search engineFull-text, facets, fuzzy matchElasticsearch/OpenSearch; fed by CDCNear-real-time (~1 s refresh), not the source of truth
Object storageBlobs: images, video, backups, data lakeS3/GCS; multipart upload; lifecycle tiers11 nines durability; upload direct via pre-signed URL
Message queueTask distribution, decouplingSQS, RabbitMQ; visibility timeout; DLQAt-least-once → consumers must be idempotent
Event logOrdered, replayable streamKafka, Pulsar, Kinesis; partitions, retentionOrdering only within a partition
Stream processorStateful real-time aggregationFlink, Kafka Streams, Spark Structured StreamingWindows, watermarks, checkpointing
Batch / warehouseAnalytics over historySpark; BigQuery, Snowflake, Redshift; lakehouse (Delta, Iceberg)Columnar formats (Parquet) for scans
CoordinationLeader election, config, locksZooKeeper, etcd, ConsulSmall, strongly consistent; don't store data there
Workflow engineDurable multi-step processesTemporal, Step Functions, Airflow (batch)Retries and timers survive crashes
Service discovery / meshFind instances; mTLS, retries, telemetryConsul, Kubernetes DNS; Istio/Linkerd sidecarsAdds latency hop; centralises policy
Check yourself 2 questions
  1. Why do low DNS TTLs matter?

    Show answer

    TTL caching delays failover by minutes.

  2. 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#

AlgorithmUse when
Round robin / weightedUniform, short requests
Least connections / least outstandingVariable request duration
Power of two choicesLarge fleets; near-optimal with little state
IP / consistent hashSession affinity, cache locality
Latency-aware (EWMA)Heterogeneous backends
Check yourself 2 questions
  1. Variable request durations: which algorithm?

    Show answer

    Least connections or least outstanding requests.

  2. 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#

StyleFit
OLTP vs OLAPRow store for transactions; column store for analytics
ETL vs ELTTransform before load vs load raw into warehouse then transform (dbt)
LambdaBatch (correct) + speed layer (fresh); two codebases
KappaOne streaming path; replay the log to recompute
CDCDebezium reads the DB log → Kafka → search, cache, warehouse
File formatsParquet/ORC columnar; Avro row-based with schema evolution
Check yourself 2 questions
  1. Row store or column store for analytics?

    Show answer

    Column store.

  2. 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#

L = λ × Win-flight requests = arrival rate × latency1,000 req/s × 0.2 s = 200 concurrent requests
  • 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. 1,000 req/s at 0.2 s latency: concurrency?

    Show answer

    200 concurrent requests.

  2. 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
  1. Where are auth and rate limiting usually enforced?

    Show answer

    At the API gateway.

  2. 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#

ComponentSitsMain jobs
Forward proxyIn front of clientsOutbound filtering, caching, anonymity for clients
Reverse proxyIn front of serversTLS termination, compression, caching, hiding backends (Nginx, Envoy)
Load balancerIn front of a server poolSpread traffic, health checks, connection draining (L4 or L7)
API gatewayEdge of the service estateAuth, rate limits, routing, request transformation, API keys, usage plans
Service meshBeside every service (sidecar)Service-to-service mTLS, retries, timeouts, traffic shifting, telemetry
In practice one product often plays several roles (Envoy can be reverse proxy, load balancer and mesh sidecar). Name the job, not the product.
Check yourself 2 questions
  1. What does a reverse proxy do?

    Show answer

    TLS termination, compression, caching and hiding servers.

  2. 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#

StructureGood atCostSeen in
B+ treePoint and range reads; in-place updatesRandom writes, page splitsPostgres, MySQL InnoDB
LSM tree (memtable → SSTables)High write throughput; sequential I/ORead and space amplification; compactionCassandra, RocksDB, LevelDB
Hash indexO(1) point lookupNo rangesRedis, Bitcask
Inverted indexFull-text searchIndex build and update lagElasticsearch, Lucene
Geo indexNearby queriesCell-size tuningGeohash, quadtree, S2, H3, R-tree
Vector indexApproximate nearest neighboursRecall vs memory vs latencyHNSW, IVF-PQ
Bitmap / columnarAnalytics filters and scansSlow single-row updatesDruid, ClickHouse, Parquet
Composite index: leftmost-prefix rule. Put equality columns first, range column last. Covering index avoids table lookups.
Check yourself 2 questions
  1. Which engine favours high write throughput?

    Show answer

    LSM trees.

  2. 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#

LevelPreventsStill allows
Read uncommitted—Dirty reads
Read committed (Postgres default)Dirty readsNon-repeatable reads, lost updates
Repeatable read / snapshot (MySQL default)Non-repeatable readsWrite skew (phantoms depend on engine)
Serializable (2PL or SSI)All of the aboveLower throughput, retries on conflict
  • Lost update fix: SELECT … FOR UPDATE, atomic UPDATE … 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
  1. Postgres default isolation?

    Show answer

    Read committed.

  2. 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#

ModeProsCons
Single leaderSimple; no write conflictsLeader is the write bottleneck; failover risk
Multi-leaderMulti-region writes; offline clientsConflict resolution (LWW, CRDT, app merge)
Leaderless (Dynamo)High availability; tunable quorumRead repair, hinted handoff, sloppy quorums
SynchronousNo data loss on failoverLatency; blocked by slow replica
AsynchronousFast writesReplication lag; possible loss on failover
Replication-lag fixes: read-your-writes (read own data from leader or wait for LSN), monotonic reads (pin user to one replica), consistent prefix (same partition order).
Check yourself 2 questions
  1. Main con of single-leader replication?

    Show answer

    The leader is the write bottleneck, with failover risk.

  2. 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)#

StrategyGood forWatch out
RangeRange scans, time seriesHot latest partition
HashEven spreadNo range queries; resharding moves data
Consistent hash + vnodesElastic clustersOnly ~K/N keys move on change
Directory / lookupFlexible placement, tenant movesLookup service is critical path
Geo / tenantData residency, isolationUneven 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
  1. Hot-spot risk of range sharding?

    Show answer

    The latest partition gets all new writes.

  2. 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#

QuestionIf 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
  1. Money and inventory invariants: which model?

    Show answer

    Relational, keeping the invariant in one database.

  2. 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
  1. On a write, update or delete the cache entry?

    Show answer

    Delete (invalidate) after updating the database.

  2. 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#

ProblemDeep divesKey takeaway
URL shortenerID generation; redirect latency; custom aliases100:1 read-heavy → cache in Redis; 302 not 301 for analytics
Pastebinlarge content; expiry; abusemetadata in DB, content in S3, serve via CDN
Rate limiteralgorithms; distributed; rule hot pathstoken bucket in Redis + Lua (atomic); fail open
Unique IDSnowflake; alternatives; clock sync41b ts + 10b machine + 12b seq; no coordination, time-sortable
KV storeconsistent hashing; vector clocks; failure detectioncommit log → MemTable → SSTable; quorum R/W
Leaderboardsorted-set internals; segments; percentileZADD + ZREVRANK, O(log N)
Autocompletetrie storage; trending; personalisationcache top-K for short prefixes in Redis; trie only for long tail
Bookingdouble-booking; availability search; refundsHOLD → CONFIRM; idempotency keys
Web crawlerpoliteness; dedup; recrawl priorityURL frontier (PQ) + Bloom filter + per-domain rate limits
E-commerceoverselling; catalog search; ordersflash sale: Redis atomic DECR, DB eventually consistent
Instagrampush vs pull feed; media upload; graphhybrid fan-out (pull for celebrities)
Twitter feedcelebrity fan-out; sharding; trendinganswer the hotspot problem proactively
Notificationat-least-once; preferences / quiet hours; tokenspreference check + dedup before fan-out
Typeaheadtrie vs ES; ranking; freshnessoffline top-K + CDN for common prefixes + Kafka trending
WhatsAppWS routing; ordering / exactly-once; E2E Signalregistry user_id → server_id in Redis
YouTubetranscoding; ABR; view countssplit upload path (async) from streaming (CDN + ABR)
Chat (Slack)large-channel fan-out; ordering; searchuser → gateway map is the core
Distributed cachering; replication; evictionvirtual nodes; hot keys → local cache + key sharding
Job schedulerduplicate execution; 10M jobs; retriesCAS claim on status + idempotent jobs
Message queuepartition log; consumer groups; exactly-oncepartitions + pull + ISR replication
Dropbox / DriveCDC chunking; conflicts; dedupSHA-256 content-addressed chunks → dedup + delta sync
GitHubgit storage; code search; mergesrepo routing via consistent hashing + replica sets
Google Mapsrouting; live traffic; ETAContraction Hierarchies: ms instead of seconds
Hotel bookingdouble booking; search; pricingHOLD 10-min TTL; UNIQUE(room_id,date) as safety net
Ticketmasterseat locking; flash sale; waitlistRedis SETNX + 10-min TTL; virtual waiting room
Ride sharinggeo index; matching; surgeH3/S2 cells in Redis; avoid haversine full scans
Paymentidempotency; ledger; PCIidempotency key + double-entry ledger; timeout ≠ failure
Stock exchangeorder book; price-time matching; recoverysingle-threaded matcher per symbol
Ad-click aggregatordedup; Flink aggregation; fraudlambda: Flink realtime + Spark batch for billing
MetricsTSDB compression; queries; alertscardinality control at ingestion
CDNanycast; cache tiers; invalidationanycast + origin shield
Searchinverted index; PageRank; rankinginverted index + BM25 is the core
LLM chatSSE streaming; context window; GPU routingSSE + KV-cache-aware routing
RAGchunking; HNSW; hybrid + rerankANN for recall, cross-encoder for precision, BM25 for exact terms
Gaming leaderboardZSET; friends board; tournamentsfriends: on-demand ZSCORE lookups
Check yourself 2 questions
  1. URL shortener key insight?

    Show answer

    100:1 read-heavy, so cache in Redis; use 302 not 301 to keep analytics.

  2. 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
  1. How does the server find the recipient's connection?

    Show answer

    Redis maps each user to their gateway.

  2. 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 dec
Check yourself 2 questions
  1. Why not fan out a celebrity's post on write?

    Show answer

    Millions of follower timeline writes per post.

  2. 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

writes ≈ 100M / 86,400 ≈ 1.2K/s (peak ~3K)reads ≈ 120K/s (peak ~350K)storage ≈ 500 B × 100M × 365 × 5 y ≈ 90 TBbase62, 7 chars → 62⁷ ≈ 3.5 trillion codes

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
  1. 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.

  2. 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

posts ≈ 300M × 2 / 86,400 ≈ 7K/sfeed reads ≈ 300M × 10 / 86,400 ≈ 35K/s (peak ~100K)fan-out at ~200 followers ≈ 1.4M cache writes/sfeed cache: 800 IDs × 8 B × 300M ≈ 2 TB

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
  1. What decides feed design?

    Show answer

    The celebrity problem.

  2. 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

messages ≈ 500M × 40 / 86,400 ≈ 230K/s (peak ~700K)storage ≈ 230K × 100 B × 86,400 ≈ 2 TB/dayconnections ~100M → ~1–2K gateways at 50–100K each

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
  1. How is ordering guaranteed?

    Show answer

    Per conversation, for example by partitioning on chat ID with sequence numbers.

  2. 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

normal: ~1K bookings/sflash sale: 1M waiting, admit ~2–5K users/sseat map reads ≫ writes → cache, short TTL

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
  1. How do you prevent double-selling a seat?

    Show answer

    Atomic holds with TTL (conditional update or lock), then confirm on payment.

  2. 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

location updates ≈ 5M / 4 s ≈ 1.25M writes/sride requests ≈ 1–5K/slatest location only: 5M × ~50 B ≈ 250 MB in memory

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
  1. How often do drivers send location?

    Show answer

    About every 4 seconds.

  2. 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

CREATED → AUTHORIZED → CAPTURED → SETTLED ↘ FAILED ↘ REFUNDEDtimeout from PSP = UNKNOWN → query PSP, never assume failure

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
  1. How do you prevent double charges on retries?

    Show answer

    Idempotency keys.

  2. 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

1 hour at ~5 Mbps ≈ 2.25 GB per renditionbitrate ladder of ~6 renditions ≈ 2–3× raw storageegress dominates cost → CDN hit ratio is the key metric

Pipeline

  1. Client uploads in chunks directly to object storage (resumable).
  2. An event enqueues a transcode job; split the video into chunks to transcode in parallel.
  3. Produce several resolutions and bitrates, segment into 2–6 s pieces, write HLS/DASH manifests.
  4. 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
  1. How are large uploads handled?

    Show answer

    Pre-signed multipart uploads to object storage.

  2. 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
  1. How do you avoid duplicate notifications?

    Show answer

    Idempotency or dedup keys per event and user.

  2. 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#

ConceptOne-liner
Consistent hashingring + virtual nodes; move only K/N keys
Replicationleader-follower, multi-leader, leaderless (quorum)
QuorumOverlapping read/write quorums can support strong reads only with compatible replica/version guarantees; otherwise plan for stale reads and repair. Cassandra quorum notes
Sharding keyshash (even) vs range (scans); avoid hot shards (salt)
ConsensusRaft: leader, log replication, majority commit
Vector clocksdetect concurrent writes; app resolves
Exactly-once effectsUsually require at-least-once delivery plus deduplication/idempotency and atomic state/offset updates; guarantees stop at system boundaries.
Outboxwrite event in same DB txn; relay to Kafka
Sagalocal txns + compensations (orchestrated / choreographed)
2PCblocking coordinator; avoid across services
Check yourself 2 questions
  1. Quorum condition for reading the latest write?

    Show answer

    R + W > N.

  2. 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
  1. How do you keep a user's events in order in Kafka?

    Show answer

    Use the user ID as the partition key.

  2. 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
  1. Server-to-client token streaming?

    Show answer

    SSE.

  2. 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
  1. How many consumers in a group can read one partition?

    Show answer

    One.

  2. 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#

ModelGuaranteeExample
LinearizableEvery read sees the latest write; real-time orderetcd, Spanner, single-leader sync reads
SequentialOne global order consistent with each client's orderZooKeeper writes
CausalCause precedes effect everywhereComment shows after the post it replies to
Read-your-writesYou see your own updatesProfile edit visible immediately
Monotonic readsNever go back in timePin session to a replica
EventualReplicas converge if writes stopDNS, likes counters, Dynamo defaults
Check yourself 2 questions
  1. Strongest consistency model?

    Show answer

    Linearizable.

  2. 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.
SystemPACELC
DynamoDB, Cassandra (default)PA / EL
Spanner, CockroachDB, etcdPC / EC
MongoDB (majority)PC / EC (tunable)
Quorum: N replicas, write W, read R. R + W > N gives overlapping sets (N=3, W=2, R=2). Choose per operation.
Check yourself 2 questions
  1. What does PACELC add to CAP?

    Show answer

    Even without partitions, there's a latency versus consistency trade-off.

  2. 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
  1. How many nodes tolerate 2 failures?

    Show answer

    5.

  2. 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#

ToolUse
Physical clocks (NTP)Drift ms–100s of ms; don't order events across machines with them
Lamport clockTotal order consistent with causality (counter max+1)
Vector clockDetect concurrent writes (siblings) in leaderless stores
Hybrid logical clockPhysical time + logical counter (CockroachDB)
TrueTimeBounded uncertainty; Spanner waits it out for external consistency
Heartbeats + timeoutsSimple failure detection; tune to avoid flapping
GossipMembership and state spread in O(log N) rounds
Phi-accrual detectorSuspicion level instead of binary up/down (Cassandra)
Check yourself 2 questions
  1. What can vector clocks detect that Lamport clocks can't?

    Show answer

    Concurrent (causally unrelated) events.

  2. 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#

ApproachHowUse whenDownside
Single-DB transactionKeep related data on one shard/DBAlways try firstConstrains data model
Two-phase commitCoordinator: prepare → commitInside one database system (Spanner, XA)Blocking if coordinator dies; latency
Saga (orchestrated)Central workflow runs steps + compensationsMulti-service business flows (order → payment → shipping)No isolation; design compensations
Saga (choreographed)Services react to each other's eventsFew steps, loosely coupled teamsHard to trace the overall flow
Transactional outboxWrite row + event in one local txn; relay publishesDB update must emit an event reliablyRelay adds delay; consumers dedupe
TCC (try-confirm-cancel)Reserve resources, then confirm or cancelInventory, bookings, payments holdsEvery service implements three APIs
Check yourself 2 questions
  1. What should you try first?

    Show answer

    Keep related data on one database or shard.

  2. 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
  1. Downside of last-write-wins?

    Show answer

    Silently drops concurrent updates.

  2. 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
  1. Inventory reservation fails after payment. What happens?

    Show answer

    The orchestrator refunds the payment (compensation).

  2. 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
  1. When does the leader reply to the client?

    Show answer

    After a majority acknowledges and the entry is committed.

  2. 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#

OptionHowCaveat
Database lockSELECT … FOR UPDATE, advisory locks, or a unique row as the lockSimple and correct if you already depend on that database
Redis single nodeSET key token NX PX 30000; release with a Lua script that checks the tokenLost on failover before replication; fine for efficiency, not for correctness
Redlock (several Redis nodes)Acquire on a majority of independent nodes within a time limitRelies on timing assumptions; disputed for correctness-critical use
ZooKeeper / etcdEphemeral (lease-backed) nodes; the lowest sequence number holds the lockConsensus-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
  1. What prevents a paused lock-holder corrupting data?

    Show answer

    Fencing tokens checked by the resource.

  2. 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#

AlgorithmHowProsCons
Fixed windowCounter per time bucketTiny, simple2× burst at window edges
Sliding logStore each timestampExactMemory per request
Sliding window counterWeighted current + previous windowAccurate, cheapApproximation
Token bucketRefill at rate r, capacity bAllows bursts; most commonTwo parameters to tune
Leaky bucketQueue drains at fixed rateSmooth outputAdds queueing delay
Distributed: Redis + Lua script for atomic check-and-decrement; return 429 with Retry-After; decide fail-open vs fail-closed.
Check yourself 2 questions
  1. Flaw of fixed windows?

    Show answer

    Up to 2× bursts at window edges.

  2. 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#

PatternPurpose
TimeoutsNever wait forever; budget across the call chain
Retries + exponential backoff + jitterRecover from transient errors without thundering herds; cap attempts
Circuit breakerClosed → open on failures → half-open probe; fail fast
BulkheadSeparate pools per dependency so one can't exhaust all threads
Load sheddingDrop low-priority work when saturated
Back-pressureBounded queues; slow producers instead of crashing
Graceful degradationServe cached or partial results (hide recommendations, keep checkout)
Hedged requestsSend a duplicate after p95 to cut tail latency
Idempotency keysMake retries safe for writes
Check yourself 2 questions
  1. What do bulkheads do?

    Show answer

    Isolate resources so one failure can't drain everything.

  2. 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#

PatternWhen
Database per serviceIndependent deploys; share data via APIs/events
API gateway / BFFOne entry per client type
Service mesh / sidecarmTLS, retries, telemetry without app code
CQRSSeparate write model from read-optimised views
Event sourcingAudit trail, temporal queries; state = fold over events
Strangler figIncrementally replace a monolith behind a router
Anti-corruption layerTranslate a legacy model at the boundary
Cell-based architectureIndependent copies of the stack per user shard; limits blast radius
Check yourself 2 questions
  1. Why database per service?

    Show answer

    Independent deploys; share data via APIs and events.

  2. 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#

StrategyTrade-off
RollingNo extra capacity; mixed versions during rollout
Blue-greenInstant switch and rollback; double capacity
CanarySmall % first, compare metrics, then ramp
Feature flagsDecouple deploy from release; kill switch
Shadow / dark launchMirror real traffic to the new path; no user impact
Expand–contract migrationAdd new column → dual write → backfill → switch reads → drop old
Check yourself 2 questions
  1. Blue-green trade-off?

    Show answer

    Instant switch and rollback, at double capacity.

  2. 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#

SetupRTO / RPOCostNotes
Backup and restoreHours / hoursLowTest restores regularly
Pilot lightTens of minutes / minutesLow–mediumData replicated, compute scaled to zero
Warm standbyMinutes / secondsMediumScaled-down copy running
Active-passiveMinutes / near zero (sync) or seconds (async)HighFailover via DNS or global LB
Active-active~0 / ~0 for local writesHighestWrite conflicts; home-region per user; data residency
Definitions: RTO = how long until service is back. RPO = how much data you can lose. State both before picking a setup.
Check yourself 2 questions
  1. Which setup has the lowest RTO and RPO?

    Show answer

    Active-active multi-region.

  2. 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
  1. When does the breaker open?

    Show answer

    When the failure rate exceeds a threshold.

  2. 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#

StructureAnswersError / sizeUsed in
Bloom filter"Definitely not" or "maybe" in set~10 bits/item → ~1% false positives; no deletesCrawler seen-URLs, LSM read path, username check
Counting / cuckoo filterMembership with deletesSlightly more space than BloomCache admission, dedup with expiry
HyperLogLogCount distinct~12 KB for ~0.81% error at any cardinalityUnique visitors, distinct searches
Count-min sketchApproximate frequencyOverestimates only; width × depth countersHeavy hitters, trending topics, top-K
t-digest / KLLApproximate percentilesAccurate at tailsp99 latency over streams
Skip listSorted set with O(log n) opsProbabilistic balancingRedis sorted sets (leaderboards)
Merkle treeWhich ranges differ between replicasO(log n) comparisonAnti-entropy (Cassandra), Git, blockchains
Consistent hash ringWhich node owns a keyMoves ~K/N keys on resizeCaches, KV stores, load balancers
Geohash / quadtree / S2 / H3What is near this pointCell size vs precisionRide matching, nearby search, maps
TriePrefix lookupStore top-K per node for speedTypeahead, routing tables
Inverted indexWhich documents contain the termPosting lists, compressedSearch engines
Timing wheelMillions of timers in O(1)Bucketed by tickSchedulers, TTL expiry, Kafka delays
Ring bufferFixed-size FIFO, lock-free optionsOverwrites oldestLogging, metrics, LMAX disruptor
Reservoir samplingUniform sample of a streamO(k) memoryLog sampling, analytics
Check yourself 2 questions
  1. Bloom filter answers?

    Show answer

    'Definitely not' or 'maybe' in the set.

  2. 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#

ProtocolPatternUse for
REST over HTTP/1.1–2Request/response, resourcesPublic CRUD APIs; cache-friendly
gRPC (HTTP/2, protobuf)Typed RPC, streamingInternal low-latency service calls
GraphQLClient-shaped queriesMany clients with different needs; watch N+1 and caching
WebSocketFull-duplex, persistentChat, multiplayer, collaborative editing
Server-Sent EventsServer → client stream over HTTPLLM token streaming, live feeds, notifications
Long pollingHeld requestFallback when sockets are blocked
WebhooksServer → server callbackPayment status, integrations; sign and retry
HTTP/3 (QUIC)UDP, no head-of-line blockingMobile and lossy networks
MQTTLightweight pub-subIoT devices
Check yourself 2 questions
  1. Internal low-latency typed RPC?

    Show answer

    gRPC.

  2. 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-Key header.
  • 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
  1. How do you make POST safe to retry?

    Show answer

    An Idempotency-Key header.

  2. 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#

MechanismNote
Session cookieServer-side state; easy revocation; CSRF protection needed
JWTStateless, signed; short expiry + refresh token; hard to revoke
OAuth 2.0Delegated authorisation; auth-code + PKCE for apps
OpenID ConnectIdentity layer on OAuth (ID token)
mTLSService-to-service identity
API keysServer-to-server; rotate, scope, hash at rest
RBAC / ABAC / ReBACRoles / attributes / relationships (Zanzibar)
Check yourself 2 questions
  1. Main drawback of JWTs?

    Show answer

    Hard to revoke; use short expiry plus refresh tokens.

  2. 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
  1. Defence against SQL injection?

    Show answer

    Parameterised queries.

  2. 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#

ConceptMeaning
Golden signalsLatency, traffic, errors, saturation
RED (services)Rate, errors, duration
USE (resources)Utilisation, saturation, errors
Logs · metrics · tracesStructured logs with request ID; metrics for alerting; distributed tracing (OpenTelemetry) for latency breakdown
SLI / SLO / SLAMeasured indicator / internal target / contractual promise
Error budget1 − SLO; spend it on releases, freeze when exhausted
AlertingPage on user-facing symptoms (burn rate), not on every cause
Check yourself 2 questions
  1. The four golden signals?

    Show answer

    Latency, traffic, errors, saturation.

  2. 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
  1. What does PKCE protect against?

    Show answer

    Interception of the authorization code.

  2. 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#

ModelIsolationCost and effortFits
Pool (shared everything)tenant_id on every row, row-level security, per-tenant quotasCheapest, simplest to operateMany small tenants
Bridge (shared app, separate schemas or databases)Data separated per tenant; compute sharedModerate; migrations run per schemaMid-size tenants, compliance needs
Silo (dedicated stack or cell)Full isolation per tenantMost expensiveLarge 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
  1. Cheapest multi-tenancy model?

    Show answer

    Pool: shared everything with tenant_id and row-level security.

  2. 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 askStrong 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 downHealth 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 downtimeExpand–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 disagreeCache-aside with delete-on-write, short TTL, versioned keys, or CDC-driven invalidation.
Queue consumers fall behindScale consumers up to partition count; increase partitions; batch; DLQ poison messages; back-pressure producers.
Latency p99 is bad, p50 fineFind fan-out and GC pauses; hedged requests; timeouts per hop; cache warmers; reduce payload size.
Schema change across many servicesBackward-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
  1. Traffic grows 10×: how do you answer?

    Show answer

    Walk the path: DB writes, cache hit ratio, hot keys, connection pools; autoscale stateless tiers.

  2. 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#

TimeFocus
0–6Use cases, constraints, edge cases
6–12Entities, value objects, invariants
12–18Public method signatures and ownership
18–24Relationships and state transitions
24–44Implement core path; extend only as needed
44–50Concurrency and atomicity
50–60Errors, 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
  1. What comes right after use cases?

    Show answer

    Entities, value objects and invariants.

  2. 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
  1. Where should invariant-preserving operations live?

    Show answer

    Near the state they protect, on the entity.

  2. 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 blockOwnsDesign cue
EntityIdentity and lifecycle stateKeep invariant-preserving operations near state.
Value objectImmutable values such as Money or AddressValidate once; compare by value.
ServiceUse-case orchestrationCoordinate collaborators; avoid god classes.
Repository / gatewayPersistence or external boundaryDepend on an interface for testability.
Strategy / stateReplaceable rule or legal transitionsUse when the variation is visible.
Check yourself 2 questions
  1. Give an example of a value object.

    Show answer

    Money or Address.

  2. 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#

PillarWhat it meansInterview cue
EncapsulationState is private; change it only through methods that keep invariantsNo public setters on balance; expose deposit() / withdraw()
AbstractionCallers depend on what an object does, not howPaymentGateway interface hides Stripe/Razorpay details
Inheritance"is-a" reuse of type and behaviourUse for true subtypes only; prefer composition for reuse
PolymorphismOne call, many implementations (runtime dispatch / overloading)Replace if type == … chains with subclasses or strategies
Check yourself 2 questions
  1. Encapsulation interview cue?

    Show answer

    No public setter on balance; expose deposit() and withdraw().

  2. 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#

RelationNotationLifetimeCode shape
Dependencydashed arrowtemporary useparameter or local variable
Associationsolid lineindependentfield holding a reference
Aggregationhollow diamondpart outlives wholeTeam has Players passed in
Compositionfilled diamondpart dies with wholeOrder creates its OrderLines
Inheritancehollow triangle, solid—class Car extends Vehicle
Realizationhollow triangle, dashed—class Card implements Payment
Multiplicity: write 1, 0..1, 1..*, * on both ends. It drives collection types and null checks.
Check yourself 2 questions
  1. Composition versus aggregation?

    Show answer

    In composition the part's lifetime is owned by the whole; in aggregation it's independent.

  2. 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#

PrincipleRuleSmell you'll seeFixLLD example
S · Single responsibilityOne reason to changeInvoice computes, prints and saves itselfSplit into calculator, printer, repositoryParkingLot doesn't compute fees; FeeCalculator does
O · Open/closedExtend without editingGrowing switch(paymentType)Interface + new class per variantAdd UpiPayment without touching checkout
L · Liskov substitutionSubtypes honour the parent's contractSquare extends Rectangle breaks setWidth; Penguin.fly() throwsRe-model the hierarchy; split capabilitiesFlyable as a separate interface
I · Interface segregationSmall, client-specific interfacesClasses implementing methods with throw UnsupportedOperationSplit fat interface into rolesPrinter, Scanner, Fax instead of Machine
D · Dependency inversionDepend on abstractions; inject themnew MySqlRepo() inside a serviceConstructor injection of an interfaceSwap in-memory repo for tests
Check yourself 2 questions
  1. SRP smell?

    Show answer

    One class that computes, prints and saves (several reasons to change).

  2. 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
  1. Tell, don't ask example?

    Show answer

    account.withdraw(x) rather than reading the balance and deciding outside.

  2. 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?#

PrincipleAssign the responsibility to…
Information expertthe class that has the data needed
Creatorthe class that contains or aggregates the created object
Controllera use-case/facade object, not the UI
Polymorphismthe types that vary, not a conditional
Pure fabricationa made-up service class when no domain object fits (repository, notifier)
Indirectionan intermediary that decouples two classes
Protected variationsan interface wrapped around whatever is likely to change
Check yourself 2 questions
  1. Information expert rule?

    Show answer

    Give the responsibility to the class with the needed data.

  2. 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#

TopicJavaPythonInterview cue
Interface vs abstract classInterface: a contract, multiple inheritance, default methods. Abstract class: shared state and code, single inheritanceabc.ABC with @abstractmethod; typing.Protocol for structural typingInterface for a capability or strategy; abstract class when subclasses share real state
Immutabilityfinal fields, no setters, defensive copies; record for value objects@dataclass(frozen=True), tuplesValue objects (Money, Address) and anything shared across threads
Equality and hashingOverride equals and hashCode together; equal objects must have equal hashes__eq__ and __hash__; frozen dataclasses generate bothMutating a field used in the hash after inserting into a HashMap/set loses the entry
EnumsEnums can hold fields and per-constant behaviourenum.Enum; add methods on the classModel statuses and types as enums, not strings
GenericsBounded types; PECS rule: producer extends, consumer superTypeVar, Generic[T] (hints only)Repository<T, ID>, Cache<K, V>
ExceptionsChecked (recoverable, declared) vs unchecked (programming errors); custom domain exceptionsAll unchecked; subclass Exception per domain errorSeatUnavailableException beats returning null or -1
Visibility and encapsulationprivate by default; package-private for testsLeading underscore by convention; @property for computed or read-only attributesNo public mutable fields on entities
Composition helpersConstructor injection; Optional for absent valuesPass collaborators to __init__; None checks or Optional[T]Makes swapping and testing collaborators trivial
Check yourself 2 questions
  1. Interface versus abstract class in Java?

    Show answer

    Interfaces are contracts with multiple inheritance; abstract classes share state and code with single inheritance.

  2. 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)#

PatternIntentUse when
SingletonOne shared instanceConfig, registry, ID generator; make it thread-safe and injectable
Factory MethodSubclass decides which product to createCreate Vehicle by type; hide new
Abstract FactoryFamilies of related productsUI themes, DB driver families (connection + command)
BuilderStep-by-step constructionMany optional params; immutable result (Pizza, HTTP request)
PrototypeClone an existing objectExpensive setup; templates (documents, game units)
Check yourself 2 questions
  1. When use Builder?

    Show answer

    For objects with many optional parameters.

  2. 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)#

PatternIntentUse when
AdapterConvert one interface to anotherWrap a third-party payment SDK
BridgeSplit abstraction from implementationShape × renderer, Remote × device
CompositeTree of parts treated uniformlyFile system, nested comments, menu
DecoratorAdd behaviour by wrappingPizza toppings, stream compression, logging
FacadeSimple front for a subsystemBookingService over seats, payments, notifications
FlyweightShare intrinsic stateChess piece types, text glyphs, map tiles
ProxyStand-in that controls accessLazy loading, caching, auth, remote stub
Check yourself 2 questions
  1. Wrap a third-party payment SDK?

    Show answer

    Adapter.

  2. Tree of items treated uniformly?

    Show answer

    Composite.

Takeaway Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy shape how objects compose.

Behavioral (11)#

PatternIntentUse when
StrategySwap algorithmsPricing, matching, split types, eviction
StateBehaviour changes with stateVending machine, ATM, order lifecycle
ObserverNotify subscribers of changeStock alerts, order status, UI events
CommandRequest as an objectUndo/redo, job queues, macro recording
Chain of ResponsibilityPass along handlersLog levels, approval flows, middleware, ATM notes
Template MethodFixed skeleton, overridable stepsGame turn, report generation, data import
IteratorTraverse without exposing internalsCustom collections, paginated results
MediatorCentral hub for interactionsChat room, air-traffic control, UI dialogs
MementoSnapshot and restore stateEditor undo, game save points
VisitorNew operations over a fixed structureAST evaluation, tax/export over shapes
InterpreterGrammar evaluationRule engines, simple expression parsers
Check yourself 2 questions
  1. Vending machine behaviour changes with state?

    Show answer

    State pattern.

  2. Swap pricing algorithms?

    Show answer

    Strategy.

Takeaway Strategy, State, Observer, Command, Chain of Responsibility, Template Method and others organise behaviour.

Modern and enterprise patterns#

PatternUse when
Dependency injectionAlways: pass collaborators in; enables tests and swaps
RepositoryHide storage behind a collection-like interface
Unit of WorkCommit several changes atomically
SpecificationComposable business rules (eligibility, filters)
Null ObjectAvoid null checks (NoDiscount)
Object PoolReuse expensive objects (connections, threads)
Producer–ConsumerDecouple work creation from execution
Event bus / Pub-SubMany-to-many async notifications
Circuit breakerStop calling a failing dependency
Rule engineCoupons, fraud rules, pricing stored as data
Check yourself 2 questions
  1. When use dependency injection?

    Show answer

    Always: pass collaborators in for testability and swaps.

  2. 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#

PairDifference
Strategy vs StateClient picks the strategy; a state object switches itself to the next state
Decorator vs ProxyDecorator adds behaviour and stacks; proxy controls access to the same interface
Adapter vs FacadeAdapter converts one interface; facade simplifies many
Factory Method vs Abstract FactoryOne product via inheritance vs a family via composition
Builder vs FactoryBuilder assembles step by step; factory picks a type in one call
Observer vs Pub-SubObserver: subject knows observers. Pub-sub: broker in between, often async
Template vs StrategyInheritance fills steps vs composition swaps the whole algorithm
Composite vs DecoratorBoth wrap the same interface; composite has many children, decorator one
Mediator vs ObserverMediator coordinates two-way logic; observer only broadcasts
Bridge vs AdapterBridge is designed up front so abstraction and implementation vary independently; adapter retrofits a mismatch
Command vs StrategyCommand is a request object you can queue, log or undo; strategy is an interchangeable algorithm
Flyweight vs SingletonFlyweight shares many immutable instances by key; singleton has exactly one instance
Chain of Responsibility vs DecoratorA chain link may stop the request; a decorator always delegates and adds behaviour
Check yourself 2 questions
  1. Strategy versus State?

    Show answer

    The client picks a strategy; a state object switches itself to the next state.

  2. 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
  1. 'Support multiple types, add more later'?

    Show answer

    Strategy + Factory.

  2. '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#

What varies in the requirements?
1An algorithm or rule?
yes
Strategy
no
2Behaviour depends on state?
yes
State
no
3Others react to changes?
yes
Observer
no
4Create objects by type?
yes
Factory
no
5Add features by wrapping?
yes
Decorator
no
6Undo or queue requests?
yes
Command
no
Plain classes, no pattern
Check yourself 2 questions
  1. Behaviour depends on state?

    Show answer

    State.

  2. 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
  1. What moves HasMoney to Dispensing?

    Show answer

    A selection with stock and enough funds.

  2. 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#

SmellLooks likeRefactoring
God classOne class with dozens of methods and fields across concernsExtract class by responsibility; introduce a facade that delegates
Long methodA method that needs comments to explain its sectionsExtract method per step; name the steps
Switch on typeif type == CAR … elif type == BIKE … repeated in several placesReplace conditional with polymorphism (Strategy or subclasses)
Primitive obsessionMoney as double, IDs as raw strings, status as intIntroduce value objects and enums
Feature envyA method mostly reads another object's dataMove the method to the class that owns the data
Data clumps / long parameter listsThe same 4–5 arguments passed together everywhereIntroduce a parameter object or builder
Shotgun surgeryOne change requires edits in many classesMove related behaviour together; one place per decision
Anemic domain modelEntities are bags of getters/setters; all logic in servicesMove invariant-protecting behaviour into the entity
Hidden dependenciesnew or singletons called deep inside methodsConstructor injection behind interfaces
Speculative generalityAbstract layers and patterns with a single implementationInline them until a second variation appears (YAGNI)
Check yourself 2 questions
  1. Fix for a god class?

    Show answer

    Extract classes by responsibility, with a facade delegating.

  2. 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
  1. What does the factory return?

    Show answer

    The right PricingStrategy implementation for the context.

  2. 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
  1. What do default methods do in the State interface?

    Show answer

    Throw IllegalStateException for invalid actions.

  2. 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
  1. Why CopyOnWriteArrayList for subscribers?

    Show answer

    Safe iteration while subscribers are added or removed.

  2. 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
  1. Why is the holder idiom thread-safe?

    Show answer

    Class loading initialises the holder once, safely.

  2. 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#

ProblemPatternsGotcha / key insight
Parking lotStrategy (spot allocation), Factory, SingletonParkingLot → ParkingFloor → ParkingSpot; delegate, don't god-class
Rate limiterStrategytoken bucket w/ lazy refill; ConcurrentHashMap per user
Tic-tac-toe—O(1) win check with row/col/diag counters
Vending machineStateno if-else state; polymorphic states
SplitwiseStrategy (split types)+ minimise cash flow greedy on net balances
BookMyShowStrategy, ObserverSeat vs ShowSeat; lock ShowSeat with TTL
ChessTemplate, Factorypieces validate geometry; Board validates path/check
Snake & ladder—single Jumper(start→end) class
ElevatorStrategy, StateSCAN/LOOK sweep with sorted sets, not FIFO
Comment systemCompositematerialised path for O(1) thread fetch
Hotel managementStrategy (pricing)date-range overlap in availability
ATMState, Chain (cash dispenser)external BankService does atomic debit
LRU cache—HashMap + DLL with dummy head/tail; know the wiring cold
Food deliveryStrategy (dispatch), Observer (status)focus on core models
LockerStrategysize ordering: S fits S/M/L/XL, L fits L/XL
NotificationStrategy, Observer, Factoryadd WhatsAppStrategy without touching core
Coupon systemStrategy / Rule enginecoupons as DB rows → strategy, never hardcode
LoggerChain of Responsibility, Strategy, Producer-ConsumerBlockingQueue for async
Library—Book vs BookItem (copies)
Order managementSaga / CommandOrderOrchestrator with compensating steps
Ride sharingStrategy (match, price), State (ride)black-box LocationService
Pub-subObserverBlockingQueue per topic + worker
Inventory—available vs reserved vs purchased quantity
Check yourself 2 questions
  1. Parking lot gotcha?

    Show answer

    Delegate through Lot → Floor → Spot; don't build a god class.

  2. 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 phrasePattern
multiple algorithms / pricing / payment typesStrategy
create objects by typeFactory
notify on change / subscribeObserver
single shared instance (config, registry)Singleton (thread-safe)
many optional paramsBuilder
add behaviour dynamically (toppings, filters)Decorator
behaviour depends on state (vending, ATM, order)State
undo / queue requestsCommand
pass through handlers (log levels, approvals)Chain of Responsibility
tree of parts (folders, comments)Composite
Check yourself 2 questions
  1. Why use at most two patterns?

    Show answer

    Over-patterning adds complexity without value.

  2. 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
  1. ISP in one line?

    Show answer

    Small, focused interfaces.

  2. 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 --> Ticket
Check yourself 2 questions
  1. Who finds a free spot?

    Show answer

    ParkingFloor.findSpot(type).

  2. 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#

ProblemCore entitiesKey methodsPatternsWhat they probe
Parking lotParkingLot, Floor, Spot(type), Vehicle, Ticket, FeeCalculator, Gatepark(vehicle) → Ticket, unpark(ticket) → ReceiptStrategy (allocation, fees), Factory, SingletonConcurrent spot allocation; per-type free lists
ElevatorElevatorSystem, Elevator, Request, Direction, Dispatcher, Doorrequest(floor, dir), step()Strategy (dispatch), State (moving/idle/maintenance)SCAN/LOOK scheduling, choosing the nearest same-direction car
BookMyShow / movie bookingMovie, Theatre, Screen, Show, Seat, ShowSeat, Booking, PaymentholdSeats(show, seats), confirm(bookingId)Strategy (pricing), ObserverSeat hold with TTL; no double booking
SplitwiseUser, Group, Expense, Split (Equal/Exact/Percent), BalanceSheetaddExpense(), balances(user), settle()Strategy, FactoryValidate splits sum; simplify debts with heaps on net balance
Vending machineMachine, State, Inventory, Product, CoininsertCoin(), select(), dispense(), refund()StateIllegal transitions; change-making
ATMATM, Card, Account, Transaction, CashDispenser, BankServiceauthenticate(), withdraw(amount)State, Chain (note denominations)Atomic debit + dispense; reversal on failure
Library managementBook, BookItem(copy), Member, Loan, Reservation, Finecheckout(), return(), reserve()Observer (availability), Strategy (fines)Book vs BookItem; limits per member
ChessGame, Board, Cell, Piece(subtypes), Move, PlayermakeMove(from, to), isCheckmate()Template, Factory, Command (undo)Piece validates shape; board validates path and check
Tic-tac-toe (n×n)Game, Board, Player, Movemove(r, c) → result—O(1) win check using row/col/diagonal counters
Snake & ladderGame, Board, Jumper(start→end), Player, DiceplayTurn()Strategy (dice)One Jumper class covers snakes and ladders
LRU / LFU cacheCache, Node, DoublyLinkedList, (freq buckets)get(k), put(k, v) in O(1)Strategy (eviction)Map + DLL wiring; LFU min-freq tracking; thread safety
Rate limiterRateLimiter, Bucket, Rule, Clockallow(clientId) → boolStrategy (algorithm)Lazy refill; per-key locking; injectable clock
LoggerLogger, Level, Appender(console/file), Formatterlog(level, msg)Chain, Strategy, Singleton, Producer-ConsumerAsync appender with bounded queue; level filtering
Pub-sub / message queueBroker, Topic, Partition, Message, Publisher, Subscriber, Offsetpublish(topic, msg), subscribe(topic, s)ObserverPer-subscriber offsets; ordering; back-pressure
Hotel bookingHotel, Room(type), Booking, Guest, DateRange, Invoicesearch(range, type), book(), cancel()Strategy (pricing)Date-range overlap check; holds
Ride sharingRider, Driver, Trip(state), Location, Matcher, PricingrequestRide(), accept(), complete()Strategy, State, ObserverMatching nearest available driver atomically
Food deliveryRestaurant, Menu, Order(state), Cart, DeliveryAgent, DispatcherplaceOrder(), assignAgent(), track()State, Strategy, ObserverOrder lifecycle; reassignment on reject
File systemEntry (File / Directory), Path, Permissionsmkdir, ls, find(filter)Composite, SpecificationRecursive size; search filters composed with AND/OR
Task schedulerTask, Trigger(once/cron), Scheduler, Worker, DelayQueueschedule(task, at), cancel(id)Command, StrategyMin-heap by next run time; worker pool; retries
Shopping cart / inventoryProduct, Cart, CartItem, Inventory, Order, Couponadd(), checkout(), applyCoupon()Strategy, SpecificationReserve vs purchased stock; coupon stacking rules
Notification serviceNotification, Channel(Email/SMS/Push), Template, Preferencesend(userId, event)Strategy, Factory, ObserverAdd a channel without touching core; retries, dedup
Stack OverflowUser, Question, Answer, Comment, Vote, Tag, Reputationpost(), vote(), accept()Observer, CompositeOne vote per user; reputation updates
Cricket scoreboardMatch, Innings, Over, Ball, Player, ScorecardrecordBall(event)Observer, CommandExtras, wickets and strike rotation rules
Check yourself 2 questions
  1. Parking lot key methods?

    Show answer

    park(vehicle) → Ticket; unpark(ticket) → Receipt.

  2. 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
  1. Data structures for an O(1) LRU?

    Show answer

    A hash map plus a doubly linked list.

  2. 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-After computed from the token deficit.
Check yourself 2 questions
  1. How are tokens refilled?

    Show answer

    By elapsed time × refill rate, capped at capacity.

  2. 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
  1. Why use a record for Ticket?

    Show answer

    It's an immutable value.

  2. 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
  1. 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.

  2. 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
  1. Which pattern routes log levels?

    Show answer

    Chain of Responsibility.

  2. 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
  1. Why per-subscriber offsets?

    Show answer

    Each subscriber reads independently and can replay.

  2. 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
  1. What does the LOOK algorithm do?

    Show answer

    Keeps moving in one direction while stops remain, then reverses.

  2. 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

  1. Check every seat is still locked by this user (not expired).
  2. Charge with an idempotency key.
  3. Mark ShowSeats BOOKED and save the booking in one transaction.
  4. Unlock; publish a BookingConfirmed event.
  5. On payment failure or timeout, release the lock and mark the booking FAILED.

Extensions to mention

  • Distributed lock: Redis SET key NX PX per 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
  1. Why model ShowSeat separately from Seat?

    Show answer

    Availability is per show, not per physical seat.

  2. 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 long cents; 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
  1. Pattern for equal, exact and percent splits?

    Show answer

    Strategy, each with validation.

  2. 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
  1. What happens if payment fails?

    Show answer

    Release the seat locks.

  2. 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#

ProblemMechanismInvariant
Concurrent map updateAtomic map op / lockCheck-and-set is one operation.
Shared counterAtomic integer / synchronized allocatorNo lost or duplicate increments.
Multi-field transitionLock or database transactionNo partial state visible.
Work queueBlockingQueue / bounded channelBackpressure and shutdown are defined.
Retryable commandIdempotency key + stored resultRetry returns same logical outcome.
External side effectOutbox / saga boundaryFailure can be retried or compensated.
Check yourself 2 questions
  1. Concurrent map update mechanism?

    Show answer

    An atomic map operation (e.g. computeIfAbsent) or a lock.

  2. 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
  1. Name a concurrency review question.

    Show answer

    Any of: who owns each mutable field, can two requests race, what makes the method atomic.

  2. 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 tryLock with a timeout.
  • CAS can suffer the ABA problem; use a versioned reference such as AtomicStampedReference.
Check yourself 2 questions
  1. When prefer optimistic locking?

    Show answer

    Low contention.

  2. 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#

NeedJavaPython
Mutual exclusionsynchronized, ReentrantLock (tryLock, fairness)threading.Lock / RLock
Many readers, one writerReentrantReadWriteLock, StampedLockLock + Condition (no built-in RW lock)
Limit concurrent accessSemaphorethreading.Semaphore
Wait for a conditionCondition.await/signal, wait/notifyAllthreading.Condition, Event
Lock-free counterAtomicInteger, LongAdder (CAS)Lock (GIL doesn't make += atomic)
Visibilityvolatile, happens-before—
Concurrent mapConcurrentHashMap.compute/mergedict + Lock
Hand-off queueBlockingQueue (Array/Linked), DelayQueuequeue.Queue, PriorityQueue
Wait for N tasksCountDownLatch, CyclicBarrier, PhaserBarrier, concurrent.futures.wait
Thread poolExecutorService, CompletableFuture, virtual threads (21+)ThreadPoolExecutor, ProcessPoolExecutor, asyncio
Python GIL: threads help I/O-bound work; use processes for CPU-bound work. Free-threaded builds exist from 3.13 but are optional.
Check yourself 2 questions
  1. Many readers, one writer in Java?

    Show answer

    ReentrantReadWriteLock or StampedLock.

  2. 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#

HazardLooks likePrevention
Race conditioncheck-then-act, read-modify-writeAtomic op (CAS, computeIfAbsent) or one lock around both steps
DeadlockTwo threads hold locks the other needsGlobal lock ordering, tryLock with timeout, fewer locks
LivelockThreads keep yielding to each otherRandomised back-off
StarvationA thread never gets the lockFair locks, bounded priorities
Visibility bugThread never sees a flag changevolatile, locks, atomics
Lost updateTwo writers overwrite each otherOptimistic version check or row lock
ABACAS succeeds on a recycled valueVersioned/stamped references
Priority inversionLow-priority holder blocks high priorityPriority inheritance, short critical sections
Coffman conditions for deadlock: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one, usually circular wait via ordering.
Check yourself 2 questions
  1. How do you prevent deadlock?

    Show answer

    Acquire locks in a global order, or use tryLock with timeouts.

  2. 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#

ProblemCore idea
Producer–consumer / bounded blocking queueLock + two conditions (notFull, notEmpty); loop on the predicate
Readers–writersRW lock; decide reader vs writer preference
Dining philosophersOrder the forks or limit diners with a semaphore of N−1
Print in order / FooBar / ZeroEvenOddSemaphores or condition hand-off between threads
Building H₂OSemaphores (2 H, 1 O) + barrier
Multithreaded web crawlerConcurrent visited set + work queue + pool; stop when queue empty and no task in flight
Thread-safe LRU cacheOne lock, or segment the key space into shards
Delayed task schedulerPriority queue + condition wait until the earliest deadline
Check yourself 2 questions
  1. Producer–consumer core idea?

    Show answer

    A lock with two conditions (notFull, notEmpty), looping on the predicate.

  2. 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
  1. When does put() wait?

    Show answer

    While the queue is full.

  2. 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
  1. What happens when the queue is full?

    Show answer

    Producers block.

  2. 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)#

MinDo
0–10Clarify scope; write the 4–6 must-have commands
10–20Models (enums, value objects, entities) and interfaces
20–65Services for the happy path; in-memory repositories
65–80Driver/demo with the sample input; validation and exceptions
80–90Extension point demo, concurrency note, cleanup
Check yourself 2 questions
  1. What happens in minutes 0–10?

    Show answer

    Clarify scope and write the 4–6 must-have commands.

  2. 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
  1. Where do pluggable rules go?

    Show answer

    The strategy package.

  2. 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
  1. What shows extensibility?

    Show answer

    A new type means a new class, not edits.

  2. 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
  1. What should methods return?

    Show answer

    Domain objects or results, never raw maps.

  2. 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
  1. Domain exception examples?

    Show answer

    SeatUnavailable, InsufficientFunds.

  2. 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
  1. How does DIP help testing?

    Show answer

    You can inject fakes for clock, repository and payment gateway.

  2. 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
  1. 1M requests a day is roughly how many QPS?

    Show answer

    About 12.

  2. 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
  1. Which numbers should you estimate?

    Show answer

    Only those that change the architecture.

  2. 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
  1. What comes before drawing classes?

    Show answer

    Confirming use cases.

  2. 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.

No cards match. Try fewer or different words, or press Esc to clear.