FullStack AI Hub
Studio
Back to Interactive Diagrams
62 Reference Cards
6 Tracks

Interactive Engineering Reference Cheatsheets

Distilled architectural reference cards auto-compiled from every interactive simulation—featuring pattern trade-off matrices, production rules of thumb, and step-indexed concepts.

System Design · 01. Foundations · Beginner · 9 steps

Client-Server & DNS

Open lesson

KEY TAKEAWAYS

  • Trace the request-response cycle between browsers, IP addresses, and application origins
  • Follow a recursive DNS lookup across Root, TLD, and Authoritative nameservers
  • Choose A/AAAA/CNAME records and tune DNS TTL to balance lookup speed vs failover agility
  • Eliminate cross-ocean latency and DNS outages using Anycast resolvers and GeoDNS routing

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
A / AAAA RecordMapping apex domains directly to IPv4 / IPv6 addressesRequires DNS update + TTL wait if the target server IP changes
CNAME / ALIASPointing subdomains (api.) to managed CDN or LB hostnamesAdds an extra DNS lookup hop; standard CNAME forbidden at zone apex
Short TTL (30–60s)Fast disaster failover and blue-green migrationsHigher recursive lookup volume and slight extra latency on expiry
Anycast + GeoDNSGlobal apps routing users to their closest healthy regional PoPSome ISP resolvers sit far from users (solved by EDNS Client Subnet)
Rule of thumb:Use ALIAS flattening at the apex, 60s TTLs for critical endpoints, and dual Anycast GeoDNS providers so resolution is fast and unbreakable.
System Design · 01. Foundations · Beginner · 10 steps

Latency & Throughput

Open lesson

KEY TAKEAWAYS

  • Measure P50, P95, and P99 tail latency instead of misleading arithmetic averages
  • Apply Little’s Law (L = λ·W) and keep utilization below the ~75–80% queueing knee
  • Diagnose fan-out tail amplification across microservices and tame it with Hedged Requests
  • Balance micro-batching throughput gains against per-request latency budgets

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
P95 / P99 PercentilesSLOs and catching slow outliers hidden by averagesCannot average percentiles across servers—must merge histograms
Headroom (< 75% Util)Interactive APIs avoiding exponential queue-wait hockey sticksCosts ~25–30% idle compute headroom during normal hours
Hedged RequestsFan-out read services suffering 1% straggler shardsAdds ~5% extra load; requires strictly idempotent reads
Micro-BatchingHigh-throughput telemetry, logs, and ML inference pipelinesAdds deliberate batch-fill delay (e.g., 10–50 ms) to single items
Rule of thumb:Watch P99, size for < 75% peak utilization, cap concurrency to preserve goodput, and use hedging + edge caching to defeat tail latency.
System Design · 01. Foundations · Beginner · 10 steps

Networking & HTTP

Open lesson

KEY TAKEAWAYS

  • Measure TCP 3-way + TLS 1.3 handshake RTT overhead and eliminate it with Keep-Alive connection pooling
  • Resolve HTTP/1.1 head-of-line blocking using HTTP/2 binary framing and multiplexed streams
  • Diagnose why packet loss stalls all HTTP/2 streams on TCP and how HTTP/3 (QUIC) fixes it over UDP
  • Leverage QUIC 0-RTT resumption and Connection ID migration for seamless mobile Wi-Fi-to-5G handoffs

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
HTTP/1.1 + Keep-AliveLegacy proxies and simple internal REST servicesApp-layer HOL blocking; browsers open 6 parallel TCP sockets per host
HTTP/2 (over TCP)Multiplexed APIs, gRPC, and clean wired broadband trafficSingle dropped TCP packet stalls every multiplexed stream together
HTTP/3 (QUIC / UDP)Mobile apps, global edges, and lossy cellular/Wi-Fi networksSlightly higher CPU encryption cost; some corporate firewalls block UDP 443
Edge TLS TerminationCutting handshake RTT from 180 ms to 20 ms worldwideRequires trusted edge PoPs + persistent origin connection pools
Rule of thumb:Terminate HTTP/3 + HTTP/2 at nearby Edge PoPs with TLS 1.3, keep warm HTTP/2 pools to origins, and restrict 0-RTT strictly to idempotent GETs.
System Design · 02. Scaling · Beginner · 11 steps

Vertical vs Horizontal Scaling

Open lesson

KEY TAKEAWAYS

  • Recognize where vertical scaling shines and where hardware ceilings and reboot downtime bite
  • Externalize session state into Redis so horizontal fleets scale cleanly behind a load balancer
  • Match fleet capacity to diurnal night dips and flash peaks without paying for idle iron
  • Combine horizontal stateless compute with pragmatically scaled stateful databases

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Vertical Scaling (Scale Up)Early-stage apps, primary SQL databases, and single-node workloads avoiding distributed complexityHard hardware ceiling, steep non-linear cost curve, reboot downtime, and single-point-of-failure risk
Horizontal Scaling (Scale Out)Stateless web/API tiers, high availability (N+1 fault tolerance), and elastic cloud cost controlRequires a load balancer, externalized session state, and distributed observability
Externalized Session Store (Redis)Keeping application nodes interchangeable so any server can handle any user requestAdds a ~1–2 ms network hop and makes Redis availability critical for login sessions
Hybrid Tiered ScalingProduction architectures: scale stateless app fleets horizontally and primary DBs vertically firstDemands clear boundaries between stateless compute and stateful persistence tiers
Rule of thumb:Interview rule of thumb: scale stateless services horizontally (min 2 AZs), scale relational writes vertically + read replicas until you genuinely outgrow the largest node.
System Design · 02. Scaling · Beginner · 12 steps

Load Balancing

Open lesson

KEY TAKEAWAYS

  • Spread traffic evenly across multiple servers with a load balancer
  • Choose between round robin and least connections under uneven workloads
  • Eliminate single points of failure with health checks and standby failover
  • Route by URL path (L7) and drain connections cleanly during deploys

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Round Robin / Weighted RRHomogeneous stateless APIs with fast, uniform request costsBlind to slow heavy requests—one host can build a deep local queue
Least ConnectionsMixed workloads (8 ms JSON + 3 s PDF exports) or uneven host speedsRequires tracking in-flight connections per backend inside the balancer
Layer 7 Path RoutingTerminating TLS and splitting /api, /media, and /checkout pools cleanlySlightly higher CPU cost than L4 TCP passthrough because HTTP is parsed
Active-Passive VIP + DrainingEliminating balancer SPOFs (1–3 s failover) and zero-502 rolling deploysNeeds VRRP/Keepalived heartbeats and a bounded drain timeout (e.g. 30 s)
Rule of thumb:Rule of thumb: start with managed L7 load balancers using Least Connections, shallow /health probes, and 30s connection draining.
System Design · 02. Scaling · Beginner · 11 steps

Caching Strategies

Open lesson

KEY TAKEAWAYS

  • Shield read-heavy databases with Cache-Aside and calculate effective hit-rate latency
  • Compare Write-Through consistency against Write-Back throughput and durability risks
  • Tune LRU/LFU eviction and TTL windows to balance memory usage against stale reads
  • Stop thundering-herd stampedes using Singleflight coalescing, TTL jitter, and L1/L2 tiers

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Cache-Aside (Lazy)Read-heavy feeds, product pages, user profilesFirst read misses; brief staleness if invalidation lags
Write-ThroughSession stores, config flags, strong read freshnessHigher write latency; caches keys that may never be read
Write-Back (Behind)Like counters, telemetry bursts, write-heavy analyticsRisk of data loss if cache crashes before async DB flush
L1 + L2 + SingleflightViral hot keys and global high-RPS API fleetsExtra coordination complexity and tiny per-node L1 drift
Rule of thumb:Default to Cache-Aside + Singleflight + Jittered TTLs; use Write-Through when staleness is unacceptable and Write-Back only when losing a few seconds of counters is safe.
System Design · 02. Scaling · Beginner · 10 steps

Content Delivery Networks

Open lesson

KEY TAKEAWAYS

  • Slash cross-ocean latency by serving static and cacheable assets from regional Edge PoPs
  • Prevent multi-PoP cache-miss storms from crushing origin using an Origin Shield tier
  • Update assets safely using content-hashed immutable URLs and stale-while-revalidate headers
  • Choose between Pull CDNs, Push CDNs, and edge compute for dynamic personalization

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Pull CDN (Cache-on-First-Miss)Web assets, images, JS/CSS bundles, and public API responses with Zipfian hot popularityFirst visitor in each PoP pays a cold-miss round-trip to origin until cached
Push CDN (Pre-Warm Edge)Large software releases, video premieres, and rarely updated static media packagesConsumes edge storage even for unpopular files and complicates deployment pipelines
Origin Shield (Mid-Tier Cache)Global fleets with 50+ PoPs where simultaneous TTL expiries would hammer origin 50×Adds one small (~10 ms) intermediate hop on a true cold miss in exchange for 95%+ origin offload
Content-Hashed URLs + Long TTLImmutable JS/CSS/images (`app.9f3a2c.js`) with `max-age=31536000, immutable`Requires build-pipeline asset fingerprinting; HTML shell must still stay short-TTL
Rule of thumb:Checklist: Anycast PoPs + Origin Shield + content-hashed immutable assets + s-maxage/SWR headers + WAF at the edge.
System Design · 02. Scaling · Intermediate · 10 steps

Autoscaling & Traffic Spikes

Open lesson

KEY TAKEAWAYS

  • Diagnose why reactive CPU autoscaling fails during vertical 30-second flash spikes
  • Prevent oscillation thrashing using queue-depth/RPS triggers and asymmetric cooldowns
  • Eliminate startup lag with pre-initialized Warm Pools and scheduled predictive pre-scaling
  • Protect core checkout availability during unpredicted 10× bursts via priority load shedding

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Target-Tracking Reactive AutoscaleSmooth diurnal morning ramps (5–20 minute climb) using RPS or in-flight request signalsAlways lags behind sudden step-function spikes by metric window + container/VM boot time
Warm Standby Pool (Pre-Initialized)Unpredictable viral bursts needing extra capacity online in 5–15 seconds instead of 3 minutesPays modest memory/disk reservation fee for stopped-but-hydrated instances
Predictive / Scheduled Pre-ScalingKnown events (9 AM market open, push notifications, concert ticket drops, TV ads)Requires calendar/ML discipline—cannot predict surprise viral social media mentions
Priority Load Shedding (Fast 503)Capping concurrency so checkout/payments stay 100% healthy while low-priority traffic sheds fastDeliberately rejects non-critical requests instead of letting queues blow up P99 for everyone
Rule of thumb:Rule of thumb: scale OUT fast on RPS/queue depth, scale IN slowly (10 min cooldown), keep a Warm Pool, and always set maxInstances + priority shedding.
System Design · 03. Data & Storage · Beginner · 10 steps

SQL vs NoSQL

Open lesson

KEY TAKEAWAYS

  • Recognize when normalized SQL tables, foreign keys, and ACID joins beat every alternative
  • Model flexible, aggregate-oriented records cleanly in document stores without multi-table joins
  • Design partition-key-first wide-column tables for massive write-heavy time or feed streams
  • Combine relational, document, key-value, and search stores cleanly in a polyglot production stack

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Relational SQL (PostgreSQL / MySQL)Financial ledgers, orders, inventory, and relational data needing ACID transactions and ad-hoc JOINsSchema migrations need care and horizontal write sharding adds operational complexity
Document Store (MongoDB / DynamoDB JSON)Product catalogs, CMS profiles, and self-contained aggregates with varying attributes per itemCross-document joins are slow and duplicated nested fields require fan-out updates
Wide-Column (Cassandra / ScyllaDB)High-throughput append-heavy logs, chat history, and IoT events queried strictly by partition keyNo arbitrary JOINs; you must design tables backward from known query patterns
Polyglot PersistenceProduction platforms: SQL for billing/orders, Document for catalog, Redis for sessions/hot readsAdds CDC/event synchronization and more database engines for teams to operate
Rule of thumb:Interview winning heuristic: "Start with PostgreSQL for ACID + relational clarity; introduce Redis, Document, or Wide-Column stores only where specific access patterns demand them."
System Design · 03. Data & Storage · Intermediate · 10 steps

Indexing & B-Trees

Open lesson

KEY TAKEAWAYS

  • Trace how high-fanout B+ Trees locate any row among 100M records in 3–4 disk page reads
  • Order composite index columns cleanly using the leftmost-prefix and equality-before-range rules
  • Eliminate random heap table lookups entirely using covering (index-only) scans
  • Balance read speedup against write amplification, low-cardinality traps, and partial indexes

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
B+ Tree Secondary IndexPoint lookups (`=`) and range scans (`BETWEEN`, `ORDER BY`) across millions of rows in O(log N)Every INSERT/UPDATE/DELETE must update the tree and handle occasional 8 KB page splits
Composite Index (Equality → Range)Multi-column filters like `WHERE tenant_id = ? AND created_at > ?` using leftmost-prefix orderQuerying only the second column (`created_at`) skips the index unless it has its own index
Covering Index (`INCLUDE`)Hot read queries answered 100% from index leaf pages without touching the main heap tableWider leaf entries reduce tree fan-out and increase RAM/SSD footprint
Partial Index (`WHERE status = ...`)Indexing only the tiny active slice (e.g., 2% pending orders) instead of 98% archived rowsPlanner only uses the partial index when the query’s `WHERE` predicate matches the index filter
Rule of thumb:Never guess whether an index helps—run `EXPLAIN (ANALYZE, BUFFERS)` and check actual shared page hits vs reads.
System Design · 03. Data & Storage · Intermediate · 10 steps

Storage Engines

Open lesson

KEY TAKEAWAYS

  • Explain how Write-Ahead Logs (WAL) and fsync guarantee crash recovery without random disk writes on commit
  • Contrast in-place B-Tree page mutations against append-only LSM-Tree Memtable + SSTable flushes
  • Eliminate wasted SSTable disk reads across LSM levels using in-memory Bloom Filters
  • Navigate compaction strategies and the Read, Write, and Space Amplification triangle

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Write-Ahead Log (WAL + fsync)Guaranteeing crash durability on every committed write via fast sequential appendsGroup-commit batching is needed so per-commit `fsync` doesn’t bottleneck throughput
B-Tree Engine (PostgreSQL / InnoDB)Read-heavy OLTP workloads needing predictable p99 latency and single-location key lookupsRandom in-place 8 KB page rewrites cause high write amplification under heavy ingestion
LSM-Tree Engine (RocksDB / Cassandra)Write-heavy streams converting random mutations into sequential Memtable → SSTable flushesBackground compaction steals disk bandwidth and can cause tail-latency write stalls
Bloom FiltersAnswering "definitely not in this SSTable" in RAM before issuing a wasted SSD readSmall tunable false-positive rate (typically 1%) and ~10 bits of RAM per stored key
Rule of thumb:Understanding WAL, Memtables, SSTables, Bloom Filters, and Compaction unlocks how PostgreSQL, MySQL, RocksDB, Cassandra, and Kafka actually achieve speed and durability.
System Design · 03. Data & Storage · Beginner · 10 steps

Replication

Open lesson

KEY TAKEAWAYS

  • Offload read-heavy queries from a saturated Primary Leader onto Follower Read Replicas
  • Navigate the speed-vs-durability trade-off between Async, Sync, and Semi-Sync WAL replication
  • Fix replication-lag stale reads with Read-Your-Writes routing and LSN watermarks
  • Promote a standby leader cleanly while preventing split-brain data corruption with fencing tokens

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Async ReplicationRead scaling across regions with low write latencyRecent committed writes can be lost if Leader dies suddenly (RPO > 0)
Semi-Sync (1 Sync + N Async)Production OLTP databases balancing RPO=0 and speedOne extra network RTT on commits; stalls briefly if sync standby drops
Read-Your-Writes (LSN)User profiles, comments, and post-checkout order pagesRouting logic must track recent writer timestamps or LSN watermarks
Fencing Tokens / EpochsAutomated leader failover under network partitionsStorage layer must reject writes carrying stale epoch numbers
Rule of thumb:Use Semi-Sync for durability, Async Replicas for read scale, LSN watermarks for Read-Your-Writes, and Epoch Fencing for safe failovers.
System Design · 03. Data & Storage · Intermediate · 10 steps

Transactions & ACID

Open lesson

KEY TAKEAWAYS

  • Enforce atomic all-or-nothing multi-row updates with WAL rollback when crashes strike mid-transfer
  • Explain how Multi-Version Concurrency Control (MVCC) lets readers never block writers and writers never block readers
  • Eliminate lost-update race conditions using atomic increments, `SELECT FOR UPDATE`, or Optimistic Locking
  • Recognize subtle Write Skew under Snapshot Isolation and stop it with Serializable (SSI) or row locks

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Read Committed (Postgres Default)Standard CRUD apps where preventing dirty reads and dirty writes is sufficientStill vulnerable to non-repeatable reads, lost updates, and write skew
Snapshot Isolation / Repeatable Read (MVCC)Consistent multi-query reports, backups, and read-heavy dashboards without blocking writersAllows Write Skew when two transactions read overlapping conditions and write disjoint rows
Optimistic Concurrency (`version = v`)Low-contention edits (profiles, carts) where holding DB row locks across user think time is badHigh contention causes frequent CAS retry storms on hot rows
Serializable (SSI / `FOR UPDATE`)Bank transfers, seat booking, on-call schedules, and inventory invariants where zero anomalies are allowedAdds lock waits or serialization aborts requiring client retry logic
Rule of thumb:Interview cheat code: explain MVCC ("readers don’t block writers"), distinguish Lost Updates from Write Skew, and mention `40001` retries + short transactions.
System Design · 03. Data & Storage · Intermediate · 10 steps

CAP & Consistency Models

Open lesson

KEY TAKEAWAYS

  • Explain why Network Partitions (P) are unavoidable and force a strict choice between CP and AP
  • Tune Dynamo-style leaderless quorums (`R + W > N`) to balance read/write latency against staleness
  • Heal divergent replicas cleanly using Read Repair, Hinted Handoff, and Merkle-tree Anti-Entropy
  • Distinguish Linearizability, Causal Consistency, Read-Your-Writes, and Eventual Consistency

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
CP (Consistency over Availability)Distributed locks, leader election, and bank balances where split-brain writes cause corruptionMinority side of a network partition rejects writes (returns errors) until the link heals
AP (Availability over Consistency)Shopping carts, likes, DNS caches, and product catalogs where staying writable beats instant syncNodes diverge during a partition and require conflict resolution (LWW or CRDTs) afterward
Leaderless Quorums (`R + W > N`)Tunable multi-node stores (Cassandra/DynamoDB): `N=3, W=2, R=2` guarantees overlapping read/write setsSloppy quorums or clock skew can still expose brief stale reads without full linearizability
PACELC TheoremEveryday architecture decisions: even with NO partition (E), you still trade Latency (L) vs Consistency (C)Synchronous cross-region consistency adds speed-of-light RTT to every single write
Rule of thumb:Interview cheat code: always state *both* CAP (partition behavior) and PACELC (normal latency vs consistency), then show `N=3, W=2, R=2` overlap math.
System Design · 03. Data & Storage · Intermediate · 9 steps

Sharding

Open lesson

KEY TAKEAWAYS

  • Recognize when vertical scaling hits a ceiling and horizontal sharding is needed
  • Compare range-based sharding against hash-based sharding to avoid hot shards
  • Mitigate single hot keys ("celebrity partitions") with key salting
  • Handle cross-shard scatter-gather queries and resharding costs

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Range ShardingOrdered range scans (e.g. time windows or contiguous ID ranges on 1 shard)Monotonic keys (timestamps, auto-increment IDs) create a rolling hot shard
Hash Sharding (% N)Uniform write distribution across all shards for high-throughput OLTPDestroys range scan locality and reshuffles ~(N-1)/N keys on scale-out
Selective Key SaltingTaming viral single-key hot spots ("celebrity partitions") across K shardsReads for salted keys must scatter-gather and merge all K buckets
Secondary Index / Consistent RingAvoiding cross-shard scatter-gather lookups and minimizing resharding copiesAdds async index maintenance or ring-membership gossip complexity
Rule of thumb:Delay sharding until vertical scaling, indexing, caching, and read replicas are exhausted—it adds real operational complexity.
System Design · 03. Data & Storage · Intermediate · 10 steps

Consistent Hashing

Open lesson

KEY TAKEAWAYS

  • Understand why hash(key) % N invalidates ~80% of keys when cluster size changes
  • Place both servers and keys on a 0 → 2³² ring and resolve ownership clockwise
  • Use virtual nodes to smooth lopsided arcs and cut the biggest server share
  • Replicate keys to the next N distinct servers along the ring for fault tolerance

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Modulo Hashing (% N)Fixed-size static clusters that almost never add or remove nodesAdding/removing 1 node invalidates ~(N-1)/N (~80%) of cached keys at once
Basic Consistent Ring (1 pin)Conceptual routing where scaling moves only ~1/N of keysRandom 1-pin spacing leaves lopsided arcs (one node can hold 40%+ of keys)
Virtual Nodes (12–200 vnodes)Production caches & Dynamo/Cassandra clusters needing smooth load varianceSlightly larger routing table in memory (still O(log V) binary search)
Clockwise RF=3 ReplicationDurable storage rings surviving host or AZ outages with zero data lossCoordinator must skip duplicate vnodes from the same physical host/AZ
Rule of thumb:Used under the hood by Amazon Dynamo, Apache Cassandra, Discord, and modern CDN edge routing.
System Design · 03. Data & Storage · Beginner · 10 steps

Object & Blob Storage

Open lesson

KEY TAKEAWAYS

  • Bypass application servers completely for media uploads and downloads using short-lived Presigned URLs
  • Make large video uploads resumable with Multipart Uploads and content-addressed immutable object keys
  • Achieve 11 nines (99.999999999%) durability at half the storage cost of 3× replication using Erasure Coding
  • Pair Edge CDNs with automated Hot → Infrequent → Archive lifecycle tiering to slash petabyte bills

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Presigned URLs (Direct-to-S3)User avatar, photo, and video uploads/downloads without burning API server RAM or bandwidthRequires short expirations (e.g., 5 min), strict MIME/size policies, and async upload-complete webhooks
Multipart Chunked UploadFiles >5–10 MB over flaky mobile links—uploads 5 MB parts in parallel and retries only failed chunksMust run lifecycle rules to abort incomplete multipart fragments after 24 hours
Reed-Solomon Erasure Coding (e.g., 10+4)Petabyte-scale durability (11 nines) using only 1.4× storage overhead instead of 3× raw copiesSlightly higher CPU to compute parity shards during writes and rebuild failed disks
Automated Storage Lifecycle TiersTransitioning older media automatically from Standard → Infrequent Access → Glacier Cold ArchiveCold archive retrievals incur minutes-to-hours restore delay and per-GB retrieval fees
Rule of thumb:Interview cheat code: draw the triangle — Client ↔ API (tiny presigned URL + metadata) and Client ↔ S3/CDN (direct multi-megabyte data plane).
System Design · 03. Data & Storage · Intermediate · 10 steps

Search Engines

Open lesson

KEY TAKEAWAYS

  • Explain why SQL `LIKE "%term%"` cannot use B-Trees and how an Inverted Index turns scans into instant posting-list lookups
  • Trace tokenization, stemming, and BM25 scoring (TF, IDF, and field-length normalization) to rank relevant results first
  • Scale search indexes horizontally via Query-Then-Fetch scatter-gather across shards
  • Keep search clusters fresh via CDC streams, near-real-time (NRT) segment refreshes, and prefix autocomplete tries

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Inverted Index (Elasticsearch / OpenSearch)Full-text keyword search, fuzzy typo matching, faceted e-commerce filters, and relevance rankingEventual consistency (~1s refresh lag) and not suitable as your primary ACID source of truth
BM25 Relevance ScoringRanking matches by rare-term importance (IDF), saturating term frequency (TF), and short-title boostsPure lexical matching misses semantic synonyms unless paired with synonym dictionaries or vector embeddings
Query-Then-Fetch Scatter-GatherSearching multi-terabyte sharded indexes by fetching only top-K `(doc_id, score)` pairs firstDeep pagination (`OFFSET 50,000`) forces every shard to sort 50k items—use `search_after` cursors instead
CDC → Search Sync PipelineKeeping search automatically synchronized with your primary SQL database without dual-write driftAdds ~1–2 second near-real-time indexing delay before brand-new listings appear in search
Rule of thumb:Interview cheat code: always keep Search decoupled from Primary SQL via CDC—never dual-write from the app and never run `LIKE "%term%"` on production SQL.
System Design · 03. Data & Storage · Intermediate · 10 steps

Time-Series Databases

Open lesson

KEY TAKEAWAYS

  • Replace random B-Tree index thrashing and expensive `DELETE` vacuums with time-partitioned immutable chunks
  • Shrink telemetry disk footprint 12× using Delta-of-Delta timestamps and XOR float compression
  • Prevent TSDB memory explosions by keeping tag labels strictly bounded in the inverted series index
  • Serve 1-year Grafana dashboards in milliseconds using continuous downsampling rollups and hot/cold object tiering

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Time-Partitioned Chunks (2h–1d)Append-only telemetry ingestion and O(1) instant retention expiry via whole-file chunk dropsOut-of-order late backfill writes touching old closed chunks are more expensive
Gorilla Compression (Delta-of-Delta + XOR)Compressing regular 10s metric streams from 16 bytes/point down to ~1.37 bytes/point (12× smaller)Compressed bit-packed blocks are sequential to scan rather than random-row editable
Continuous Downsampling RollupsPre-aggregating raw 10s points into 1m and 1h min/max/avg/p99 summaries for instant 1-year chartsRaw per-second granularity is discarded after the short hot window (e.g., 14 days)
Low-Cardinality Tag HygieneKeeping TSDB in-memory series indexes lean (`service`, `region`, `status`) instead of unbounded `user_id`High-cardinality entity IDs must be stored in structured logs or wide-column stores instead
Rule of thumb:Interview cheat code: mention four pillars — Time Chunks (O(1) drops), Gorilla 12× compression, Low-Cardinality tags, and Downsampling Rollups + S3 tiering.
System Design · 04. Communication · Beginner · 10 steps

REST, GraphQL & gRPC

Open lesson

KEY TAKEAWAYS

  • Leverage REST resource URLs and HTTP GET semantics for effortless CDN caching
  • Eliminate mobile waterfall round-trips with GraphQL while guarding against resolver N+1 storms
  • Cut internal microservice latency and CPU serialization overhead using gRPC, Protobuf, and HTTP/2
  • Combine REST/GraphQL at the public edge with gRPC inside the private service mesh

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
REST (HTTP/JSON)Public developer APIs, CRUD resources, and read-heavy endpoints that benefit from CDN HTTP GET cachingFixed response shapes cause overfetching or multi-request waterfalls on mobile screens
GraphQL (Query Graph + DataLoader)Mobile & web BFF layers stitching multiple domain services into one tailored client queryPOST-by-default breaks CDN caching unless using Persisted Queries; naïve resolvers trigger N+1 DB storms
gRPC (HTTP/2 + Protobuf)Low-latency internal service-to-service RPC, strict typed contracts, and bidirectional streamingBinary payloads are not human-readable in curl and browsers need a gRPC-Web proxy
Edge-to-Core Protocol StackProduction architectures: REST/GraphQL facing browsers & mobile, gRPC between internal microservicesRequires schema governance and gateway translation between external JSON and internal Protobuf
Rule of thumb:Interview cheat code: say "REST or GraphQL at the client boundary for compatibility and aggregation, translated to gRPC over HTTP/2 inside the VPC."
System Design · 04. Communication · Beginner · 11 steps

Message Queues

Open lesson

KEY TAKEAWAYS

  • Decouple bursty producers from slow downstream services with queues and competing consumers
  • Protect memory and critical flows using bounded queue capacities, backpressure, and priority lanes
  • Handle at-least-once redeliveries and visibility timeouts safely with idempotency keys
  • Quarantine poison pills in a Dead-Letter Queue (DLQ) and guarantee atomic publishing via Transactional Outbox

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Competing ConsumersParallelizing slow emails, video transcodes, webhooksStrict global FIFO ordering is lost across parallel workers
Bounded BackpressurePreventing broker OOM crashes during sustained floodsCallers must handle 429/503 retries or shed low-priority work
Idempotency KeysPayments, order creation, inventory deductions on retryRequires dedup key storage (Redis/DB unique index) + TTL
DLQ + Outbox PatternZero lost events and zero infinite poison-pill crash loopsNeeds DLQ alerting/replay tooling and an outbox relay worker
Rule of thumb:Decouple spikes with bounded queues, design every consumer to be idempotent, and always route repeated failures to a monitored DLQ.
System Design · 04. Communication · Intermediate · 10 steps

Event Streaming & Logs

Open lesson

KEY TAKEAWAYS

  • Distinguish destructive point-to-point queues from immutable append-only commit logs
  • Scale throughput with keyed partitions and understand the 1-partition-per-consumer-group rule
  • Diagnose hot-partition skew and consumer lag before retention windows expire
  • Use offset rewinding, time retention, and log compaction to recover from bugs and feed downstream systems

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Append-Only Commit Log (Kafka)Fanning out one immutable event stream to many independent downstream consumers (Billing, Analytics, Search)Brokers must manage disk retention, replication, and partition leadership
Keyed Partitions + Consumer GroupsHorizontal throughput while preserving strict message ordering per entity key (e.g., `order_id`)Max parallelism per consumer group equals partition count; skewed keys create hot partitions
Offset Replay (Time Travel)Recovering from a downstream consumer bug or bootstrapping a brand-new Search index from historical eventsConsumers must be idempotent because replaying offsets re-delivers previously processed events
Log CompactionChangelog topics (user profiles, config state) where you only need the latest value per key foreverLoses intermediate historical mutations once background compaction cleans older segments
Rule of thumb:Pick a Queue (SQS/RabbitMQ) for simple competing background jobs; pick an Event Log (Kafka) for multi-team fan-out, ordered streams, and offset replay.
System Design · 04. Communication · Intermediate · 10 steps

WebSockets & Real-Time

Open lesson

KEY TAKEAWAYS

  • Choose cleanly between Short Polling, Long Polling, Server-Sent Events (SSE), and WebSockets
  • Scale stateful WebSocket gateways horizontally using a Redis Pub/Sub message backplane
  • Detect half-open mobile connections accurately with application ping/pong heartbeats and TTL presence
  • Prevent reconnect thundering herds and slow-consumer OOM crashes using jittered backoff and bounded queues

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Short / Long PollingLow-frequency status checks (e.g., async export job every 10s) where plain stateless HTTP is simplestWastes up to 95% of requests on empty responses and adds polling delay + HTTP header overhead
Server-Sent Events (SSE)Server → Client only streams: live stock tickers, notifications, news feeds, and LLM token streamingUnidirectional (client sends via normal HTTP POST) and UTF-8 text frames only
WebSockets + Redis Pub/SubTrue bidirectional sub-50ms interactivity: live chat, multiplayer games, and collaborative cursorsStateful TCP connections complicate deploys, load balancing, and require a cross-node Pub/Sub backplane
Jittered Exponential BackoffReconnecting tens of thousands of dropped sockets safely after a WebSocket gateway crashes or deploysAdds a few randomized seconds before the last clients finish re-establishing their sockets
Rule of thumb:Production real-time systems always pair live WebSockets (for instant push) with a REST catch-up endpoint (for offline & reconnect sync).
System Design · 05. Reliability · Beginner · 11 steps

Rate Limiting

Open lesson

KEY TAKEAWAYS

  • Choose between Fixed Window, Sliding Window, Token Bucket, and Leaky Bucket algorithms
  • Enforce accurate distributed quotas across multiple gateways using atomic Redis Lua scripts
  • Shape client traffic cleanly with HTTP 429 Retry-After headers, jittered backoff, and tiered quotas
  • Decide consciously between Fail-Open and Fail-Closed behavior when the rate-limit store fails

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Token BucketGeneral public APIs allowing short user burstsTwo parameters (burst + refill); bursts still reach backend briefly
Leaky BucketStrict smooth outflow into fragile downstream partnersQueues bursts and adds latency; recent traffic waits behind old queue
Sliding Window CounterMemory-efficient fairness without boundary 2× spikesSlight approximation using weighted previous-window overlap
Redis Atomic LuaConsistent global quotas across horizontally scaled gatewaysAdds 1–2 ms Redis RTT; requires explicit Fail-Open/Closed policy
Rule of thumb:Enforce per-tenant Token Buckets via Redis Lua, communicate 429 + Retry-After clearly, and add a local in-memory fallback so Redis blips never take down your API.
System Design · 05. Reliability · Intermediate · 10 steps

Circuit Breakers & Retries

Open lesson

KEY TAKEAWAYS

  • Recognize how naive immediate retries multiply load 3×–10× and trigger cascading outages
  • Tame retry waves using Exponential Backoff + Full Jitter and fleet-wide Retry Budgets
  • Protect struggling dependencies using Closed, Open, and Half-Open Circuit Breakers with graceful fallbacks
  • Contain slow downstream dependencies inside isolated Bulkhead thread/connection pools

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Backoff + Full JitterTransient network blips and temporary 503 throttlingStill sends load during prolonged outages if uncapped
Retry Budget (≤ 10%)Multi-hop microservice chains preventing exponential amplificationNeeds sliding-window tracking of retries vs original requests
Circuit Breaker (3-State)Failing fast (< 2 ms) when a downstream dependency is downRequires tuned failure thresholds and meaningful fallback behavior
Bulkhead IsolationStopping one slow non-critical service from starving checkout threadsPartitioned pools reduce peak sharing efficiency across endpoints
Rule of thumb:Use strict timeouts + deadlines, cap fleet retries to ≤ 10% with Full Jitter, bulkhead non-critical pools, and trip Circuit Breakers to cached fallbacks.
System Design · 05. Reliability · Intermediate · 11 steps

Distributed Consensus

Open lesson

KEY TAKEAWAYS

  • Understand why majority quorums (⌊N/2⌋ + 1) guarantee any two majorities overlap by at least one node
  • Trace Raft terms, heartbeat timeouts, randomized election timers, and leader election without split votes
  • Follow Raft two-phase log replication: append to followers, wait for majority ACK, then commit
  • Prove how Raft prevents split-brain during network partitions and size clusters (3 vs 5 nodes) wisely

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
3-Node Raft QuorumMetadata stores (etcd, Consul) tolerating 1 node crashLosing 2 nodes halts writes; maintenance + crash simultaneously fails
5-Node Raft QuorumProduction control planes surviving 1 planned reboot + 1 crashLeader replicates to 4 peers; slightly higher network fan-out
Randomized TimersBreaking split-vote ties rapidly (150–300 ms election timeout)Brief ~200–500 ms write pause while a new term leader elects
Lease / ReadIndexServing linearizable reads from the Leader without disk log writesMinority stale leader must confirm quorum heartbeat before answering
Rule of thumb:Use proven 5-node Raft stores (etcd/Consul/CockroachDB) for coordination state—never roll your own leader election over raw heartbeats.
System Design · 05. Reliability · Beginner · 9 steps

Observability & Alerting

Open lesson

KEY TAKEAWAYS

  • Monitor every service with the Four Golden Signals: Latency, Traffic, Errors, and Saturation
  • Correlate structured logs and distributed trace spans across microservices using a Trace ID
  • Define customer-centric SLIs, SLOs, and Error Budgets instead of paging on noisy raw CPU spikes
  • Eliminate alert fatigue with multi-window SLO burn-rate alerts and decoupled telemetry collectors

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Metrics (Golden Signals)Cheap real-time dashboards, P99 histograms, and SLO alertingExplodes memory if you put unbounded high-cardinality user_id labels in metrics
Structured Logs (JSON)Detailed error payloads and forensic debugging for specific failuresExpensive to index at 100% volume—sample debug logs in prod
Distributed TracesPinpointing which single hop caused a slow microservice requestRequires propagating W3C traceparent headers across HTTP/queues + tail sampling
SLO Burn-Rate AlertsPaging on-call ONLY when real users are losing error budget fastRequires defining accurate SLIs before turning off legacy CPU pages
Rule of thumb:Decouple telemetry export asynchronously, keep metric labels low-cardinality, tail-sample noisy 200 OK spans, and page exclusively on user-impacting SLO burn.
System Design · 06. Architecture · Beginner · 10 steps

Monoliths vs Microservices

Open lesson

KEY TAKEAWAYS

  • Recognize why a well-structured modular monolith beats premature microservices on latency and simplicity
  • Identify true microservice triggers: independent scaling profiles, blast-radius isolation, and org-wide deploy contention
  • Extract services incrementally with the Strangler Fig pattern instead of risky big-bang rewrites
  • Budget for the hidden microservice tax: network serialization, tail latency amplification, and distributed tracing

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Modular MonolithEarly-to-mid stage teams (1–40 devs) needing sub-ms in-process calls, ACID joins, and fast refactorsAll modules share one deploy pipeline, runtime memory, and scaling unit
MicroservicesLarge orgs (50+ devs) with independent scaling needs (e.g., GPU ML vs CRUD) and strict team autonomyIntroduces network latency, partial failures, distributed transactions, and DevOps overhead
Strangler Fig PatternSafely migrating legacy monolith routes one domain at a time behind an edge routing proxyTemporarily operates dual systems and data sync bridges during transition
Distributed Monolith (Anti-Pattern)Avoid! Happens when microservices share one database or require lockstep deploymentsWorst of both worlds: microservice network latency with monolith coupling
Rule of thumb:Decision Rule: earn your microservices. Modular Monolith first → Strangler Fig extraction → Private DBs → Parallel/Async hops + OTel Tracing.
System Design · 06. Architecture · Beginner · 10 steps

API Gateways

Open lesson

KEY TAKEAWAYS

  • Eliminate duplicated auth, TLS, CORS, and rate-limiting code across services with a single L7 API Gateway
  • Design Backend-for-Frontend (BFF) gateways tailored for mobile vs desktop payloads without chatty round trips
  • Protect origins using token-bucket rate limits, request coalescing (singleflight), and circuit breakers at the gateway
  • Keep the gateway thin (no business logic) and horizontally redundant across availability zones

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
L7 API Gateway (Kong / Envoy / AWS APIGW)Centralizing TLS, JWT validation, per-tenant rate limits, path routing, and access logs at the edgeBecomes a critical blast radius if overloaded with domain logic or deployed without multi-AZ HA
Backend for Frontend (BFF)Shaping lean mobile JSON vs rich web dashboards from multiple microservices in 1 client round tripAdds one BFF codebase per client surface (iOS/Android vs Web vs Partner API)
Request Coalescing (Singleflight)Collapsing 5,000 identical concurrent cache-miss requests for a hot product into 1 upstream callApplies strictly to idempotent GET requests and requires careful timeout sharing
Thin Gateway PrincipleKeeping routing, auth, and throttling fast in C++/Rust/Go proxies while leaving domain rules in servicesComplex cross-service workflows belong in dedicated orchestrators, never gateway plugins
Rule of thumb:Gateway Checklist: Multi-AZ HA · TLS 1.3 · Local JWKS Auth + Header Strip · Redis Token Bucket · Singleflight Coalescing · BFF Aggregation · Per-Route Bulkheads.
System Design · 06. Architecture · Intermediate · 10 steps

Event-Driven Systems

Open lesson

KEY TAKEAWAYS

  • Eliminate dual-write event loss by combining state changes and Outbox events inside one local ACID transaction
  • Compare Event Choreography vs Saga Orchestration for multi-service checkout workflows without 2PC locks
  • Undo partial distributed commits cleanly using compensating transactions (refund, release stock) on failure
  • Defend consumers against duplicate deliveries, out-of-order events, and poison pills using Inbox deduplication and DLQs

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Transactional Outbox + CDCGuaranteeing that every committed SQL row publishes its domain event to Kafka with zero dual-write lossRequires a CDC relay (Debezium) and idempotent consumers for at-least-once delivery
Event ChoreographySimple 2–3 service flows where services react autonomously to domain events without a central bossHard to trace or debug once 6+ services form implicit event cycles ("pinball architecture")
Saga Orchestrator (Temporal / Step Functions)Complex multi-step workflows (Order → Pay → Reserve → Ship) needing explicit state & compensating rollbacksAdds a durable workflow engine to run, though it keeps domain services simple
Idempotent Inbox + DLQSafely absorbing Kafka/SQS redeliveries and isolating malformed poison messages without stalling partitionsStores `processed_event_id` keys for the deduplication window and needs DLQ replay ops
Rule of thumb:Event-Driven Mastery: Outbox + CDC → Schema Registry → Orchestrated Sagas + Compensations → Partition Ordering + Idempotent Inbox + DLQ.
System Design · 06. Architecture · Intermediate · 10 steps

Multi-Region Active-Active

Open lesson

KEY TAKEAWAYS

  • Quantify speed-of-light WAN penalties and compare Active-Passive vs Active-Active RPO and RTO budgets
  • Route global users to their nearest healthy region via GeoDNS / Anycast with fast automated health failover
  • Resolve concurrent multi-region writes cleanly via home-region pinning, LWW timestamps, or CRDTs
  • Enforce GDPR data residency boundaries and validate failover readiness with live regional evacuation drills

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Active-Passive (Warm Standby)Disaster recovery where 1–5 min RTO is acceptable and you want simple single-leader SQL consistencyStandby region sits partially idle and remote continents still pay 150–250 ms cross-ocean RTT
Active-Active + Home-Region PinningGlobal SaaS & banking needing local speed, GDPR data residency, and zero write conflicts per userUsers traveling across continents experience slightly higher latency back to their home region
Active-Active + CRDT / Multi-MasterShopping carts, collaborative docs, and counters requiring < 30 ms local writes everywhere + instant failoverComplex conflict semantics; unsuitable for strict zero-oversell financial account debits
Global Spanner / CockroachDB ConsensusStrongly consistent global transactions (external consistency) across continents with RPO = 0Every commit pays cross-region WAN quorum RTT (~80–160 ms)
Rule of thumb:Multi-Region Playbook: Anycast < 15s failover · Self-contained regions · Home-Region Pinning (GDPR) + CRDTs (carts) + Global Raft (RPO=0 ledgers) · Monthly Chaos Drills.
System Design · 07. Security · Beginner · 10 steps

Authentication

Open lesson

KEY TAKEAWAYS

  • Protect stored passwords with per-user salts and memory-hard Argon2id hashing
  • Weigh stateful Redis session cookies against stateless JWTs and rotating refresh tokens
  • Delegate login safely via OAuth 2.0 + OIDC PKCE and phishing-resistant Passkeys
  • Defend login endpoints against botnet credential stuffing with layered rate limits

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Argon2id + 128-bit SaltStoring user passwords in your own credential databaseIntentionally uses ~64 MB RAM & 150–250 ms CPU per login to defeat GPU cracking
Opaque Session Cookie (Redis)Web apps requiring instant logout, device revocation, and minimal token sizeRequires a fast ~1 ms Redis lookup per authenticated request
Short JWT (15m) + Rotating RefreshMicroservices & mobile apps verifying identity locally via cached JWKSAccess tokens stay valid until expiry; refresh rotation requires reuse detection
Passkeys (WebAuthn) + OIDC PKCEEliminating password reuse and phishing across consumer and enterprise appsRequires account recovery flows when users lose all synced devices
Rule of thumb:Default rule of thumb: browser apps → HttpOnly Redis Session Cookie; multi-service / mobile APIs → 15-min Access JWT + Rotating Refresh Token + Passkey/OIDC.
System Design · 07. Security · Intermediate · 10 steps

Authorization & RBAC

Open lesson

KEY TAKEAWAYS

  • Separate Authentication from Authorization and prevent Broken Object-Level Authorization (IDOR)
  • Model clean RBAC hierarchies and adopt ABAC + Policy-as-Code sidecars when roles explode
  • Scale fine-grained document sharing using Google Zanzibar ReBAC tuple graphs and Leopard indexes
  • Enforce defense-in-depth multi-tenant isolation with Row-Level Security and Least Privilege

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
RBAC (Role-Based)Admin dashboards, B2B org tiers (Viewer / Editor / Admin) with coarse permissionsCauses role explosion when rules depend on resource owner, region, or time
ABAC (OPA / Cedar Sidecar)Compliance rules combining user attributes, resource tags, region, and request contextHarder to answer "who can access document X?" without scanning policies
ReBAC (Google Zanzibar)Google Docs, GitHub repos, Slack channels with nested folders, teams, and per-object sharesRequires a dedicated low-latency tuple store + cache invalidation (Zookies)
Database Row-Level SecurityMulti-tenant SaaS defense-in-depth guaranteeing tenant A can never query tenant B rowsAdds query planner overhead if `tenant_id` is missing from composite indexes
Rule of thumb:Default Deny everywhere: if an AuthZ engine times out or a policy returns undefined, fail closed with `403 Forbidden`—never fail open!
System Design · 07. Security · Beginner · 10 steps

Encryption & TLS

Open lesson

KEY TAKEAWAYS

  • Trace how TLS 1.3 pairs ECDHE key exchange with AES-GCM for 1-RTT Forward Secrecy
  • Compare edge TLS termination against Zero-Trust service-to-service Mutual TLS (mTLS)
  • Protect database PII with KMS Envelope Encryption (DEK + KEK) and local DEK caching
  • Rotate encryption keys and X.509 certificates automatically with zero downtime

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
TLS 1.3 (ECDHE + AES-256-GCM)All public internet traffic between browsers/mobile apps and edge load balancersRequires automated ACME cert renewal to prevent sudden expiry outages
Zero-Trust mTLS (SPIFFE)Internal microservice-to-microservice traffic inside cloud VPCs and KubernetesRequires a service mesh or sidecar proxy to rotate short-lived client certs automatically
Disk Encryption at RestCompliance baseline protecting stolen physical drives or EBS volume snapshotsTransparent to the DB—does NOT stop SQL injection or compromised DBA accounts
KMS Envelope Encryption + CacheApplication-level encryption of SSNs, payment tokens, and tenant secretsEncrypted columns cannot use normal B-Tree range queries (need blind HMAC indexes)
Rule of thumb:Encrypt in transit (TLS 1.3 + mTLS), encrypt at rest (Disk + Envelope PII), keep master keys inside HSMs, and automate every rotation.
System Design · 08. Shipping · Beginner · 10 steps

CI/CD & Deployments

Open lesson

KEY TAKEAWAYS

  • Eliminate snowflake server drift with automated CI gates and immutable signed artifacts
  • Ship zero-downtime releases using rolling connection draining and Blue-Green cutovers
  • Evolve live production database schemas safely with the Expand-and-Contract pattern
  • Track DORA engineering metrics and achieve sub-minute MTTR via instant artifact rollback

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Rolling DeploymentCost-efficient stateless fleets replacing pods gradually (25% surge / 0 unavailable)Old and new app versions run concurrently; rollback requires another rolling wave
Blue-Green DeploymentMission-critical APIs needing instant 1-second cutover and <10-second rollbackRequires temporary 2× compute capacity while Blue stays warm beside Green
Expand-and-Contract DBRenaming or splitting live production SQL columns without breaking running codeSplits one schema change into 3 small sequential PRs (Expand → Backfill → Contract)
Immutable Signed DigestGuaranteeing Staging and Production run the exact bit-for-bit verified containerEnvironment differences must be injected strictly via runtime config/secrets, never rebuilds
Rule of thumb:If deploying on a Friday afternoon feels scary, fix your pipeline—not your calendar!
System Design · 08. Shipping · Beginner · 10 steps

Feature Flags & Canaries

Open lesson

KEY TAKEAWAYS

  • Decouple code deployment from user-facing feature release using Feature Flags and targeted rings
  • Evaluate flags in <0.1 ms locally via streaming SDK caches with safe fallback defaults
  • Contain blast radius with 1%→10%→50% Canary splits, Automated Canary Analysis, and instant kill switches
  • Validate v2 silently with shadow traffic mirroring while pruning stale flags to prevent tech debt

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Local Streaming Flag SDKToggling features per user/cohort at 100k+ rps with <0.1 ms latency and zero network hopsRequires safe hardcoded fallback defaults if the control plane is unreachable at boot
Sticky Hash Rollout RingGradually exposing a feature (1% → 10% → 50%) while keeping each user’s experience consistentRequires deterministic `hash(flagKey + userId) % 100` so users never flicker ON/OFF
Canary + Automated AnalysisShipping risky infrastructure or runtime binary changes to 1% of live traffic firstNeeds enough canary traffic volume for statistically valid P95 and 5xx comparisons
Shadow / Dark Launch TrafficLoad-testing a brand-new search or pricing engine on 100% real production reads risk-freeMust strip or sandbox side effects so mirrored requests never double-charge or send emails
Rule of thumb:You’ve completed the entire Shipping pipeline—from Git PR and Immutable Digests to Blue-Green, Canaries, Shadow Launches, and Feature Flag Kill Switches!
System Design · 09. Whole Systems · Beginner · 10 steps

HLD & LLD

Open lesson

KEY TAKEAWAYS

  • Separate functional requirements from non-functional SLAs and convert daily traffic into read/write QPS
  • Design clean High-Level Design service tiers, private data ownership, and async decoupling
  • Zoom inside a service to structure controllers, domain services, state machines, and repository interfaces
  • Connect LLD guards (idempotency keys, Strategy plug-ins, Transactional Outbox) back to HLD resilience

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
High-Level Design (HLD)Macro topology: traffic math, bounded services, caching, queues, and fault isolation across networksHides class coupling, edge-case race conditions, and domain state invariants
Low-Level Design (LLD)Inside one service: layered interfaces, entities, state machines, and unit-testable business rulesCannot rescue a flawed HLD bottleneck, missing cache, or unsharded hot database
Finite State Machine (FSM)Orders, payments, rides, and bookings where out-of-order webhooks could corrupt lifecycle stateRequires explicit transition-table updates and migrations when adding new workflow states
Strategy + Transactional OutboxSwappable payment rails (Open/Closed) and atomic DB-plus-event publishing without dual-write lossAdds thin interface indirection and an outbox relay poller to operate
Rule of thumb:Two-Altitude Checklist: HLD (SLAs, QPS math, bounded services, cache, async queues) + LLD (Hexagonal layers, FSM, Idempotency-Key + CAS, Strategy, Outbox).
System Design · 09. Whole Systems · Intermediate · 12 steps

Design a News Feed

Open lesson

KEY TAKEAWAYS

  • Estimate read/write QPS and expose why pull-time joins collapse at scale
  • Precompute per-user home timelines with asynchronous fan-out workers
  • Diagnose why 50M-follower accounts overwhelm pure fan-out on write
  • Combine precomputed timelines with read-time celebrity merging (Hybrid Fan-Out)

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Fan-Out on Read (Pull)Small apps or celebrity accounts (>10k followers) with huge fan-out costsEvery feed open queries N followed authors (4.6M lookups/s at 200M DAU)
Fan-Out on Write (Push)99.9% of regular users—delivers O(1) Redis timeline reads in < 40 msPure push explodes into 50M cache writes when a mega-celebrity posts
Hybrid Celebrity MergeGlobal social feeds combining push for normal users + read-time merge for ~3 celebsRequires tracking celebrity threshold flags and merging sorted ID lists in memory
ID Hydration + Cursor PagingConsistent post edits/deletes, edge CDN media offload, and zero scroll duplicatesNeeds a fast MGET object cache and opaque cursor tokens instead of OFFSET
Rule of thumb:Interview formula: quantify the read/write ratio first, propose Push vs Pull, surface the celebrity edge case, then land on Hybrid Fan-Out.
System Design · 09. Whole Systems · Beginner · 10 steps

Design a URL Shortener

Open lesson

KEY TAKEAWAYS

  • Size a 100:1 read-heavy URL shortener for 100K redirects/s, 1K creates/s, and 5-year storage
  • Calculate 7-char Base62 keyspace (3.52T keys) and replace hash retries with a dedicated KGS
  • Choose between HTTP 301 vs 302 redirects and absorb 92%+ of clicks with Edge PoPs and Redis LRU
  • Scale storage across hash-sharded KV nodes and decouple viral click counters via Kafka and OLAP

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Base62 + Dedicated KGSHigh-throughput short link creation with O(1) RAM minting, zero collisions, and unpredictable keysRequires a standby KGS and pre-populated unused-keys database
HTTP 301 vs 302 Redirect301 minimizes origin load via browser caching; 302 gives 100% accurate analytics & instant link edits301 blinds analytics on repeat clicks and cannot easily revoke abusive links
Edge PoPs + Redis LRU CacheZipfian viral link skew where the top 5% of links drive 92%+ of 100K redirects/sec in < 10 msMust publish cache invalidation whenever a link is edited or flagged for abuse
Async Kafka → ClickHouse AnalyticsRecording geo, referrer, and click totals without creating row-lock hotspots on viral linksAnalytics dashboards trail real-time clicks by ~5 seconds
Rule of thumb:Interview Gold Checklist: 100:1 read skew · 62^7 = 3.52T keys · KGS RAM blocks · 302 + Redis LRU (92% hit) · Sharded KV · Lazy TTL · Kafka → OLAP clicks.
System Design · 09. Whole Systems · Intermediate · 10 steps

Design a Chat System

Open lesson

KEY TAKEAWAYS

  • Split stateful WebSocket messaging from stateless HTTP APIs and route cross-node frames via Redis Sessions
  • Generate time-ordered 64-bit Snowflake IDs and store 2B daily messages in bucketed wide-column storage
  • Scale presence heartbeats with debounced TTLs and switch small groups (push) vs mega-channels (pull)
  • Support offline APNs/FCM push, O(1) per-device read cursors, and direct-to-S3 media uploads

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Stateful WS + Stateless HTTPSub-100 ms bi-directional chat frames while keeping auth, profiles & heavy media off socketsStateful WS gateways require service discovery, sticky sockets, and graceful draining
64-Bit Snowflake IDsLock-free, globally unique, chronologically sortable chat message IDs across distributed gatewaysRequires NTP clock-drift protection; gives k-ordering across separate machines
Cassandra ((channel_id, month), msg_id DESC)2B write-heavy daily messages with 1-seek paginated scrollback and bounded partition sizesFull-text message search requires an asynchronous inverted search index via CDC
Hybrid Group Fan-Out (Push ≤500 / Pull >500)Instant delivery for team chats without 50,000× write amplification on supergroupsClients must support both live inbox pushes and cursor-based channel log fetches
Rule of thumb:Flagship Interview Summary: WS + HTTP split · Redis Session Registry · 64-bit Snowflake IDs · Bucketed Cassandra LSM · Debounced presence · Push ≤500 / Pull >500 · Per-device read cursors.
AI & LLM Systems · 01. Transformer Architecture · Beginner · 6 steps

Tokenization, Embeddings & RoPE

Open lesson

KEY TAKEAWAYS

  • Explain why Byte-Pair Encoding (BPE) balances vocabulary size against O(N²) sequence length
  • Inspect how discrete token IDs project into dense semantic vectors measurable via cosine similarity
  • Understand why self-attention is permutation-invariant without explicit positional encodings
  • Verify how Rotary Positional Embeddings (RoPE) encode exact relative distance (m − n) via 2D rotation

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
BPE Subword TokenizationGeneral-purpose multilingual & code LLMs (GPT-4, Llama 3)Compresses ~4 chars/token without unknown <UNK> tokens, but struggles with character-level spelling
Sinusoidal PE (2017)Classic Encoder-Decoder Transformers with fixed training sequence lengthsAdded once to input embeddings; degrades rapidly when extrapolating past training context length
Learned Absolute PEFixed-window encoders like BERT (512 tokens) and early GPT-2Hard ceiling at max trained position — cannot attend beyond learned embedding table
RoPE (Rotary Position)Modern long-context LLMs (Llama 3, Mistral, Gemma, Qwen)Rotates Q/K pairs at every layer so dot product depends strictly on relative offset (m − n)
Rule of thumb:Tensor shape leaving this stage: [Batch, SeqLen, d_model]. Every token is now a rich geometric vector ready to query the entire context.
AI & LLM Systems · 01. Transformer Architecture · Intermediate · 6 steps

Self-Attention & Q/K/V Mechanics

Open lesson

KEY TAKEAWAYS

  • Explain how Queries (what I seek), Keys (what I advertise), and Values (what I pass along) contextualize words
  • Demonstrate why dividing dot products by √d_k prevents softmax saturation and vanishing gradients
  • Contrast causal triangular masking (GPT decoders) against bidirectional attention (BERT encoders)
  • Recognize the O(N²) attention matrix bottleneck and how FlashAttention tiles SRAM to stay fast

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Query · Keyᵀ Dot ProductComputing pairwise relevance between every token pair in parallelProduces an N × N score matrix whose memory & FLOPs grow quadratically with context length
1 / √d_k ScalingKeeping pre-softmax variance near 1.0 regardless of head dimension d_kWithout scaling, large dot products push softmax into near-one-hot saturation with ~0 gradients
Causal Mask (−∞ Upper Tri)Autoregressive LLMs trained on next-token prediction without leaking future wordsBlocks right-to-left context; each token only sees positions j ≤ i
FlashAttention (IO-Aware)Long-context training & serving (32K–1M tokens) without materializing N×N in HBMComputes exact attention in fused GPU SRAM tiles using online softmax rescaling
Rule of thumb:Open the Math & Tensor Shape Inspector below the stage to review the exact shape flow: [1, H, T, d_k] → [1, H, T, T] → [1, T, d_model].
AI & LLM Systems · 01. Transformer Architecture · Intermediate · 6 steps

Multi-Head Blocks, Residual Stream & SwiGLU

Open lesson

KEY TAKEAWAYS

  • Explain why splitting d_model into H parallel heads lets a single layer track syntax, coreference, and locality simultaneously
  • Trace how the residual stream (+) acts as a shared memory bus and unbroken gradient highway across 32–128 layers
  • Contrast modern Pre-RMSNorm stability and speed against classic 2017 Post-LayerNorm
  • Understand how SwiGLU gated FFNs store factual associations more efficiently than classic ReLU MLPs

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Multi-Head Attention (MHA)Learning diverse parallel relationships (coreference, syntax, local bigrams) at onceSplits d_model into H heads of size d_k = d_model / H so total FLOPs stay constant
Residual Stream (+)Training deep 32–128 layer networks without vanishing gradientsEvery attention and FFN sublayer writes additive deltas (x + Δ) onto one shared bus
Pre-RMSNorm (Modern)Stable large-scale LLM pretraining without fragile learning-rate warmupDrops mean-centering subtraction (faster GPU kernel than LayerNorm) and keeps residual trunk untouched
SwiGLU FFN (8/3 d_model)Modern frontier LLMs (PaLM, Llama, Gemma, Mistral) needing higher quality per FLOPUses 3 weight matrices (W_gate, W_up, W_down) at 8/3 hidden width to match 4× ReLU parameter count
Rule of thumb:Open the Math Inspector to inspect both the residual equations and exact [1, T, 4096] → [1, T, 10923] → [1, T, 4096] tensor shapes.
AI & LLM Systems · 01. Transformer Architecture · Intermediate · 6 steps

Encoder-Decoder, Decoding & Modern LLMs

Open lesson

KEY TAKEAWAYS

  • Trace how Classic 2017 Encoder-Decoder Cross-Attention aligns reordered source and target phrases (e.g., "black cat" → "chat noir")
  • Explain why modern LLMs converged on Decoder-Only stacks with Grouped-Query Attention (GQA) for 4–8× smaller KV caches
  • Predict how Temperature (T) sharpens or flattens softmax logits before next-token sampling
  • Combine Top-K and Top-P (Nucleus) truncation to preserve creativity while eliminating tail hallucinations

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Encoder-Decoder (T5, Whisper)Sequence-to-sequence translation, audio transcription, and fixed-input summarizationBidirectional encoder + Cross-Attention bridge shines on alignment, but splits parameter budget in two
Decoder-Only + GQA (Llama 3)General-purpose chat, reasoning, coding, and long-context servingUnified next-token objective scales effortlessly; GQA shares KV heads to shrink decode memory 4–8×
Temperature Scaling (z / T)Controlling determinism (T ≤ 0.3 for code/JSON) vs creative diversity (T ≈ 0.8–1.0)High T (> 1.4) inflates improbable junk tokens unless paired with Top-P truncation
Top-P Nucleus SamplingAdaptive candidate pruning that shrinks dynamically when the model is confidentKeeps smallest prefix summing to p (e.g., 90%) and renormalizes—preventing incoherent tail picks
Rule of thumb:Every modern inference optimization (PagedAttention, Continuous Batching, Speculative Decoding) exists specifically to serve the GQA KV-cache and autoregressive loop you just mastered.
AI & LLM Systems · 02. Inference & Retrieval · Intermediate · 6 steps

LLM Inference & KV Cache

Open lesson

KEY TAKEAWAYS

  • Distinguish compute-bound prompt prefill (TTFT) from memory-bandwidth-bound token decode (TPOT)
  • Prevent GPU out-of-memory fragmentation using PagedAttention virtual KV blocks
  • Multiply throughput by swapping static batching for iteration-level continuous batching
  • Isolate long-prompt prefill spikes from streaming decode workers

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Static BatchingOffline bulk document scoring with uniform prompt lengthsFast requests wait idle until the longest response in the batch finishes
Continuous BatchingInteractive chat APIs with highly variable output lengthsRequires iteration-level scheduler that swaps finished sequences every token step
PagedAttentionHigh-concurrency serving where KV cache dominates GPU HBMAdds block-table indirection, reclaiming 60%+ wasted contiguous memory
Prefill/Decode DisaggregationMixed workloads combining 32k-token RAG prompts with low-latency streamingTransfers KV cache state over high-speed RDMA/NVLink between worker pools
Rule of thumb:Measure TTFT, TPOT, and KV cache utilization together—optimizing tokens/sec alone hides painful P99 time-to-first-token stalls.
AI & LLM Systems · 02. Inference & Retrieval · Intermediate · 6 steps

RAG & Vector Retrieval Pipelines

Open lesson

KEY TAKEAWAYS

  • Identify why dense-only vector search misses exact product IDs, acronyms, and fresh edits
  • Combine BM25 lexical search with HNSW vector search via Reciprocal Rank Fusion (RRF)
  • Boost top-5 precision with a fast cross-encoder reranker before LLM generation
  • Keep document chunks fresh and permission-filtered with event-driven ingestion

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Dense Vector (HNSW)Conceptual similarity and paraphrased natural-language questionsWeak on exact SKU codes, error codes, and rare proper nouns
Sparse Lexical (BM25)Exact keyword, API symbol, and compliance clause matchingMisses synonyms unless expanded or paired with embeddings
Hybrid RRF + RerankerProduction enterprise RAG requiring high recall and grounded citationsAdds 40–90 ms rerank latency on the top-50 candidate set
Metadata Pre-FilteringMulti-tenant ACL enforcement (only search docs the user can read)Overly selective filters can degrade HNSW graph traversal recall
Rule of thumb:Evaluate Retrieval Recall@K separately from Generation Faithfulness so you always know which half of the pipeline needs work.
AI & LLM Systems · 03. Agents & Production Ops · Intermediate · 6 steps

Agentic Tool-Calling & Guardrails

Open lesson

KEY TAKEAWAYS

  • Orchestrate stateful Reason → Act → Observe loops with strict step and token budgets
  • Isolate untrusted code and API tools inside least-privilege sandboxes with idempotency keys
  • Intercept prompt injection and PII exfiltration using dual input/output policy guardrails
  • Gate destructive write tools behind human-in-the-loop approval checkpoints

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Bounded ReAct LoopMulti-step research, debugging, and support triage tasksRequires max-iteration caps, wall-clock timeouts, and loop-detection guards
MicroVM Tool SandboxRunning generated Python, SQL, or shell scripts safelyAdds 80–200 ms cold start unless warm snapshot pools are kept ready
Parallel Input/Output GuardrailBlocking prompt injection, jailbreaks, and secret/PII leaksRuns a fast classifier alongside generation to avoid doubling user latency
Approval CheckpointIrreversible actions (refunds, production deploys, external emails)Pauses durable agent state until a human confirms the structured diff
Rule of thumb:Design your agent assuming the model will occasionally hallucinate a bad argument—make every tool call safe, idempotent, and auditable.
AI & LLM Systems · 03. Agents & Production Ops · Intermediate · 6 steps

LLM Routing, Eval & Prompt Caching

Open lesson

KEY TAKEAWAYS

  • Layer exact and semantic caches to serve recurring questions in under 30 ms
  • Route easy requests to small fast models and escalate complex tasks to frontier models
  • Survive upstream LLM rate limits (429s) with multi-region circuit-broken fallbacks
  • Catch prompt regressions before shipping using golden datasets and LLM-as-a-Judge

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Semantic CacheHigh-volume FAQ, support, and template queries with slight phrasing shiftsRequires a tight cosine threshold (≥0.95) to avoid returning wrong answers
Model Router / CascadeMixed complexity workloads (classification + deep code reasoning)Classifier misrouting can hurt quality if escalation thresholds are too loose
Multi-Provider GatewayMission-critical AI apps exposed to single-vendor quota caps or outagesPrompts must be benchmarked across fallback models to preserve format fidelity
CI Eval Gate + Shadow JudgeContinuous prompt/model upgrades without silent quality regressionsJudge models need human-calibrated rubrics to prevent self-preference bias
Rule of thumb:Great AI systems win on economics and reliability as much as model IQ—route smartly, cache aggressively, and measure continuously.
Cloud & Kubernetes · 01. Containers & Control Plane · Beginner · 6 steps

Containers, Layers & Cgroups

Open lesson

KEY TAKEAWAYS

  • Contrast lightweight container process isolation against full hypervisor VMs
  • Prevent noisy-neighbor CPU starvation and host crashes with cgroup v2 limits
  • Accelerate builds and cold starts via cached read-only OverlayFS image layers
  • Shrink attack surface and pull times with multi-stage distroless builds

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Linux NamespacesIsolating PID trees, network interfaces, mounts, and hostnames per containerAll containers still share one host Linux kernel (not a VM boundary)
Cgroups v2 LimitsBounding CPU shares and RAM so one memory leak cannot crash the nodeToo-tight CPU limits cause CFS throttling; RAM ceilings trigger OOMKill
OverlayFS LayersDeduplicating shared base OS/runtime layers across dozens of containersPoor Dockerfile ordering invalidates cache on every code edit
Multi-Stage DistrolessShipping 22 MB production images without compilers, shells, or OS CVEsDebugging shifts to logs, traces, and ephemeral debug containers
Rule of thumb:Pair slim images with explicit memory ceilings and readiness probes before deploying to Kubernetes.
Cloud & Kubernetes · 01. Containers & Control Plane · Intermediate · 6 steps

Kubernetes Control Plane & Scheduling

Open lesson

KEY TAKEAWAYS

  • Explain how controllers continuously reconcile actual state toward desired state in etcd
  • Understand predicate filtering and node scoring (affinity, topology spread, requests)
  • Trace how Kubernetes detects a dead node and reschedules pods onto healthy capacity
  • Protect live traffic during maintenance using Readiness Probes and PodDisruptionBudgets

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
API Server + etcd WatchSingle source of truth with event-driven controller notificationsAll control-plane components depend on etcd quorum stability
Topology Spread ConstraintsDistributing pod replicas evenly across Availability ZonesStrict rules can leave pods Pending if one zone fills up
Readiness vs Liveness ProbeRemoving slow pods from Service endpoints without unnecessary restartsBad liveness probes cause cascading restart loops on DB blips
PodDisruptionBudget (PDB)Guaranteeing minimum available replicas during node upgradesSetting minAvailable to 100% blocks voluntary node drains
Rule of thumb:Even if the Control Plane restarts briefly, already-scheduled data-plane pods continue serving live traffic.
Cloud & Kubernetes · 02. Traffic & GitOps · Intermediate · 6 steps

Ingress, Service Mesh & mTLS

Open lesson

KEY TAKEAWAYS

  • Terminate external TLS and route host/path traffic with Kubernetes Gateway API
  • Automate short-lived SPIFFE mTLS certificates between microservices via a service mesh
  • Shift 5% → 50% → 100% canary weights at Layer 7 without scaling pod counts
  • Weigh Envoy sidecar CPU/memory overhead against ambient/eBPF mesh alternatives

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Gateway API (L7)Role-separated TLS termination, header routing, and weighted splitsHandles north-south entry only; internal hops stay unencrypted
Sidecar Service MeshAutomatic mTLS, per-route retries, and cross-language telemetryAdds an Envoy proxy per pod (~50 MB RAM, ~2 ms hop)
NetworkPolicy (L3/L4)Default-deny firewall rules restricting namespace communicationOperates on IPs/ports only—cannot inspect HTTP paths or JWTs
Ambient / eBPF MeshZero-trust mTLS without per-pod sidecar RAM tax at large scaleSplits L4 node tunnel from optional L7 waypoint proxies
Rule of thumb:Zero-trust inside Kubernetes ties identity to cryptographic certificates, never mutable pod IPs.
Cloud & Kubernetes · 02. Traffic & GitOps · Intermediate · 6 steps

Cluster Autoscaling & GitOps Rollouts

Open lesson

KEY TAKEAWAYS

  • Scale pods on leading signals like queue depth and RPS (KEDA) rather than lagging CPU alone
  • Eliminate Pending-pod stalls by pairing HPA with Karpenter just-in-time node provisioning
  • Replace push-based CI cluster credentials with pull-based GitOps controllers (Argo CD)
  • Automate canary promotion and rollback directly from Prometheus error-rate queries

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
HPA (CPU / Memory)Predictable compute-bound APIs with gradual daily curvesLags sudden spikes and misses I/O-bound queue backlogs
KEDA Event ScalingQueue workers, LLM inference batches, and scale-to-zero jobsNeeds cooldown stabilization windows to prevent flapping
Karpenter ProvisionerLaunching right-sized spot/on-demand nodes in ~45 secSpot nodes need interruption draining handlers and fallbacks
Pull-Based GitOpsAuditable multi-cluster drift healing with zero prod creds in CISecrets must stay out of Git via ExternalSecrets
Rule of thumb:Bound autoscalers with `maxReplicas` and test failover under burst loads.
Frontend & Browser · 01. Browser & Rendering Engine · Beginner · 6 steps

Critical Rendering Path & Compositing

Open lesson

KEY TAKEAWAYS

  • Map the Critical Rendering Path from HTML/CSS bytes to DOM, CSSOM, Render Tree, Layout, Paint, and Composite
  • Detect and eliminate forced synchronous layouts caused by interleaving DOM reads and writes
  • Keep animations silky at 60–120fps by animating compositor-only `transform` and `opacity`
  • Optimize LCP and CLS using intrinsic dimensions, `font-display: swap`, and CSS containment

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Layout (`top`/`width`)Structural geometry shifts on responsive resizeTriggers full Layout → Paint → Composite; expensive inside 60fps loops
Paint (`color`/`shadow`)Hover state and subtle surface emphasis transitionsSkips Layout geometry but still re-rasterizes bitmaps on CPU/GPU
Compositor (`transform`/`opacity`)Scroll reveals, drawers, cards, and interactive dragsRuns off the main thread on the GPU; avoids layout and paint completely
CSS `contain: layout paint`Isolating complex widgets or virtualized rows from full-page reflowsCreates a stacking/containing block; clips overflow if `paint` is set
Rule of thumb:Profile in Chrome DevTools Performance tab—purple Layout bars inside an animation loop are your highest-ROI fix.
Frontend & Browser · 01. Browser & Rendering Engine · Beginner · 6 steps

JS Event Loop & Main Thread Scheduling

Open lesson

KEY TAKEAWAYS

  • Order execution across the Call Stack, Microtask Queue, Macrotask Queue, and rAF paint step
  • Understand how 250 ms Long Tasks block clicks and degrade Interaction to Next Paint (INP)
  • Break up heavy UI work using `scheduler.yield()` and React concurrent transitions
  • Offload CPU-heavy parsing, search indexing, and encryption to dedicated Web Workers

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Microtask (`Promise.then`)Immediate async state continuations before next paintRecursive microtasks starve painting and freeze the tab completely
Cooperative YieldingSplitting medium 150 ms UI updates into <50 ms chunksLets urgent clicks paint between chunks without worker serialization
Web Worker ThreadFuzzy search, CSV/JSON parsing, crypto, and canvas layout mathNo direct DOM access; transfer large buffers via `Transferable`
Concurrent TransitionKeeping typing input responsive while filtering large listsRequires clear pending indicator so slow filter updates feel intentional
Rule of thumb:Use the scenario switcher above to compare Queue Ordering, 250ms Long Tasks, Microtask Storms, Cooperative Yielding, and Web Workers side by side.
Frontend & Browser · 02. Web Scale Patterns · Intermediate · 6 steps

SSR, Streaming & Edge Hydration

Open lesson

KEY TAKEAWAYS

  • Diagnose why client-only SPAs suffer serial HTML → JS → API fetch waterfalls
  • Unblock Time to First Byte (TTFB) by streaming Suspense shells before slow APIs finish
  • Shrink client JS bundles with Server Components and selective out-of-order hydration
  • Balance dynamic personalization against stale-while-revalidate CDN caching

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Client-Side Rendering (CSR)Auth-gated internal dashboards and thick offline-capable editorsBlank white screen until JS downloads, parses, and fetches APIs
Blocking SSRFast SEO pages backed by uniformly fast (<50 ms) databasesOne slow recommendation query delays the entire HTML response
Streaming SSR + SuspensePages mixing instant static shells with slow personalized panelsRequires streaming-capable proxies and careful error boundaries
Server Components (RSC)Content-rich apps keeping heavy markdown/DB code strictly on the serverClear boundary required between server data and interactive client leaves
Rule of thumb:Render static shells closest to the user, stream slow dynamic regions, and ship client JS only where interactivity lives.
Frontend & Browser · 02. Web Scale Patterns · Beginner · 6 steps

Client State & Optimistic Caching

Open lesson

KEY TAKEAWAYS

  • Separate ephemeral local UI state from asynchronous cached server state
  • Eliminate redundant API calls across sibling components with keyed request deduplication
  • Make likes, toggles, and edits feel 0 ms via optimistic updates with snapshot rollback on error
  • Handle flaky mobile connections with idempotent mutation queues and conflict handling

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Local UI State (Zustand/React)Modals, sidebar toggles, draft inputs, and active filter tabsSynchronous & client-owned; do not manually mirror server tables here
Keyed Server Cache (SWR/Query)API entities shared across cards with background revalidationRequires disciplined cache-key design for targeted invalidation
Optimistic MutationHigh-confidence actions (likes, checkboxes, drag reorder)Must snapshot prior cache state to roll back cleanly on 4xx/5xx
Offline Outbox QueueMobile-first editors and field apps on intermittent networksNeeds client idempotency keys and server conflict resolution
Rule of thumb:Fast frontend architecture feels instantaneous because it avoids unnecessary network waits while staying honest about server truth.
DB & Data Pipelines · 01. Storage & Execution · Intermediate · 6 steps

WAL, Buffer Pool & MVCC

Open lesson

KEY TAKEAWAYS

  • Understand how sequential WAL appends deliver ACID durability without slow random disk writes
  • Size the RAM buffer pool to keep hot working sets in memory and avoid page-thrash eviction
  • See how MVCC lets readers never block writers by serving versioned row snapshots
  • Prevent dead-tuple table bloat and transaction ID wraparound with tuned autovacuum

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Write-Ahead Log (WAL)Fast durable commits via sequential `fsync` before modifying heap pagesRequires periodic checkpoints to bound crash-recovery replay time
Buffer Pool (LRU/Clock)Absorbing hot reads and coalescing multiple dirty page edits in RAMWhen working set exceeds RAM, page thrashing spikes IOPS 10×
MVCC Row VersionsHigh-concurrency OLTP where analytical reads coexist with live writesUpdates create dead tuples that must be reclaimed asynchronously
Autovacuum & HOT UpdatesKeeping B-Trees compact and preventing table bloat on update-heavy tablesLong idle-in-transaction sessions pin old snapshots and block vacuum
Rule of thumb:Use the 3 mode tabs above (B+Tree Index · LSM-Tree & Bloom · MVCC Timeline) to test any storage engine trade-off hands-on.
DB & Data Pipelines · 01. Storage & Execution · Intermediate · 6 steps

Query Planner, Joins & Columnar Scans

Open lesson

KEY TAKEAWAYS

  • Understand how cost-based optimizers use table histograms and cardinality statistics
  • Choose between Nested Loop, Hash Join, and Sort-Merge Join based on selectivity and RAM
  • Explain why columnar formats (Parquet/ClickHouse) beat row stores 50× on analytical aggregations
  • Skip 95% of disk reads using partition pruning, min/max zone maps, and vectorized SIMD

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Nested Loop JoinJoining 10 selective indexed rows against a huge table (OLTP)Turns catastrophic O(N×M) if planner underestimates outer row count
Hash JoinJoining two large unindexed sets when the smaller side fits in `work_mem`Spills slow temp files to disk if hash table overflows RAM
Row-Oriented StorePoint lookups and inserting/updating complete user recordsReads all 40 unused columns just to `SUM(revenue)`
Columnar + Zone MapsBI dashboards aggregating millions of rows across 2–3 columnsSlow for single-row random updates; designed for batch/append writes
Rule of thumb:Always read `EXPLAIN (ANALYZE, BUFFERS)`—it reveals exact disk pages read, row estimate accuracy, and memory spills.
DB & Data Pipelines · 02. Analytical Pipelines · Intermediate · 6 steps

CDC & Lakehouse Streaming Pipelines

Open lesson

KEY TAKEAWAYS

  • Eliminate heavy `SELECT * WHERE updated_at` polling by tailing the DB WAL via Change Data Capture
  • Prevent broken downstream pipelines with backward-compatible Schema Registry contracts
  • Achieve ACID snapshots, time-travel, and safe concurrent reads on S3 using Apache Iceberg
  • Prevent the small-files problem with automated streaming Parquet compaction

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Nightly Batch ETLSmall static reporting tables tolerant of 24-hour stalenessHammers OLTP read replicas and silently misses hard `DELETE` rows
Log-Based CDC (Debezium)Low-impact near-real-time capture of every INSERT, UPDATE, and DELETERequires monitoring Postgres replication slots so disk does not fill
Apache Iceberg TableACID metadata commits, schema evolution, and time-travel over S3 ParquetNeeds periodic snapshot expiration and file compaction jobs
Medallion Layers (Bronze→Gold)Reproducible raw audit history plus clean business-ready martsExtra storage hops—keep Silver/Gold strictly tied to real consumers
Rule of thumb:Decouple OLTP from OLAP through an immutable event log so every downstream BI tool and ML pipeline consumes clean, replayable history.
Networking & Security · 01. Transport & Internet Routing · Intermediate · 6 steps

TCP Congestion Control & QUIC

Open lesson

KEY TAKEAWAYS

  • Measure how TCP + TLS 1.3 handshakes inflate cold TTFB compared to QUIC 1-RTT / 0-RTT
  • Explain why a single dropped TCP packet stalls every multiplexed HTTP/2 stream
  • See how QUIC isolates per-stream recovery over UDP and survives Wi-Fi-to-5G roaming via Connection IDs
  • Tune congestion control (CUBIC vs BBR) and enforce HTTP 425 replay guards on 0-RTT writes

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
TCP + TLS 1.3 (HTTP/2)Universal enterprise compatibility & long-lived data-center links2–3 RTT cold setup and connection-level head-of-line blocking on loss
TCP BBR Congestion ControlHigh-BDP WAN links and video/API delivery over cellular networksModels bottleneck bandwidth to avoid bufferbloat; can compete with CUBIC
QUIC / HTTP/3 (UDP)Mobile users, lossy last-mile networks, and seamless IP roamingHigher user-space CPU per packet and occasional corporate UDP-443 blocks
QUIC 0-RTT ResumptionRepeat idempotent GET/HEAD requests to warm edge PoPsReplayable by on-path attackers; must reject non-idempotent POSTs with 425
Rule of thumb:Allow 0-RTT only on idempotent GET/HEAD routes; enforce 1-RTT on payments and mutations.
Networking & Security · 01. Transport & Internet Routing · Intermediate · 6 steps

BGP, Anycast & NAT Traversal

Open lesson

KEY TAKEAWAYS

  • Understand how BGP chooses inter-domain routes using Local Preference and AS-Path length
  • Use Anycast for nearest-PoP failover and RPKI Route Origin Validation to stop BGP hijacks
  • Prevent cloud NAT gateway SNAT port exhaustion under high-churn egress traffic
  • Combine STUN hole punching with global TURN TLS-443 relays for 99.9% WebRTC call setup

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
BGP Peering (IXP)Cutting transit costs and shaving latency between major ASNsSlow global convergence (30–90s) and route-leak risks without RPKI
Anycast IP PrefixGlobal DNS, CDNs, edge APIs, and distributed DDoS absorptionMid-flow BGP flaps can reset stateful TCP connections
STUN Hole PunchingZero-relay-cost direct peer-to-peer WebRTC media behind Cone NATsFails behind symmetric corporate NATs and UDP-blocking firewalls
TURN Media RelayGuaranteed call connectivity through strict enterprise firewallsEgress bandwidth scales linearly with relayed call minutes
Rule of thumb:Always deploy regional TURN clusters with TLS 443 fallback so enterprise users never hit silent call drops.
Networking & Security · 02. Zero Trust & Perimeter Defense · Intermediate · 6 steps

Zero Trust, WAF & DDoS Mitigation

Open lesson

KEY TAKEAWAYS

  • Absorb volumetric L3/L4 SYN and UDP floods across Anycast PoPs with eBPF/XDP before hitting origin links
  • Mitigate L7 credential stuffing and scraping using JA4 TLS fingerprints and adaptive WAF rate limits
  • Replace flat castle-and-moat VPNs with per-request Identity-Aware Proxies checking user + device posture
  • Eliminate lateral movement inside clusters with short-lived SPIFFE mTLS identities and default-deny policies

PATTERN COMPARISON

PATTERNBEST FORTRADE-OFF
Anycast + eBPF/XDP ScrubbingL3/L4 SYN and UDP amplification floods (Tbps scale)Drops packets in NIC driver at line rate; cannot inspect encrypted HTTP bodies
L7 Edge WAF & JA4 ScoringSQLi, XSS, scraping, and credential stuffing over valid HTTPSOver-aggressive rules risk false positives; tune with shadow logging first
Identity-Aware Proxy (IAP)Securing internal admin apps without flat corporate VPN blast radiusRequires high-availability IdP and managed device posture attestation
SPIFFE Workload mTLSDefault-deny service-to-service authorization inside KubernetesNeeds automated hourly cert rotation and CI policy validation
Rule of thumb:Layered controls ensure no single misconfiguration collapses perimeter or internal confidentiality.
Free Guided Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.