13 / 16

Distributed Systems

The fundamentals under every large system: data, scale, failure.

0/37 studied
01Back-of-the-envelope estimation

Order-of-magnitude arithmetic (latency, QPS, storage, tokens/s) done in two minutes to decide whether a design is feasible and which component dominates, before anyone builds anything.

Core◇ Diagram</> Code
02CAP & PACELC

During a network partition, a replicated system either refuses some requests (consistency) or serves possibly stale data (availability). PACELC adds: otherwise, every request trades latency against consistency.

Core◇ Diagram</> Code
03Consistency models

The contract for what a read may return on replicated data, from linearizable (behaves like one up-to-date copy) to eventual (converges someday). Stronger contracts cost latency and availability.

Advanced◇ Diagram</> Code
04Replication

Keep copies of the same data on several nodes for durability, availability and read scale. You choose who accepts writes (one, many or any node) and whether to wait for copies before acknowledging.

Core◇ Diagram</> Code
05Partitioning & sharding

Split data across nodes by a shard key, scaling writes and storage past one machine. The key decides load balance, which queries stay on one shard, and how painful rebalancing is.

Core◇ Diagram</> Code
06Consistent hashing

Place nodes and keys on the same hash ring and give each key to the next node clockwise, so adding or removing a node moves only ~1/N of the keys.

Core◇ Diagram</> Code
07Consensus (Raft)

A cluster agrees on one ordered log of commands despite crashes: a leader replicates each entry and commits it once a majority stores it, so 2f+1 nodes survive f failures.

Advanced◇ Diagram</> Code
08Caching strategies

Keep copies of expensive reads in faster storage; choose how writes reach the cache, bound staleness with TTLs or invalidation, and protect the origin from stampedes when hot keys expire.

Core◇ Diagram</> Code
09Queues vs streams (Kafka)

A queue hands each message to one worker and deletes it on ack; a stream (Kafka) keeps an ordered, replayable log that many consumer groups read at their own offsets.

Core◇ Diagram</> Code
10Idempotency

Doing an operation N times has the same effect as doing it once. It's what makes retries and at-least-once delivery safe; get it with upserts, conditional writes or client-supplied idempotency keys.

Core◇ Diagram</> Code
11Retries, backoff & circuit breakers

Retry only transient errors, with exponential backoff plus jitter, within a deadline and a retry budget; when a dependency is clearly down, a circuit breaker fails fast or falls back instead of piling on.

Core◇ Diagram</> Code
12Rate limiting

Cap how much each client can consume per unit of time so one tenant can't starve the rest; for LLMs, meter tokens per minute, not just requests, and answer excess with 429 plus Retry-After.

Core◇ Diagram</> Code
13Backpressure & load shedding

When demand exceeds capacity, bound every queue, push the slowdown back to callers that can wait, and reject the rest early and cheaply so the work you accept still finishes in time.

Advanced◇ Diagram</> Code
14Load balancing

Spread requests across replicas so none overloads and dead ones get skipped; for LLM serving, pick by live load (queue depth, KV-cache use) and prefix affinity, because request costs differ by orders of magnitude.

Core◇ Diagram</> Code
15SLIs, SLOs & error budgets

An SLI measures what users feel, an SLO sets its target, and the gap to 100% is an error budget you spend on change; alert on how fast you burn it, not on raw errors.

Core◇ Diagram</> Code
16Disaster recovery (RPO & RTO)

Decide how much data you can lose (RPO) and how long you can be down (RTO), buy the cheapest strategy that meets both, and prove it with regular failover and restore tests.

Advanced◇ Diagram
17SQL vs NoSQL

Pick the store from your access patterns, consistency needs and scale, not the label: Postgres by default (JSONB, pgvector), a specialized NoSQL store when one access pattern outgrows a single primary.

Core◇ Diagram</> Code
18Database indexes: B-tree vs LSM

A B-tree keeps keys sorted in pages updated in place: great for reads and ranges. An LSM tree buffers writes in memory and merges sorted files later: great for ingest. Every index taxes writes.

Advanced◇ Diagram</> Code
19Event sourcing & CQRS

Event sourcing stores every change as an immutable event and derives state by replaying them; CQRS splits the write model from query-shaped read models. Great for audit and replay, costly in complexity and eventual consistency.

Advanced◇ Diagram</> Code
20Sagas & the outbox pattern

Without distributed transactions, a saga chains local transactions and undoes completed steps with compensating actions on failure; the outbox makes each "update DB + publish event" atomic by writing both in one local transaction.

Advanced◇ Diagram</> Code
21Monolith vs microservices

Start with a modular monolith; split out a service only when a team needs independent deploys or a part needs different scaling, because every split pays for autonomy with network hops and distributed data.

Core◇ Diagram</> Code
22Observability: logs, metrics, traces

Metrics tell you *that* something is wrong, traces *where*, logs *why*. Instrument with OpenTelemetry, alert on RED and USE, and keep high-cardinality detail on spans, not metric labels.

Core◇ Diagram</> Code
23Multi-tenancy patterns

Serve many customers from one system by choosing, per layer, silo (dedicated), pool (shared with a tenant_id) or a bridge of both, trading cost per tenant against isolation, noisy neighbors and compliance.

Advanced◇ Diagram</> Code
24API design: REST, gRPC, async

REST for public resource APIs, gRPC for typed internal calls and streaming, an async contract (202 + status, webhooks, SSE) for anything slow; build in pagination, versioning and idempotency from day one.

Core◇ Diagram</> Code
25CDNs and edge caching

A CDN caches your responses on servers near users, keyed by URL, so most requests never reach your origin; you control freshness with Cache-Control TTLs, versioned URLs and purges.

Core◇ Diagram</> Code
26Object storage (S3-style)

Store files as whole objects under bucket + key, over HTTP: virtually unlimited, very durable and cheap per GB, but you rewrite whole objects, pay per request, and keep metadata and queries in a database.

Core◇ Diagram</> Code
27Probabilistic data structures

Trade a small, bounded error for huge memory savings: a Bloom filter answers "seen it?" with no false negatives, HyperLogLog counts distinct items, and Count-Min estimates frequencies, in kilobytes instead of gigabytes.

Advanced◇ Diagram</> Code
28Storage engines: LSM-tree vs B-tree

B-trees update pages in place for cheap reads; LSM-trees append and compact later for cheap writes, so choose by the amplification your workload can afford: write, read or space.

Staff+◇ Diagram</> Code
29Clocks and event ordering

Machine clocks drift and jump, so timestamps can't order events across nodes; use logical clocks for causality (Lamport, vector) or hybrid clocks that also stay close to wall time.

Advanced◇ Diagram</> Code
30Gossip protocols & failure detection

Every node periodically swaps what it knows with a few random peers, so membership and failure news reach the whole cluster in O(log N) rounds with no coordinator.

Advanced◇ Diagram</> Code
31Distributed locks and fencing tokens

A distributed lock is really a lease that expires, so a paused holder can outlive it; for correctness, take the lease from a consensus store or database and have storage reject stale fencing tokens.

Advanced◇ Diagram</> Code
32Stream processing: windows, watermarks, state

Compute continuously over unbounded event streams: group events into windows by event time, use watermarks to decide when a window is complete, and checkpoint state so results survive failures exactly once.

Advanced◇ Diagram</> Code
33Real-time delivery: polling, SSE, WebSockets

Push server events over the simplest channel that fits (polling for rare updates, SSE for one-way streams, WebSockets for two-way); at scale, the hard part is the stateful gateway tier and fan-out.

Core◇ Diagram</> Code
34Geospatial indexing (geohash, S2, H3)

Map coordinates to cell ids so "what's near me?" becomes a lookup of a few cells plus an exact distance filter; size cells to the search radius and split cells that get hot.

Advanced◇ Diagram</> Code
35AuthN vs AuthZ: sessions, JWT, OAuth

Authentication proves who you are and authorization decides what you may do: log in with OIDC (auth code + PKCE), carry identity in short-lived tokens or sessions, and check permissions server-side on every request.

Core◇ Diagram</> Code
36Encryption & secrets management

Encrypt data on the wire with TLS and on disk with keys held in a KMS, keep secrets in a vault as short-lived credentials, and store passwords only as slow, salted hashes.

Core◇ Diagram</> Code
37Deployment strategies (canary, blue-green, flags)

Ship changes to a small slice first, watch the metrics, then widen or roll back automatically; separate deploy from release with feature flags, and change schemas in backward-compatible expand/contract steps.

Advanced◇ Diagram</> Code