๐Ÿ  Hub ๐Ÿ“ System Design Notes by Amit Mahata โ€ข 8+ YoE
Page 1 / 10

Table of Contents (System Design Master Notes)

System Design Framework & Fundamentals

โ‘ 

4-Step Senior System Design Framework (45 mins)

๐ŸŽฏ
1. Clarify & Scope
โ€ข Functional requirements
โ€ข Non-functional (SLA/QPS)
โ€ข Back-of-envelope math
(5 - 7 mins)
๐Ÿ—๏ธ
2. High-Level Flow
โ€ข API contract (REST/gRPC)
โ€ข Core DB schema entity
โ€ข End-to-end block diagram
(10 - 15 mins)
๐Ÿ”
3. Deep Dive Core
โ€ข Scale bottlenecks
โ€ข Cache / Sharding / Queue
โ€ข Algorithms & data models
(15 - 20 mins)
๐Ÿ›ก๏ธ
4. Bottlenecks & Scale
โ€ข SPOF & Fault tolerance
โ€ข Monitoring, SLOs, Tracing
โ€ข Cost & trade-offs
(5 mins)
โ‘ก

End-to-End Architecture Flow

๐ŸŒ Client (Web/Mobile) Anycast / GeoDNS
โ†“ Static Assets & Edge Cache
โšก CDN Edge Server (Cloudflare/CloudFront) Edge PoP
โ†“ Dynamic Requests
โš–๏ธ L4/L7 Load Balancer (NGINX / ALB) SSL / Health
โ†“ Rate Limiting & Auth
๐Ÿšช API Gateway (Routing, Circuit Breaker) Token Bucket
โ†“ Internal Microservices
โš™๏ธ App Services + Cache (Redis Cluster) Cache-Aside
โ†“ Async Events / DB Writes
๐Ÿ—„๏ธ Primary/Replica DB + Kafka Queue WAL / CDC
โ‘ข

Numbers Every 8+ YoE Engineer Must Know

โฑ๏ธ Latency Hierarchy (Orders of Magnitude)
  • L1 cache reference: ~ 0.5 - 1 ns
  • L2 cache reference: ~ 3 - 7 ns
  • Main Memory (RAM) access: ~ 100 ns
  • NVMe SSD random read: ~ 50 - 100 ยตs (1000x RAM)
  • Read 1 MB sequentially from RAM: ~ 3 ยตs
  • Read 1 MB sequentially from SSD: ~ 1 ms
  • Datacenter network roundtrip (RTT): ~ 0.5 ms
  • Intercontinental RTT (US โ†” EU): ~ 150 ms
๐Ÿ“Š Back-of-Envelope Quick Multipliers
โ€ข 1 Day = 86,400 s โ‰ˆ 100K seconds (for quick mental math)
โ€ข 1 Million req/day โ‰ˆ 12 QPS | 100M req/day โ‰ˆ 1.2K QPS
โ€ข Peak Traffic multiplier: Design for 2x to 5x of average QPS!
โ‘ฃ

Availability & SLA Tiers

Availability Tiers (The "Nines")
99.0% ("2 Nines")3.65 days downtime / year
99.9% ("3 Nines")8.76 hours downtime / year
99.99% ("4 Nines")52.6 minutes downtime / year
99.999% ("5 Nines")5.26 minutes downtime / year (Telco/Fintech)
Key Reliability Metrics
MTBF (Mean Time Between Failures)System Uptime reliability
MTTR (Mean Time to Repair)Recovery speed & automated failover
RPO (Recovery Point Objective)Max acceptable data loss
RTO (Recovery Time Objective)Max acceptable downtime
โ‘ค

Napkin Math, Worked Out Like You Would on the Whiteboard

given: 50M DAU ยท 20 requests / user / day ยท 10% writes ยท 1 KB / record requests / day = 50M ร— 20 = 1B avg QPS = 1B รท 10โต s โ‰ˆ 10K QPS peak โ‰ˆ 3 ร— avg โ‰ˆ 30K QPS writes = 10% โ‡’ 100M / day โ‰ˆ 1K WPS storage = 100M ร— 1 KB = 100 GB / day 5 years โ‰ˆ 100 GB ร— 365 ร— 5 โ‰ˆ 180 TB โ†’ must shard cache 20% of reads โ‰ˆ 0.2 ร— 900M ร— 1 KB โ‰ˆ ~200 GB โ†’ a few Redis nodes app servers @ ~3K QPS each 30K รท 3K = 10 +50% headroom โ†’ 15 pods read : write = 9 : 1 โ‡’ read replicas + cache
Fig 1.1 โ€” round aggressively: 1 day โ‰ˆ 10โต s, 1M/day โ‰ˆ 12 QPS. Interviewers care about orders of magnitude, not decimals

๐Ÿ”ข Powers of two

  • 2ยนโฐ โ‰ˆ 1 thousand (KB)
  • 2ยฒโฐ โ‰ˆ 1 million (MB)
  • 2ยณโฐ โ‰ˆ 1 billion (GB)
  • 2โดโฐ โ‰ˆ 1 trillion (TB)

๐Ÿ‹๏ธ Ballpark per-node capacity

  • Redis: ~100K simple ops/s
  • Postgres primary: a few K writes/s
  • Stateless app pod: 1โ€“5K RPS
  • Kafka broker: 100+ MB/s

โ“ Ask before drawing

  • Who are the users & how many?
  • Read-heavy or write-heavy?
  • Strong or eventual consistency?
  • Latency target (p99)?
โญ Senior Takeaway
โœ“ Never jump straight to drawing databases or Kafka topics! First establish Read-to-Write ratio (e.g., Twitter 100:1 vs Chat 1:1), storage size per record, and whether strong consistency is non-negotiable (e.g. Payments) or eventual consistency is acceptable (e.g. Likes, News Feed).
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you stand out as an 8+ YoE candidate in the first 10 minutes?
A: Don't wait for the interviewer to give you requirements. Actively drive the scope: "Assuming 50M DAU, each user making 20 requests daily yields ~12,000 QPS average, peaking at 35,000 QPS. At 500 bytes per payload, we'll store 500GB/day = 180TB over 5 years. I propose starting with an API Gateway + Cache-Aside architecture to offload 90% of reads."

Scalability, Load Balancing & API Gateways

โ‘ 

Layer 4 (Transport) vs Layer 7 (Application) Load Balancing

VS
Layer 4 Load Balancer (TCP/UDP)
Routing Level:IP + Port (Socket level)
Payload Visibility:Blind to HTTP headers/cookies
Performance:Ultra-fast, lowest latency (no decrypt)
Use Cases:DNS, Gaming, HAProxy TCP mode, AWS NLB
Layer 7 Load Balancer (HTTP/HTTPS)
Routing Level:URL Path, Headers, Cookies, Auth token
Payload Visibility:Full HTTP message inspection + SSL Termination
Smart Features:Path routing (/api/v1/orders), Rate limit, WAF
Use Cases:NGINX, Envoy, Traefik, AWS ALB
โ‘ก

Load Balancing Algorithms & Consistent Hashing

๐Ÿ”„
Round Robin / Weighted
Distributes sequentially. Weighted assigns higher traffic to bigger machines.
โšก
Least Connections
Routes to instance with fewest active connections. Best for long-lived sessions (WebSockets).
๐ŸŽฏ
Consistent Hashing
Maps keys & nodes on a 360ยฐ ring with virtual nodes. Adding node remaps only K/N keys!
๐Ÿ“
Geo-Proximity
Routes users to the closest datacenter based on GeoDNS latency / BGP Anycast.
โ‘ข

API Gateway Core Responsibilities & Rate Limiting Algorithms

๐Ÿšช API Gateway Pattern
  • Single Entry Point: Hides internal microservice topologies.
  • Authentication & JWT Validation: Offloads auth checks.
  • SSL / TLS Termination: Decrypts at perimeter; HTTP internally.
  • Protocol Translation: Translates HTTP/REST to internal gRPC.
  • Circuit Breaking: Fails fast on downstream service degradation.
๐Ÿ›ก๏ธ Rate Limiting Algorithms
1. Token Bucket Allows Bursts
Tokens added at fixed rate. Request consumes 1 token. If empty, HTTP 429 Too Many Requests.
2. Leaky Bucket Smooths Out Flow
Requests enter FIFO queue and processed at strictly constant rate. Drops excess requests.
3. Sliding Window Counter Accurate & Memory-Efficient
Weights previous window + current window: prev_count ร— (1 - weight) + curr_count.
โ‘ฃ

Resilience: Circuit Breaker State Machine

๐ŸŸข CLOSED (Normal)
All requests pass through.
Failures counted over rolling time window.
If failures > Threshold (e.g. 50%) โ†’
๐ŸŸก HALF-OPEN (Testing)
Allows canary sample requests.
If success โ†’ CLOSED
If failure โ†’ OPEN
โ† Timeout expires (e.g. 30s)
๐Ÿ”ด OPEN (Tripped)
Fails immediately (Fast-Fail) or returns fallback cache response. Protects downstream service!
โ‘ค

Sketches: the Hash Ring & the Token Bucket

A B C D new node k1 k2 k3 k1 used to go to B โ€ฆ โ€ฆ now lands on D (the only key that moves!) keys walk clockwise to the next node
Fig 2.1 โ€” adding D only steals keys in the arc A โ†’ D; everyone else stays put
refill r tokens/sec capacity b requests 200 OK (took 1 token) 429 if empty bursts up to b, long-run rate r
Fig 2.2 โ€” store only (tokens, lastRefillTs) per user; refill lazily on each request

๐Ÿงฎ Why virtual nodes?

  • 3 physical nodes = 3 uneven arcs โ†’ hot spots
  • 100โ€“300 vnodes each โ†’ arcs average out (ยฑ5โ€“10%)
  • Bigger machine? give it more vnodes

โš™๏ธ Distributed limiter

  • Key: `rl:{userId}:{endpoint}` in Redis
  • Lua script = read + refill + decrement atomically
  • Return `X-RateLimit-Remaining` + `Retry-After`
โญ Golden Rule for Consistent Hashing
โœ“ Standard hash (hash(key) % N) causes 99% cache misses when cluster size $N$ changes! Consistent hashing with Virtual Nodes (100-300 per physical server) prevents Hotspots and ensures uniform load distribution.
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you prevent Thundering Herd on cache invalidation or server restart?
A: Use Mutex / Singleflight locks (only 1 thread fetches from DB while others wait), Probabilistic Early Expiration (XFetch algorithm), and Randomized TTL Jitter so millions of cached keys don't expire simultaneously at the top of the hour.

Distributed Caching & Invalidation Strategies

โ‘ 

4 Core Caching Patterns (Where & How Writes Occur)

๐Ÿ“–
Cache-Aside (Lazy)
โ€ข App reads Cache first.
โ€ข If Miss โ†’ Read DB โ†’ Write to Cache.
โœ“ Only caches requested data.
โœ— Cache misses have 3x latency.
โœ๏ธ
Write-Through
โ€ข App writes to Cache.
โ€ข Cache synchronously writes to DB.
โœ“ High data consistency.
โœ— Higher write latency.
โšก
Write-Back (Behind)
โ€ข App writes to Cache immediately.
โ€ข Cache async flushes to DB in batches.
โœ“ Extreme write throughput.
โœ— Data loss risk if cache dies.
๐Ÿ”„
Write-Around
โ€ข App writes directly to DB.
โ€ข Bypasses Cache completely.
โœ“ Prevents cache pollution.
โœ— Fresh writes trigger cache miss.
โ‘ก

Cache Production Pitfalls & Battle-Tested Fixes

๐ŸŒŠ Cache Avalanche
Problem: Massive number of keys expire at the exact same second, causing DB CPU to spike to 100%.

Solution:
โ€ข Add Random TTL Jitter (TTL = base_ttl + rand(1, 300)s).
โ€ข Multi-region distributed cache deployment.
๐Ÿ•ณ๏ธ Cache Penetration
Problem: Attackers query non-existent keys (e.g. user_id = -999). Misses bypass cache and hit DB directly.

Solution:
โ€ข Bloom Filter in front of Cache (O(1) space/time to check existence).
โ€ข Cache empty/null results with short TTL (60s).
๐Ÿ’ฅ Cache Breakdown / Stampede
Problem: A single viral "hot key" (e.g. World Cup score) expires; 50,000 concurrent threads hit DB.

Solution:
โ€ข Distributed Mutex (Redis SETNX): only 1 worker regenerates cache.
โ€ข Background async pre-warm cron job.
โ‘ข

Redis vs Memcached

VS
Redis
Data Types: Strings, Hashes, Lists, Sets, Sorted Sets (ZSET), Bitmaps, HyperLogLog, Streams
Threading: Single-threaded event loop (I/O multiplexing epoll) + Multi-threaded I/O in v6+
Persistence: RDB snapshots + AOF write log
Replication: Native Master-Replica + Sentinel + Cluster (16,384 Hash Slots)
Memcached
Data Types: Pure Key-Value byte strings only
Threading: True Multi-threaded architecture (scales linearly with CPU cores)
Persistence: None (Pure in-memory, volatile)
Replication: No native clustering (client-side consistent hashing required)
โ‘ฃ

Cache Eviction Algorithms

๐Ÿ—‘๏ธ Eviction Policy Cheatsheet
  • LRU (Least Recently Used): Evicts keys not read for the longest time. (Standard choice; implemented via Doubly Linked List + Hash Map in O(1)).
  • LFU (Least Frequently Used): Tracks access counters. Evicts least popular items. Great for static catalog access.
  • FIFO: First-In-First-Out queue order. Simple but suboptimal.
  • 2Q / ARC (Adaptive Replacement Cache): Balances recency and frequency dynamically.
โ‘ค

Cache-Aside, Step by Step (sequence sketch)

โš™๏ธ App โšก Redis ๐Ÿ—„๏ธ DB โ‘  GET user:42 โ‘ก (nil) โ€” miss โ‘ข SELECT * FROM users WHERE id = 42 โ‘ฃ row โ‘ค SET user:42 EX 300 (+ jitter) โ€” write path โ€” โ‘ฅ UPDATE users SET โ€ฆ (commit first) โ‘ฆ DEL user:42 next read repopulates (step โ‘ )
Fig 3.1 โ€” update DB, then delete the key. Deleting is idempotent; "updating" the cache races

๐Ÿ“ˆ Hit-ratio math

  • avg latency = hยท0.5ms + (1 โˆ’ h)ยท10ms
  • h = 0.90 โ†’ 1.45 ms ยท h = 0.99 โ†’ 0.6 ms
  • Every extra "9" of hit-rate โ‰ˆ halves DB load

๐Ÿ”‘ Key hygiene

  • Namespaced + versioned: `v2:user:42`
  • Bump the version to invalidate a whole schema
  • Keep values small (< 100 KB) โ€” big values block Redis' single thread

๐ŸงŠ What NOT to cache

  • Balances / inventory used for a decision
  • Data with a 1:1 read:write ratio
  • Anything you can't afford to be stale
โญ Dual-Write Problem: Invalidate vs Update
โœ“ Never update cache directly on DB write due to race conditions (e.g. Thread A writes DB, Thread B writes DB, Thread B updates Cache, Thread A updates Cache $\to$ Stale Cache!).
โœ“ Standard Pattern: Write to DB first $\to$ Delete (Invalidate) from Cache.
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you achieve 100% cache-DB consistency without race conditions?
A: Use Change Data Capture (CDC via Debezium) connected to the Database Write-Ahead Log (WAL). DB commits the transaction $\to$ Debezium publishes change to Kafka $\to$ Dedicated consumer service invalidates Redis cache asynchronously with retry guarantees.

Databases: SQL vs NoSQL, Sharding & CAP

โ‘ 

SQL (Relational) vs NoSQL Taxonomy

๐Ÿ—„๏ธ
Relational (SQL)
โ€ข Postgres, MySQL
โ€ข ACID transactions, strict schema, complex JOINs.
โ€ข Storage: B+ Tree indexes.
๐Ÿ“„
Document (NoSQL)
โ€ข MongoDB, Couchbase
โ€ข Flexible JSON/BSON schema, nested sub-objects.
โ€ข Great for Catalogs, User profiles.
๐Ÿ“Š
Wide-Column (NoSQL)
โ€ข Cassandra, ScyllaDB, HBase
โ€ข High write throughput, LSM-Tree.
โ€ข Great for Time-series, IoT, Chat.
๐Ÿ•ธ๏ธ
Graph DB
โ€ข Neo4j, Amazon Neptune
โ€ข Nodes, Edges & Properties.
โ€ข Social networks, Fraud detection.
โ‘ก

CAP Theorem & The Realistic PACELC Theorem

๐Ÿ”บ CAP Theorem (Pick Any 2 during network partition)
  • Consistency (C): Every read receives the most recent write or an error.
  • Availability (A): Every non-failing node returns a non-error response (without guarantee of latest data).
  • Partition Tolerance (P): System continues operating despite network drops between nodes. (Mandatory in distributed systems!).
  • CP Systems: Google Spanner, HBase, ZooKeeper.
  • AP Systems: Apache Cassandra, CouchDB, DynamoDB.
โš–๏ธ PACELC Theorem (Extended Real-World Model)
If there is a Partition (P), trade off Availability (A) vs Consistency (C);
Else (E) (normal operation), trade off Latency (L) vs Consistency (C).

โ€ข PA/EL: Cassandra, DynamoDB (Low latency favored over strong consistency in normal state).
โ€ข PC/EC: Google Spanner, CockroachDB (Strong consistency always prioritized).
โ‘ข

Database Sharding Strategies & Challenges

1. Range-Based Sharding
Sharded by key ranges (e.g. Users A-D on Shard 1, E-H on Shard 2).
โœ“ Range queries easy.
โœ— Hotspot risk (Celebrity 'J' overloads Shard 3).
2. Hash-Based Sharding
Shard = hash(user_id) % N.
โœ“ Uniform data distribution.
โœ— Range queries require scatter-gather across all shards.
3. Directory / Lookup-Based
Lookup service maps partition key to shard ID.
โœ“ Flexible dynamic re-sharding.
โœ— Lookup service is single point of failure / latency hop.
โ‘ฃ

Sketches: Shards with Replicas & the CAP Triangle

hash(user_id) % 4 S0 lead S1 lead S2 lead S3 lead writes โ†’ leader ยท reads โ†’ replicas (lag!) cross-shard JOINs & transactions get expensive
Fig 4.1 โ€” sharding scales writes, replication scales reads & availability
C A P CP etcd ยท ZooKeeper HBase ยท Spanner AP Cassandra ยท DynamoDB CA = single node (no network, no P) partitions WILL happen โ†’ choose C or A
Fig 4.2 โ€” and when there's no partition, PACELC asks: latency or consistency?
Isolation levelDirty readNon-repeatable readPhantomWho uses it by default
Read Uncommittedpossiblepossiblepossiblealmost nobody
Read CommittedpreventedpossiblepossiblePostgreSQL, SQL Server, Oracle
Repeatable Readpreventedpreventedpossible*MySQL InnoDB (*gap locks block most)
Serializablepreventedpreventedpreventedmoney movement, inventory decrements
โญ Storage Engine Tradeoff: B-Tree vs LSM-Tree
โœ“ B+ Tree (Postgres/MySQL): In-place updates, faster reads (O(log N)), higher write amplification.
โœ“ LSM-Tree (Log-Structured Merge-Tree - Cassandra/RocksDB): Sequential append-only writes to MemTable + WAL, background SSTable compaction. Massive write throughput!
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you handle Cross-Shard Transactions without blocking the entire database?
A: Avoid distributed 2-Phase Commit (2PC) in high-throughput systems because coordinator locks cause high tail latency. Instead, co-locate related records using a shared Composite Partition Key (e.g., tenant_id:user_id), or use an asynchronous Saga Orchestration Pattern.

Asynchronous Messaging & Distributed Transactions

โ‘ 

Apache Kafka vs RabbitMQ Deep Comparison

VS
Apache Kafka (Distributed Event Streaming)
Model:Distributed Commit Log (Partitioned append-only file)
Consumption:Pull model (Consumers track own offset pointer)
Message Retention:Time/Size based (e.g. 7 days). Replayable!
Throughput:Millions msg/sec (Zero-Copy OS page cache)
Ordering:Strict ordering guaranteed within a single partition
RabbitMQ (Traditional Message Broker)
Model:AMQP Broker with Exchanges (Direct, Fanout, Topic)
Consumption:Push model (Broker pushes to consumers)
Message Retention:Deleted immediately after consumer ACK
Throughput:Tens of thousands msg/sec
Features:Complex routing, priority queues, Dead Letter Exchanges
โ‘ก

Delivery Semantics & Idempotency Pattern

โšก
At-Most-Once
Commit offset before processing.
โ€ข Messages never reprocessed.
โ€ข Data loss if consumer crashes!
๐Ÿ”„
At-Least-Once
Commit offset after DB processing.
โ€ข Zero data loss.
โ€ข Duplicates possible on crash.
๐ŸŽฏ
Exactly-Once (Effective)
At-Least-Once + Idempotency:
Unique idempotency_key stored in DB deduplication table.
โ‘ข

Distributed Transactions: Outbox Pattern & Sagas

๐Ÿ“ฆ Transactional Outbox Pattern
Problem: Updating DB and publishing to Kafka is NOT atomic (one can fail).

Solution Flow:
1. App saves business entity + message into outbox_table in the same local DB transaction.
2. CDC engine (Debezium) reads DB WAL log and publishes to Kafka.
โœ“ 100% atomic dual-write guarantee without distributed locks.
๐ŸŽญ Saga Pattern for Distributed Workflows
Replaces slow blocking Two-Phase Commit (2PC) across microservices:

โ€ข Choreography: Services listen to domain events and execute local transactions independently.
โ€ข Orchestration: Central orchestrator (Temporal / AWS Step Functions) coordinates workflow.
โ€ข On failure, executes explicit Compensating Transactions (e.g. Refund Payment).
โ‘ฃ

Picture Kafka: Partitions, Offsets & Consumer Groups

Order API Payment svc key = order_id hash(key) % 3 topic: orders P0P1P2 01234 012 0123 append-only log ยท offsets โ†‘ ยท retained 7 days newest group: fulfillment consumer 1 consumer 2 consumer 3 group: analytics 1 consumer โœ“ order within a partition only ยท โœ“ each group reads independently ยท โœ— consumers > partitions โ‡’ idle consumers
Fig 5.1 โ€” partitions are the unit of parallelism and of ordering; pick the key that must stay ordered

๐Ÿ“ Sizing partitions

  • #partitions โ‰ฅ peak MB/s รท per-consumer MB/s
  • Over-provision a bit โ€” increasing later reshuffles key โ†’ partition

๐Ÿ”ฅ Hot partition

  • One celebrity key = one overloaded partition
  • Fix: salt the key (`key#0..N`) when ordering isn't needed

๐Ÿ“‰ Watch consumer lag

  • lag = latest offset โˆ’ committed offset
  • Rising lag = scale consumers or speed up handlers
โญ Kafka Partitioning Law
โœ“ In Kafka, 1 partition can only be read by 1 consumer thread in a consumer group at any time! To scale consumer throughput, you must increase the number of partitions. Setting partition key = user_id guarantees all events for that user arrive in exact chronological order.
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you prevent Poison Pill messages from blocking an entire Kafka partition?
A: Implement a Dead Letter Queue (DLQ) with Exponential Backoff + Jitter. On message deserialization or unrecoverable error, write the payload + stack trace to a order-events-dlq topic after $N$ retry attempts, alert on-call, and commit the partition offset so valid customer messages continue processing.

Storage Systems, CDNs & Media Pipelines

โ‘ 

Storage Types: Block vs File vs Object Storage

๐Ÿงฑ
Block Storage (EBS, SAN)
โ€ข Raw disk blocks without metadata.
โ€ข Ultra-low latency IOPS.
โ€ข Attached to single instance.
Best for: Databases, OS boot disks.
๐Ÿ“
File Storage (EFS, NFS)
โ€ข Hierarchical folder structure.
โ€ข Shared across multiple servers.
โ€ข POSIX compliant file locks.
Best for: Shared configs, Legacy apps.
๐Ÿชฃ
Object Storage (S3, GCS)
โ€ข Flat namespace with metadata.
โ€ข Immutable files accessed via HTTP API.
โ€ข 99.999999999% (11 9's) durability.
Best for: Videos, Images, Backups.
โ‘ก

Content Delivery Networks (CDN): Push vs Pull

VS
Pull CDN (Origin Fetch - Default)
Workflow: Edge PoP fetches content from Origin server on first user request (Cache Miss), then caches it for TTL.
Storage Cost: Minimal (only popular cached assets stored at edge)
Maintenance: Zero origin management; automatic eviction.
Best For: High-traffic web apps, blogs, YouTube thumbnails.
Push CDN (Proactive Upload)
Workflow: Origin server pushes all new/updated content to edge servers proactively prior to user requests.
Storage Cost: Higher (all assets distributed to all edge locations).
Latency: 0ms origin miss latency for all users.
Best For: Large software updates (iOS updates, game patches).
โ‘ข

Large Video / File Upload Pipeline (e.g. YouTube, Google Drive)

1. Client requests upload signature from API Pre-Signed S3 URL (5-min expiry)
โ†“ Direct Client-to-S3 bypasses API Servers
2. Client uploads file in 5MB chunks in parallel S3 Multipart Upload / TUS Protocol
โ†“ S3 Object Created Event Trigger
3. S3 triggers SNS/SQS Transcoding Queue Event-Driven Pipeline
โ†“ Distributed Worker Cluster (FFmpeg on GPU)
4. Workers encode video into HLS / DASH (1080p, 720p, 480p) HLS .m3u8 manifests + .ts segments
โ‘ฃ

The Upload โ†’ Transcode โ†’ Stream Pipeline (sketch)

๐Ÿ“ฑ Client Upload API โ‘  ask for URL โ‘ก presigned URL ๐Ÿชฃ S3 (raw)multipart, resumable โ‘ข upload direct (bypass app tier) ๐Ÿ“ฌ Queue โ‘ฃ event โš™๏ธ Transcoders (DAG) โ€ข 1080p / 720p / 480p โ€ข 4-sec HLS/DASH chunks โ€ข thumbnails ยท DRM โ€ข safety scan ๐Ÿชฃ S3 (renditions) โ‘ค ๐ŸŒ CDN edge โ‘ฅ origin โ–ถ๏ธ Viewers โ‘ฆ adaptive bitrate
Fig 6.1 โ€” app servers only hand out signed URLs; bytes flow client โ‡„ storage โ‡„ CDN

๐Ÿงพ Cache-Control cheat

  • Video chunks / hashed assets: `public, max-age=31536000, immutable`
  • Manifests (.m3u8): short TTL, e.g. `max-age=10`
  • Private content: signed URL + `private`

โ™ป๏ธ Resumable uploads

  • Split into 5โ€“100 MB parts, upload in parallel
  • Retry only the failed part; complete with ETag list
โญ Never Stream Large Files Through App Servers!
โœ“ Streaming 2GB video uploads through your API Gateway / Node.js servers exhausts thread pools and network bandwidth immediately! Always generate an Amazon S3 Pre-Signed Upload URL or use the TUS open resumable upload protocol for direct client-to-storage transfers.
๐Ÿ’ก Staff / Senior Interview Tip
Q: How do you search across billions of text records in sub-50ms?
A: Use an Inverted Index (Elasticsearch / OpenSearch). Unlike relational DBs that scan rows, an inverted index maps every unique word/token to a sorted list of Document IDs (Posting List). Combining multiple terms uses fast bitwise AND / OR operations across posting lists.

Distributed Consensus, Coordination & ID Gen

โ‘ 

Consistency Models Spectrum (Strongest to Weakest)

๐Ÿ”’
1. Linearizable (Strict)
โ€ข 1. Linearizable (Strict)
All operations appear instantaneous on a global real-time clock. Total global order.
โšก
2. Sequential
โ€ข 2. Sequential
All operations seen in the same order by all nodes; may lag real physical clock.
๐Ÿ‘ค
3. Read-Your-Own-Writes
โ€ข 3. Read-Your-Own-Writes
A user always sees their own updates immediately. Other users see it eventually.
๐ŸŒŠ
4. Eventual Consistency
โ€ข 4. Eventual Consistency
If no new updates, all replicas eventually converge to identical state.
โ‘ก

Consensus (Raft Algorithm)

๐Ÿ—ณ๏ธ Raft Core Mechanics (etcd, Consul)
  • Leader Election: Randomized election timers (150-300ms) prevent split-vote deadlocks.
  • Quorum Rule: Requires majority vote (Q = โŒŠN/2โŒ‹ + 1). A 5-node cluster survives 2 node failures.
  • Log Replication: Leader appends entry โ†’ replicates to followers โ†’ commits once majority ACKs.
  • Split-Brain Proof: Only 1 partition can have a majority quorum.
โ‘ข

Distributed Locks & Fencing Tokens

โš ๏ธ The Dangerous Distributed Lock Trap
Client 1 acquires lock โ†’ JVM triggers Full GC pause for 15s โ†’ Lock TTL expires โ†’ Client 2 acquires lock โ†’ Client 1 wakes up and writes to DB โ†’ Data Corruption!

Mandatory Fix: Fencing Tokens
Lock service issues monotonically increasing token (e.g. 33, 34, 35). Storage engine rejects writes with token < current highest token.
โ‘ฃ

Twitter Snowflake 64-Bit Unique ID Generator

โ„๏ธ 64-bit Binary Bit Layout (Roughly Time-Sorted)
1 Bit
Sign (0)
41 Bits: Timestamp
Epoch ms (69 yrs)
10 Bits: Machine ID
1024 workers
12 Bits: Sequence
4096 IDs/ms/node
โ€ข Generates 4,096,000 unique sortable IDs per second per server without cross-network synchronization!
โ‘ค

Sketches: a Raft Quorum & Why Locks Need Fencing Tokens

๐Ÿ‘‘ S1term 7 S2 S3 S4 S5 ack โœ“ack โœ“ slowโ€ฆdown AppendEntries(x = 5) S1 + S2 + S3 = 3/5 โ‡’ commit
Fig 7.1 โ€” majority = โŒŠn/2โŒ‹ + 1 โ†’ 5 nodes survive 2 failures
Client 1Client 2 LockStorage lease, token 33 GC pause ๐Ÿ’ค lease expiresโ€ฆ token 34 write(โ€ฆ, 34) โœ“ write(โ€ฆ, 33) 33 < 34 โ†’ rejected
Fig 7.2 โ€” the storage enforces safety; a lease alone can't
๐Ÿง  Quorum rule: with N replicas, write quorum W and read quorum R, you read your latest write when W + R > N (e.g. N = 3, W = 2, R = 2). Cassandra/Dynamo let you tune it per query.
โญ NTP Clock Drift is Real
โœ“ Physical server clocks drift via NTP adjustments or leap seconds. Never rely on wall-clock time for strict distributed ordering. Use Logical Clocks (Lamport Timestamps / Vector Clocks) or hardware atomic clocks with bounded uncertainty intervals (Google Spanner TrueTime API).
๐Ÿ’ก Staff / Senior Interview Tip
Q: Why is Redis Redlock controversial for distributed locking?
A: Distributed systems expert Martin Kleppmann showed that Redlock relies on synchrony assumptions (bounded network delays and monotonic physical clocks). If a process experiences an unpredicted GC pause or VM migration, Redlock can grant two clients the lock simultaneously. For safety-critical state, always use etcd / ZooKeeper linearizable sessions with fencing tokens.

FAANG Blueprints & 8+ YoE Staff Playbook

โ‘ 

6 Core Product System Blueprints (Cheat Sheet)

1. TinyURL / Bitly
โ€ข Encoding: Base62 (a-z, A-Z, 0-9). 7 chars = 3.5 Trillion URLs.
โ€ข KGS: Pre-generate unique keys to avoid DB collision loops.
โ€ข Ratio: 100:1 read-heavy โ†’ 95% served from Redis.
2. WhatsApp / Slack Chat
โ€ข Protocol: Full-duplex WebSockets.
โ€ข Session: Presence Servers maintain connection map.
โ€ข Storage: HBase / Cassandra (LSM-Tree for chat history).
3. Twitter / Instagram Feed
โ€ข Hybrid Fanout:
- Regular users: Fanout-on-Write (Push).
- Celebrities (>100K followers): Fanout-on-Read (Pull) merged dynamically at query time.
4. Distributed Rate Limiter
โ€ข Storage: Redis Cluster.
โ€ข Script: Atomic Lua Script executes Sliding Window Counter in 1 roundtrip.
โ€ข Sync: Local In-memory cache + async Redis sync.
5. Multi-Channel Notifications
โ€ข Channels: APNs (iOS), FCM (Android), SMS, Email.
โ€ข Priority Queues: High (OTP) vs Low (Promo).
โ€ข Deduplication: 5-min sliding window check.
6. Distributed Web Crawler
โ€ข URL Frontier: Priority + Politeness FIFO queue.
โ€ข Deduplication: Bloom Filter for visited URLs.
โ€ข Parser: Distributed HTML scrapers + S3 storage.
โ‘ก

What Distinguishes an 8+ YoE Senior/Staff Candidate?

๐ŸŽฏ Mid-Level vs Senior / Staff Behaviors
AreaSenior / Staff Engineer Mindset
Ambiguity:Asks targeted clarifying questions, states assumptions explicitly.
Trade-offs:Never says "X is best". Explains why X fits this workload despite its downsides.
Failure Modes:Designs proactively for hardware crashes, split-brains, network partitions.
Operational:Considers observability (OpenTelemetry), deployment strategy & AWS cloud cost.
๐Ÿ“Š Observability Pillar (Metrics, Logs, Traces)
  • Golden Signals: Latency (p50/p95/p99), Traffic (QPS), Errors (5xx rate), Saturation (CPU/Memory/Disk I/O).
  • Distributed Tracing: Trace ID & Span ID propagated across all microservices headers (W3C TraceContext / Jaeger).
  • Graceful Degradation: Serve cached / read-only content if write path is impaired.
โ‘ข

Hybrid News-Feed Fanout (sketch)

write path ๐Ÿ™‚ normal user Fanout workers post timeline:alice [p9, p7, โ€ฆ] timeline:bob [p9, p5, โ€ฆ] timeline:carol [p9, โ€ฆ] push (fanout-on-write) Redis lists, cap ~800 ids celebrity (> 100K followers) โญ celebrity Posts DB only no fanout โ€” 50M writes avoided Timeline service merge + rank at read ๐Ÿ“ฑ reader read = precomputed timeline โˆช recent posts of followed celebrities
Fig 8.1 โ€” push for the many, pull for the few: bounded write amplification and fast reads
โญ The Ultimate Interview Checklist
โœ“ 1. Functional: Top 2-3 core user journeys.
โœ“ 2. Non-Functional: Scale, Availability (99.99%), Latency (p99 < 100ms), Consistency.
โœ“ 3. Data Model: SQL vs NoSQL, Primary/Foreign keys, Access patterns.
โœ“ 4. Deep Dive: Cache invalidation, Kafka partitions, DB sharding, Lock safety.
โœ“ 5. Resiliency: Circuit breakers, Dead letter queues, Zero Single Points of Failure (SPOF).
๐Ÿ’ก Final Staff Interview Wisdom
"System design is not about memorizing architectures; it is the art of balancing trade-offs under constraints." Always drive the conversation, defend your design decisions with data, and guide the interviewer through bottlenecks before they even have to point them out!

Case Study: Design a URL Shortener (TinyURL)

โœŽ A full 45-minute answer, written the way you'd talk through it. Follow the numbered rail.
โ‘ 

Scope It (5 min)

โœ… Functional
  • Shorten a long URL โ†’ 7-char code
  • Redirect `GET /{code}` โ†’ long URL
  • Optional custom alias & expiry
  • Click analytics (async, can lag)
๐Ÿ“ Non-functional & napkin math
  • 100M new URLs / month โ‰ˆ 40 writes/s
  • Read:write = 100:1 โ‡’ ~4K redirects/s, peak ~20K
  • 5 yrs ร— 1.2B/yr ร— 500 B โ‰ˆ 3 TB
  • 62โท โ‰ˆ 3.5 trillion codes โ€” plenty
  • p99 redirect < 50 ms ยท 99.99% available
โ‘ก

API & Data Model (5 min)

๐Ÿ”Œ API
`POST /api/v1/urls``{ longUrl, alias?, expiresAt? }` โ†’ 201 `{ shortUrl }`
`GET /{code}`302 + `Location:` header (404 / 410 if expired)
`GET /api/v1/urls/{code}/stats`clicks by day / country
๐Ÿ—„๏ธ Table `urls`
code (PK)char(7)
long_urltext (โ‰ค 2 KB)
owner_id ยท created_at ยท expires_atfor quotas & TTL cleanup
Pure key lookups, no joins โ‡’ a key-value store (DynamoDB / Cassandra) shards trivially by `code`.
โ‘ข

High-Level Architecture (10 min)

๐Ÿ‘ค Client LB + API GWrate limit write path (40/s) Shorten svc Key Gen Servicehands out ranges of 1K ids ZooKeeperrange counter read path (4Kโ€“20K/s) Redirect svc โšก Redis hit โ‰ˆ 95% (hot links) ๐Ÿ—„๏ธ urls KVsharded by code miss Kafka clicks โ†’ ClickHouse stats
Fig 9.1 โ€” reads and writes are scaled independently; analytics never sits on the redirect hot path
โ‘ฃ

Deep Dives the Interviewer Will Push On (15 min)

Key generation optionHow๐Ÿ‘๐Ÿ‘Ž
Hash + truncatefirst 7 chars of base62(MD5(url))stateless, same URL โ†’ same codecollisions โ†’ retry loop & extra reads
Global counter + base62DB sequence โ†’ base62no collisions, shortsingle hot counter; codes are guessable
KGS ranges โœ…each server leases 1K ids from ZooKeeper, encodes locallyno coordination per request, no collisionsa crash wastes โ‰ค 1K ids (fine)

โ†ช๏ธ 301 or 302?

  • 301 permanent: browser caches it โ†’ fewer hits, but you lose analytics
  • 302 temporary: every click reaches you โ†’ accurate stats โœ…

๐Ÿ›ก๏ธ Abuse & safety

  • Rate-limit creates per user / IP
  • Scan targets against malware lists (async)
  • Shuffle the id โ†’ code mapping so codes aren't sequential

โณ Expiry

  • Check `expires_at` on read (lazy)
  • Nightly sweeper deletes rows (or native TTL in DynamoDB/Cassandra)
โญ Trade-offs to Say Out Loud
โœ“ Cache-aside with long TTL is safe here because mappings are immutable.
โœ“ Eventual consistency is fine for analytics, not for code uniqueness โ€” that's why KGS owns id ranges.
โœ“ Custom aliases go through a conditional write (`PutItem if not exists`) to avoid races.
๐Ÿ’ก Staff-Level Follow-up
Q: A link goes viral โ€” 1M redirects/s for one code. What breaks?
A: One Redis shard becomes hot. Add an in-process LRU cache (seconds-long TTL) on every redirect pod, and serve the 302 from the CDN edge with a short `max-age`, so the origin sees a trickle instead of the flood.

Case Study: Design a Chat System (WhatsApp / Slack)

โ‘ 

Scope It

โœ… Functional
  • 1:1 and group chats (โ‰ค 500 members)
  • Sent โœ“ ยท delivered โœ“โœ“ ยท read receipts
  • Online / last-seen presence
  • Push notification when offline
  • Multi-device history sync
๐Ÿ“ Napkin math
  • 500M DAU ร— 40 msgs = 20B msgs/day
  • รท 10โต s โ‰ˆ 200K msgs/s avg
  • 20B ร— 100 B โ‰ˆ 2 TB/day of text
  • ~50M concurrent sockets รท ~500K per gateway โ‰ˆ 100 gateways
โ‘ก

Architecture (sketch)

๐Ÿ“ฑ Alice ๐Ÿ“ฑ Bob WS Gateway 1stateful sockets WS Gateway 7stateful sockets wss Chat servicevalidate ยท seq ยท persist Session registryRedis: user โ†’ gateway Kafkakey = conv_id ๐Ÿ—„๏ธ Cassandra messagesPK (conv_id, bucket) ยท CK msg_id โ†“ Fanout workerwho's online? online โ†’ push frame APNsFCM offline heartbeat every 30s โ†’ presence (TTL key)
Fig 10.1 โ€” gateways only hold sockets; all logic lives in stateless services behind them
โ‘ข

The Life of One Message (โœ“ โ†’ โœ“โœ“ โ†’ blue โœ“โœ“)

Alice Server Store Bob send(text, clientMsgId) persist, msg_id = snowflake โœ“ sent (ack msg_id) deliver over socket ack delivered โœ“โœ“ delivered opened chat โ†’ read up to msg_id โœ“โœ“ read (blue)
Fig 10.2 โ€” clientMsgId makes retries idempotent; receipts carry "up to msg_id" so one ack covers many messages
โ‘ฃ

Deep Dives

๐Ÿ”ข Ordering

  • Order per conversation, not globally
  • Kafka key = conv_id โ†’ one partition per chat
  • Server assigns msg_id; clients sort by it, never by device clock

๐Ÿ‘ฅ Group fanout

  • Small groups: write once, fan out to each member's inbox/socket
  • Huge channels (Slack): members pull since their last-read cursor

๐Ÿ“ฒ Multi-device sync

  • Each device keeps `lastSeenMsgId` per chat
  • On reconnect: fetch `msg_id > cursor` from Cassandra

๐Ÿ”Œ Gateway dies?

  • Clients reconnect with jittered backoff to any gateway
  • Registry entry has a TTL, so stale routes expire
  • Nothing lost: messages were persisted before โœ“
โญ Why Cassandra for Messages?
โœ“ Write-heavy (200K/s) append-only workload โ†’ LSM-tree storage shines.
โœ“ Access pattern is always "latest N messages of conversation X" โ†’ partition by `(conv_id, month_bucket)`, cluster by `msg_id DESC`.
โœ“ The bucket keeps partitions from growing forever in long-lived chats.
๐Ÿ’ก Staff-Level Follow-up
Q: How would you add end-to-end encryption?
A: Clients exchange keys (Signal protocol: identity + pre-keys published to a key server); the server only relays ciphertext. Consequences: no server-side search, group messages are encrypted per member (or via sender keys), and push notifications carry only a "you have a message" hint.