CSCheatsheets
System design

High-Level Design

Requirements to architecture: estimation, building blocks, databases, consistency and consensus, resilience, APIs, security, 35 problem summaries and 8 full worked designs.

16sections
69cards
19diagrams
0%known

00HLD atlas: topics and routes

The whole sheet on one screen. Select an area or topic to jump to it; hover the boxes in any diagram below for explanations.

How to use this sheet#

  1. Learning: read Interview method, then Building blocks and Data and storage in order; they are the vocabulary for everything else.
  2. Going deeper: Distributed systems and Scale and resilience cover the senior-level follow-ups.
  3. Practising: pick a worked design, cover the page, design it out loud in 45 minutes, then compare.
  4. Interview tomorrow: numbers to know, the 35-problem table, follow-up questions, then the last-minute checklist.

The five questions behind every design#

QuestionWhere it's covered
What load, and what must never break?Estimates · Requirements
Where does the data live?Data model · Store by access
How do reads stay fast?Caching · Replicas
How do writes stay correct?Transactions · Isolation
What happens when parts fail?Resilience · Disaster recovery
Check yourself 2 questions
  1. First question behind every design?

    Show answer

    What load, and what must never break?

  2. Which topics answer 'how do reads stay fast?'

    Show answer

    Caching and replication.

Takeaway What load and invariant, where data lives, how reads stay fast, how writes scale, and what happens on failure.

01HLD: requirements to architecture

60-minute interview route#

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.

02Numbers 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.

03Trade-offs, stores, caching & scale

SystemDesign/07-interview-templates/02-cheat-sheets (trade-offs, architecture-by-scale, concept map), 02 building blocks

Core trade-offs#

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.

04Building blocks catalogue

Each component you might draw, what it is for, the choice you have to make, and the number or failure mode to mention.

Components at a glance#

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.

05Databases and storage internals

What you need to justify a data-store choice and to answer "how does it scale" and "what anomalies can happen".

Index and storage engines#

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.

06HLD problem breakdowns (35 problems)

SystemDesign/05-hld-problems/{01-easy,02-medium,03-hard}/*.md — Deep Dive headings + Key takeaway

Every HLD problem: 3 deep dives + the one insight#

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.

07Worked designs: eight full walkthroughs

Five classic prompts carried through the 60-minute route: requirements, estimates, API and data model, architecture, deep dives and trade-offs. Use them as model answers to rehearse out loud.

URL shortener#

Read-heavy key lookup. The interesting parts are generating short unique codes and keeping redirects under ~50 ms at 100K+ QPS.

flowchart LR
  C["Client"] --> CDN["CDN edge"]
  CDN --> LB["Load balancer"]
  LB --> R["Redirect service"]
  LB --> W["Create service"]
  R --> RC[("Redis<br/>code → URL")]
  R --> DB[("KV store: urls")]
  W --> IDG["ID range allocator"]
  W --> DB
  R -.->|"click event"| K[["Kafka"]]
  K -.-> AN[("Analytics store")]

Requirements

  • Shorten a URL to a 7-character code; redirect; optional custom alias and expiry; click analytics.
  • 100M new URLs/day, 100:1 read:write, p99 redirect < 50 ms, highly available.

Back-of-envelope

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.

08Distributed 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.

09Consistency, 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.

10Scalability, resilience and deployment patterns

The patterns that turn a box diagram into something that survives load spikes, dependency failures and bad deploys.

Rate-limiting algorithms#

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.

11Probabilistic 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.

12APIs 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.

13Security, 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.

14Follow-up questions and strong answers

The curveballs asked after the main design. A good answer names the mechanism, the trade-off and the number.

Curveball → answer#

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

15HLD last-minute checklist

HLD last-minute checklist#

  • State users, core actions, and the invariant to preserve.
  • Estimate only numbers that change the architecture.
  • Show read and write paths; mark sync and async boundaries.
  • Explain cache freshness, shard key, hot-key plan, consistency.
  • Make retries safe; treat timeouts as unknown outcomes.
  • Cover overload, dependency failure, regional recovery, degradation.
  • Name SLO, observability, security, rollout, and rollback.
  • For each choice: alternative → reason → failure mode.
Check yourself 2 questions
  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.

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