System design walkthroughs 1: foundations
Problem. Full interview answers for the bank’s foundation questions — each with requirements, estimation math, API, core design, and deep dives, in the order you’d actually say them. Part 1 of 6: foundations. (2: feeds · 3: geo & marketplaces · 4: media & storage · 5: money · 6: AI era)
1. URL shortener [Google, Amazon, Microsoft, Uber]
Requirements. Functional: shorten URL, redirect on visit, optional custom aliases and expiry. Non-functional: 10:1 read-to-write ratio, redirect p99 under 50 ms, highly available reads.
Estimation. 100M new URLs/month ≈ 40 writes/s, ~400 reads/s. 500 bytes per row × 100M × 36 months ≈ 1.8 TB — one sharded database plus a cache, since reads repeat.
API. POST /shorten {url, alias?, ttl?} → {code}, GET /{code} → 302.
Core design. Counter + base62 codes (collision-free, ~3.5 trillion at 7 chars); cache-aside reads; 302 so browsers don’t cache permanently and clicks stay measurable. Full version with diagrams in part 5 of the system design course.
2. Rate limiter [Stripe, Cloudflare, Google, Amazon]
Requirements. Functional: allow/deny per key against a configured rate. Non-functional: single-digit-ms overhead on every request, must not become the outage when it fails (fail open for reads, closed for writes — state it).
Estimation. 10k decisions/s per gateway. 10M active keys × (tokens + timestamp ≈ 32 B) ≈ 320 MB per window in Redis — fits one instance, shard by key past that.
API. Usually middleware, not REST: allow(key, limit, window) → bool.
Core design. Token bucket in Redis via atomic Lua (capacity bounds bursts,
refill bounds the average); 429 + Retry-After on empty.
Deep dives. Fixed window’s 2× boundary spike vs sliding-window counters; two-tier limits (local approximate + global exact); always return limit headers so clients back off instead of hammering.
3. Web crawler [Google, Microsoft, Amazon, ByteDance]
Requirements. Functional: fetch N pages, refresh on a schedule. Non-functional: politeness (per-domain delays, robots.txt), no duplicate work, survive worker death.
Estimation. 1B pages × 10 KB ≈ 10 PB stored. Crawling 1B pages/week needs ≈ 1,650 pages/s; 100 fetchers × 20 pages/s covers it with headroom.
API. Internal: seed(urls), status(url) → state.
Core design. Priority frontier queue (PageRank, then change-rate), fetcher pool with per-host delay, parser extracting links, content-hash dedup (SimHash for near-dupes), connection and DNS reuse.
flowchart LR
F[Frontier queue] --> FE[Fetcher]
FE --> P[Parser]
P --> D[Dedup by hash]
D --> S[(Content store)]
P -.->|new links| F
Deep dives. Recrawl scheduling by observed change rate; distributed dedup (bloom filter first, exact second); trap defenses (calendars, infinite facets); freshness vs coverage trade-off stated up front.
4. Distributed key-value store [Amazon, Google, Redis Labs, MongoDB]
Requirements. Functional: get/put by key. Non-functional: p99 under 10 ms, survives node loss without data loss, scales by adding boxes.
Estimation. 100k reads/s, 10k writes/s; 10 TB dataset × replication factor 3 = 30 TB; ~1k QPS per node → ~100 storage nodes plus headroom.
API. GET /v1/keys/{k}, PUT /v1/keys/{k} {value, version?}.
Core design. Consistent-hash ring for placement, quorum reads/writes (\(W + R > N\) so reads overlap fresh copies), hinted handoff for dead nodes, Merkle-tree anti-entropy for background repair.
Deep dives. Say when you’d flip to consistency-first (locks, money) and what breaks when a node flaps (gossip storms, reboot loops). This answer reappears inside half the bank — nail it once.
5. Distributed cache [Meta, Amazon, Google, Redis]
Requirements. Functional: get/set with TTL. Non-functional: sub-ms p99, hit ratio as the business metric, no cold-start death spiral.
Estimation. 1M reads/s at 95% hit ratio leaves 50k/s for the database — verify the DB survives exactly that. 100 GB hot set across the pool.
API. GET key, SET key value ttl, DELETE key (invalidate on write).
Core design. Look-aside from the app, client hashes to pool nodes, LRU within nodes, jittered TTLs, request coalescing so one miss triggers one fill. Mechanics in depth in the caching chapter.
6. CDN [Cloudflare, Akamai, Fastly, AWS]
Requirements. Functional: serve static bytes near users, purge on deploy. Non-functional: 90%+ origin offload, TLS everywhere, survive origin outages (stale-serve).
Estimation. 5 PB library, 800 Gbps peak; each offloaded percent is origin servers not bought.
API. Origin pull on miss; POST /purge {paths} or versioned filenames
instead of purging.
Core design. Edge PoPs, regional shield tiers to collapse misses, TTL by content type, TLS termination at edge. Stale-while-revalidate during origin brownouts, stated as policy not accident.
7. Distributed message queue [LinkedIn, Confluent, Amazon, Google]
Requirements. Functional: publish, consume in order per partition, retain for days. Non-functional: survive broker loss, backpressure instead of silent drops.
Estimation. 500k msgs/s × 1 KB = 500 MB/s ingress; 7-day retention ≈ 300 TB; consumers scale by partition count, so size partitions for the consumer fleet, not the producers.
API. POST /topics/{t}/publish, GET /topics/{t}/poll?offset=,
POST /ack, consumer-group coordination.
Core design. Partitioned append-only log, consumer-tracked offsets, group rebalancing on membership change, at-least-once default with idempotent consumers. Full treatment in the messaging chapter.
8. Task and delayed-job scheduler [Google, Amazon, OpenAI, Cursor, Decagon]
Requirements. Functional: run at time T, recurring cron, cancel. Non-functional: at-least-once execution, second-level precision, survive worker death mid-job.
Estimation. 50M jobs/day ≈ 600/s average, 5k/s peak; 30-day history for audit.
API. POST /jobs {run_at, payload, idempotency_key}, DELETE
/jobs/{id}, GET /jobs/{id}/status.
Core design. Due jobs in a time-ordered structure (sorted set / timer wheel), workers lease with heartbeats, visibility timeouts redeliver on death, durable state before the first ack. Jobs themselves idempotent — delivery is at-least-once, always.
9. Logging and metrics pipeline [Splunk, Elastic, Datadog]
Requirements. Functional: ingest structured events, query recent fast, alert in real time. Non-functional: never lose crash evidence, survive source spikes.
Estimation. 50k events/s × 1 KB = 50 MB/s ≈ 4 TB/day; hot 7 days (~30 TB), warm 90 days, cold archive after.
API. Agent ship protocol; POST /query {timerange, filters, agg};
POST /alerts {condition, channel}.
Core design. Agents → buffered ingest → stream aggregation (p50/p99 histograms, never averages alone) → tiered storage. Cardinality caps on label sets, tail sampling kept whole, and the alerting path physically separate from batch analytics so one can’t starve the other.