Kayavak / Recaps / System Design
Recaps · Volume 12
System Design
The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.
121
Key ideas
- Requirements before boxes: users, workflows, core operations, scale, failure behaviour and invariants decide the design.
- Functional (what it does: use cases, API sketches), non-functional (how well: latency, throughput, availability, durability, consistency, security, privacy, cost, operability), constraints (fixed: budget, regulation, existing systems, team).
- Testable NFRs name a measure, a threshold and conditions; write them as checks where you can.
- Ask about failure and "must never happen" to find hidden requirements (idempotency, durability, isolation).
- Scope: explicit non-goals; prioritise (must/should/could, or by risk and value).
- Conflicts are resolved by design choices that change wording (receipt vs payment confirmation), recorded in ADRs.
- A repeatable method: requirements → estimates → API and data model → high-level design → deep dives → failure modes → evolution.
Numbers to remember
- Lab: in-memory v1 passed latency (p99 3.6 ms) but failed idempotency and durability.
- Lab: durable, idempotent v2 had p99 9.1 ms, within a 50 ms requirement.
- 86,400 seconds in a day; peak is commonly 2–10× average.
Pitfalls
- Designing before asking about scale, failure and invariants.
- Untestable NFRs ("fast", "secure", "scalable").
- Testing durability with a graceful shutdown instead of a hard kill.
- Gold-plating for scale nobody asked for.
- Unrecorded trade-offs that later look like mistakes.
Glossary
- Use case: a goal-directed interaction between an actor and the system.
- Quality attribute: a non-functional property such as availability or latency.
- Invariant: a condition that must always hold (no double charge).
- ADR: architecture decision record (context, decision, consequences).
- Non-goal: scope deliberately excluded.
122
Key ideas
- Order of magnitude is the goal; state assumptions, round aggressively, sanity-check against known systems.
- Traffic: users × actions per user per day ÷ 86,400 = average QPS; × peak factor (2–10×); split reads and writes.
- Storage: rows × (data + overhead + indexes) × replicas × retention, plus backups and growth headroom.
- Bandwidth: QPS × response size; compression changes it dramatically.
- Memory: working set (hot fraction × size) for caches; connections × per-connection memory.
- Latency hierarchy: cache ns → DRAM ~100 ns → SSD tens of µs → same-DC network ~0.5 ms → cross-continent ~100–200 ms.
- Batching amortises round trips and fsyncs; it's usually the biggest lever.
- Capacity: measure one instance, then instances = peak load ÷ (per-instance capacity × target utilisation).
Numbers to remember
- 86,400 s/day; 1 M/day ≈ 12/s; 1 B/day ≈ 12,000/s.
- Lab: DRAM 188 ns, SSD read 35 µs, fsync 152 µs, local PG query 120 µs, PG insert+commit 582 µs.
- Lab: PostgreSQL row ≈ 68 B for 34 B of columns; with two indexes ≈ 117 B (3.4×).
- Lab: one-statement bulk load ≈ 450,000 rows/s vs ≈ 1,700/s with one commit per row.
- Light in fibre ≈ 200,000 km/s → ~1 ms round trip per 100 km, before routing.
Pitfalls
- Averages without peaks; forgetting write amplification, indexes and replicas.
- Precision theatre (five significant figures on a guess).
- Mixing bits and bytes (Mbit/s vs MB/s, ×8).
- Assuming per-request cost from server time while ignoring round trips.
- Never checking estimates against a measurement.
Glossary
- Peak factor: peak load ÷ average load.
- Working set: the data actively accessed in a period.
- Write amplification: bytes physically written per byte of logical data.
- Headroom: spare capacity kept for spikes and failures.
- IOPS: I/O operations per second.
123
Key ideas
- DNS: names → addresses; TTLs trade agility for load; resolvers cache, so changes are never instant.
- Load balancers: L4 (connections) vs L7 (requests, headers, paths); algorithms (round robin, weighted, least connections, power of two choices, consistent hash, EWMA); active and passive health checks; retries and redispatch; connection draining.
- API gateways: authentication, rate limiting, routing, request shaping; keep them thin and redundant.
- Application servers: stateless where possible; state in shared stores.
- Caches: in-process vs distributed; eviction (LRU, LFU); TTLs; invalidation.
- Databases: relational vs key-value, document, wide-column, graph, time-series; replication and partitioning.
- Object storage: cheap, durable, high-latency blobs with HTTP APIs; pair with a CDN.
- Queues and streams: decouple producers and consumers, absorb bursts, enable replay (streams).
- CDN: edge caching of static and cacheable dynamic content.
- Search: inverted indexes, eventually consistent with the source of truth.
- Coordination: consensus stores (etcd, ZooKeeper) for leader election, config and locks; need a quorum.
Numbers to remember
- Lab: a 10× slower server got 33% of traffic with round robin and 7% with least connections; average latency 41 → 19 ms.
- Lab: health checks at 500 ms × fall 2 → 81 failures in 0.57 s at 200/s; retries + redispatch → 0.
- A 3-node quorum tolerates 1 failure; 5 nodes tolerate 2.
Pitfalls
- Round robin across uneven servers or uneven requests.
- Default timeouts of tens of seconds hiding hung backends.
- Retrying non-idempotent requests at the balancer.
- A single load balancer or gateway as a hidden single point of failure.
- Long-lived connections never rebalancing.
- Low DNS TTLs everywhere (load) or very high ones (slow failover).
Glossary
- L4 / L7 load balancing: by connection / by HTTP request.
- Health check (active / passive): probing servers / observing real traffic.
- Redispatch: retrying on a different server.
- Connection draining: letting in-flight requests finish before removing a server.
- Quorum: a majority of members required for decisions.
124
Key ideas
- Scalability: throughput grows with resources while meeting latency targets.
- Vertical (bigger machine: simple, ceiling, failure domain) vs horizontal (more machines: needs statelessness or partitioning).
- Stateless services + shared stores scale out linearly; state goes to databases, caches, queues and object storage.
- Amdahl's law: speed-up ≤ 1/σ for serial fraction σ. USL adds coherency κ, giving a peak and retrograde scaling.
- Autoscaling on a metric that tracks saturation (CPU, concurrency, queue depth), with headroom and warm-up.
- Read scaling: replicas and caches. Write scaling: partitioning, batching, queues.
- Partitioning: range (scans, hot ranges), hash (even, no scans), directory/lookup (flexible, extra hop); consistent hashing, rendezvous, jump hash; rebalancing and split/merge.
- Hot keys defeat partitioning; split, cache or isolate them.
Numbers to remember
- Lab: 1 → 2 → 4 stateless servers gave 1.97× and 3.92×.
- Lab: 1 ms serial in a 10.6 ms request capped throughput near 850/s; with coherency it peaked at N=8 and fell to 350/s at 64.
- Lab: 4 → 5 nodes moved 80% of keys with mod N, ≈20% with consistent hashing at ≥100 vnodes.
Pitfalls
- Scaling out a service whose bottleneck is a shared database or lock.
- Sticky in-memory state on app servers.
hash mod N for anything that must survive resizing.
- Too few vnodes (uneven load); ignoring hot keys.
- Autoscaling on a metric that lags or doesn't reflect saturation.
- Cross-partition queries and transactions everywhere after sharding.
Glossary
- σ (contention) / κ (coherency): USL parameters.
- Shard / partition: a subset of data on its own node.
- Virtual node: one of many ring positions per physical node.
- Rebalancing: moving partitions when nodes join or leave.
- Hot key / hot partition: one key or range getting a disproportionate share of load.
125
Key ideas
- Availability = good time ÷ total time, or good requests ÷ total; define it per user-facing operation.
- Series multiplies availabilities; parallel multiplies unavailabilities, only if failures are independent.
- Eliminate single points of failure at every layer: instances, zones, load balancers, databases, DNS, credentials, deploys, people.
- Correlated failures (shared rack, zone, deploy, config, dependency, bug) defeat redundancy; diversify and stagger.
- Failover: detection (health checks, heartbeats) + decision (election, promotion) + redirection (clients, DNS); each takes time.
- Quorums: majority-based systems tolerate ⌊(N−1)/2⌋ failures; W + R > N for overlapping reads and writes.
- Degraded modes: stale reads, read-only operation, feature shedding keep partial service when full service isn't possible.
- MTTR matters as much as MTBF: availability ≈ MTBF ÷ (MTBF + MTTR).
Numbers to remember
- 99.9% ≈ 43.8 min/month; 99.99% ≈ 4.4 min/month; 99.999% ≈ 26 s/month.
- Lab: etcd leader kill → 1.55 s without successful writes; quorum loss → no writes or linearizable reads.
- 3 members tolerate 1 failure; 5 tolerate 2.
Pitfalls
- Redundant stateless tiers in front of a single database.
- Failover that has never been tested (or that needs a human at 3 a.m.).
- Clients pinned to one endpoint or caching DNS forever.
- Health checks that test dependencies, causing a whole fleet to restart when the database blips.
- Even-sized quorums; two-node clusters with split-brain risk.
- Counting availability by uptime of servers rather than success of user requests.
Glossary
- SPOF: single point of failure.
- MTBF / MTTR: mean time between failures / to recovery.
- Leader election: choosing the member that orders writes.
- Split brain: two members both acting as leader.
- Linearizable vs serializable read (etcd): quorum-confirmed latest value vs local, possibly stale value.
126
Key ideas
- Why caches work: temporal and spatial locality, and skew; hit ratio drives benefit.
- Where: browser/client, CDN, gateway, in-process, distributed (Redis, Memcached), database buffer cache.
- Patterns: cache-aside (lazy), read-through, write-through, write-behind (write-back), refresh-ahead.
- Eviction: LRU, LFU, TinyLFU/W-TinyLFU (Caffeine), random; size and TTL limits.
- Invalidation: TTL, delete-on-write, write-through, CDC-driven, versioned keys; decide staleness per data item.
- Stampedes: single-flight locks, probabilistic early refresh, stale-while-revalidate, coalescing.
- Failure modes: cold start after restart (warm-up), cache outage sending full load to the database, hot keys, memory fragmentation, inconsistent copies.
- Negative caching: cache "not found" briefly to stop repeated misses.
Numbers to remember
- Lab: 1% LRU cache → 1% hits uniform, 34% at Zipf 0.9, 66% at Zipf 1.1.
- Lab: 20.7 ms query → 0.13 ms cache hit (p50); database load cut to a sixth.
- Lab: stampede 24 → 2 database queries with a lock.
Pitfalls
- Caching without measuring skew or hit ratio.
- Updating cache values on write (ordering races) instead of deleting.
- Same TTL for every key (synchronised expiry); add jitter.
- The database sized only for cache-hit load, so a cache restart takes it down.
- Caching personalised or authorised data under shared keys.
- Unbounded caches and missing negative caching.
Glossary
- Hit ratio: hits ÷ requests.
- Cache-aside: application checks cache, loads source on miss.
- Write-behind: writes acknowledged from cache, persisted later.
- Stampede / thundering herd: many concurrent misses on one key.
- Stale-while-revalidate: serve the old value while fetching a new one.
127
Key ideas
- Choose the data model first (relational, document, key-value, wide-column, graph, time-series, search) by access patterns and invariants.
- One well-tuned database goes far; indexes, query design and connection pooling before distribution.
- Read replicas scale reads; async lag breaks read-your-writes and monotonic reads; route accordingly or wait for LSN/GTID.
- Synchronous replication trades commit latency and availability for zero lag on chosen replicas.
- Partitioning (range, list, hash) inside one database: pruning, cheap archiving, smaller indexes.
- Sharding across servers: shard key choice (high cardinality, even load, aligned with queries and invariants), resharding, cross-shard joins and transactions, global IDs.
- Distributed SQL (Spanner, CockroachDB, YugabyteDB, TiDB) and sharding middleware (Vitess, Citus).
- Migrations at scale: expand and contract, online schema change, backfills in batches.
Numbers to remember
- Lab: 93% of immediate replica reads missed a just-committed write, even idle.
- Lab: waiting for LSN replay cost p50 17.5 ms (max 97 ms) under write load.
- Lab: monthly partitions made a month's aggregate 4.5× faster; DROP partition 37 ms vs DELETE 142 ms + vacuum.
Pitfalls
- Reading your own writes from a replica.
- Sharding before exhausting one database (indexes, pooling, replicas, partitions).
- Shard keys that create hot shards or force cross-shard queries for the main use case.
- Partitioning without the key in queries (no pruning).
- Replicas and WAL not counted in disk capacity.
- Long transactions and replication slots retaining WAL indefinitely.
Glossary
- WAL / LSN: write-ahead log / position in it.
- Replication lag: how far a replica is behind the primary.
- Partition pruning: skipping partitions that can't match.
- Shard key: the attribute that decides which shard holds a row.
- Resharding: changing the shard layout while running.
128
Key ideas
- Why: decouple in time (consumer can be down), load (bursts buffered), and knowledge (publisher doesn't know consumers).
- Queues vs streams: queues deliver and delete; streams retain an ordered log for replay and many independent consumers.
- Topologies: point-to-point (work queue), pub/sub (fan-out), competing consumers, request/reply over messaging.
- Delivery: at-most-once, at-least-once (normal), effectively-once via deduplication + idempotent consumers (+ transactions where supported).
- Ordering is per partition/subject; route by entity key to keep per-entity order with parallelism.
- Acks and redelivery: ack after processing; ack timeouts; max deliveries; dead-letter queues for poison messages.
- Backpressure and lag: monitor pending/lag; drain time = backlog ÷ (consume − produce).
- Schemas: versioned, compatible (Avro, Protobuf, JSON Schema with a registry).
Numbers to remember
- Lab: queue group of 3 split 3,000 messages 1,006 / 1,007 / 987; each plain subscriber got all 3,000.
- Lab: un-acked messages redelivered after
ack_wait = 2 s; a duplicate publish with the same ID was stored once.
- Lab: confirmed one-at-a-time publishing ≈ 4,000/s, bounded by round trips.
Pitfalls
- Assuming exactly-once delivery; non-idempotent consumers.
- Acking before processing (loses work on crash) or ack_wait shorter than processing.
- No dead-letter handling, so a poison message blocks a partition.
- Global ordering expectations with parallel consumers.
- Unbounded backlogs nobody watches; retention shorter than worst-case downtime.
- Messaging used for request/response that needs an immediate answer.
Glossary
- Queue group / consumer group: consumers sharing a stream of work.
- Ack wait / visibility timeout: time before an unacked message is redelivered.
- DLQ: dead-letter queue for messages that repeatedly fail.
- Consumer lag: messages produced but not yet consumed.
- Idempotent consumer: one whose effect is the same however many times a message is processed.
129
Key ideas
- Start from invariants: which rules must never break; spend strong consistency there.
- Isolation levels and anomalies: dirty read, non-repeatable read, phantom, lost update, write skew; read committed < repeatable read/snapshot < serializable.
- PostgreSQL: read committed default; repeatable read = snapshot isolation (detects write-write conflicts); serializable = SSI (detects dangerous read-write cycles; needs retries).
- Techniques: atomic updates,
SELECT … FOR UPDATE, optimistic concurrency (versions), constraints, materialised conflicts, append-only ledgers.
- Distributed guarantees: linearizability, sequential, causal, read-your-writes, monotonic reads, eventual; CAP (during partitions choose C or A) and PACELC (else latency vs consistency).
- Across services: no distributed transaction by default; sagas, outbox, idempotency and reconciliation (chapter 131).
Numbers to remember
- Lab: write skew broke the rule under read committed and repeatable read; serializable aborted one of two.
- Lab: lost update left ₹70 instead of ₹20 under read committed;
FOR UPDATE gave ₹20.
Pitfalls
- Read-modify-write in application code without locks or versions.
- Assuming repeatable read prevents write skew.
- Serializable without retry loops.
- One global consistency level for everything (too slow or too weak).
- Caches and replicas on paths that enforce invariants.
- Treating "eventual" as "soon" without measuring lag.
Glossary
- Write skew: concurrent transactions each preserve an invariant alone but break it together.
- Lost update: one write silently overwrites another's effect.
- SSI: serializable snapshot isolation.
- Optimistic concurrency: detect conflicts at write time via versions.
- Linearizability: single-copy, real-time-ordered behaviour per object.
130
Key ideas
- Cascading failure: slowness → queueing → resource exhaustion → more failures; retries and missing timeouts amplify it.
- Timeouts on every remote call, derived from latency requirements; deadlines propagated end to end.
- Retries: only idempotent operations; one layer; exponential backoff with jitter; caps; retry budgets; honour
Retry-After and "don't retry" signals.
- Circuit breakers: closed → open (fail fast) → half-open (probe); per dependency.
- Bulkheads: separate pools/concurrency limits per dependency or tenant.
- Load shedding and admission control: reject early (429/503) when over capacity; prioritise important traffic; adaptive concurrency limits.
- Fallbacks and graceful degradation: cached or default answers, feature shedding; mark degraded responses.
- Idempotency: keys for writes; makes retries and redelivery safe.
Numbers to remember
- Lab: 3 attempts at each of 3 layers → 27 requests at the bottom; retrying only at the edge → 3.
- Simulation: full jitter cut the busiest 100 ms from 1,000 to 145 requests.
- Common retry budget: about 10% extra load.
Pitfalls
- Default timeouts of 30–60 s or none at all.
- Retries at every layer; retrying non-idempotent writes.
- Backoff without jitter; unlimited retries.
- Breakers or bulkheads shared across unrelated dependencies.
- Fallbacks that hide outages from monitoring.
- Health checks that cascade failures (restarting healthy instances).
Glossary
- Retry amplification: retries multiplying load across layers.
- Full / decorrelated jitter: randomised backoff schemes.
- Retry budget: limit on retries relative to normal traffic.
- Half-open: breaker state allowing trial requests.
- Adaptive concurrency: limits that adjust to observed latency (e.g. Netflix's concurrency-limits, Envoy's adaptive concurrency filter).
131
Key ideas
- Events (facts, past tense) vs commands (requests to act) vs queries.
- Notification events (ID only, consumers call back) vs event-carried state transfer (enough data to act).
- Envelope: type, version, event ID, time, subject/aggregate ID, producer, trace context; payload.
- Reliable publishing: transactional outbox + relay (polling or CDC); never dual write.
- Reliable consuming: idempotency (inbox/dedup table), ordering per aggregate, retries, DLQ.
- Schema evolution: additive changes, versioned types, registries, upcasting.
- Sagas: choreography or orchestration, with compensations and timeouts.
- Event sourcing: state as a fold over an event log; powerful audit and replay, costly migrations and queries (pair with CQRS read models).
- Ownership: each event type owned by one domain/service.
Numbers to remember
- Lab: 5% crashes between commit and publish lost 54 of 1,000 events.
- Lab: outbox with 53 relay crashes → 1,053 messages, 53 duplicates skipped, 0 missing.
Pitfalls
- Dual writes to a database and a broker.
- Consumers that can't handle duplicates or reordering.
- Events that leak internal table structure (consumers coupled to producer schemas).
- Fat events with sensitive data broadcast to everyone.
- Choreography so complex nobody can trace a flow; no reconciliation.
- Event sourcing adopted for CRUD domains.
Glossary
- Outbox / inbox: tables making publish / consume atomic with local state.
- CDC: change data capture from the database log.
- Saga: a sequence of local transactions with compensations.
- CQRS: separate write model and read models.
- Upcasting: converting old event versions to the current shape on read.
132
Key ideas
- Resources and operations shaped by client use cases; nouns for resources, HTTP methods for verbs; status codes used correctly.
- Pagination: cursor/keyset for large or changing lists; opaque cursors; limits.
- Errors: consistent, machine-readable (RFC 9457 problem details), with stable codes.
- Idempotency: PUT/DELETE by definition; POST with idempotency keys.
- Caching and concurrency: Cache-Control, ETag/If-None-Match (304), If-Match (412) for optimistic writes.
- Long-running operations: 202 + status resource, or webhooks/events.
- Evolution: additive changes; tolerant readers; versioning (URL, header, media type) only for breaking changes; deprecation with sunset dates.
- Styles: REST, GraphQL (field selection, DataLoader, cost limits), gRPC (Protobuf, deadlines, streaming), async APIs (AsyncAPI).
- Round trips dominate; design for one call per screen or use batching.
Numbers to remember
- Lab: OFFSET at row 1,000,000 took 70 ms; keyset 0.37 ms.
- Lab: 30 per-item requests 20.6 ms vs 1 batched request 1.3 ms (16×).
- Lab: Nagle + delayed ACK added ≈40 ms per keep-alive request until
TCP_NODELAY.
- Lab: a 38 KB menu became a 0-byte 304 with an ETag.
Pitfalls
- OFFSET pagination on large tables; unbounded list endpoints.
- Chatty APIs that force N+1 round trips.
- Ad-hoc error formats; 200 responses with error bodies.
- Breaking changes without versioning or notice; strict deserialisers.
- GraphQL without depth/cost limits or batching.
- POST retries without idempotency keys.
Glossary
- Keyset (cursor) pagination: "rows after this key".
- ETag: response version identifier for caching and concurrency.
- Problem details: RFC 9457 JSON error format.
- DataLoader: batches and caches per-request lookups in GraphQL.
- Sunset header: announces when a deprecated API will be removed.
133
Key ideas
- Two isolation requirements: data (no cross-tenant access) and performance (no noisy neighbours).
- Models: pooled (shared tables + tenant ID), bridge (schema per tenant), silo (database or stack per tenant), hybrid tiers.
- Tenant context: from authentication, propagated through every hop (headers, context,
set local on DB connections), never from client input alone.
- Enforcement in depth: RLS or query scoping in a data-access layer, per-tenant encryption keys where needed, tests for cross-tenant access.
- Performance isolation: per-tenant rate limits, quotas, concurrency caps, fair queueing, separate queues, timeouts; dedicated capacity for big tenants.
- Operations: onboarding/offboarding automation, per-tenant migrations, backups and restores per tenant, data residency, tenant-level metrics and cost attribution.
Numbers to remember
- Lab: one missing filter exposed 3 rows of another tenant; RLS reduced it to 0 and blocked cross-tenant inserts.
- Lab: superuser connections bypass RLS even with FORCE.
- Simulation: a tenant at 150% of capacity pushed a small tenant's p50 to 9 s; a per-tenant cap restored 20 ms.
Pitfalls
- Trusting a tenant ID from the request body or URL without checking it against the authenticated identity.
- RLS with the application connected as owner or superuser.
- Session-level tenant settings leaking across pooled connections.
- Shared caches keyed without the tenant.
- No per-tenant limits; one tenant's batch job harming everyone.
- Restoring one tenant's data being impossible in a pooled model.
Glossary
- Pooled / silo: shared resources / dedicated resources per tenant.
- RLS: database-enforced row filtering by policy.
- Noisy neighbour: a tenant whose usage degrades others.
- Tenant tiering: different isolation and limits per plan.
- Cost attribution: assigning infrastructure cost to tenants.
134
Key ideas
- Why global: latency for distant users, regional disaster tolerance, data residency and sovereignty.
- Physics: ~1 ms RTT per 100 km of fibre at best; routes add 50–100%; handshakes add round trips.
- Traffic routing: geo-DNS, latency-based DNS, anycast, global load balancers; health-based failover and its DNS-TTL lag.
- Edge: CDNs for static and cacheable content, TLS termination near users, edge compute for simple logic.
- Data: active-passive (async, RPO > 0), synchronous within a region across zones, partitioned ownership (home regions), globally consistent databases (consensus per write).
- Conflicts in multi-writer designs: avoid by ownership; otherwise last-writer-wins (lossy), CRDTs, or application merges.
- DR: RPO and RTO targets, runbooks, regular failover drills, regional independence of dependencies (auth, DNS, secrets).
- Residency: per-tenant or per-user region pinning; keep PII in-region; replicate only what's allowed.
Numbers to remember
- Hyderabad → Frankfurt ≈ 7,100 km ≈ 71 ms best-case RTT; → N. Virginia ≈ 133 ms.
- Lab: async commit 0.9 ms with a 70 ms-away replica; sync commit 74 ms; sync with the replica unreachable: writes blocked.
Pitfalls
- Chatty request paths that cross regions several times.
- Synchronous cross-region replication with a single standby (writes stop on a partition).
- Failover plans that depend on a service hosted only in the failed region.
- Active-active without a conflict strategy.
- Ignoring residency for logs, backups and analytics copies.
- Never practising regional failover.
Glossary
- RPO / RTO: recovery point (data loss) / recovery time objectives.
- Anycast: one IP announced from many locations; routing picks the nearest.
- Home region: where an entity's authoritative data lives.
- CRDT: data type whose replicas merge without conflicts.
- Data residency: legal or contractual requirement on where data is stored.
CS
Key ideas
- One method for every design: requirements → estimates → API and data model → architecture → deep dives → failure modes → evolution.
- URL shortener: read-heavy; code generation (random with uniqueness check, or counter ranges); redirect caching; analytics off the hot path.
- News feed: fan-out on write vs on read; hybrid for celebrities; ranking; caching timelines.
- Chat: persistent connections, per-conversation ordering, delivery receipts, offline storage, presence.
- Ride-hailing dispatch: geospatial indexing, location update rates, matching under contention, state machines.
- Payments ledger: double-entry, idempotency, strong consistency, reconciliation, audit.
- Review checklist: requirements met, single points of failure, bottlenecks, consistency per data item, failure handling, security, cost, operability, evolution.
Numbers to remember
- 62⁷ ≈ 3.5 × 10¹²; random codes collide around √N ≈ 1.9 million.
- Lab: 1,846 observed collisions vs 1,863 predicted for 1 M hex codes.
- Lab: 148 bytes per short link; 1 billion ≈ 150 GB; PK lookup ≈ 0.1 ms.
Pitfalls
- Starting from a remembered architecture instead of the requirements.
- Unchecked estimates driving premature sharding (or under-provisioning).
- Designs with no failure-mode or evolution section.
- Ignoring the hot path vs off-path split (analytics in the redirect path).
- Treating interviews as recall rather than reasoning out loud.
Glossary
- Fan-out on write / read: precompute feeds when posting / assemble when reading.
- Geohash / S2 / H3: spatial indexing schemes.
- Double-entry ledger: every transaction records equal debits and credits.
- Birthday bound: collisions likely around √N random draws from N values.
- Hot path: the latency-critical request path.