SD·CS
Case Studies: Putting It All Together
Five complete designs worked through with the method from chapter 121 (requirements, estimates, API and data model, high-level architecture, deep dives, failure modes and evolution): a URL shortener, a social news feed, a chat and messaging system, a ride-hailing dispatch system, and a payments ledger, plus a checklist and rubric for reviewing any design.
Start here: one method, five systems
Every case study in this chapter runs the same seven steps, and the steps matter more than any one design: requirements → estimates → API and data model → high-level architecture → deep dives on the hardest parts → failure modes → evolution. Practise the steps and the designs follow; memorise designs and the first unfamiliar requirement breaks them.
The method on a small example: tiffin short links
The tiffin centre texts customers links like tfn.in/aB3xK9q to today's menu. A few numbers decide the design:
code length: 62^6 = 56.8 billion codes; 62^7 = 3.5 trillion
random 7-char codes, chance of at least one collision:
1,000,000 codes → 13% 100,000,000 codes → certain (≈1,420 expected)
measured in PostgreSQL (1 million links): 148 bytes per link incl. index; lookup 103 µs
Random codes will collide long before the key space fills (the birthday paradox), so the design must either check for collisions on insert (a unique constraint plus retry) or generate codes from a counter (no collisions, but guessable and needs coordination). A billion links at 148 bytes is about 150 GB: one database with replicas, not a cluster. And a 0.1 ms lookup, cached at the edge for popular links, makes redirects cheap. Three measurements settled three design questions.
How deep to go in the case studies
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L4 everywhere, and its projects at L5.
| Level | What you can do |
|---|---|
| L1 | Follow a worked design and name its building blocks |
| L2 | Reproduce a case study's design from its requirements without notes |
| L3 | Explain why each choice was made and what would change it |
| L4 | Critique a design with the checklist: find missing requirements, bottlenecks and failure modes |
| L5 | Design an unfamiliar system end to end with the method, under time pressure |
| L6 | Review and guide others' designs across an organisation |
How to use these case studies
Each case study follows the same structure so you can practise the method:
- Requirements: functional scope, NFRs as targets, out of scope.
- Estimates: the numbers that drive the design (chapter 122).
- API and data model.
- High-level design: components and data flows.
- Deep dives: the two or three hardest problems.
- Failure modes and operations.
- Evolution: what changes at 10× scale or with new requirements.
Try designing each yourself first (45–60 minutes, on paper), then compare. There's no single correct answer: what matters is that decisions trace back to requirements and that trade-offs are explicit.
Case 1: URL shortener
Requirements
Functional: create short links (random code or custom alias, optional expiry), redirect, click statistics per link (by day, country, referrer), delete links, API access with keys. Out of scope: custom domains, link editing, QR codes.
| NFR | Target |
|---|---|
| Redirect latency | p99 < 50 ms server-side, served near users |
| Redirect availability | 99.99% |
| Create availability | 99.9% |
| Durability | No created link lost |
| Freshness | New links work within 1 s globally; deletes propagate within 60 s; stats within 5 min |
| Abuse | Malicious URLs blocked; creation rate-limited |
Estimates
From chapter 122: ~40 creates/s average (400 peak), ~4,000 redirects/s average (40,000 peak), 6 billion links over 5 years (~3 TB + replicas), a hot set of ~10 GB, click events ~70 GB/day raw.
API and data model
POST /v1/links { "url": "...", "alias": "spring-sale", "expiresAt": "2027-01-01T00:00:00Z" }
→ 201 { "code": "spring-sale", "shortUrl": "https://sho.rt/spring-sale" }
GET /{code} → 301/302 Location: <url> | 404 | 410
GET /v1/links/{code}/stats?from=&to=&groupBy=day,country
DELETE /v1/links/{code} → 204
links(code PK, long_url, owner_id, created_at, expires_at, status) -- key-value access by code
clicks_hourly(code, hour, country, referrer_domain, count) -- aggregated stats
High-level design
Deep dives
Code generation. Options:
| Approach | How | Trade-offs |
|---|---|---|
| Random base62 (7–8 chars) + conditional insert | Generate random code; PutItem with attribute_not_exists(code) / INSERT … ON CONFLICT DO NOTHING; retry on collision |
Simple, no coordination, unguessable; collision probability tiny at this density |
| Counter + base62 encoding | Global sequence (or ranges allocated to each instance from a coordinator) | Short codes, no collisions; codes are enumerable (privacy/abuse issue) unless scrambled with a bijective permutation |
| Hash of URL (truncated) | base62(sha256(url))[:7] |
Deduplicates identical URLs; collisions must be handled; same URL by different users gets same code (privacy) |
Choose random codes with conditional writes: no coordination service, safe under concurrency, and unguessable. Custom aliases use the same conditional insert (uniqueness enforced by the store).
Redirect path performance. The hot path must be tiny: edge cache → in-memory cache → KV store. Status code choice: 301 (permanent) is cached aggressively by browsers and CDNs (cheapest, but you lose click visibility and can't change/delete reliably); 302/307 keeps every click visible to the service. Common choice: 302 with short CDN TTL (e.g. 60 s) and click logging at the edge/service. Negative caching for unknown codes (short TTL) stops enumeration scans from hitting the store.
Click analytics. Never write to a database synchronously per click. Emit events (from the redirect service or edge logs) to a stream; a stream processor aggregates per (code, hour, country, referrer domain) and upserts counts into an analytical store (ClickHouse, or partitioned Postgres tables as in the ADR of chapter 121). Bot filtering in the pipeline; raw events archived to object storage.
Abuse. Check URLs against threat-intelligence APIs (e.g. Google Safe Browsing) at creation and periodically; rate limits per API key and IP; block shortening of known shortener domains (redirect chains); a takedown process that disables codes globally (purge CDN, delete cache keys).
Failure modes
- Store unavailable: serve from cache/edge (most traffic); creation fails gracefully.
- Cache cluster loss: redirect service falls back to the store with concurrency limits and request coalescing (hot links).
- Stream down: buffer click events locally/drop with sampling; redirects must never block on analytics.
- Region failure: links replicated to other regions (global tables or async replicas); edge routes redirects to healthy regions.
Evolution
10× traffic: more edge caching, regional read replicas of the links store. Custom domains: per-domain routing table and certificate automation (ACME). Real-time analytics: stream-native store. Link editing: switch to 302-only and invalidation by tag.
Case 2: Social news feed
Requirements
Functional: users follow others; post text/images; see a home feed of posts from people they follow, newest/ranked first; like and comment counts. Out of scope: ads, stories, search.
NFRs: feed load p99 < 300 ms; 99.95% availability for reads; new posts appear in followers' feeds within a few seconds (eventual is fine); 200 M DAU; average 200 follows; some accounts have tens of millions of followers.
Estimates
- Posts: 200 M × 0.5/day = 100 M/day ≈ 1,200/s (peak ~4k/s).
- Feed reads: 200 M × 20 refreshes/day = 4 B/day ≈ 46k/s (peak ~150k/s).
- Fan-out on write: 100 M posts × 200 followers = 20 B feed insertions/day ≈ 230k/s average: heavy but feasible; but a celebrity post to 50 M followers is a 50 M-write burst.
- Feed cache: keep the latest ~500 post IDs per active user: 200 M × 500 × 16 B ≈ 1.6 TB in memory across a cluster (IDs only).
Core design decision: fan-out on write vs read
| Fan-out on write (push) | Fan-out on read (pull) | |
|---|---|---|
| On post | Insert post ID into every follower's precomputed feed | Just store the post |
| On feed read | Read the user's precomputed list (fast) | Fetch recent posts from all followees and merge (slow for users following many) |
| Problem | Celebrities: millions of writes per post; wasted work for inactive followers | Read latency and load for every feed view |
Hybrid (used by large social networks): push for normal accounts to their active followers; for celebrity accounts (followers above a threshold), don't fan out; at read time, merge the precomputed feed with recent posts pulled from the few celebrities the user follows.
Data and storage
- Posts: sharded by
post_id(Snowflake-style time-ordered IDs make "newest" sorting easy); media in object storage behind a CDN. - Follow graph: two directions (followers of X, followees of Y) stored separately, partitioned by user ID (wide-column store or sharded SQL); cached for hot users.
- Feed cache: per-user list of recent post IDs (Redis sorted sets or lists, trimmed to N); rebuilt on demand for users who return after a long time (don't fan out to inactive users).
- Counters (likes, comments): sharded counters with asynchronous aggregation; approximate display ("1.2M") is fine.
- Ranking: candidate generation (feed + celebrity posts + recommendations) → ranking model scoring → final ordering; ranking features from a feature store; results cached briefly per user.
Failure modes and trade-offs
- Fan-out backlog during spikes: queue-based leveling; feeds slightly stale; prioritise active users.
- Celebrity threshold tuning: balance write amplification vs read merge cost.
- Deleted/edited posts: tombstones checked at hydration time (fan-out entries may still point to them).
- Privacy changes (blocked users, private accounts) enforced at read time (filter during hydration), since precomputed feeds may be stale.
- Cache loss: rebuild feeds lazily from followees' recent posts (pull) with protection against stampedes.
Case 3: Chat and messaging
Requirements
Functional: 1:1 and group chats (up to 1,000 members), text and media, delivery and read receipts, online presence, push notifications when offline, message history across devices. Out of scope: voice/video calls, end-to-end encryption details (mention as an option).
NFRs: message delivery p99 < 500 ms when both online; no message loss once acknowledged; per-conversation ordering; 500 M DAU (estimates in chapter 122: ~600k sends/s peak, ~2.4 M deliveries/s, 250 M concurrent connections, ~6 TB/day).
Design
- Connection gateways hold WebSocket (or MQTT) connections; a presence/session registry maps user → gateway(s) and devices (chapter 132).
- Message flow: client sends message with a client-generated ID (idempotency) → gateway → chat service assigns a per-conversation sequence number, persists to the message store, acknowledges to the sender ("sent") → fan-out: for each recipient device, look up the gateway and deliver via pub/sub; if offline, enqueue a push notification (APNs/FCM) and leave it for sync.
- Message store: partitioned by
conversation_id, clustered by sequence (wide-column store such as Cassandra/ScyllaDB/Bigtable, or sharded SQL), so "fetch messages after seq N" is a single-partition range scan. Hot old data tiered to cheaper storage. - Sync model: each device tracks the last sequence number it has per conversation (or a per-user inbox cursor); on reconnect, it fetches everything newer. This makes delivery robust: real-time push is an optimisation; sync is the source of truth.
- Ordering: per-conversation sequence assigned by the single owner of that conversation's partition (or a per-conversation counter with conditional increments); clients render by sequence, not arrival time.
- Receipts: delivered/read receipts are themselves small messages (or per-member "last read seq" pointers updated with coalescing: one pointer update rather than a receipt per message).
- Groups: fan-out to up to 1,000 members' devices; for very large groups/channels, switch to pull (members fetch from the conversation log) instead of per-member pushes.
- Media: uploaded directly to object storage via pre-signed URLs; messages carry references; CDN for downloads; thumbnails generated asynchronously.
- End-to-end encryption (Signal protocol, MLS for groups): the server stores and routes ciphertext only; affects search, moderation and multi-device design.
Failure handling: client retries with the same client message ID (deduplicated server-side) → exactly-once appearance; gateway failure → clients reconnect elsewhere and sync; store region failure → replicated store with local quorum per region and cross-region async replication; hot conversations (huge groups) → dedicated partitions and pull-based delivery.
Case 4: Ride-hailing dispatch
Requirements
Functional: riders request rides; system finds nearby available drivers, offers the trip, driver accepts; live tracking; fare estimate and payment after the trip. Focus: matching and location.
NFRs: match within 5–10 s; location freshness within ~5 s; 1 M online drivers at peak, updates every 4 s (250k writes/s, chapter 122); 99.99% availability for requesting rides in each city; city-level independence (an outage in one city shouldn't affect others).
Design
- Geospatial indexing: divide the map into cells (Uber's H3 hexagons, Google S2 cells, geohashes). Each driver's latest position maps to a cell; the location service keeps
cell → set of available driversanddriver → (position, status, timestamp)in memory, partitioned by city/region (natural sharding: matching never crosses cities). - Ingest: driver apps send updates to regional gateways → location service shards (in-memory, replicated for failover) → also published to a stream for history, ETA models and analytics. Losing an individual update is fine (next one arrives in 4 s); the store keeps only the latest.
- Matching: on a ride request, query the rider's cell and neighbouring rings (k-ring in H3) for available drivers, compute ETAs (road-network routing service, not straight-line distance), rank by ETA and other factors, and offer to the best driver with a short timeout; on decline/timeout, offer to the next. To prevent double-booking, the driver's state transition
AVAILABLE → OFFEREDis an atomic conditional update (compare-and-set on the driver's state/version) in the dispatch shard that owns the driver. - Trip service: durable state machine for the trip (
REQUESTED → MATCHED → ARRIVING → IN_PROGRESS → COMPLETED/CANCELLED) in a strongly consistent store, with events to pricing, payments, notifications. - Live tracking: rider apps subscribe (WebSocket/SSE) to the assigned driver's location stream for the trip's duration.
- Surge/dynamic pricing: stream processing computes supply/demand per cell every minute.
Failure handling: a location shard failure → replica takes over (positions refill within seconds anyway); dispatch idempotency (request IDs) so retries don't create two trips; trip service outage in a city is the critical failure (cell per city/region with independent stacks); degraded mode when routing/ETA is down: fall back to straight-line estimates.
Case 5: Payments ledger
Requirements
Functional: accept payments from customers via external payment providers (cards, UPI, wallets), track balances for merchants, pay out to merchants daily, refunds, reporting and reconciliation. Focus: correctness.
NFRs: no money created or lost (every movement balanced); exactly-once effect for charges, refunds and payouts; full audit trail (immutable); availability 99.95% for accepting payments; regulatory record retention (years); strong consistency for balances; throughput ~2,000 payments/s peak.
Design principles
- Double-entry ledger: every financial event is recorded as a journal entry with two or more postings (debits and credits) across accounts that sum to zero. Balances are derived (sum of postings per account), never updated arbitrarily.
- Immutability: entries are append-only; corrections are new reversing entries, never edits or deletes.
- Idempotency everywhere: idempotency keys for incoming API requests; provider idempotency keys on outbound calls; unique constraints on external references (provider charge IDs) to prevent double recording.
- State machines for payments (
CREATED → AUTHORIZED → CAPTURED → SETTLED,FAILED,REFUNDED) with explicit transitions; webhooks and polling drive transitions; unknown outcomes (timeouts) resolved by querying the provider. - Reconciliation: daily automated comparison of internal ledger with provider settlement reports and bank statements; mismatches raise investigations.
CREATE TABLE accounts (
id uuid PRIMARY KEY,
type text NOT NULL, -- e.g. 'customer_receivable', 'merchant_payable', 'fees_revenue', 'psp_clearing'
currency char(3) NOT NULL
);
CREATE TABLE journal_entries (
id uuid PRIMARY KEY,
idempotency_key text UNIQUE NOT NULL, -- one entry per business event
kind text NOT NULL, -- 'payment_captured', 'refund', 'payout', 'reversal'
external_ref text, -- provider charge/refund ID
occurred_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE postings (
entry_id uuid NOT NULL REFERENCES journal_entries(id),
account_id uuid NOT NULL REFERENCES accounts(id),
amount_minor bigint NOT NULL, -- positive = debit, negative = credit (convention)
currency char(3) NOT NULL
);
-- Invariant: for each entry, SUM(amount_minor) = 0 per currency (enforced in the posting function
-- and verified by a constraint trigger or periodic checks)
Payment of ₹1,000 captured, platform fee 2%:
debit psp_clearing +100000
credit merchant_payable(M42) −98000
credit fees_revenue −2000
----------------------------------------
sum 0
Architecture
- Payments API (idempotent) → payment orchestrator (durable workflow: authorise, capture, handle 3-D Secure/UPI collect flows, timeouts, retries, provider failover) → provider adapters (one per PSP).
- Ledger service: the only writer of journal entries; single strongly consistent database (PostgreSQL with serializable transactions for posting, or a purpose-built ledger database such as TigerBeetle for very high throughput); partitioned by account set when scaling demands, keeping each entry's postings within one transaction.
- Outbox events from the ledger (
EntryPosted) feed balances read models, merchant dashboards, accounting exports and analytics. - Payout service: scheduled daily: compute payable balances per merchant from the ledger, create payout instructions with idempotency keys, submit to banking APIs, record entries on confirmation.
- Reconciliation service: ingest provider and bank reports; match by external references and amounts; flag breaks.
Hard problems:
- Unknown outcomes: the provider call times out; did the charge happen? Never blindly retry with a new key: retry with the same idempotency key or query the provider by your reference; mark the payment
PENDING_VERIFICATIONuntil resolved. - Webhook ordering and duplicates: process idempotently, use state machine guards (ignore
capturedwebhook if alreadyrefundedunless valid), and re-fetch the authoritative state from the provider. - Currency and rounding: integer minor units, explicit rounding rules for fees and FX, separate accounts per currency; FX conversions as explicit entries.
- Hot accounts: a platform fee account receives a posting with every payment (write contention on its balance row): don't keep a mutable running balance row for hot accounts; compute balances from postings with periodic snapshots, or shard the account into sub-accounts.
- Auditability: immutable tables, database audit logging, access controls, segregation of duties for manual adjustments (maker-checker approvals).
Reviewing any design: a checklist
Use this list in design reviews (yours or others'):
Requirements - Are functional scope, non-goals and NFRs explicit and measurable? Which NFRs dominate? - Are compliance, residency and security requirements identified?
Capacity - Peak QPS per operation, data volume over retention, bandwidth, fan-out, concurrency: estimated and sanity-checked? - What's the bottleneck at 10×?
Data - Is the source of truth for each data type clear? Are derived stores (caches, indexes, read models) rebuildable? - Partition keys and access patterns aligned? Hot keys handled? - Consistency per data type stated; invariants protected by a strongly consistent mechanism? - Schema evolution, backups, PITR, retention and deletion covered?
Communication - Sync vs async choices justified? Timeouts, retries (idempotency), circuit breakers, bulkheads in place? - Messaging: delivery guarantees, ordering, dedupe, DLQs, outbox for dual writes? - APIs: style justified; versioning, errors, pagination, limits?
Availability and operations - No single points of failure? Multi-AZ? DR strategy with RTO/RPO? Static stability? - Graceful degradation for non-critical dependencies? Load shedding? - Observability: SLIs/SLOs, dashboards, tracing, alerts, runbooks? - Deployment safety: progressive rollout, feature flags, rollback, migrations?
Security and tenancy - Authentication, authorisation (object-level), tenant isolation, secrets, encryption, audit logs, abuse controls?
Cost and evolution - Main cost drivers known? Cost per unit of value? - What will need to change at 10×, or with the next likely requirement? Decisions recorded (ADRs)?
A rubric for practice (and interviews)
| Dimension | Weak | Strong |
|---|---|---|
| Requirements | Jumps to boxes | Clarifies scope, NFRs, non-goals; states assumptions |
| Estimation | None or wildly off | Quick, explicit numbers that drive decisions |
| High-level design | Generic boxes | Components with clear responsibilities and data flows tied to requirements |
| Data | "Use NoSQL" | Access patterns, keys, consistency per data type, invariants |
| Deep dives | Superficial | Identifies the hardest problems and explores alternatives with trade-offs |
| Failure | Ignored | Failure modes, degradation, recovery, idempotency |
| Communication | Monologue | Structured, checks in, adapts to feedback, summarises decisions |
Lab: checking a case study's numbers
PostgreSQL 16 on the lab machine and Python. The URL shortener (Case 1) makes claims about key space, collisions, storage and lookup cost; this lab checks each one.
Experiment 1: key space and collisions
62^6 = 56,800,235,584 62^7 = 3,521,614,606,208
random 7-char codes P(≥1 collision) expected collisions
1,000,000 0.132 0.1
100,000,000 ≈1 1,419.8
1,000,000,000 ≈1 141,980.3
The formula is the birthday approximation, P ≈ 1 − e^(−n²/2N). As a check against reality, loading 1 million links with 7-hex-character codes (16⁷ ≈ 268 million possible) skipped 1,846 duplicates; the formula predicts n²/2N ≈ 1,863. Designs that generate random codes therefore need primary key (or unique) on the code and a retry on conflict; at 100 million links, about 1 in 70,000 inserts retries, which is harmless as long as it's handled.
Experiment 2: storage and lookup
loaded 998,154 links in 8.9 s
storage: table 117 MB + index 31 MB = 148 bytes per link (URLs ~60 characters)
redirect lookup by primary key: 103 µs (one connection, from Python)
| Links | Storage (×1) | With 2 replicas |
|---|---|---|
| 100 million | 15 GB | 45 GB |
| 1 billion | 148 GB | 444 GB |
| 10 billion | 1.5 TB | 4.4 TB |
Up to a billion links, one PostgreSQL primary with replicas holds everything and serves lookups in well under a millisecond; beyond that, or for very high redirect rates, the case study's sharding by code hash and edge caching of hot links take over. The point of the lab is the habit: when a design says "this needs sharding" or "one database is enough", measure a sample and multiply.
Try it yourself
- Repeat Experiment 1's real-data check with 6-character base62 codes and 10 million rows. Does the observed collision count match n²/2N?
- Replace random codes with a sequence encoded in base62 and measure insert throughput with 8 concurrent writers.
- Put Redis in front of lookups with a Zipf-distributed workload and measure database queries per second at 95% hit ratio.
- Pick Case 2, 3, 4 or 5 and check one of its estimates with a measurement of your own.
Revision sheet: case studies
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.