Not sure if this is the right Sprint? Start with the assessment.
Refund terms are drafted and are not a current offer. Refund policy
Live 1:1 is $349. Introductory live 1:1 is $299 — a configured price, not a countdown.
Who this is for
SWE II
Senior Software Engineer
Backend Engineer
Tech Lead
Staff Engineer
Principal Engineer
Solutions Architect
Engineering Manager with architecture rounds
Best fit: You already understand basic services, databases, APIs, and production concepts but want a repeatable interview method and realistic practice.
Not ideal: You are learning software engineering fundamentals for the first time.
Short lessons in order. Each one explains one idea in plain language, then tells you what to say in the interview. Labs 301–501 need no AWS. Lab 701 is optional. Use search if you want to jump to a topic.
·
You will
See the full lesson path before you book
Know this is vendor-neutral first — AWS names are optional examples
Course overview5 min
Course overview
System Design Interview Sprint
Today we learn a simple way to open a fuzzy problem, estimate size, start small, find the first thing that breaks, and explain the trade-off out loud. Then we get feedback.
The idea: Draw a small picture, put a number on it, then say what you give up.
Why we learn this
This is a 4-hour LIVE BayLearn Interview Sprint plus ONGOING practice — not four hours of videos. Vendor-neutral first. Optional AWS mappings are examples only. Lab 701 (PayRail) is optional same-day deploy — the 4-hour core does not require an AWS account.
LIVE journey (about 240 minutes)
text
ASSESS + TWO GAPS → D-SCALE + ONE NAPKIN → TARGETED PROMPTS
→ ONE CHALLENGE (Linkly | ClinicDocs | TicketDrop)
→ 45-MINUTE SCENARIO MOCK → FEEDBACK + 7-DAY PLAN
ONGOING
Building-block lessons, second canvas, 108-question bank, 25 practice problems, written rehearsal, changed-telemetry drill, extra mocks, optional PayRail 701.
D-SCALE
Six workloads
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
Do not memorize the diagram
Understand the requirements. Estimate size with honest guesses. Start small. Find the hop that breaks first. Add one fix. Say what you give up. If the interviewer changes the numbers, do the math again — don’t recite 4,630/s from memory.
The assessment result is a study map. The timed design and the mock tell you more. A score here does not mean you will or will not get hired.
Draw a small picture, put a number on it, then say what you give up.
In one sentence: You learn a repeatable way to open a vague design problem, estimate scale, start simple, find the bottleneck, and defend trade-offs out loud.
LIVE vs ONGOING
The product is a 4-hour LIVE experience plus ONGOING practice. The full catalog is longer than 240 minutes if you treat every lesson as live lecture.
LIVE (~4 hours, especially 1:1)
Readiness assessment + debrief — pick two priority gaps
D-SCALE + one capacity napkin (Lab 301)
Two to four spoken prompts from those gaps (not a Module 2/3 tour)
One design challenge: Linkly, ClinicDocs, or TicketDrop
Real 45-minute mock on an unfamiliar prompt
9-dimension score, feedback, personalized 7-day plan
ONGOING (after the room, or self-paced extras)
Module 2–3 building-block lessons and knowledge checks
Second canvas, changed-telemetry drill, TicketDrop if unused live
108-question bank (filter by weak skill; live instructors use only a small subset)
25 System Design practice problems in the player
Written interview rehearsal (six spoken-style answers) — not the Full Mock
Optional PayRail Lab 701 (Path A/B/C)
Downloads and extra M-xx scenarios
Why this matters
System-design interviews are hard because the prompt is fuzzy and the clock is short. People fail by drawing first, skipping numbers, and never naming what they gave up.
D-SCALE order
Six workloads you will reuse
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
You will meet the same six stories with labeled assumptions (not leaked telemetry): Linkly, PulseFeed, RideHail, PayRail, ClinicDocs, TicketDrop. If the interviewer changes the numbers, erase and recompute.
What you will do
Take a 15-question diagnostic and see seven skill scores (directional, not a hiring forecast)
Learn D-SCALE
Treat building blocks as *selection problems* (ongoing unless the live room needs one)
Run Lab 301, then one live challenge; keep the other canvases for ongoing
Optionally deploy PayRail (701)
Practice from the 108-question bank and the 25-problem set
Run a scored 45-minute scenario mock (not six unrelated essays)
Leave with instructor feedback and a 7-day plan mapped to your gaps
The lessons
LIVE spine: Start here · Module 0 · Module 1 (framework + napkin + changed telemetry) · one of Module 4 / 501 / TicketDrop · Module 6 Full Mock · Module 7
ONGOING: Module 2 · Module 3 · extra canvases · question bank · 25 problems · written rehearsal · Lab 701
Vendor-neutral first. If you see an AWS name, it is an *example*, not the only valid design.
INTERVIEW TIP: Silent reading does not survive a whiteboard.
NOTE: The certificate is a BayLearn course-completion certificate, not a professional accreditation.
You will
Answer 15 scenario questions (not a trivia dump)
See weak dimensions before the live session
How the assessment works5 min
How the assessment works
How the readiness assessment works
Today we take a short readiness assessment. Fifteen questions show which skills to practice.
The idea: The result is a study map, not a trophy and not a hiring forecast.
Why we practice this
If you jump straight into 100 questions, you practice at random. The assessment tells you whether you skip numbers, skip what you give up, or skip the user.
Your instructor can see these scores before a live 1:1. A low band is not a fail. It tells everyone where the four hours should go.
Seven skills
Six workloads you will meet
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
What is scored
Each question has one right choice and an in-depth answer with a professional diagram (shown after you finish, never before). Use the review to learn the why, the interview line, and why the other choices fail. Each question is tagged with a skill:
Skill
What it checks
A strong answer sounds like
Requirements
Scope before you draw
“Paid mapping cannot be lost. Analytics is out.”
Scale
Daily → QPS with units
“100M/86,400 ≈ 1,157/s — now I ask about the write shape.”
Data
APIs and keys before the brand
“Key = code. Bytes live in object storage.”
Architecture
Thin path, then one box
“API, app, KV — then a cache because reads dominate.”
Reliability
Timeout, retry, what the user sees
“If ranking is down, chronological feed.”
Trade-offs
What you give up
“We cache; takedown may linger 60s.”
Communication
Assumptions out loud
“Stop me if 80k PDFs/day is wrong.”
Trade-offs and Communication are one question each. Treat those two bars as directional, not precise.
Bands
Score
Label
What it means
What to do next
0–40%
Foundation
Method first
D-SCALE + napkin math only
41–60%
Developing
Pieces, no glue
Replay Linkly on the canvas
61–75%
Interview Capable
You can start
Drill the two weakest skills
76–90%
Ready for Timed Practice
Clock is the next gap
Timed design + mock
91–100%
Advanced
Teach it
Staff probes (delete a box)
This diagnostic is a study map. The timed design and the mock tell you more about how you perform under a clock.
This is practice. A score here does not mean you will or will not get hired.
How the questions feel
They are short decision scenes, not a trivia dump. Examples of what you will actually see:
“Design Instagram” — do you scope or draw first? (A-01)
100 million daily writes — what is average QPS, and what must you still ask before sharding? (A-02)
Short-link POST vs PUT when the service mints the id (A-03)
Access patterns before the ER diagram (A-04)
A payments ledger vs slogan NoSQL (A-05)
Cache-aside, sticky sessions, pub/sub vs a competing queue (A-06–A-08)
When vertical scale is the honest first answer (A-09)
Retries without jitter; likes vs wallet consistency (A-10–A-11)
Observability and abuse on a public shortener (A-12–A-13)
Say what you give up after you pick a queue; evolve when the interviewer changes the requirement (A-14–A-15)
The six teaching workloads (Linkly, PulseFeed, RideHail, PayRail, ClinicDocs, TicketDrop) show up in lessons and labs. Most assessment stems are shorter than those full napkins.
If two answers look smart, pick the one that starts with the user and a number.
How to take it
Close other tabs.
Answer from first principles — do not open the cheat sheet the first time.
Finish all 15. Partial saves do not give a band.
Write the two weakest skills on paper.
Use those two skills as your question-bank filter.
INTERVIEW TIP: If two answers look smart, pick the one that starts with the user and a number.
NOTE: In-depth answers and diagrams appear only after you submit the last question. They do not change your score. A score here does not mean you will or will not get hired.
Readiness Assessment (15 questions)15 min
Readiness Assessment (15 questions)
Take the readiness assessment
Fifteen scenarios. One at a time. The teal label is the skill this question scores.
After the last answer you get a band and seven skill percentages. Write down the two weakest.
Seven skills
This is practice. A score here does not mean you will or will not get hired. It is a study map.
INTERVIEW TIP: Answer from first principles. Do not open another tab to confirm.
15 scenario questions. Each card is tagged with the skill it scores. Open a card to read the prompt and the four choices.
Draw CDN, cache, shard the photos table, then ask questions if time remains.
Ask who the users are, which 2–3 features are in scope, and what “done” means in 45 minutes.
List every Instagram feature so the design is complete.
Pick Kafka immediately because feeds are event-driven.
Scored take: enroll, open Learn, then this same lesson. One question at a time. After 15 you see your band and eight skill scores.
You will
Open answers with a clarifying sentence
Walk D → S → C → A → L → E in order
D-SCALE12 min
D-SCALE
D-SCALE — how we open a system design interview
Today we learn a simple order for the whiteboard. Write units as you go. Don’t start with a product logo.
text
D — Define Requirements
S — Size the System
C — Create High-Level Design
A — Analyze Data & APIs
L — Locate Bottlenecks
E — Evolve & Explain Trade-offs
Why we learn this
Interviewers watch how you think. A 20-box picture that skipped users and traffic looks junior. A four-box path that grew from 400 million redirects a day looks prepared.
If you skip D and S and start with Kafka, you can lose even if every box is fashionable.
D-SCALE on Linkly with units
Six interview workloads — what you are designing
These six teaching products show up in every later lesson. The boxes are labeled napkin numbers, not a spec. Cards under the diagram walk each use-case in depth — who uses it, the journeys, APIs, a D-SCALE board, what you give up, and the diagrams: Linkly, PulseFeed, RideHail, PayRail, ClinicDocs, TicketDrop.
Six reusable workloads
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
The six letters in plain English
D — Define. Who uses this? Which two or three features fit 45 minutes? What does “done” mean? What failure is unacceptable?
S — Size. Daily volume ÷ 86,400 = average QPS. Multiply by a peak factor. Ask object size. Stop when another decimal will not change a box.
C — Create. Draw the smallest path that works. No extras yet.
A — Analyze. Write 2–4 APIs. Name the lookup key. That key picks the store.
L — Locate. Point at the hop that dies first at 10×.
E — Evolve. Add *one* box that fixes that hop. Name what you gave up.
How to open (say it)
“Before I start designing, I’d like to clarify a few requirements and assumptions. If we do not have numbers, I will pick some and design to them.”
Real world — walk Linkly in 45 seconds
A news company wants short links for articles and ads.
Letter
What you write
D
Anyone with the link redirects. Logged-in staff create. Done = 201 create, 302 read. Must not lose a paid campaign mapping.
Cache-aside, 92% hit → 3,200 miss/s on the store. Takedown may linger 60s unless we invalidate that key.
You did not need a stream, a search cluster, or four regions.
Contrast: ClinicDocs in two lines
80k PDFs/day is 0.93/s average, ~19/s peak, 240 GB/day. The interview is a pipeline (202 + queue + 152 in-flight scanners), not “internet scale.” Same letters, different boxes.
If they ask
“Why not start with the final design?”
Because I will invent boxes the requirements do not need. 23 creates/s do not justify a log.
“What if they refuse numbers?”
I write the Linkly or ClinicDocs assumption on the board and invite them to correct me.
What to say
I will not name a queue or a cache until a requirement or a number needs it. I walk D-SCALE, start with a thin path, then evolve the bottleneck and name the trade-off — with units.
COMMON MISTAKE: Drawing Redis, Kafka, Kubernetes, and four regions in the first two minutes.
Open the Trade-off matrix on this lesson. The table is the scan. Each card below it is the interview: when to pick A vs B, what you give up, a workload example, and a diagram.
INTERVIEW TIP: Write the letters in the corner. Tick them. Write 86,400 under S.
Module overview
Module overview
Module 1 — The System Design Interview Framework
Duration: 35 minutes · D-SCALE
Today we learn a simple order for the whiteboard: clarify, quantify, draw a thin path, then evolve.
The idea:D-SCALE is the method. Every later module uses it. If you skip D and S and start with Kafka, you can lose even if every box looks fashionable.
Why we learn this
They are not grading whether you memorized a blog diagram. They are grading whether you can take a fuzzy problem and reduce it.
D-SCALE
text
D — Define Requirements
S — Size the System
C — Create High-Level Design
A — Analyze Data & APIs
L — Locate Bottlenecks
E — Evolve & Explain Trade-offs
How to open (say it every time)
INTERVIEW TIP: “Before I start designing, I’d like to clarify a few requirements and assumptions.”
That sentence buys you permission to think. Silence looks like panic. A short plan looks like you have done this before.
D — Define Requirements
Do not start drawing immediately.
Functional examples: user uploads a file, creates a short URL, sends a message, follows another user, searches products.
SENIOR-LEVEL EXPECTATION: You can delete a box you added too early.
Define requirements6 min
Define requirements
D — Define Requirements — deep dive
Today we learn how to lock the problem before anyone draws a box.
The idea: Agree what you are designing before you draw, or you will build the wrong product — usually the celebrity version.
Why we learn this
“Design Instagram” is a brand name. Turn it into users, two features, what “done” means, one failure you will not accept, and a labeled scale. If you start shading boxes first, you are designing a poster, not a system.
If you skip this step, every later number is decoration.
Students often start shading boxes because it feels like designing. That is not enough.
In class we will answer five questions out loud:
Who changes a box?
What two features are in scope?
What does done mean?
What failure is unacceptable?
What scale do we assume — labeled, then design to 10×?
Common mix-ups we will clear up:
The product name is a brand, not a spec.
If they shrug on scale, label ASSUMPTION and design to 10×.
If they insist on a third feature, swap, do not stack.
Five questions
The five questions — on each product
Seniors write these five answers before any box. The product name is not a spec. If they will not answer, write ASSUMPTION and proceed.
Open with this: I will design create + redirect for a news-and-ads short-link product. Anyone with the link redirects. Staff create. Done is 201 and 302. Losing a paid campaign mapping is unacceptable. I will assume 400 million GET/day unless you give other numbers.
On the board: Anonymous readers (GET), logged-in marketing staff (POST), crawlers, and bots.
Why it changes the design: “Users” is too vague. The GET actor never logs in. The POST actor is staff with a budget. Bots will mint codes if you treat everyone as a reader.
What it forces: Rate-limit creates per staff identity, not per IP only. Redirects stay public. A bot farm is why you do not leave POST open.
What to say: Readers hit GET. Staff hit POST. I rate-limit creates because bots are an actor, not an edge case.
2. What is in scope?
On the board: Create a code. Redirect on GET. Optional custom slug if they insist — swap, do not stack.
Why it changes the design: Analytics, QR campaigns, and a public directory are other interviews. 45 minutes dies if you design the ads dashboard.
What it forces: Two APIs. No stream, no search cluster, no four-region story until a number needs it.
What to say: Create + redirect. Analytics is out. If you want a third feature, I will swap, not stack.
3. What does done mean?
On the board: POST → 201 + code. GET → 302 Location. Work is ~1 ms, so “done” is the HTTP response.
Why it changes the design: This sentence keeps you sync. You do not return 202 for a one-millisecond write.
What it forces: Idempotency-Key on create so a double-click does not mint two codes. 302, not 301, if takedown must win.
What to say: Done is 201 on create and 302 on read. I will not 301 if legal disable matters.
4. What failure is unacceptable?
On the board: Lose a paid campaign mapping. Serve a disabled code because a browser cached 301 forever.
Why it changes the design: Revenue sits on those codes. A 404 on a printed ad is a business incident, not a 404.
What it forces: Durable KV, backups, invalidate-on-delete. No 301 on the hot path.
What to say: I must not lose a paid mapping. I will not use 301 if takedown has to win.
5. What scale should we assume?
On the board: ASSUMPTION: 400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200 B values. Design also to 10× and to one viral code at 50k/s.
Why it changes the design: Without units you will draw Kafka for 23 writes/s. With units, reads are the product.
What it forces: Cache on GET. Creates stay simple. One hot key is not a shard problem.
What to say: I assume 400 million redirects/day unless you correct me. Peak about 40,000 GET/s. Creates are 23/s.
2. PulseFeed · home feed
Open with this: I will design publish and a home feed for 80 million DAU. Ads, stories, and live are out. Done is 201 on publish; fan-out may finish later. An empty home or a 12-million-row sync write is unacceptable. Likes can lag.
On the board: Logged-in readers, ordinary authors, and one celebrity with 12 million followers.
Why it changes the design: The celebrity is a different machine. If you only model “users,” you will fan-out-on-write for everyone and melt on one post.
What it forces: Hybrid fan-out. Do not join the follow graph on every Home GET. Ranking can degrade to chronological.
What to say: Readers, authors, and one 12-million-follower account. That last actor changes the write path.
2. What is in scope?
On the board: Publish + home feed. Not stories, ads, live, DMs, or search.
Why it changes the design: “Design Instagram” is a brand. Two features fit 45 minutes. A third feature is a swap.
What it forces: POST /posts and GET /feed?cursor=. Likes are optional and may lag.
What to say: Publish and home only. If you want ads, I drop live or DMs — I will not stack.
3. What does done mean?
On the board: Publish returns 201. Home is fast enough to open (p99 a few hundred ms). Fan-out may still be in flight.
Why it changes the design: If “done” means every follower has the post, you just promised 12 million writes on the request.
What it forces: Async fan-out for normal users. Pull celebrity posts at read time. Cursor pagination.
What to say: Done is 201 on publish and a fast home. Fan-out can finish later. Likes can lag.
4. What failure is unacceptable?
On the board: An empty home because you joined 12 million follow edges on GET. A celebrity publish that writes 12 million timeline rows synchronously.
Why it changes the design: Empty home is churn. Sync celebrity fan-out is an outage wearing a feature.
What it forces: Precomputed or cached timelines for normal users. Hybrid pull for celebs. Circuit-break ranking to chronological.
What to say: I will not empty Home to be “correct,” and I will not pause publish for 12 million writes.
Why it changes the design: The ratio is the design. Publish is modest. Home is the product.
What it forces: Cache + hybrid fan-out. Do not shard writes first. Design also to 10× morning peak.
What to say: I assume 80 million DAU and about 150,000 peak feed reads/s. Writes are 185/s. If those are wrong, I erase and recompute.
3. RideHail · live map
Open with this: I will design latest-driver location and request/match a trip. Pricing ML is out. The map may be 4s stale. Charging the rider twice is unacceptable. I assume 300k drivers pinging every 4s — that is 75k writes/s — and 1.5M trips/day ≈ 17/s.
On the board: Riders, ~300k drivers at evening peak, dispatch, and payments after drop-off.
Why it changes the design: Four actors, two SLOs. Drivers generate the hot path. Payments own the trust path. Dispatch sits in between.
What it forces: Two stores. The driver app is a writer at 75k/s. The rider is a nearby-read. Finance is not on the ping table.
What to say: Rider, driver, dispatch, pay-after-trip. Those are two products that share a brand.
2. What is in scope?
On the board: Latest location + request/match a trip. Not pricing ML, incentives, or a forever ping warehouse.
Why it changes the design: The live map is the 45-minute problem. A warehouse of breadcrumbs is a data interview.
What it forces: PUT location by driverId. GET nearby by geo cell. POST /trips. Pay after complete.
What to say: Map + match. Pricing ML is out. I will not keep every ping on the serving path.
3. What does done mean?
On the board: The map shows nearby cars. A trip start is a committed row. Pay happens after drop-off — not on the ping.
Why it changes the design: If “done” is “we stored the breadcrumb,” you just designed the wrong product.
What it forces: Overwrite latest. Trip is transactional. Stale-by-4s is acceptable on the map.
What to say: Done is a live-enough map and a committed trip. The rider is not charged on the ping write.
4. What failure is unacceptable?
On the board: Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Why it changes the design: Double charge is trust and regulation. Append-forever is a storage outage you scheduled.
What it forces: Trip store ≠ ping store. Idempotent complete/charge. TTL / overwrite on location.
What to say: I will not charge twice, and I will not put money on the ping table.
5. What scale should we assume?
On the board: ASSUMPTION: 300k drivers / 4s = 75k writes/s, 200 B, 1.5M trips/day ≈ 17/s. Keep ~15 min of pings; warehouse the rest.
Why it changes the design: 75k/s vs 17/s is why you change the data model before you buy nodes.
What it forces: Overwrite, not append. Geo cell can still be a downtown hot key. Design to 10× evening peak.
What to say: I assume 300,000 drivers pinging every 4 seconds — 75,000 writes/s. Trips are 17/s. Correct me if that is wrong.
4. PayRail · card charges
Open with this: I will design idempotent authorize/capture and a ledger row. Rewards and FX are out. Done is 201 + chargeId, not an email. Two $49 captures are unacceptable. I assume 8 million charges/day, Black Friday 1,200/s, p99 under 400 ms.
On the board: Cardholder, merchant, finance export, fraud batch, and mobile clients that retry on timeout.
Why it changes the design: The retrying phone is an actor. If you forget it, you design a happy-path ledger and fail on Black Friday.
What it forces: Idempotency-Key from the client. Finance reads a replica; GET-after-capture for the shopper hits primary. Fraud is batch — off the 400 ms path.
What to say: Cardholder, merchant, finance, fraud — and the client that retries. That last actor is why I require a key.
2. What is in scope?
On the board: Idempotent authorize + capture + one ledger row. Not an issuing bank, rewards, or every FX corridor.
Why it changes the design: Payments interviews die when you draw a network instead of a charge.
What it forces: POST /charges with a key. State machine pending → captured. Email is off the path.
What to say: Authorize and capture. A full card network is out. I will not stack rewards on minute one.
3. What does done mean?
On the board: 201 + chargeId. One ledger row. The same key returns the original charge. Email sent is not done.
Why it changes the design: If done is “receipt emailed,” you will cache or queue the money path and lose a capture.
What it forces: Single writer for capture. Timeouts inside the 400 ms budget. Read-your-writes on GET.
What to say: Done is a ledger row, not an email. Duplicate POST with the same key is the same $49.
4. What failure is unacceptable?
On the board: Two $49 captures for one tap. Blind retry without a key. GET-after-capture from a lagging replica.
Why it changes the design: Double capture is a lawsuit. “Exactly-once” without a key is a slogan.
What it forces: Idempotency store, one writer, primary for read-your-writes. Replicas do not add write QPS.
What to say: Two captures cannot happen. I require an Idempotency-Key. I will not send GET-after-write to a replica.
5. What scale should we assume?
On the board: ASSUMPTION: 8M/day ≈ 93/s, peak 1,200/s, p99 < 400 ms, 2% retries → +24/s duplicates if you are not idempotent.
Why it changes the design: 8 million sounds large. 93/s is easy. 1,200 simple writes/s often still fits one primary. The 24 retries/s is the trap.
What it forces: Do not shard in minute five. Name the key. Design to 10× peak as a stress, not as a logo.
What to say: I assume 8 million charges/day and 1,200/s at noon. 2% retries is 24 potential double-charges/s without a key.
5. ClinicDocs · hospital PDFs
Open with this: I will design upload, status, and download-clean for 80k PDFs/day at 3 MB. This is not an EHR. Done is 202 on upload and a clean object in 60 seconds. Serving an unscanned landing file is unacceptable. Data class is PHI.
On the board: Clinic uploader, malware-scan workers, clinician, patient portal, auditor.
Why it changes the design: The auditor will ask who fetched a file. The patient portal must never see landing. Workers are a different scale lever than the API.
What it forces: Private landing, signed clean URLs, audit log of fetches. PHI out of logs. Separate worker pool.
What to say: Clinic, scanner, clinician, patient, auditor. PHI means no public origin and no bytes in logs.
2. What is in scope?
On the board: Upload, status, download clean. Not a full EHR, e-prescribe, scheduling, or billing.
Why it changes the design: “Hospital system” is a career. Three verbs fit 45 minutes.
What it forces: POST 202, GET status, signed GET download. Search may lag and is not the official record.
What to say: Upload, status, clean download. If you want search as a third, I swap scheduling — I will not stack an EHR.
3. What does done mean?
On the board: Upload returns 202 accepted + job id. Clean object ready in ≤ 60 seconds. Status API tells you when.
Why it changes the design: If done is 201 with a public URL, you skipped the scan and leaked PHI.
What it forces: Queue + ~152 in-flight workers. Landing vs clean prefixes. 202, never “file ready” on the HTTP call.
What to say: Done is 202 on upload and clean in 60 seconds. The HTTP call does not wait 8 seconds.
4. What failure is unacceptable?
On the board: Serve an unscanned landing file. Put 240 GB/day in a row store. PHI in logs or a public bucket.
Why it changes the design: An unscanned PDF on the patient portal is a security incident. Bytes in Postgres is a later outage.
What it forces: Never serve landing. Object store for bytes. SQL for pointers. Short-lived signed URLs.
What to say: I will not serve landing “to be helpful.” Unscanned is unacceptable.
Why it changes the design: 80,000 sounds like internet scale. 19/s is a queue. The headline million is a pipeline-time problem.
What it forces: 202 + workers on queue age. Lifecycle to cold storage. Do not call this internet scale. Design to 10× open-of-clinic.
What to say: I assume 80,000 files/day at 3 MB — about 19/s peak and 152 in-flight scanners. That is a pipeline, not internet scale.
6. TicketDrop · on-sale
Open with this: I will design a waiting room, a hold, and a checkout that decrements inventory once. Season tickets are out. Done is a real seat or a clear miss. Oversell is unacceptable. I assume 80k tickets and 500k people in the room at 10:00.
On the board: Fans, bot farms, box office. Inventory is a uniquely numbered seat — not a reprintable file.
Why it changes the design: Bots will skip the line. Stadium NAT makes IP a bad rate-limit key. Box office still needs a fair story when it sells out.
What it forces: Waiting room + per-user poll limits. Hold id is the retry token. Stop admits on sell-out.
What to say: Fans, bots, box office. Bots are why the room is the product, not a decoration.
2. What is in scope?
On the board: Waiting room, hold, pay, inventory decrement once. Not season tickets, dynamic pricing ML, or a social feed of who got in.
Why it changes the design: On-sale is crowd control. A 365-day storefront is a different interview.
What it forces: Room status poll, POST hold, POST checkout on holdId. Checkout is closed before 10:00.
What to say: Room, hold, pay. If you want pricing ML, I swap the social feed — I will not stack.
3. What does done mean?
On the board: Inventory decremented once. The fan has a seat or a clear miss. HTTP 200 without a decrement is not done.
Why it changes the design: If done is “checkout 200,” retries will sell 80,001 seats.
What it forces: Atomic decrement or unique seat row. Same hold id on retry. Sold-out stops admits.
What to say: Done is inventory once. A 200 that retries into a new decrement is an oversell.
4. What failure is unacceptable?
On the board: Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Why it changes the design: Oversell is a venue night that cannot exist. 500k QPS is an outage you invited.
What it forces: Waiting room admit ~3k/s. Inventory is the gate — even 90k in-flight holds are more than 80k seats.
What to say: I will not take 500k checkouts at 10:00. Oversell is zero. Retry the same hold id.
5. What scale should we assume?
On the board: ASSUMPTION: 80k tickets, 500k in the room at 09:59:58, checkout ~30s, admit ~3k/s → ~90k in-flight holds. Inventory still gates. Design to 10× admit as a stress, not 500k checkout boxes.
Why it changes the design: If 500k hit checkout you invented a 500k QPS event. A box sized for 10:00 sits idle 364 days/year.
What it forces: Room first. Inventory second. Autoscale checkout is not the architecture.
What to say: I assume 80,000 seats and 500,000 people in the room. I admit a survivable rate. Inventory is the gate.
1. Who? Actors that change a box — bots, a celebrity, a retrying phone — not “users.”
2. What is in scope? Two or three features that fit 45 minutes. The product name is a brand, not a spec.
3. What does done mean? This sentence picks sync vs async (201 vs 202; ledger row vs email).
4. What failure is unacceptable? The must-not that forces a key, a private bucket, or inventory as the gate.
5. What scale should we assume? A labeled napkin. Then design to 10×. Erase if they give telemetry.
NFRs that actually change boxes
Do not recite twelve. Rank two or three:
Driver
Example
Box it changes
Latency
Linkly p99 GET < 200 ms
Cache, region
Pipeline time
ClinicDocs clean ≤ 60s
Queue + workers
Consistency
PayRail no double capture
Single writer + key
Data class
ClinicDocs PHI
Private origin, no PDF in logs
Fairness
TicketDrop
Waiting room
Staff-level move
If they want “five nines, 10 ms worldwide, strong consistency on every PulseFeed like,” negotiate. Likes can lag. Charges cannot. Say who owns the risk.
Real world — two openings you can use
Instagram-style: “I will design photo upload and a home feed for 80 million DAU. Done means upload accepted and feed p99 under 400 ms. Ads and live are out. I will assume 16 million posts/day (185/s) and ~28k feed reads/s, peak ~150k/s.”
Hospital: “I will design ingest and retrieve for 80k PDFs/day at 3 MB. Done is 202 on upload and a clean object in 60 seconds. Serving landing-bucket files is unacceptable.”
If they ask
“What if they still will not give volume?”
I pick Linkly or ClinicDocs numbers, write ASSUMPTION, proceed.
“Isn’t this wasting time?”
Two minutes of scope saved twenty minutes of Kafka-for-23-writes/s.
What to say
I will not name a compute service until I know who uses this, what done means, and what failure we cannot tolerate. I will write assumptions if you want me to proceed.
COMMON MISTAKE: Treating the product name as a specification.
STAFF-LEVEL EXPECTATION: Negotiate impossible SLOs and name who owns failure.
Size the system6 min
Size the system
S — Size the System — deep dive
Today we learn how a few honest numbers pick the next box.
The idea: A few honest numbers tell you if you need a queue, a cache, or a different store. You do not need a spreadsheet, and “scale” is not a number.
Why we learn this
Without units, “we will scale later” is a shrug. With units, you can say “average is 4,630 per second, peak is 40,000, so I will not put every GET on one primary.”
They are not grading calculator skill. They want 86,400, a peak factor, an object size, and a stop rule.
Students often say “we will scale” with no units. That is not enough.
In class we will answer three questions out loud:
What is the average QPS — daily requests divided by 86,400?
What is the peak — average times a peak factor?
Does another decimal change a box, or do we stop?
Common mix-ups we will clear up:
“Scale” is not a number. Units are.
Every number below is a labeled assumption. If they give different telemetry, erase yours and recompute. The method stays.
1,157 vs 1,200 does not matter. 12/s vs 12,000/s does.
Three real napkin sheets
The six workloads we reuse
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
The formulas (memorize)
text
Average QPS = Daily requests / 86,400
Peak QPS = Average QPS × peak factor (often 3–10×)
Daily bytes = Writes per day × average object size
In-flight = Peak QPS × work time in seconds
86,400 is the number of seconds in a day. Always say units: requests/sec, MB/s, GB/day.
The Capacity napkin on this lesson runs the same math. Open capacity_formulas.py below if you want to read the units as code.
Stop when another decimal will not change a box. 1,157 vs 1,200 does not matter. 12/s vs 12,000/s does.
Real world — six napkin sheets
Linkly (short links for a news + ads company)
Assumption: 400 million redirects/day, 2 million creates/day, value ≈ 200 bytes.
Math
Number
What it changes
400e6 / 86,400
≈ 4,630 GET/s average
Already more than a casual single-node demo
Peak × 8.6 (morning news)
≈ 40,000 GET/s
Cache or you melt the KV
2e6 / 86,400
≈ 23 POST/s
Creates do not need a stream
400e6 × 200 B
≈ 80 GB/day of reads
Reads, not storage; mappings stay tiny
One viral code
50,000 GET/s for 10 min
One key. Sharding does not help
You say: “Reads are the product. I cache. I will not draw Kafka for 23 creates a second.”
You say: “This is a pipeline-time problem. Upload returns 202. Scan is behind a queue.”
RideHail (live driver map)
Assumption: 300,000 drivers online at evening peak, ping every 4 seconds, payload 200 bytes. 1.5 million trips/day.
Math
Number
What it changes
300,000 / 4 s
75,000 writes/s
A different store than trip checkout
75k × 200 B
≈ 15 MB/s ≈ 1.3 TB/day if you keep every ping
You must overwrite latest point
1.5e6 / 86,400
≈ 17 trip starts/s
That path can be transactional
Keep 15 minutes of pings
75k × 200 B × 225 ≈ 3.4 GB ring
Warehouse the rest overnight
You say: “Pings and payments are two products. I will not put the ledger on the ping table.”
PulseFeed (home feed)
Assumption: 80 million DAU, 0.2 posts written per user per day → 16 million posts/day. Each user opens the feed ~30 times.
Math
Number
What it changes
16e6 / 86,400
≈ 185 writes/s
Publish is modest
80e6 × 30 / 86,400
≈ 27,800 feed reads/s
Reads dominate
Peak morning × 5.4
≈ 150,000 reads/s
Cache + precompute
Read:write
≈ 150:1
Fan-out strategy is the interview
A celebrity with 12 million followers: fan-out-on-write is 12 million timeline writes for one publish. That is why hybrids exist.
PayRail (card charges)
Assumption: 8 million charges/day, Black Friday noon 1,200 authorize/s, p99 < 400 ms, 2% client retries on timeout.
Math
Number
What it changes
8e6 / 86,400
≈ 93/s average
Easy if you are not silly
Peak
1,200/s
Still one well-run primary *if* the query is simple
2% retries
+24/s duplicates
Without idempotency keys that is 24 double-charges/s
TicketDrop (on-sale)
Assumption: 80,000 tickets, 500,000 people in the waiting room at 09:59:58, checkout 30 seconds.
If those 500k hit checkout, you invented a 500,000 QPS event. A waiting room that admits 3,000/s and a 30s checkout means ≈ 90,000 in-flight holds — still more than inventory, so inventory is the gate, not hope.
What to estimate (and what to skip)
Estimate if it changes a box: read vs write QPS, payload size, in-flight work, yearly bytes.
Skip extra decimals, “internet scale,” and CPU percentages you cannot know.
How to use the estimator (Lab 301)
The Capacity napkin on this lesson is the lab. Pick a preset. Change object size or peak factor and say which box moved. Run Linkly, then ClinicDocs, then PayRail before you leave.
Open Lab 301 — Capacity napkin in this Course Player. The napkin on that lesson is the lab — do not download a file.
If they ask
“Do I need exact telemetry?”
No. I need a labeled assumption and a 10× story.
“What about five years of ClinicDocs?”
88 TB × 5, plus versions. That is when object lifecycle beats a database.
“Can one Postgres take PayRail peak?”
Often yes for 1,200 simple writes/s. I will not shard in minute five. I will shard when the primary’s write path or blast radius says so.
What to say
I divide daily volume by 86,400, ask object size, then apply a peak factor. I stop when the next decimal will not change a box. On Linkly that cache is mandatory at 40k GET/s. On ClinicDocs the headline million is actually 19 files/s and a 152-worker pipeline.
SCALE CHECK: If average and peak differ by ~10×, prefer a queue over a box sized for Monday and idle on Sunday.
COMMON MISTAKE: Saying “internet scale” with no units on the board.
REAL WORLD: Public talks often quote hundreds of millions of short-link clicks or tens of millions of DAU. We use assumptions in that neighborhood, never fake precision.
Capacity estimation
Capacity estimation
Capacity Estimation Cheat Sheet
text
Daily requests = DAU × actions/user/day
Average QPS = daily requests / 86,400
Peak QPS = average QPS × peak factor
Daily storage = writes/day × average record size
Retention = daily storage × retention days
Bandwidth ≈ requests/sec × average payload size
Cache size ≈ hot keys × value size × replicas
Always say units. Stop when another decimal will not change a box.
Lab 301 brief
Lab 301 brief
Lab 301 — Capacity napkin
Today we practice turning a daily headline into QPS, bytes, and in-flight work — then say which box on the architecture moved.
The idea: Turn a daily headline into QPS, bytes, and in-flight work — then say which box on the architecture moved.
Why we practice this
Lab 301 is the S in D-SCALE — Size the system.
Interviewers do not want a calculator performance. They want you to convert a headline (“400 million redirects a day”) into units a design can use:
Average QPS — daily volume ÷ 86,400
Peak QPS — average × a peak factor you label
Write QPS — writes/day ÷ 86,400
Daily / yearly bytes — writes × object size
In-flight work — peak QPS × seconds of work (Little’s Law)
Cache miss QPS — peak × (1 − hit ratio)
Those six numbers decide the first box: cache, queue, overwrite store, object storage, waiting room, or “one well-run primary.” A number that does not change a box is decoration. Stop there.
This sprint is vendor-neutral. The AWS sprint’s analog of “apply Terraform” is doing this napkin out loud until 86,400 is muscle memory.
Why it exists
Juniors recite “we need to scale.” Seniors put units on the board.
4,630/s (Linkly average) is a cache-first read path, not a stream.
19/s × 8s ≈ 152 in-flight (ClinicDocs) is a queue, not “internet scale.”
~1,200/s simple PayRail commits often still fit one primary. Idempotency-Key is the design, not a shard.
75k writes/s RideHail pings are an overwrite, not 1.3 TB/day of appends.
500k people in a waiting room is not 500k checkout QPS. Inventory is the gate.
If the interviewer gives different telemetry, erase yours and recompute. The skill is transfer, not memorizing Linkly.
How to use it on this page
Scroll to Capacity napkin on this lesson (same widget also sits on Size the system).
Run Linkly. Write avg QPS, peak QPS, and miss QPS (92% hit) on paper.
Run ClinicDocs. Write daily bytes, peak files/s, and in-flight scanners.
Run PayRail. Say whether 1,200/s forces a shard.
Change one number (object size or peak factor). Say which output box moved.
Optional: open capacity_formulas.py on Size the system — same math as the widget, as code.
Formulas (say them with units)
What you compute
Formula
Why it matters
Average QPS
daily volume / 86,400
Shared scale with the interviewer
Peak QPS
average × peak factor
The box you provision for
Write QPS
writes per day / 86,400
Separate from read QPS
Daily bytes
writes × object size
Database vs object store
Yearly bytes
daily bytes × 365
Lifecycle, not one disk
In-flight
peak QPS × work seconds
Queue depth / holds / scanners
Cache miss QPS
peak × (1 − hit%)
What actually hits origin
Stop when another decimal will not change a box.
Expected napkin (labeled assumptions)
Product
Headline
What you should see
Linkly
400M GET/day, 200 B, 92% hit
~4,630/s avg, ~40k/s peak, ~3,200 miss/s
ClinicDocs
80k × 3 MB, 8s scan
240 GB/day, ~19/s peak, ~152 in-flight
PayRail
8M/day, peak ×13
~93/s avg, ~1,200/s peak
RideHail
300k × ping/4s
75k writes/s — overwrite, do not append
PulseFeed
16M posts, ~2.4B feed reads
~150:1 read:write — fan-out or cache the timeline
TicketDrop
500k in the room, admit 3k/s
Waiting room ≠ 500k checkout QPS
NOTE: These are teaching assumptions, not leaked production telemetry. If the room gives different numbers, yours are wrong until you recompute.
What “done” looks like
Mark this lab complete when:
[ ] You can say “400 million / 86,400 ≈ 4,630/s” without looking
[ ] You can explain why ClinicDocs is a queue at 19/s, not a cluster
[ ] You can explain why TicketDrop is a waiting room, not 500k checkout QPS
[ ] You changed one input and named which box moved
Time: 10–15 minutes. No AWS.
Common mistakes
Treating “millions a day” as Kafka before dividing by 86,400
Using average QPS as the provisioned number (peak is)
Appending RideHail pings instead of overwriting latest location
Equating waiting-room headcount with checkout QPS
Chasing extra decimals that do not change a box
Read the lab source
Same files as the zip. Open one at a time — map the function to the interview sentence.
capacity_formulas.py
python
"""Lab 301 — the napkin as code.
Same formulas as the Capacity napkin on Size the system.
Assumptions are labeled. If the interviewer gives different numbers, change
the inputs and recompute. Do not memorize a vendor SKU.
Average QPS = daily / 86_400
Peak QPS = average * peak_factor
Daily bytes = writes_per_day * object_bytes
In-flight = peak_qps * work_seconds
Cache miss = peak_qps * (1 - hit_ratio)
"""
SECONDS_PER_DAY = 86_400
# (name, daily_reads_or_ops, peak_factor, object_bytes, work_seconds, hit_ratio, writes_per_day)
WORKLOADS = [
("Linkly redirects", 400_000_000, 8.6, 200, 0, 0.92, 2_000_000),
("PulseFeed feed reads", 2_400_000_000, 5.4, 1_200, 0, 0.0, 16_000_000),
("RideHail pings", 6_480_000_000, 1.0, 200, 4, 0.0, 6_480_000_000),
("PayRail charges", 8_000_000, 13.0, 800, 0.4, 0.0, 8_000_000),
("ClinicDocs PDFs", 80_000, 20.0, 3_000_000, 8, 0.0, 80_000),
("TicketDrop checkout", 80_000, 1.0, 400, 30, 0.0, 80_000),
]
def napkin(daily, peak_factor, object_bytes, work_seconds, hit_ratio, writes_per_day):
avg_qps = daily / SECONDS_PER_DAY
peak_qps = avg_qps * peak_factor
daily_bytes = writes_per_day * object_bytes
in_flight = peak_qps * work_seconds
miss_qps = peak_qps * (1 - hit_ratio)
return {
"avg_qps": round(avg_qps),
"peak_qps": round(peak_qps),
"daily_gb": round(daily_bytes / 1_000_000_000, 1),
"in_flight": round(in_flight),
"miss_qps": round(miss_qps),
"write_qps": round(writes_per_day / SECONDS_PER_DAY),
}
if __name__ == "__main__":
for name, *args in WORKLOADS:
print(f"{name}: {napkin(*args)}")
High-level design20 min
High-level design
C — Create the high-level design
Today we learn how to draw the smallest picture that still works.
The idea: Draw the smallest picture that works. Add a box only when a number says you need it — like 40,000 reads a second.
Why we learn this
A board with 20 services in the first four minutes looks busy and says almost nothing. A small picture you can explain with one number looks like a senior answer.
Students often fill the board with logos because it looks advanced. That is not enough.
In class we will answer three questions out loud:
What is the thin path — users, door, app, store?
Which hop is busy, and what number proves it?
What one box do we add, and what do we give up?
Common mix-ups we will clear up:
Start small. Find the busy hop. Add one box.
Don’t add a box unless you can finish this out loud: *I need this box because of this number (or this rule). What I give up is that.*
How you host the app is not a box. Say “about 20 copies behind a load balancer” until they ask.
Words we use
Word
Meaning
QPS
How many requests per second
Front door / API
Where the user’s request enters
Store of record
The official copy of the data
Cache
A fast copy used to take load off the official store
Queue
A waiting line so slow work does not block the user
What you give up
The cost of the box you added
Gold box
On implementation boards: the official store, or the runtime piece a number buys
Dashed arrow
Reply, or work that happens later (email, fan-out, scan) — not “done”
Sequence
Who talks to whom, in order. Top banners are trust boundaries
Second line on a box
An AWS example. Other clouds and datastores are valid
Placement
Where a box runs: public subnet, private subnet, or regional managed
Two AZs
Two buildings. If one dies, the other still serves
RPO
How much data you may lose if a region dies
RTO
How long until you serve again
SLO
The promise you page on (one journey)
Hot key
One id that takes all the traffic — sharding that id does nothing
How to draw (every product)
People on the left (who uses this).
One request across the middle. If it is really two products (RideHail map vs trip), draw two pictures.
The official store on the right.
Write the busy number on the hottest arrow.
Leave room. Add one box. Say what you gave up.
How you host the app is not a box. Say “about 20 copies of the app behind a load balancer” until they ask how you run them.
Six pictures
The cards below are the lesson. Each product has a high-level architecture, an implementation architecture, a deployment diagram (where each box runs, two AZs, public vs private, how deployed pieces talk), sequence diagrams, then an interview kit (keys, APIs, states, napkin numbers, latency, what may be stale, the hot key, what dies, one SLO, security that changes a box, and a second-region answer), then a map onto Architecture Building Blocks, then the first picture and the one box you add next.
Vendor names are AWS examples only. PayRail includes the Lab 701 student deploy (API Gateway + Lambda + DynamoDB, no VPC) next to the production-shaped VPC. Gold boxes are the store of record.
TIP: Start small → find the busy hop → add one box.
COMMON MISTAKE: Drawing Kafka, Redis, Kubernetes, or shards without a number on the arrow.
Data and APIs20 min
Data and APIs
A — Analyze Data & APIs
Today we learn how to write the contract and the lookup key before we name a store.
The idea: Write the APIs and the lookup key first. Pick the database last, after you know the traffic.
Why we learn this
How you look data up picks the database. If you pick a document store first, you will twist PayRail into a blog.
In the room they want two or four endpoints, a primary key, and one sentence about a hot key. That is the A-step. The cards below walk the contract the same way High-level design walks the boxes.
Students often name a database brand first. That is not enough.
In class we will answer three questions out loud:
What two or four APIs do we expose — verb, path, success, failure?
What is the lookup key, and is it a hot key?
What store fits that access pattern — brand last?
Common mix-ups we will clear up:
Do not start with “we will use NoSQL because it scales.”
201 means the official row exists. 202 means accepted; work happens later.
Design storage around access patterns, not around a favorite brand.
Words we use
Word
Meaning
Lookup key
What you look the official row up by
Idempotency
Same retry key returns the same row
Cursor
A continuation token, not a page number
201
The official row exists
202
Accepted. Work happens later
302
Redirect I can still turn off
301
Browser caches forever — Linkly disable dies
Gold box
Official row, or the contract that stops a double write
How to write A (every product)
Two or four APIs: verb, path, success code, failure code, who may call it.
Name the lookup key. One hot-key sentence.
Write the QPS (or bytes, or in-flight work) on that key.
Then name the store. Brand is a footnote.
Do not start with “we will use NoSQL because it scales.”
Method, then six contracts
Start with the comparison matrix, a blank sheet, the status-code cheat, and one retry walk. Then key scope, cursor guts, and fields you refuse. Then the A-step clock and the six product kits (API table + worked JSON, keys, access → store, replay, lifecycle, guards). Finish with three 4-minute drills — cover the kits first, then time yourself.
Vendor names are AWS examples only. PayRail’s retry key is the same state machine as Lab 701.
ARCHITECTURE DECISION: Design storage around access patterns.
COMMON MISTAKE: Starting with “we will use NoSQL because it scales.”
A-step one-pager
A-step one-pager
Data and APIs — one-pager
BayLearn · System Design Interview Sprint
Clock: 2–4 APIs → lookup key → QPS on that key → then the store. Retry key. I will not: ____.
Six rows
Product
2 APIs
Key
Hot key
Store instinct
Replay
Linkly
GET /{code} 302 · POST /v1/urls 201
code
viral code 50k/s
KV + cache
optional key / hash(url+owner)
PulseFeed
POST /v1/posts 201 · GET /feed?cursor=
postId · Home userId
celebrity author
ids cache, not a join
optional client key
RideHail
PUT /location · POST /trips
driverId vs tripId
downtown cell
two stores
PUT replace · pay key
PayRail
POST /charges + header · GET by id
merchant + key · chargeId
not a shard story
one primary
same key → same chargeId
ClinicDocs
POST 202 · signed GET when clean
fileId
none at 19/s
SQL pointer + objects
overwrite landing
TicketDrop
status · POST /holds · checkout
holdId · seat
one show lock
cached status ≠ inventory
same holdId · 410 gone
Codes
Code
Means
Use
201
Official row exists
Post, charge, code, hold
202
Accepted, work later
ClinicDocs upload
302
Redirect I can turn off
Linkly. Never 301
409
In flight, same key
PayRail processing
410
Gone. Stop.
TicketDrop sold out
429
Mint limiter
Bots / POST quota — not a cache
Refuse in the API
Landing download URL · file bytes · PAN · shard id · replica lag as truth · guessable holdId · click charts on GET /{code}.
This is not a hiring prediction tool.
Bottlenecks and trade-offs20 min
Bottlenecks and trade-offs
L & E — Bottlenecks and trade-offs
Today we learn how to find the first dying hop and defend one fix out loud.
The idea: Point to the hop that will break first at your peak traffic, add one fix, and say what you gave up — time, money, or freshness.
Why we learn this
Anyone can add boxes. The harder part is deleting a box you do not need. The interview is often decided in the sentence after you draw.
A trade-off has a winner and a cost. If you cannot name the cost, you are not done. The table below is your menu. The cards walk L and E the same way we walked boxes and APIs.
Students often pile on Kafka, four regions, or a service per noun. That is not enough.
In class we will answer three questions out loud:
At the peak we wrote under S, which hop saturates first?
What one fix unsticks that hop?
What do we give up — seconds, dollars, or staleness?
Common mix-ups we will clear up:
Every winner has a cost. Say both, with units.
You can delete a box you added too early.
Do not start with Kafka, four regions, or a microservice per noun.
Words we use
Word
Meaning
L
First hop to die at the peak you wrote under S
E
One evolve plus what you give up
Gold box
Store of record, or the piece a number buys
What you give up
Seconds, dollars, or staleness — not a vibe
202
Accepted. Work happens later. Not “done”
Hit ratio
A number. Miss QPS = peak × (1 − hit)
How to walk L then E
Finger on a hop. “If traffic is the peak we wrote under S, which box saturates first?”
Add one fix that unsticks that hop — cache, queue, key, split, waiting room.
Say what you give up, with units.
Say when you would delete the fancy box (QPS drops 10×, 500 files/day, no must-not).
Do not start with Kafka, four regions, or a microservice per noun.
Method, then ten rows
Start with locate, the L→E sentence, a blank sheet, the six-product overlay, and a 60-second script. Then open each matrix row (when to pick A vs B, what you give up, the hop it unsticks, six products, probes). Finish with three 4-minute drills — cover the cards first, then time yourself.
AWS names are examples only. The line you say does not change: *I picked X because of Y. What I give up is Z.*
SENIOR-LEVEL EXPECTATION: You can delete a box you added too early.
TRADE-OFF: Every winner has a cost. Say both, with units.
Trade-off matrix one-pager
Trade-off matrix one-pager
System Design Trade-Off Matrix — one-pager
Scan this at the table. The cards walk the hop that breaks first, one fix, what you give up, and the six products.
Today’s idea: I picked X because of Y (a number or a hard rule). What I give up is Z.
Decision
A
B
Discussion
Database
SQL
NoSQL / KV
Transactions and relations vs access-pattern scale
Communication
Sync
Async
End-to-end errors vs buffering and retries
Consistency
Strong
Eventual
Correctness vs availability and lag
Compute
Monolith
Microservices
One failure domain vs independent scale
Cache
None
Cache
Freshness vs origin offload (hit ratio is a number)
Replication
Single region
Multi-region
HA in-region vs DR / locality
Processing
Immediate
Queue
User waits vs load leveling
Reads
Primary only
Read replicas
Read-your-writes vs read scale with lag
APIs
Offset pages
Cursors
Jump-to-page vs a moving list
Delivery
At-most-once
At-least-once
Loss vs duplicates (then idempotency)
L = hop that dies first. E = one box + loser with units. If Z is missing, you added furniture.
D-SCALE cheat sheet5 min
D-SCALE cheat sheet
D-SCALE cheat sheet — deep dive
Today we keep this sheet open while we design.
The idea: Keep this page open. Tick the letters. Write units on the board. Don’t invent a seventh step.
Why we use this sheet
Students invent a seventh step called “add Kafka.” We will not. Six letters, units on the board, then stop.
Write D-SCALE in the corner. Tick each letter. Write 86,400 under S. Do not still be drawing new logos at minute 40.
D-SCALE on Linkly
Six workloads
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
The letters
text
D — Define Requirements Who, what, done, fail, scale
S — Size the System Daily / 86,400 × peak · ask size
C — Create High-Level Users → door → app → store
A — Analyze Data & APIs Contract + primary key
L — Locate Bottlenecks 10×, which hop dies first?
E — Evolve & Explain One box + what you give up
Default sentences
Open: “Before I start designing, I’d like to clarify a few requirements and assumptions.”
If no numbers: “I will assume 400 million redirects/day, about 4,630 per second average, 40,000 at peak. Stop me if that is wrong.”
Before a new box: “I picked this because of this number (or this rule). What I give up is this.”
Close: “Here is the thin path, the first bottleneck, and the one trade-off I would defend to a VP.”
Pocket math
text
Average QPS = daily requests / 86,400
Peak QPS = average × 3–10
In-flight = peak QPS × work seconds
Daily bytes = writes/day × object size
Stop when another decimal will not change a box. 1,157 vs 1,200 does not matter. 12/s vs 12,000/s does.
Close: requirements, core path, biggest risk, next evolution.
This is not a hiring prediction tool.
D-SCALE knowledge check5 min
D-SCALE knowledge check
D-SCALE knowledge check — recap
Today we check that you can walk the six letters with units.
The idea: Check that you can walk the six letters with units before you add more building blocks.
D-SCALE on Linkly
Why we practice this
If the letters are still fuzzy, Module 2 will become a brand list. This quiz is a gate, not a grade. A score here does not mean you will or will not get hired.
Students often want to skip ahead to caches. That is not enough.
If you cannot explain a letter in one breath *with a unit*, you are not ready to skip ahead.
Say each letter out loud (Linkly)
Letter
One breath with a number
D
Anyone redirects. Staff create. Do not lose a paid mapping. Analytics out.
S
400M/86,400 ≈ 4,630 GET/s, peak 40k/s, 23 POST/s, 200 B
C
Users, door, app, KV. No extras yet
A
POST /v1/urls, GET /{code}, key = code
L
At 40k/s the KV dies first
E
Cache 92% → 3,200 miss/s. What I give up: 60s takedown unless we invalidate
Now switch products in one breath: ClinicDocs is 19/s and 152 in-flight, not 40k GET/s. Same letters.
Default sentences
Open: “Before I start designing, I’d like to clarify a few requirements and assumptions.”
If no numbers: “I will assume 400 million redirects/day and design to 40,000/s peak. Stop me if that is wrong.”
Trade-off: “I picked a cache because 40k/s. What I give up is instant global purge.”
After you finish
Missed D or S? Reread those two lessons and teach them to a wall. Do not skip ahead to caches.
INTERVIEW TIP: If you cannot explain a letter in one breath *with a unit*, you are not ready to skip ahead.
Changed telemetry challenge15 min
Changed telemetry challenge
Changed telemetry challenge
Today we practice sizing when the interviewer changes the numbers.
The idea: Erase your napkin and recompute from their telemetry. If you write 4,630/s from memory, you are recalling, not transferring.
Why we practice this
In class you learned Linkly’s defaults. In the room they will hand you different numbers. The method stays. The sheet does not.
Use the live widget on this lesson. Numbers are interviewer-provided assumptions, not the Size-the-system defaults.
Lab 302 brief
Lab 302 brief
Lab 302 — Changed telemetry
Today we practice recomputing when the interviewer changes the numbers.
The idea: Recompute a Linkly-shaped product whose numbers are not the canon 400M / 4,630/s / 40k peak story.
Why we practice this
Interviewers change the napkin on purpose. This lab trains you to erase and recompute — not to recite the classroom story.
Teaching assumptions (interviewer-provided)
These are not the Size-the-system defaults. If you catch yourself writing 4,630/s, stop.
Assumption
Value
Product
Short links for a regional publisher
Redirects / day
90 million
Creates / day
8 million
Average mapping size
80 bytes
Peak story
Morning homepage, interviewer says “about 3× average unless you justify another factor”
Prior architecture you are allowed to remember
API → app → KV + optional cache (from Lab 401). You must validate it against these numbers.
What you must produce
Average GET rate (requests / second) with units
Peak factor you will use, and why
Read / write ratio
First bottleneck
Does the previous thin architecture still hold? Yes/no + one sentence
What you would change, if anything
What changed versus the 400M/day story, and why
Accuracy of reasoning beats extra decimals. 90e6 / 86,400 ≈ 1,042 GET/s average.
Validation
[ ] Average is ~1,000/s, not 4,630/s
[ ] Peak is justified (3× → ~3,100/s unless you named a different factor)
[ ] Creates (~93/s) still do not justify a stream
[ ] You said whether cache is still the first evolution
SCALE CHECK: Transfer is the point. Reciting the course napkin fails the lab.
You will
Say why a cache, queue, or store is in the picture
Keep search and object storage off the write path unless needed
DNS and CDN20 min
DNS and CDN
DNS and CDN
Today we learn how people find your site, and when a nearby copy helps.
The idea: DNS is the address book for websites. A CDN keeps a saved copy nearby when the same file is useful to many people.
Why we learn this
“We’ll put a CDN in front” is a start, not a design yet.
In the interview, say four things in plain words:
How people find the site (the address book).
Whether a saved copy nearby actually helps.
How often that copy is enough (a percent) — and why, if that percent is low.
What you will never put on that copy.
Then say which timer and which door. If you mix those up, you can’t turn a bad link off, or 10:00 melts checkout.
We will look at pictures together, then practice on the six products.
Words we use
Word
Plain meaning
DNS
The internet address book. You type a name, you get an address
Door
The address DNS gave you — the app, the CDN, or the load balancer. Say which
Three clocks
DNS timer = old door. CDN timer = saved copy nearby. 301 / browser = that phone remembers
Three doors
DNS finds one door. CDN = saved copy nearby. Load balancer = the front desk inside
CDN
A saved copy nearby — like a photo already on your phone so you don’t re-download every time
Hit
You already have the file nearby. Fast
Miss
Fetch from the main server / original files. Then keep a copy for next time
Cache key
What makes two requests “the same file.” Extra junk in the URL can ruin the percent
Origin
Original files / main server. Keep it locked
Signed URL
A ticket that expires
302
A redirect I can still turn off
301
Browsers remember forever. Linkly cannot turn that off
How to walk this (every product)
Name the door (DNS, not the load balancer) and which TTL you mean.
Ask: is this the same file for everyone? If yes, a saved copy nearby may help.
Say the hit percent. If the file is large, also say how much traffic still hits the main server.
If the hit percent is low, say why — often a bad cache key — before you keep the CDN.
Say what you will not cache (money, login, dirty files, live location pings).
Lock the main server. A public bucket plus a CDN is still public.
Don’t start with an AWS product name.
Method, then six products
Start with the address book, the three clocks, the three doors, hit-or-miss math, big files, a bad key, and a rush on the main server. Then what you refuse to cache, and how you lock the origin. Then a blank sheet. Then the six products. Finish with three short drills.
AWS names (Route 53, CloudFront) are examples only. They are not the design. Load balancing is the next lesson — the front desk inside.
BOTTLENECK: A CDN that only helps 20% of the time is just an extra hop on the way to the main server — usually a bad cache key, not bad luck.
COMMON MISTAKE: “We put a CDN in front” with no percent, one timer for all three clocks, and an open main server.
DNS and CDN one-pager
DNS and CDN one-pager
DNS and CDN — one-pager
BayLearn · System Design Interview Sprint
Today’s idea: DNS is the address book for websites. A CDN keeps a saved copy nearby when the same file is useful to many people. Say the hit percent. Do not put money on the CDN.
Word
Plain meaning
DNS
Address book. Name → address
Three clocks
DNS TTL = old door. CDN TTL = saved copy nearby. 301 = that phone
Three doors
DNS = one door. CDN = saved copy nearby. Load balancer = front desk
Hit / miss
Already have it nearby / fetch from main server
Cache key
What makes two requests the same copy. ?utm= can ruin the percent
Origin
Original files / main server. Lock it
301
Browsers remember forever. Never for Linkly
Miss QPS = peak × (1 − hit ratio). 90% is a win. 20% is an extra hop — look at the key.
Pipes: 20,000 GET/s × 400 KB ≈ 8 GB/s off origin. At 90% hit ≈ 0.8 GB/s. Photos buy a CDN for pipes. A 200-byte 302 does not.
Six rows
Product
CDN?
TTL instinct
Never cache
Linkly
Maybe the 302
60s, never 301
Mapping in DNS
PulseFeed
Photos yes
Hours + new filename
Private Home
RideHail
Tiles maybe
One city door
Live location
PayRail
No on money
API door 60s
Capture / authorize
ClinicDocs
Clean + ticket
Minutes
Landing files, open bucket
TicketDrop
Poster yes
Versioned art
Hold / “seats left”
A public main server plus a pretty CDN is still public. DNS is not a load balancer.
This is not a hiring prediction tool.
Load balancing20 min
Load balancing
Load balancing
Today we learn how each request gets to a free, healthy server copy.
The idea: A traffic director sends each request to a free, healthy server copy. A gateway only checks front-door rules like login and rate limits. Don’t keep the user’s session in either of those boxes.
Why we learn this
If one app copy remembers the user in its own memory, you stuck that person to the same helper. When you restart that machine at Linkly’s peak, those users break.
Common mix-ups — same family as 301 vs 302:
429 means “slow down.” 503 means “nobody can help right now.”
If the user’s client gives up first, the server may still be working for nobody.
If the traffic director retries a payment, you can charge $49 twice.
You already named three layers on DNS and CDN: the name lookup, the nearby copies, and this traffic director. This lesson is only the traffic director — and you want two of them, not one box.
We will look at pictures together, then practice on the six products.
Words we use
Word
Plain meaning
Traffic director
The load balancer. It sends each person to the next free helper (server copy)
Helper
One server copy
Pair
Two traffic directors. If you have only one and it dies, nobody gets in
Layer 4
Cannot read URL details. It sees the connection, not the path
Layer 7
Can read the path. It unwraps HTTPS to do that. Use this for our APIs
Healthy
The helper can still do the real job — the database is up, not just “the process is running”
Sticky / glue
Always the same helper (fragile if that helper is down)
Front-door rules
The API gateway. Login, rate limits, body size. Not the money ledger
429
“Please wait” — too many requests. The database may be fine
503
“Closed” — no healthy copy
Three timers
Database, then the app, then the user’s client. The inside one should finish first
Retry
Retry a simple read once. Do not let the traffic director send a payment twice
Drain
Let current requests finish, then take the copy out
Fail closed
If every copy is sick, stop and show an error. Don’t guess
Warm-up
A new copy needs a few minutes before it is ready
Spare copy
Plan so one copy can be down and you still keep up
How to walk this (every product)
How many copies? Peak requests per second ÷ what one copy can handle. If one down is too much for the rest, add a spare.
Run two traffic directors. DNS found the address; it is too slow to be the backup.
Health must check the database. If all copies fail, return 503, not 429, and don’t send traffic anyway.
Don’t store the session in one copy’s memory. Use a shared store or a signed cookie. For long connections, say if you pin the user or pass messages through a bus — and how long before an idle call is dropped.
The gateway adds front-door rules. It is not PayRail’s money and not TicketDrop’s seats.
The database timer should finish first. Retry a read once. Never let the traffic director retry a payment.
On deploy, wait 30–60 seconds so in-flight work can finish.
Don’t start with an AWS product name. Finish with: I picked this because of this number (or this rule). What I give up is this.
Method, then six products
Start with the traffic director, a pair, L4 vs L7, real health, how many copies, and no glue. Then long connections, the gateway, 429 vs 503, the three timers, retries, and drain. Then a blank sheet. Then the six products. Finish with three short drills.
AWS names (ALB, API Gateway) are examples only. They are not the design.
ARCHITECTURE DECISION: Keep session data in a shared store so any copy can take the next request. Pinning a user to one machine is a last resort — and you must size it.
COMMON MISTAKE: Storing the session in one copy’s memory. Or sending 429 when you meant 503. Or letting the traffic director retry a payment.
Load balancing one-pager
Load balancing one-pager
Load balancing — one-pager
BayLearn · System Design Interview Sprint
Today’s idea: A traffic director sends each request to a free, healthy server copy. A gateway only checks front-door rules. Don’t store the user’s session in either box.
Word
Plain meaning
Traffic director
Load balancer — next free helper
Helper
One server copy
Pair
Two traffic directors, not one box
L4 / L7
Cannot read URL details / can read the path
Healthy
Helper can still do the real job (DB up)
Sticky
Always the same helper (fragile if down)
Front-door rules
Gateway: login, rate limits, size — not the money ledger
429 vs 503
Please wait vs nobody can help
Three timers
Database, then app, then client. Inside one first
Retry
Retry a simple read once. Don’t retry a payment
Drain
Wait 30–60s, then take the copy out
Fail closed
If every copy is sick → 503
Spare copy
Plan so one copy can be down
Copies ≈ peak ÷ what one copy can handle. Linkly: 40,000 / 2,000 = 20. If 19 at about 2,100 is too much, use 21. A new copy needs a few minutes. A cache buys time.
What to say: I picked this because of this number (or this rule). What I give up is this.
Six rows
Product
Copies
Health
Sticky?
Front door
Don’t do this
Linkly
20 at 40k/s
Key store up
No
429 on create
Session in one copy
PulseFeed
Many readers
Feed path
No on Home
429 on publish
Load balancer as photo CDN
RideHail
Pings ≠ trips
Per path
Long calls: say it
Login on trip
One pool for both
PayRail
Fewer, 1,200/s
Ledger up
No
Retry key + 60/min
Traffic director retries payment
ClinicDocs
Small API
API only
No
Upload ticket
PDF through JSON
TicketDrop
Many polls
Status ≠ seat
No cart in memory
1 poll / 2s
Load balancer as the 10:00 fix
DNS found the address. This traffic director picks the server copy. Run two.
Use this as a practice card while you speak out loud.
Application services20 min
Application services
Application services
Today we learn how many apps to draw — and when one is enough.
The idea: Start with the simplest one app. Split only when a number or a failure forces it. Live request when the user waits. Background job when they can leave.
Why we learn this
“Microservices” is not a personality. A team of eight with forty repos will spend the hour explaining money they cannot move safely.
You already met the traffic director in Load balancing. This lesson is which apps stand behind that director — and whether they share one official record.
Common mix-ups we will clear up:
One app is a real design. Linkly create + redirect can share a deploy.
Modules are folders inside one deploy. They are not forty repos.
Two knobs (API vs worker) can share one git repo. That is not two companies.
A chain of waiting calls (Home → rank → ads → graph) is a fake split. You paid the network tax and kept the coupling.
A shared database across “services” is still one system.
A short function with a 15s limit cannot scan for 90s. Runtime is a number, not a brand name.
We will look at pictures together, then practice on the six products.
Words we use
Word
Plain meaning
One app
One deployable unit. Monolith is honest if it is the only app
Modules
Folders inside one app. Same deploy today, easy to extract later
Separate apps
Split because scale or failure differs — 75k pings vs 17 trips — or a stable team boundary
Too many apps
Needs a platform team. Not the first cut
Short function
Often a 15s limit. Runs for one job, then stops
Always-on server
A container. Stays up. Better for 8s work that may grow to 90s
Live request
The user is staring at a spinner
Background job
They can leave (scan, receipt)
Event
One fact many apps may read
Official record
Money, seats, or mappings. Usually one commit
Shared database
Still one system if “services” share it
API contract
Must stay boring to split teams
Hold + expire
If two apps must agree: reserve with a clock, then give it back
Two knobs
Two scale controls. ClinicDocs API on QPS, workers on queue age
Chain of waiting calls
Fake split. Home waits on rank waits on ads…
How to walk this (every product)
What is the simplest one app? One deploy, or modules inside one deploy.
Do I have a number or a failure that forces a second app? Scale, failure, or a team with a stable contract. Empty reason → keep one.
How do they talk? Live request if the user is waiting. Background job if they can leave. Count hops on the spinner — more than two live calls is a smell.
Where is the official record? One commit, or hold-then-expire. Do not invent a shared transaction across apps.
Is the database shared? If yes, you did not really split.
How does it run? Short function vs always-on server. Say the timeout. Same boxes either way.
Two knobs can share one repo. Say both.
Don’t start with Lambda or ECS. Finish with: I picked this because of this number (or this rule). What I give up is this.
Method, then six products
Start with one app, modules, three reasons, too many apps, short function vs always-on, live vs background, the chain of waiting calls, two knobs, one official record, hold-and-expire, shared database, the contract, no session in one copy, and the 15s limit. Then a blank sheet. Then the six products. Finish with three short drills.
AWS names (Lambda, ECS) are examples only. They are how a box runs, not the design.
Teacher tip: Start with the simplest deployable unit that meets your requirements. Split when a number or a failure forces it.
Watch for this miss: Microservices as the first box because it sounds senior. Or eight apps that still share one database.
Application services one-pager
Application services one-pager
Application services — one-pager
BayLearn · System Design Interview Sprint
Today’s idea: Start with the simplest one app. Split only when a number or a failure forces it. Live request when the user waits. Background job when they can leave.
Word
Plain meaning
One app
One deployable unit (monolith is honest)
Modules
Folders inside one app
Separate apps
Split when scale or failure differs (or stable team boundary)
Short function / always-on
Often 15s limit / container that stays up
Live / background
User is waiting / they can leave
Official record
Money, seats, or mappings in one place
Shared database
Still one system
API contract
Must stay boring to split teams
Hold + expire
Reserve with a clock if two apps must agree
Two knobs
Two scale controls; can share one repo
Waiting chain
Fake split. Home waits on rank waits on ads…
Three honest reasons: different scale, different failure, different team + stable contract. Empty reason → keep one app.
What to say: I picked this because of this number (or this rule). What I give up is this.
Six rows
Product
Shape
Split?
Talk
Official record / DB
Don’t do this
Linkly
One app
Later if deploys fight
Live
One map
Two companies for GET vs POST
PulseFeed
Write + built Home
If hops grow
Background + copy
Feed is a copy
12-hop live chain
RideHail
Two apps
75k vs 17
Cheap ping; strict trip
Two databases
One fate for both
PayRail
Modules, one record
Email only
Live $49; background mail
One ledger
Block capture on SMTP
ClinicDocs
Two knobs, one repo
Process, not company
202 + background
Metadata vs bytes
8s on HTTP; 15s function for 90s
TicketDrop
One record or hold
Only if pay is elsewhere
Hold clock
Seats are the gate
Forty services as the 10:00 fix
A team of eight does not need forty apps. Forty apps need a platform team.
Use this as a practice card while you speak out loud.
Caches20 min
Caches
Caches
Today we learn what a cache is really for — and what it must never pretend to be.
The idea: A cache is a quick saved lookup. Say what you store, hit %, miss load on the official record, how long it lives, and what happens when everyone refreshes at once.
Why we learn this
“Add Redis” is not a design yet. A good answer names four things:
Hit percent — how often the quick saved lookup helps.
Miss QPS — how hard the official record still works.
Stampede — what happens when one hot key expires (whole class refreshes grades at once).
What the user sees when the copy is a little old.
You already used a saved copy nearby in DNS and CDN. That copy sits at the edge. This lesson is the app’s quick saved lookup — usually a shared cache next to the app.
Common mix-ups we will clear up:
Hit % without miss QPS is empty talk. Linkly 92% hit turns 40,000/s into 3,200 misses. Write that.
TTL-only delete leaves a lie for up to a minute. Delete that saved lookup.
301 is remembered forever in the browser. Use 302 if you may need to turn a link off.
Write-behind is fast and unsafe for money. If the cache dies, the $49 can vanish.
A shared Home key can leak another user’s feed. Put userId on private copies.
A stale “12 seats left” can double-sell. Inventory is the official record, not a quick saved lookup.
CDN stampede was a saved copy nearby. Redis stampede is this lookup.
We will look at pictures together, then practice on the six products.
Words we use
Word
Plain meaning
Quick saved lookup
The cache. Fast, maybe stale, maybe gone. Not the official record
Official record
The database. Misses land here
Hit
Found the lookup
Miss QPS
Peak × (1 − hit ratio). This is what the official record must survive
Layer
Browser, CDN, app RAM, shared cache, DB buffer. Name which
Cache-aside
App asks lookup → miss → official record → fill → return. Good default
Read-through
The cache layer loads the official record. Retries can hide here
Write-through
Write hits lookup and official record together. Safer, slower writes
Write-behind
Write the lookup; official record later. Fast. Can lose money
TTL
How long the saved copy is allowed to live
Jitter
Randomize TTL so keys do not die as a herd
Stampede
Whole class refreshes grades at once — one hot key expires; thousands miss together
Invalidate
Delete the saved lookup on write or DELETE
Hot set
The small slice that actually moves hit %. LRU drops the rest
Label
The cache key. Private data needs userId
How to walk this (every product)
What is copied, and which layer? CDN vs this cache vs app RAM.
Miss QPS = peak × (1 − hit). Does the official record still live?
Pattern: cache-aside unless the copy must match before you return. Never write-behind for money.
TTL as a number. Jitter. Delete the key on write. Stampede: lock or serve stale 2s.
Key: public vs userId. Maybe cache “not found” for junk.
Hot set size. Do not cache 100% of cold keys.
If the cache dies: fall through, watch QPS, shed or serve stale. The cache was never the official record.
Refuse list: money, seats, PHI, likes-as-ledger, a second copy of RideHail’s firehose.
Don’t start with ElastiCache. Finish with: I picked this because of this number (or this rule). What I give up is this.
Method, then six products
Start with lookup vs official record, miss math, which layer, cache-aside, through, write-behind, TTL, jitter, stampede, invalidate, the key, hot set, cache down, and the refuse list. Then a blank sheet. Then the six products. Finish with three short drills.
AWS names (ElastiCache, CloudFront) are examples only. CloudFront was a saved copy nearby. This lesson is the app’s quick saved lookup.
Teacher tip: Freshness vs speed is the trade-off. Write-behind is the fast choice that can lose money.
Scale check: Miss QPS = peak × (1 − hit ratio). Write that on the board.
Watch for this miss: Treating the cache as the system of record. Or using 301. Or caching a seat count.
Cache patterns one-pager
Cache patterns one-pager
Cache patterns — one-pager
BayLearn · System Design Interview Sprint
Today’s idea: A cache is a quick saved lookup, not the official record. Name hit %, miss QPS, TTL, and the stampede. Do not cache money, seats, or medical files.
Word
Plain meaning
Quick saved lookup
Cache — fast, maybe stale
Official record
Database. Misses land here
Miss QPS
Peak × (1 − hit). Linkly 40k × 8% = 3,200/s
Cache-aside
Ask lookup → miss → record → fill → return
Write-through
Write lookup and record together
Write-behind
Write lookup, record later — not for money
TTL + jitter
How long the saved copy may live; do not expire as a herd
Stampede
Whole class refreshes grades at once; lock or serve stale 2s
Invalidate
Delete the saved lookup on write
Hot set
Small slice that moves hit %. LRU the rest
What to say: I picked this because of this number (or this rule). What I give up is this.
Six rows
Product
What
Hit / miss
TTL
Don’t do this
Linkly
Redirect map
92% → 3,200 miss/s
60s + delete key
301; cache as the map
PulseFeed
Built Home (userId)
Reads from copy
10–30s
Likes as a ledger; photos in Redis
RideHail
Ping store already 30s
Skip second lookup
Overwrite is the clock
1.3 TB/day in Redis
PayRail
Profile / token only
Capture: no cache
Short on profile
Write-behind $49
ClinicDocs
Status only
Tiny
Few seconds
PHI / PDF in Redis
TicketDrop
Poll “wait” maybe
Seats: no cache
Very short if at all
Stale “12 left”
CDN was a saved copy nearby. This lesson is the app’s quick saved lookup. If the cache dies, fall through and watch official-record QPS.
Use this as a pocket card while you practice out loud.
SQL vs NoSQL7 min
SQL vs NoSQL
SQL vs NoSQL
Today we learn how to pick a store without picking a slogan.
The idea: Choose from how you look data up, how many times per second, and whether you need a real transaction — not from a brand name.
Why we learn this
“NoSQL is more scalable” is a common miss. A well-keyed relational primary often handles PayRail’s 1,200 simple writes/s. A badly keyed document store melts on one celebrity.
Pick from the lookup
Hot key
Two questions first
How do we look this up? One key? Range? Join? Full-text?
What must be true together? Money + inventory? Or can two writes land a second apart?
Then look at QPS.
Real world — one company, four stores
Imagine a consumer super-app that contains our six products. You still should not pick one database.
Path
Access
QPS (assumption)
Store instinct
Why not the other
Linkly redirect
code → url
40k GET/s (cached to 3.2k)
KV
Joins do not exist
PayRail charge
insert + unique key
1,200/s peak
SQL or transactional KV
Need unique + state machine
PulseFeed follow graph
many edges
185 posts/s, huge reads
Graph *or* two tables + cache
Do not join 12M rows on GET
ClinicDocs metadata
fileId, patientId
19/s
SQL
Boring is correct
ClinicDocs bytes
blob 3 MB
57 MB/s peak
Object store
240 GB/day in rows is pain
RideHail latest
driverId overwrite
75k/s
In-memory / specialized KV
SQL UPDATE 75k/s is a fight
TicketDrop inventory
decrement seat
burst
SQL row or atomic counter
Race = oversell
Search is a third thing: ClinicDocs full-text lags. Not the official record.
Capacity honesty (say the range)
These are order-of-magnitude interview ranges, not vendor SLAs:
Shape
Often comfortable
Time to rethink
Single SQL primary, simple writes
hundreds–low thousands/s
PayRail 1,200/s is in-range; 20k/s complex joins are not
Single KV node, 200 B gets
tens–hundreds of thousands/s
Linkly 40k uncached is the danger; cached 3.2k is calm
Object store PUTs
thousands/s with parallelism
ClinicDocs 19/s is trivial
If they challenge the number: “I am using an order of magnitude to pick a *shape*. We would load-test before we promise a contract.”
SQL / relational
Use when you need joins, ad-hoc finance queries, or multi-row commits (PayRail capture + ledger line, TicketDrop seat + payment).
Limits: one primary’s write path, lock contention on a hot eventId row during TicketDrop.
NoSQL / key-value
Use when you have the key (Linkly code, RideHail driverId) and can denormalize.
Limits: unplanned queries hurt. Transactions across keys may be weak. Hot keys stay hot no matter how many nodes you add.
How to choose
If this is true
Start with
GET by primary key, huge QPS
KV + cache
Orders + money must commit
Relational
Feed “latest N for user”
KV / time-ordered table + cache
Users type words
Separate search index
3 MB blobs
Object store + pointer
Analytics for five years
Warehouse, not the live DB
COMMON MISTAKE: “NoSQL is always more scalable.”
If they ask
“Can Postgres handle Linkly 40k GET/s?”
Maybe with a huge cache in front. I would still put a KV+cache on the redirect path and keep SQL for staff billing of custom domains.
“One database to simplify?”
Simple for the team, hostile for RideHail pings and ClinicDocs bytes. I will split by access pattern.
What to say in the room
I design storage around access patterns and QPS. Linkly is a key lookup. PayRail is a commit. ClinicDocs bytes are objects. RideHail pings are overwrites at 75k/s. Those four sentences are the design — not a brand.
Teacher tip: Design storage around how you look data up — not around a logo.
Store selection
Store selection
SQL vs NoSQL Decision Guide
Choose from access patterns, transactions, and query flexibility.
SQL when relationships, joins, and strong transactions matter.
NoSQL / specialized when the key is known, throughput dominates, and you can denormalize.
Do not say “NoSQL because scale.” Many interview-scale systems fit a primary plus replicas.
Messaging20 min
Messaging
Messaging
Today we learn how work moves when the user is not waiting on the page.
The idea: A to-do inbox holds one job. A group announcement shares one update with many listeners. A scrollable history lets a new reader catch up. Always plan for the same job arriving twice.
Why we learn this
Students often draw Kafka first because it sounds advanced. That is not enough.
In class we will answer three questions out loud:
Which shape is this — to-do inbox, group announcement, or scrollable history?
How many jobs are sitting in the inbox right now? (That is QPS × time.)
What happens if the same job shows up again?
You already chose live request vs background job in Application services. Here we go one step deeper: which box, how big, and how to stay safe when delivery is messy.
Default delivery is at-least-once. “Exactly once” usually means a unique key (same order id / receipt), not a magic switch.
PayRail 1,200/s × 2% retry ≈ 24 possible double charges without Idempotency-Key.
Claimed time (visibility) must be longer than the job.
Watch age of the oldest job, not only how many are waiting.
Linkly 302 and RideHail pings usually do not need scrollable history.
We will look at pictures together, then practice on the six products.
Words we use
Word
Plain meaning
To-do inbox
Queue. One job. Workers take turns
Group announcement
Pub/sub. One update, everyone gets it
Scrollable history
Stream / log. Catch up / replay
User waits
Live request. No buffer (Linkly 302, PayRail capture)
Background job
Async. User can leave the page
202
We got it. Not we finished
In-flight
Peak QPS × processing time. How many jobs sit in the inbox
At-least-once
The same job can show up twice. Default
Unique key
Same order id / receipt — retry does not double-do
Claimed time
Visibility timeout. Job stays claimed for N seconds. Longer than the job
Failed-jobs folder
DLQ. After 3–5 tries, park poison. Alarm on depth
Age
How long the oldest job has waited
Ledger then inbox
Save the official record / DB row, then drop the inbox job
Skip
No broker on a 2 ms path, and no 1.3 TB ping history
How to walk this (every product)
Shape: to-do inbox, group announcement, scrollable history, or user waits?
In-flight = QPS × time. Does a 15s stall still fit?
202 vs finished. Who is waiting?
Twice: assume at-least-once. Name the unique key. Claimed > job. DLQ after 3–5. Alarm on age.
Order per key, not global. Replay only if you named the day count.
Official record first, then enqueue.
Skip the broker when work is milliseconds, or when scrollable history would be terabytes.
Don’t start with SQS or Kafka. Finish with: I picked this because of this number (or this rule). What I give up is this.
Method, then six products
Start with three shapes, in-flight, 202, twice, the key, claimed time, DLQ, age, order, ledger-then-inbox, and when to skip. Then a blank sheet. Then the six products. Finish with three short drills.
AWS names (SQS, SNS, Kinesis, MSK) are examples only.
Teacher tip: When someone asks “what if the same event arrives twice?”, smile and name your key. That is the answer they want to hear.
Watch for this miss: Kafka on the board with no consumer, no DLQ, and no in-flight number.
Messaging one-pager
Messaging one-pager
Messaging — one-pager
BayLearn · System Design Interview Sprint
Today’s idea: To-do inbox = one job. Group announcement = many listeners. Scrollable history = catch up / replay. Size in-flight as QPS × time. Assume twice. Name the key.
Word
Plain meaning
To-do inbox
Queue. Workers take turns
Group announcement
Pub/sub. Everyone gets the same update
Scrollable history
Stream. Order per key. Replay is a project
User waits
Live request. No buffer
Background job
Async. User can leave
In-flight
Peak QPS × time. ClinicDocs 19 × 8s ≈ 152
202
We got it, not we finished
At-least-once
Default. Same job can show up twice
Unique key
Same order id / receipt. PayRail 1,200/s × 2% ≈ 24 replays/s
Claimed time
Visibility > job. 8s scan → 30–60s
Failed-jobs folder
DLQ. 3–5 tries, then park. Alarm
Age
Oldest job. Depth lies
Ledger then inbox
Save official record, then enqueue
What to say: I picked this because of this number (or this rule). What I give up is this.
Six rows
Product
Shape
In-flight
Twice
Don’t do this
Linkly
User waits; no broker
23/s × 2 ms < 1
N/A on 302
Kafka on create or GET
PulseFeed
Announce; history if replay
Not 12M inline
Post id
Fan-out-on-write 12M homes
RideHail
Overwrite ping
75k last-point
Last write wins
1.3 TB/day ping history
PayRail
User waits $49; inbox mail
Mail 1,200 × 0.2s ≈ 240
Idempotency-Key
SMTP on authorize
ClinicDocs
To-do inbox scan
19 × 8s ≈ 152
fileId
8s on HTTP; 15s stall at 90s
TicketDrop
Room + inbox confirm
10:00 burst
Hold / email key
500k HTTP to seats
Skip the broker when work is milliseconds. Kafka with no consumer is decoration.
Use this as a pocket card while you practice out loud.
Object storage and search5 min
Object storage and search
Object storage and search
Today we learn where big files live, and why search is not the money ledger.
The idea: Put big files in object storage. Keep a small row in a database that points to the file. Search is a late index — never the official record, never the PayRail ledger.
Why we learn this
Students sometimes stuff PDFs into Postgres, or treat a search cluster as “the database.” ClinicDocs is 240 GB/day. That mistake shows up in backups first.
Bytes vs index
Pipeline numbers
Object storage in plain English
Blobs: images, video, PDFs, backups. You get a key and the bytes. You do not get “all invoices for Dr. Chen in March” without metadata.
Control plane vs data plane
Control plane: mint fileId, status, who may read (19/s — SQL is fine)
Data plane: 3 MB × 19/s ≈ 57 MB/s at peak into the landing prefix
Upload: presigned PUT → landing (hostile) → queue → scan 8s → clean prefix → metadata status=CLEAN. Download only from clean.
Teacher tip: Keep metadata (control plane) separate from bytes (data plane).
Real world — yearly math
Assumption
Number
80,000 × 3 MB
240 GB/day
× 365
≈ 88 TB/year
Keep 7 years (legal)
≈ 616 TB
Versions / retries +20%
Plan ~0.75 PB
Lifecycle: 90 days hot, then cold. The DB still holds the pointer. You do not SELECT 3 MB out of a row store.
PulseFeed photos: 80M DAU × 0.2 posts × 50% with a 400 KB image ≈ 3.2 million images/day ≈ 1.3 TB/day. CDN + versioned filenames. Same pattern: object store + post row.
Linkly: 200-byte strings. No object store. Putting URLs in S3-for-fashion is a miss.
RideHail pings: 200 B × 75k/s. Not object storage. Overwrite a KV. Objects are for big immutable blobs.
Search in plain English
“Find PDFs that mention *creatinine*.” Built from clean text or OCR. It can be minutes behind. If you rebuild the cluster, the source of truth is still clean object + metadata row.
Never take permissions or money from the index. A reindex bug must not expose another patient’s file.
ClinicDocs 60s SLO is pipeline time to CLEAN, not “Elasticsearch is green.”
How to choose
Thing
Where
3 MB PDF / 400 KB photo
Object store
status, owner, ACL
Metadata DB
Full-text find
Search index (lags)
Linkly mapping
KV row
Card PAN
Never in a bucket listing or log
If they ask
“Why not the database for files?”
Row size, WAL, backups. 240 GB/day will own your DBA.
“Consistency of search?”
The clinician’s detail page reads metadata + signed clean URL, not the index. Search can say “still indexing.”
What to say in the room
Bytes go in object storage. A database row is the official pointer and status. Search is a helper that can lag. ClinicDocs is 240 GB/day and 88 TB/year — that is a lifecycle problem, not a SQL type. I will not put PDFs in the DB or treat the index as the system of record.
Watch for this miss: Public object URLs with no expiry, or search as the write path.
Building-blocks knowledge check5 min
Building-blocks knowledge check
Building-blocks knowledge check — recap
Today we check that you can justify each building block with a number or a rule.
The idea: Every building block is a choice. Say why it is there, using a number or a rule.
Why we practice this
Module 3 will add scale and failure. If you cannot justify a cache or a queue, those lessons will feel like trivia.
Six workloads
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
Baseline
One-line why (with the workload that proves it)
Block
Why it exists
Number / rule
Typical cost
DNS
Find the door
TTL 60s ≈ 1 min failover
24h TTL sticks
CDN
Cacheable bytes near the user
PulseFeed photo 90% hit
Extra hop at 20% hit; never cache PayRail POST
Load balancer
Healthy, stateless copies
Linkly 20 copies × 2k/s
Sticky RAM at 40k/s
App
Rules
Stateless; bytes not on disk
Snowflake boxes
Cache
Hot copies + TTL + miss path
92% hit → 3,200 miss/s
Stale takedown
SQL / NoSQL
Access pattern + transactions
PayRail ledger vs Linkly code
Wrong store = painful queries
Queue / stream / pub/sub
Async, fan-out, or replay
ClinicDocs 19/s × 8s = 152
Duplicates; no sync “done”
Object store
Bytes. DB holds the pointer
240 GB/day, 88 TB/year
Public buckets, files in the DB
Search
Lagging index
Searchable in 60s
Treating it as the record / ACL
What to say
“I picked X because of this number (or this rule). What I give up is Z.”
Example: “I picked a queue because a scan takes 8 seconds at 19/s (152 in flight). What I give up is ‘uploaded means searchable’ on the POST.”
If you cannot finish it, reread that block’s lesson before the quiz.
INTERVIEW TIP: Brand names are last. Reasons and units are first.
You will
Name the inconsistency a user can see
Protect the bottleneck you just found
Scaling6 min
Scaling
Horizontal vs vertical scaling — deep dive
Today we learn when to make one box bigger and when to add more copies.
The idea: Make one box bigger until it hits a real limit, then add more copies. 75,000 location pings a second is not the same problem as 17 trip starts.
Why we learn this
“We will scale horizontally” is not enough by itself. You need to know when a bigger box is honest (ClinicDocs metadata at 19/s) and when copies plus a queue are required (TicketDrop).
Limits: max instance size, one blast radius, resize downtime, still one AZ if you are careless.
NOTE: Vertical scaling is an honest first answer at many interview loads. 1,200 writes/s is not automatically “we must shard.”
Horizontal scaling (scale out)
More copies behind a balancer.
Works when copies are interchangeable — no unique files on local disk, no sticky RAM.
Linkly reads: 40,000/s ÷ 2,000/s per copy ≈ 20 app copies. The store is a different question — cache first.
Stateless apps
A copy can die; another takes the next 302. If ClinicDocs writes uploads to local disk, you built a snowflake. Bytes go to object storage.
Real world — 10× stories
Product
1×
10×
First move
Linkly GET
4,630/s
46,000/s
More cache + copies; watch miss QPS
PayRail
93/s
930/s
Still often one primary; then read replicas for reporting
ClinicDocs files
0.93/s
9.3/s
More workers, same API
RideHail drivers
30k
300k
Ping path already designed for overwrite; do not append
TicketDrop
8k tickets
80k
Waiting room, not 10× checkout boxes
Autoscaling: name the metric (queue age, p99, CPU), name warm-up (2–5 min), say what happens before new copies are healthy. That is why ClinicDocs has a queue and Linkly has a cache.
If they ask
“Is scale-out always better?”
No. Two copies of a badly sharded RideHail ping table can be worse than one tidy overwrite store.
“What about cost?”
A box sized for TicketDrop peak and idle 364 days/year is the expensive design. The waiting room is cheaper than 500k QPS of checkout.
What to say
I scale up until a real limit. I scale out when instances are interchangeable and state lives in a store. For Linkly I add copies and a cache. For ClinicDocs I add workers on queue age. For RideHail I change the data model (overwrite, not append) before I buy nodes.
SCALE CHECK: Peak 10× average → queue or cache, not a Sunday-idle peak box.
Replication and sharding6 min
Replication and sharding
Replication, sharding, and consistent hashing — deep dive
Today we learn how to copy data for reads and survival, and when to split it.
The idea: Copy data so reads can spread and so you survive a failure. Split only when one machine cannot take the writes, the size, or the blast. Extra shards will not help a celebrity key.
Why we learn this
Replication and sharding are different. Replicas do not increase PayRail write capacity. Shards do not fix PulseFeed’s 80k/s on one profile.
Lag is a number
Hot key
Replication
Sharding
Replication
One primary takes writes. Replicas copy.
Path
Replica OK?
Lag you name
PayRail GET after capture
No — read-your-writes on primary
0 on that path
PulseFeed like count
Yes
100–500 ms fine
Linkly redirect
Yes if cache miss
20–80 ms in-region
ClinicDocs staff report
Yes
Seconds OK
Cross-region replica
Reporting, not ledger
50–150 ms+
Replicas help availability (promote on death) and read scale. They do not let you write 10× more.
Cross-AZ copy is usually 1–3 ms. Cross-region is physics.
Sharding
Split by a shard key.
Shard when:
Writes exceed one primary (honestly: many teams shard later than 1k–3k complex writes/s; PayRail 1,200/s simple inserts may wait)
Dataset will not fit (ClinicDocs bytes already left the DB)
Blast radius (one TicketDrop event cannot lock the whole cluster)
Hash(`code`): even Linkly keys; bad for “all links this week.”
Range(time): good for logs; today is a hotspot.
Directory: flexible; the map is now critical.
STAFF-LEVEL EXPECTATION: Name who owns the shard map and how you reshard.
Resharding is a project: dual-write, backfill, cut, rollback. Do not shard Linkly in minute five.
Hot keys — the celebrity
PulseFeed profile at 80k GET/s or one post to 12M followers: hash(userId) puts all that heat on one shard. The other 99 sit idle.
Fix: cache the profile (5–15s), split counters from bio, or fan-out-on-read for celebs. Adding shards rearranges furniture.
RideHail city-center geo cell at 17:30 is the same idea. Shard by cell and you still melt downtown. Subdivide the cell or cap density.
Consistent hashing
Add a cache node, only a fraction of keys move. Useful for Linkly cache clusters. You do not need to draw a ring unless they ask. Benefit: less reshuffle than hash % N.
Ring
How to choose
Pain
First move
Number
Reads heavy
Cache + replicas
Linkly 40k GET/s
Writes exceed one primary
Shard or a managed sharded store
After you prove it
One key is hot
Cache / split key
80k/s celeb
Range scans by time
Careful with hash-only
Reports
If they ask
“What if a replica is 2 seconds behind?”
I will not send PayRail GETs there. I may send PulseFeed likes.
“How do you reshard?”
Migrate by key range with a directory and a rollback. I will not pretend it is free.
What to say
Replication helps reads and failover; I name lag and read-your-writes. I shard only when a single primary cannot take writes, size, or blast radius. I will not shard to fix a hot key — I will cache or split that key.
COMMON MISTAKE: “We will shard for high availability.” That is the wrong tool.
Consistency and CAP6 min
Consistency and CAP
Consistency models and CAP — deep dive
Today we learn what the user sees when copies cannot talk.
The idea: When the network splits, say what the user sees — a second $49, an old like count, or a car that is 4 seconds late on the map.
Why we learn this
Listing CAP letters does not help much. They want PayRail vs PulseFeed vs RideHail.
Three products
CAP without the cartoon
If two copies cannot talk (partition):
Keep taking writes on both sides → they may disagree (availability)
Refuse or delay writes until they agree (consistency)
Avoid “pick two of three.” Talk about one user action.
Physics: you cannot be strongly consistent and 10 ms worldwide. Cross-region RTT is often 50–150 ms.
Real world — same company, three answers
PayRail ledger. Partition → refuse the debit. Better a 503 than two $49 captures. One primary for writes. RPO target on captured charges: 0. Replicas are for reporting, not for “active-active because SRE blog.”
At 1,200/s peak, a 30-second split without a fence is 36,000 chances to fork money.
PulseFeed likes. Partition → still increment locally, reconcile later. Show ≈ 12.4k. Do not stall the page for 400 ms × 150k read/s.
RideHail display name. Read-your-writes: you see “Alex” now. The rider can lag 2–4s. Location pings are already 4s stale by design.
Linkly takedown. If legal disable matters, do not hide behind “eventual CDN.” Invalidate the key; accept up to TTL (60s) only if counsel agrees.
ClinicDocs ACL. A reindex must not show another patient’s PDF. Permissions come from the metadata DB, not from search eventual consistency.
TicketDrop inventory. Two regions decrementing 80k seats independently oversell. One inventory owner.
Words that matter more than CAP
Strong consistency. Next read sees the write. PayRail GET after capture.
Read-your-writes. *You* see your edit. Profile, settings.
Linearizability. Precise academic bar. Prefer “this ledger cannot fork.”
If they ask
“What do you do in a partition for a ledger?”
Stop conflicting writes. Fail closed. Do not queue debits you cannot merge.
“Can we be strongly consistent and globally fast?”
No. Fast in one region. Slower across oceans. Pin a merchant to a region if you must.
What to say
I pick consistency from the user action. Money stays on one primary — at 1,200/s I will not dual-write. Likes can lag. Map pins can be 4 seconds old. I will not recite CAP as a slogan.
FOLLOW-UP QUESTION: What do you do in a partition for a ledger?
COMMON MISTAKE: “We are AP” or “we are CP” with no user story and no QPS.
Reliability patterns6 min
Reliability patterns
Reliability patterns — deep dive
Today we learn what to do when calls fail.
The idea: Assume calls fail. Set a timeout, retry only when it is safe, keep damage in one place, and have a fallback the user can see. At 40,000 reads a second, a missing timeout is an outage.
Why we learn this
Happy-path diagrams are not enough in interviews. Talk about timeouts and what PulseFeed shows when ranking is down.
Circuit breaker
Duplicates
Multi-region
The toolbox with numbers
Timeout. Linkly KV get: 50–100 ms. PayRail downstream bank: 300–400 ms (inside the 400 ms p99 budget, so you have almost no slack — say so). ClinicDocs origin download: 2–5 s. Never “default 30s” on the 40k/s path.
Retry. Maybe on GET and 503. Never blindly retry PayRail POST without Idempotency-Key. 2% of 1,200/s = 24 retries/s.
Backoff + jitter. 50 ms, 100 ms, 200 ms + random. Without jitter, 20 app copies retry in lockstep and amplify a blip to 40k/s × 3.
Idempotency. Same key, one side effect.
Circuit breaker. If ranking errors > 20% for 30s, stop calling it; PulseFeed serves chronological. Recover with a probe.
Bulkhead. Separate pools: PayRail authorize threads cannot be eaten by receipt-email sockets.
DLQ. ClinicDocs corrupt PDFs after 5 tries. Alarm if DLQ > 50 or age > 10 min.
Graceful degradation. Ranking down → unranked feed. Search down → ClinicDocs detail page still works (metadata + signed URL). RideHail ETA service down → show raw map.
INTERVIEWER MAY ASK: What do you do when ranking is down? Serve an unranked feed.
HA vs DR (with clocks)
HA: survive a box or AZ in-region. Linkly 20 copies + Multi-AZ KV.
DR: lose a region. Name RTO and RPO, and that you rehearse.
Product
RTO instinct
RPO instinct
PayRail captured charges
15–60 min (business)
0 (or accept explicit $ risk)
Linkly mappings
1–2 h
Minutes (async copy)
PulseFeed timeline cache
Rebuild
Cache can die
ClinicDocs objects
Hours
Object store replication; landing may replay from hospital
Multi-AZ is not DR. Multi-region without a failover test is a slide.
Real world — amplification
Linkly: 40k/s, 3 retries, no jitter, dependency 500s for 10s → up to ~1.2 million extra calls in 10s. Timeouts + breaker + jitter are not decoration.
TicketDrop: retries on checkout without holds create oversell. Retry the same hold id.
If they ask
“How many retries?”
2–3 plus DLQ. Infinite retries are a self-DoS.
“Active-active?”
Only with a data story. PayRail default is active-passive. PulseFeed read replicas can be more relaxed.
What to say
Every call has a timeout inside the SLO. Retries are idempotent and jittered. I isolate pools, keep a DLQ, and name a degraded mode. HA is in-region. DR is a tested region story with RTO and RPO — 0 RPO for captured money.
COMMON MISTAKE: “We are multi-AZ” as the entire reliability answer.
HA = in-region redundancy. DR = lose a region (RTO/RPO, tested failover). Multi-AZ is not DR.
Rate limiting5 min
Rate limiting
Rate limiting — deep dive
Today we learn how to protect the hop that would break first.
The idea: Protect the hop that would break first. Allow honest bursts. Return a clear 429. Don’t treat thousands of fans behind one shared internet address as one bad user.
Why we learn this
Without a limit, one client *is* your load test. With a bad key, you lock out 40,000 fans behind one carrier IP. With no burst, you punish a PayRail mobile retry that already has an Idempotency-Key.
Token bucket vs attacker vs room
Limiter at the edge
TicketDrop waiting room
Where to put it
Edge / gateway: cheap and coarse. “This API key or this IP is too hot.” Stops a flood before 20 Linkly copies melt.
Service: fine and fair. “This user or this merchant is over quota.” Stops the noisy neighbor.
You usually want both. Edge is a flood wall. Service is a fairness rule.
TRADE-OFF: Exact global counts vs cheap approximate counts. Exact needs a central counter. Approximate is fine for Linkly reads. TicketDrop inventory is not a rate limit — it is a hold.
Four algorithms (with a number)
Token bucket (interview default). Bucket holds 100 tokens. Refill 10/s. A PayRail app that retries 10 times in one second is allowed. A script at 2,000/s empties the bucket in 0.05 s, then 429.
Leaky bucket. Constant outflow. Stricter on bursts. Useful if downstream is a bank that hates spikes.
Fixed window. 100/minute, clock resets. A user can fire 100 at 12:00:59 and 100 at 12:01:00 = 200 in two seconds. Say this if they ask why you did not pick it.
Sliding window. Fairer. More state per key.
Real world — six products, six limits
Product
What you protect
Limit you say
Key
Linkly create
KV uniqueness + abuse
30 POST/min per user
user id
Linkly redirect
App + cache, not the limiter
Very high; cache is the real shield
optional per-IP for scrapers
PulseFeed post
Write path 185/s global
5 posts/min per user
user id
PulseFeed feed
150k GET/s peak
Soft; cache first
do not IP-limit a campus
PayRail authorize
Bank + 400 ms p99
20/min per card/merchant
merchant + instrument
RideHail ping
75k writes/s already designed
Drop extra pings, keep latest
driver id
ClinicDocs upload
19/s peak, 3 MB
10 files/min per clinic
tenant id
TicketDrop
Inventory, not HTTP
Admit ~3,000/s; poll 1 / 2s
waiting-room token
PayRail Black Friday is 1,200 authorize/s. A per-merchant burst of 80/s for 10 seconds is a sale. A single card at 80/s is fraud. Same algorithm, different key.
What the client sees
Return 429 with Retry-After: 2. Log the key you limited (hashed). Never fail this as a generic 500 — the client cannot back off.
Outbound webhooks you *send* also need a limit. ClinicDocs notifying 200 hospital systems at once is a self-DoS.
If they ask
“Distributed limiters?”
A Redis-like counter for exact per-user quotas. An edge approximate count for floods. I will not pretend every POP shares one atomic integer at 150k/s.
“What if NAT hides a whole venue?”
IP is a last resort. TicketDrop issues a waiting-room token after login. PulseFeed campuses share one egress IP — limiting that IP starves a university.
“Is a waiting room a rate limiter?”
No. The limiter protects *your* hop. The room protects *inventory*. Admit 3k/s into checkout that holds seats for 30s → 90k in-flight holds. 80k tickets means you must expire holds or you lock the show.
What to say
I limit at the edge for floods and in the service for fairness. Token bucket is my default — honest PayRail retries may burst. I return 429 and Retry-After. I pick the key from the actor, not the IP. I will not use a limiter as TicketDrop inventory.
COMMON MISTAKE: One global IP limit that treats a carrier NAT as a single attacker.
SCALE CHECK: 2% of 1,200 PayRail/s = 24 retries/s. Those must still fit the bucket and the Idempotency-Key table.
Today we learn how to watch one user journey and name the usual security for that data.
The idea: Watch one user journey with real units. Page on something a person would feel. Mention the usual security for that kind of data without waiting to be asked.
Why we learn this
A design with no signals cannot be operated. A design with no auth is a demo. You do not need a security certification. You need the usual overlay for money vs likes vs PHI.
One journey, one SLO
Failure domains
Observability in plain English
Metrics. Numbers over time: QPS, error rate, latency, queue age, cache hit ratio, idempotency conflicts.
Logs. What happened to *this* request id. No PAN, no full PDF, no GPS breadcrumb.
Traces. The path across services for one request — Linkly GET from edge → cache → KV.
Alerts. Wake a human only when a journey is hurt. Queue age > 3 minutes beats worker CPU 70%.
One journey is enough (pick one and put numbers)
Journey
SLI
SLO you can say
Page on
Linkly redirect
GET /{code} success and p99 < 200 ms
99.9% in 30 days
SLO burn, 5xx, hit ratio < 80%
PayRail authorize
Capture persisted, p99 < 400 ms
99.95% captured
Error rate, duplicate-key conflicts
ClinicDocs clean
File searchable in 60 s
99% within 60 s
Queue age > 3 min, DLQ > 50
RideHail map
Fresh ping age < 8 s (2 missed pings)
99% of visible drivers
Write lag, drop rate
TicketDrop admit
Waiting-room fairness, hold expiry
Seats never oversold
Hold lock errors, oversell = page now
Error budget: 99.9% of Linkly redirects in 30 days ≈ 26 minutes of bad. That is when you freeze features.
You do not need twenty dashboards. You need one journey, one SLI, one page.
NOTE: This is not a professional security or SRE certification. It is the overlay you should mention in the room. A score here does not mean you will or will not get hired.
Security overlay (say these, with a data class)
Mention without a prompt:
Authn / authz — who are you, what may you do
TLS in transit
Encryption at rest for secrets and sensitive objects
Secrets not in source
Input validation — open redirects (Linkly), 3 MB vs 3 GB uploads (ClinicDocs)
Abuse limits — last lesson
Audit logs for admin and data-class actions
PII minimization — do not log the medical PDF or the card PAN
Data class
Extra control you name
Linkly public GET
Open redirect check; takedown + cache bust
PulseFeed PII
Retention on DMs; no raw location in logs
PayRail money
Least privilege, audit, Idempotency-Key, no PAN in logs
ClinicDocs PHI
Private origin, signed URL 5 min, landing bucket hostile until scan, ACL from metadata DB not from search
TicketDrop
Auth before the room; inventory is the source of truth
Landing buckets stay hostile until a scan. A public-by-default object URL is a miss even with a CDN in front.
Real world — what you refuse to log
Linkly: request id, code prefix, latency. Not the destination if it embeds an auth token.
PayRail: merchant id, last-4 only if policy allows, latency, idempotency outcome. Never PAN or CVV.
ClinicDocs: file id, clinic id, scan result. Never the PDF bytes or patient name in a debug dump.
RideHail: trip id, coarse geohash. Never a 4-second breadcrumb of a celebrity rider.
If they ask
“What do you page on?”
User-facing SLO burn or ClinicDocs queue age. Not disk 80% on one worker.
“Zero trust?”
Service-to-service auth and least privilege. I will not boil the ocean in minute 40.
“How do you know the cache is lying?”
Hit ratio and origin QPS on the same graph. Linkly 92% hit → 3,200 miss/s. If origin is 20k/s, the cache is sick — page that.
What to say
I pick one journey and put an SLI and SLO on it — Linkly p99 < 200 ms at 99.9%, or ClinicDocs clean in 60 s. I page on symptoms people feel. I mention TLS, auth, encryption, secrets, validation, limits, and audit, sized to the data class. Logs stay thin.
COMMON MISTAKE: Logging the full request body “for debug.”
FOLLOW-UP QUESTION: What do you page on when ranking is down but the chronological feed still works?
Scale knowledge check5 min
Scale knowledge check
Scale and reliability knowledge check — recap
Today we check that you can scale with numbers and fail with a user story.
The idea: Numbers tell you how many copies you need. Copies need a store. Failure needs a story the user can see.
Why we practice this
Scale and reliability answers need units and a user story. This quiz checks both.
Scale up vs out
Three consistency stories
Quick recap with units
Scale up until a real limit (PayRail 93/s is often one primary); scale out when copies are interchangeable (Linkly 20 app boxes)
Replicas help reads (PulseFeed likes); they do not multiply write capacity (PayRail still one writer)
Shard only with a key and a reshard story — not to fix an 80k/s celebrity key
Consistency is a user story: refuse a second $49, allow a stale like count, allow a 4s old car
Timeouts inside the SLO (PayRail almost no slack under 400 ms), jittered retries, breakers, DLQ, degradation
Rate limits protect the bottleneck; TicketDrop inventory is a hold, not a 429
One SLO + boring security overlay (ClinicDocs landing stays hostile)
Take the quiz. If a miss surprises you, reread that lesson and say the trade-off sentence out loud. A score here does not mean you will or will not get hired.
INTERVIEW TIP: “What does the user see?” is a legal answer to almost every reliability probe.
You will
Run Lab 301 — Capacity napkin in the Course Player
Run Lab 401 on Architecture canvas
Run Lab 501 on Event platform design
Run Lab 701 — PayRail AWS (BUILD-SD-701)
Lab 301 — Capacity napkin15 min
Lab 301 — Capacity napkin
Lab 301 — Capacity napkin
Today we practice turning a daily headline into QPS, bytes, and in-flight work — then say which box on the architecture moved.
The idea: Turn a daily headline into QPS, bytes, and in-flight work — then say which box on the architecture moved.
Why we practice this
Lab 301 is the S in D-SCALE — Size the system.
Interviewers do not want a calculator performance. They want you to convert a headline (“400 million redirects a day”) into units a design can use:
Average QPS — daily volume ÷ 86,400
Peak QPS — average × a peak factor you label
Write QPS — writes/day ÷ 86,400
Daily / yearly bytes — writes × object size
In-flight work — peak QPS × seconds of work (Little’s Law)
Cache miss QPS — peak × (1 − hit ratio)
Those six numbers decide the first box: cache, queue, overwrite store, object storage, waiting room, or “one well-run primary.” A number that does not change a box is decoration. Stop there.
This sprint is vendor-neutral. The AWS sprint’s analog of “apply Terraform” is doing this napkin out loud until 86,400 is muscle memory.
Why it exists
Juniors recite “we need to scale.” Seniors put units on the board.
4,630/s (Linkly average) is a cache-first read path, not a stream.
19/s × 8s ≈ 152 in-flight (ClinicDocs) is a queue, not “internet scale.”
~1,200/s simple PayRail commits often still fit one primary. Idempotency-Key is the design, not a shard.
75k writes/s RideHail pings are an overwrite, not 1.3 TB/day of appends.
500k people in a waiting room is not 500k checkout QPS. Inventory is the gate.
If the interviewer gives different telemetry, erase yours and recompute. The skill is transfer, not memorizing Linkly.
How to use it on this page
Scroll to Capacity napkin on this lesson (same widget also sits on Size the system).
Run Linkly. Write avg QPS, peak QPS, and miss QPS (92% hit) on paper.
Run ClinicDocs. Write daily bytes, peak files/s, and in-flight scanners.
Run PayRail. Say whether 1,200/s forces a shard.
Change one number (object size or peak factor). Say which output box moved.
Optional: open capacity_formulas.py on Size the system — same math as the widget, as code.
Formulas (say them with units)
What you compute
Formula
Why it matters
Average QPS
daily volume / 86,400
Shared scale with the interviewer
Peak QPS
average × peak factor
The box you provision for
Write QPS
writes per day / 86,400
Separate from read QPS
Daily bytes
writes × object size
Database vs object store
Yearly bytes
daily bytes × 365
Lifecycle, not one disk
In-flight
peak QPS × work seconds
Queue depth / holds / scanners
Cache miss QPS
peak × (1 − hit%)
What actually hits origin
Stop when another decimal will not change a box.
Expected napkin (labeled assumptions)
Product
Headline
What you should see
Linkly
400M GET/day, 200 B, 92% hit
~4,630/s avg, ~40k/s peak, ~3,200 miss/s
ClinicDocs
80k × 3 MB, 8s scan
240 GB/day, ~19/s peak, ~152 in-flight
PayRail
8M/day, peak ×13
~93/s avg, ~1,200/s peak
RideHail
300k × ping/4s
75k writes/s — overwrite, do not append
PulseFeed
16M posts, ~2.4B feed reads
~150:1 read:write — fan-out or cache the timeline
TicketDrop
500k in the room, admit 3k/s
Waiting room ≠ 500k checkout QPS
NOTE: These are teaching assumptions, not leaked production telemetry. If the room gives different numbers, yours are wrong until you recompute.
What “done” looks like
Mark this lab complete when:
[ ] You can say “400 million / 86,400 ≈ 4,630/s” without looking
[ ] You can explain why ClinicDocs is a queue at 19/s, not a cluster
[ ] You can explain why TicketDrop is a waiting room, not 500k checkout QPS
[ ] You changed one input and named which box moved
Time: 10–15 minutes. No AWS.
Common mistakes
Treating “millions a day” as Kafka before dividing by 86,400
Using average QPS as the provisioned number (peak is)
Appending RideHail pings instead of overwriting latest location
Equating waiting-room headcount with checkout QPS
Chasing extra decimals that do not change a box
Lab 401 — Linkly studio25 min
Lab 401 — Linkly studio
Lab 401 — Linkly studio
Today we design a URL shortener on the 16-section canvas *before* we open the reference diagram.
The idea: Design a URL shortener on the 16-section canvas *before* you open the reference diagram.
Why we practice this
Reading “add a cache” is not the interview. Filling the canvas with units is.
Objectives
Walk D-SCALE on Linkly
Put 4,630/s, 40k/s peak, and 23 POST/s on the board
Draw four boxes, then *one* evolution
Name a loser (60s takedown unless you invalidate)
Time
20–25 minutes.
Steps
Read the URL shortener challenge. Hide the reference picture.
Open the live canvas on Architecture canvas.
Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
Fill sections 1–7 (problem through baseline) before you decorate.
Fill 8–16. The hop that dies first is the KV at 40k GET/s.
Export Markdown if you want a copy. Mark the lab complete.
Validation
[ ] Scale row has units, not “high scale”
[ ] Baseline is four boxes (no Kafka)
[ ] Evolve is one cache with a hit ratio
[ ] Trade-off names a loser
[ ] Close is two minutes: path, bottleneck, trade-off
Common fails
Logo pile in minute two
Sharding to fix a 50k/s viral code (one key)
301 plus “instant legal disable”
Copying ClinicDocs (202 + queue) onto a redirect path
SCALE CHECK: If they say 10 million/day, recompute (~116/s avg). Do not keep 20 app copies for sport.
Lab 501 — Event studio30 min
Lab 501 — Event studio
Lab 501 — Event studio
Today we design “take the work, finish later” on a new canvas. Do not copy the URL-shortener design.
The idea: One million a day ≈ 12 per second. ClinicDocs is about 19 per second with about 152 scans in flight. TicketDrop is about seats and fairness — not this lab.
Why we practice this
The headline sounds like a giant system. The napkin picks a waiting list, a file store for big files, and workers sized by how long the oldest job has waited.
Goals
Say we got it (HTTP 202) before the heavy work finishes
Put big files in a file store; put only an id on the waiting list
Add workers when wait time grows
Say what you give up (the user does not get “fully done” on the first call)
The canvases teach you to *say* Idempotency-Key. This lab makes you *watch* a second POST return the same order_id. PayRail at 1,200/s Black Friday with 2% retries is 24 duplicate attempts per second without that key.
---
Local deployment first (Path B) — what is running on your laptop
Before AWS, you run one Python process. That process contains every role you will later see as a separate AWS service. Learn this picture first.
PayRail local lab deployment
What each box is
#
Component
File / thing
Job
1
Your terminal
curl, demo.sh, pytest
Client. Sends Idempotency-Key.
2
HTTP server
scripts/local_server.py · 127.0.0.1:8080
Front door. Same job as API Gateway later.
3
Charge logic
lambda/charge.py
Hash, claim, call Mock Stripe, write order, enqueue. Same file on AWS.
4
Worker thread
daemon in local_server.py every 0.2s
Drains the in-memory queue. Same job as Worker Lambda.
Heal stuck processing. Locally you call it; on AWS a timer calls it.
Start command:
bash
cd payrail-idempotency
python3 scripts/local_server.py
# → PayRail local lab on http://127.0.0.1:8080
Stop the process → MemoryStore is gone. That is fine for Path B.
Watch: local replay (same Payment Intent ID)
Replay the sameIdempotency-Key against the local server. You should see the samepayment_intent_id / order_id — not a second charge.
Replay Payment Intent IDs locally
Local → AWS map (same state machine)
Local lab maps to AWS lab
Local
Becomes on AWS
HTTPServer :8080
API Gateway HTTP API
charge.py in-process
Charge Lambda
MemoryStore.keys + orders
DynamoDB tables
MemoryStore.intents
DynamoDB intents (Mock Stripe)
MemoryStore.queue[]
SQS
Worker thread
Worker Lambda
POST /lab/sweep
EventBridge every 1 min → Sweeper Lambda
In the interview you still say ALB + ECS + Aurora + real Stripe. This lab trains the state machine, not the production SKUs.
AWS picture (Path C — after local)
When you run terraform apply, these are the real services in your account. Same state machine as Path B — separate boxes instead of one Python process.
No live Stripe secret. The gateway is the intents table in your account. terraform destroy the same day.
State machine (say this in the interview)
text
missing Idempotency-Key → 400
store down → 503 fail closed (do not charge)
completed → cached 201 (replay) + x-idempotent-replay: true
processing → 409 in flight (retry the SAME key)
same key + different body → 409
else → claim → gateway → order → completed → enqueue webhook
After a timeout the client is in UNKNOWN. Retry the same key. The sweeper is the backstop.
---
Flow 1 — Happy path internals (learn this first)
Story: A student taps Pay once. The network is fine. Money moves once. The webhook is recorded once.
We slow down here on purpose. Steps 3–7 are what you defend in the interview. Steps 1–2 are just validation. Steps 8–9 are “tell the client and remember the event.”
Quick map of the whole happy path
Step
Name
What it protects
1–2
Accept request
Bad input never reaches money
3
Hash the body
Same key cannot mean two different amounts
4
Claim the key
Only one request may call the gateway for this checkout
5
Mock Stripe
One PaymentIntent per key — the bank side effect
6
Order + complete
Official PayRail ledger + cached answer for retries
7
Enqueue webhook
Downstream systems hear “succeeded” once (with dedupe)
8–9
Worker + 201
Event stored; client gets IDs
Steps 1–2 (short)
Client sends POST /v1/charges with Idempotency-Key, X-Tenant-Id, and { amount_cents, currency }.
Charge checks headers and body. Missing key → 400. Bad amount → 400.
---
Step 3 — Hash the body (fingerprint of the charge)
Why: The key alone is not enough. Someone could reuse the same key and change $25 to $50.
What you store later: That hash sits on the idempotency row as requestHash.
On a retry:
Same key + same hash → allowed to replay or wait.
Same key + different hash → 409 (different body). Stop. Do not charge.
Interview line: “The key names the checkout. The hash names what they agreed to pay.”
---
Step 4 — claim_key (reserve the checkout before money)
Why: Two tabs must not both call the bank. The first writer to the key store wins.
What “claim” means in plain English:
Write a sticky reservation: “This checkout is in progress. Nobody else starts a second charge.”
Row shape (local memory or DynamoDB):
text
pk = tenant#Idempotency-Key e.g. demo#abc-123
status = processing
requestHash = <from step 3>
createdAt / updatedAt
How the race is won:
Environment
Mechanism
Local lab
MemoryStore lock + “if key exists, return it”
AWS lab
DynamoDB PutItem with attribute_not_exists(pk) — loser gets ConditionalCheckFailed and reads the winner
Return value of `claim_key`:
Result
Meaning
Next action
created: true
You own this attempt
Continue to Mock Stripe
created: false + completed
Already done
Replay cached 201
created: false + processing
Someone else is mid-flight
409 in flight
created: false + hash mismatch
Same key, different amount
409
Critical rule: Claim happens before Mock Stripe. If you call the bank first and then crash, you have money moved with no reservation — that is how double charges start under retry.
Interview line: “I claim processing before the gateway. The key store is the lock.”
---
Step 5 — Mock Stripe (the bank side effect)
What it is: Not live Stripe. No sk_live_ secret. A small intents table (in memory locally, DynamoDB on AWS) that pretends to be Stripe PaymentIntents.
What it models: Real Stripe’s rule — one logical PaymentIntent per Idempotency-Key for that merchant attempt.
`create_intent(tenant, key, amount, currency)`:
Lookup pk = tenant#key in the intents table.
If a row exists → return the samepaymentIntentId. No second charge object.
If missing → mint pi_…, save it, return it.
Why this matters for the timeout story later:
If you crash *after* create_intent but *before* writing the order, the intent still exists. The sweeper can find it and heal. That is only possible because the mock (like real Stripe) keys intents by the idempotency key.
Local vs AWS:
Local
AWS
Call site
store.create_intent(...) passed into charge()
Same function on DynamoStore
Storage
MemoryStore.intents dict
DynamoDB intents table
Extra
stripe_mock.py Lambda exists for the pack; happy path calls the store method directly
Same store method from Charge Lambda
Interview line: “Gateway side effects are keyed by Idempotency-Key. Retries must not mint a second intent.”
---
Step 6 — Order row + mark key completed (official record)
Why two writes:
Orders table — the business ledger (“order ord_… succeeded for $25”).
Idempotency key row — the retry cache (status=completed + full JSON body).
What a later retry does: Reads this row and returns responseBody with x-idempotent-replay: true. It does not call Mock Stripe again. It does not mint a second order.
Order of operations in code:put_order → complete_key. After this moment, the checkout is “done” for retries.
Interview line: “Completed means: ledger written, and the exact HTTP answer is cached on the key for replay.”
---
Step 7 — Enqueue webhook (tell the rest of the world)
Why: Real Stripe does not only return HTTP to your API. It also pushes payment_intent.succeeded so email, ledger sync, fraud, or analytics can react. Your charge handler must not do all of that inline on the user’s request.
What gets enqueued:
text
{
event_id: evt_… ← unique id for THIS delivery attempt’s event
type: payment_intent.succeeded
payment_intent_id: pi_…
order_id: ord_…
tenant_id: demo
}
Local lab:MemoryStore.enqueue appends to an in-memory list (store.queue).
AWS lab:DynamoStore.enqueue calls sqs.send_message on the webhook queue.
Important: Enqueue happens after complete. The user-facing charge is already safe. The webhook is “notify others,” not “create the charge.”
---
Steps 8–9 — Worker dedupe + client 201
Worker (`worker.py` / `process_event`):
Read event_id from the message.
put_webhook(event_id) — first write wins.
If SQS (or the local loop) delivers again → duplicate: true → ignore. No second “send receipt” side effect.
“Hash the body. Claim the key before the gateway. One intent per key. Write the order and cache the 201. Enqueue the webhook with an event id. Retries replay — they do not charge again.”
Story: The phone never got the 201, so it retries with the same key and the same body.
Step by step
Client POSTs again with the same Idempotency-Key and same amount.
claim_key finds the row already exists (created=false).
Hash matches. Status is `completed`.
Lambda returns the cached JSON. No second PaymentIntent. No second order.
Response: 201 + x-idempotent-replay: true.
Sequence diagram — replay
Interview line: “Same key + same body = replay. The side effect already happened.”
---
Flow 3 — Timeout path (the interview trap)
There are two crash drills. Both return 504 to the client and leave the key in `processing`. What the sweeper does next depends on whether the gateway already created an intent.
3A — Crash *after claim*, *before* gateway
Header: X-Lab-Crash-After-Claim: 1
What happened: You reserved the key, then died. No money moved. No PaymentIntent.
Step
What you see
First POST
504 — row stuck processing
Immediate retry same key
409 in flight
Sweeper runs
No intent found → mark `failed`
Later retry same key
Replay of the failed response (not a new charge)
3B — Crash *after* gateway (money may already have moved)
Header: X-Lab-Crash-After-Gateway: 1
What happened: Intent exists in the mock Stripe table. The client still only saw 504. This is the scary UNKNOWN case.
Step
What you see
First POST
504 — intent exists, row still processing
Immediate retry same key
409 in flight
Sweeper runs
Finds intent → heal → completed with same payment_intent_id
Later retry same key
201 + "healed": true — same IDs
Interview line: “Client got UNKNOWN. I retry the same Idempotency-Key. Reconciliation looks up the gateway. If the intent exists, I complete; if not, I fail. I never mint a new key.”
COMMON MISTAKE: A new UUID after the 504. That is a second claim_key and a second charge. At 1,200/s with 2% retries, that is ≈ 24 double-charge attempts per second.
---
Flow 4 — In flight (409 while another request holds the key)
Story: Two tabs, or a retry that arrives while the first request is still talking to Stripe.
Request A claimed processing and is still working.
Request B uses the same key.
B sees processing → 409 “request in flight — retry the same key.”
B must not start a second gateway call.
---
Flow 5 — Same key, different body (409)
Story: Reuse the key but change the amount (bug or attacker).
First request claimed with hash of $25.
Second request sends $50 with the same key.
Hash mismatch → 409 “same Idempotency-Key with a different body.”
Do not charge $50 under the $25 key.
---
Flow 6 — Store down (503 fail closed)
Story: DynamoDB (or Aurora in production) is unreachable.
You cannot record the attempt.
Return 503. Do not call the payment gateway.
Interview line: “If I cannot write the idempotency row, I fail closed. Charging without a record is how you double-bill.”
---
Flow 7 — Webhook worker (event_id dedupe)
Story: SQS can deliver the same message twice. That must not create two “succeeded” side effects downstream.
Happy path enqueues one message with event_id.
Worker calls put_webhook(event_id). First write wins.
Duplicate delivery → duplicate: true → ignore.
---
What to say on the whiteboard (60 seconds)
text
1. Client always sends Idempotency-Key for a logical checkout.
2. I claim processing in the key store BEFORE the gateway.
3. Same key + same body + completed → replay cached 201.
4. Same key + processing → 409 in flight.
5. Timeout → UNKNOWN → retry SAME key → sweeper/reconciler checks gateway intent.
6. Store down → 503. Never charge without a record.
7. PayRail numbers: 93/s avg, 1,200/s BFCM, 2% retries ≈ 24 dup attempts/s.
Path on this portal
Path
Where
Pass when
A Portal
This overview + architecture + charge.py
You can point at claim / replay / 409 / sweeper
B Local
Unzip → pytest → local_server.py → demo.sh
9 passed, then PASS + 409
C AWS
Lab 701 — Test on AWS
health ok, crash drill 201 healed, then destroy
Stay in Lab 701 — PayRail AWS in the left nav.
Read the flows above until you can redraw them from memory.
Open Lab 701 — Test and demo and follow A → B (C is optional).
Open Build PayRail and read charge.py in the source browser.
Download sd-payrail-lab.zip when you start Path B.
The canvases teach you to *say* Idempotency-Key. This lab makes you *watch* a second POST return the same order_id. PayRail at 1,200/s Black Friday with 2% retries is 24 duplicate attempts per second without that key.
---
Local deployment first (Path B) — what is running on your laptop
Before AWS, you run one Python process. That process contains every role you will later see as a separate AWS service. Learn this picture first.
PayRail local lab deployment
What each box is
#
Component
File / thing
Job
1
Your terminal
curl, demo.sh, pytest
Client. Sends Idempotency-Key.
2
HTTP server
scripts/local_server.py · 127.0.0.1:8080
Front door. Same job as API Gateway later.
3
Charge logic
lambda/charge.py
Hash, claim, call Mock Stripe, write order, enqueue. Same file on AWS.
4
Worker thread
daemon in local_server.py every 0.2s
Drains the in-memory queue. Same job as Worker Lambda.
Heal stuck processing. Locally you call it; on AWS a timer calls it.
Start command:
bash
cd payrail-idempotency
python3 scripts/local_server.py
# → PayRail local lab on http://127.0.0.1:8080
Stop the process → MemoryStore is gone. That is fine for Path B.
Watch: local replay (same Payment Intent ID)
Replay the sameIdempotency-Key against the local server. You should see the samepayment_intent_id / order_id — not a second charge.
Replay Payment Intent IDs locally
Local → AWS map (same state machine)
Local lab maps to AWS lab
Local
Becomes on AWS
HTTPServer :8080
API Gateway HTTP API
charge.py in-process
Charge Lambda
MemoryStore.keys + orders
DynamoDB tables
MemoryStore.intents
DynamoDB intents (Mock Stripe)
MemoryStore.queue[]
SQS
Worker thread
Worker Lambda
POST /lab/sweep
EventBridge every 1 min → Sweeper Lambda
In the interview you still say ALB + ECS + Aurora + real Stripe. This lab trains the state machine, not the production SKUs.
AWS picture (Path C — after local)
When you run terraform apply, these are the real services in your account. Same state machine as Path B — separate boxes instead of one Python process.
No live Stripe secret. The gateway is the intents table in your account. terraform destroy the same day.
State machine (say this in the interview)
text
missing Idempotency-Key → 400
store down → 503 fail closed (do not charge)
completed → cached 201 (replay) + x-idempotent-replay: true
processing → 409 in flight (retry the SAME key)
same key + different body → 409
else → claim → gateway → order → completed → enqueue webhook
After a timeout the client is in UNKNOWN. Retry the same key. The sweeper is the backstop.
---
Flow 1 — Happy path internals (learn this first)
Story: A student taps Pay once. The network is fine. Money moves once. The webhook is recorded once.
We slow down here on purpose. Steps 3–7 are what you defend in the interview. Steps 1–2 are just validation. Steps 8–9 are “tell the client and remember the event.”
Quick map of the whole happy path
Step
Name
What it protects
1–2
Accept request
Bad input never reaches money
3
Hash the body
Same key cannot mean two different amounts
4
Claim the key
Only one request may call the gateway for this checkout
5
Mock Stripe
One PaymentIntent per key — the bank side effect
6
Order + complete
Official PayRail ledger + cached answer for retries
7
Enqueue webhook
Downstream systems hear “succeeded” once (with dedupe)
8–9
Worker + 201
Event stored; client gets IDs
Steps 1–2 (short)
Client sends POST /v1/charges with Idempotency-Key, X-Tenant-Id, and { amount_cents, currency }.
Charge checks headers and body. Missing key → 400. Bad amount → 400.
---
Step 3 — Hash the body (fingerprint of the charge)
Why: The key alone is not enough. Someone could reuse the same key and change $25 to $50.
What you store later: That hash sits on the idempotency row as requestHash.
On a retry:
Same key + same hash → allowed to replay or wait.
Same key + different hash → 409 (different body). Stop. Do not charge.
Interview line: “The key names the checkout. The hash names what they agreed to pay.”
---
Step 4 — claim_key (reserve the checkout before money)
Why: Two tabs must not both call the bank. The first writer to the key store wins.
What “claim” means in plain English:
Write a sticky reservation: “This checkout is in progress. Nobody else starts a second charge.”
Row shape (local memory or DynamoDB):
text
pk = tenant#Idempotency-Key e.g. demo#abc-123
status = processing
requestHash = <from step 3>
createdAt / updatedAt
How the race is won:
Environment
Mechanism
Local lab
MemoryStore lock + “if key exists, return it”
AWS lab
DynamoDB PutItem with attribute_not_exists(pk) — loser gets ConditionalCheckFailed and reads the winner
Return value of `claim_key`:
Result
Meaning
Next action
created: true
You own this attempt
Continue to Mock Stripe
created: false + completed
Already done
Replay cached 201
created: false + processing
Someone else is mid-flight
409 in flight
created: false + hash mismatch
Same key, different amount
409
Critical rule: Claim happens before Mock Stripe. If you call the bank first and then crash, you have money moved with no reservation — that is how double charges start under retry.
Interview line: “I claim processing before the gateway. The key store is the lock.”
---
Step 5 — Mock Stripe (the bank side effect)
What it is: Not live Stripe. No sk_live_ secret. A small intents table (in memory locally, DynamoDB on AWS) that pretends to be Stripe PaymentIntents.
What it models: Real Stripe’s rule — one logical PaymentIntent per Idempotency-Key for that merchant attempt.
`create_intent(tenant, key, amount, currency)`:
Lookup pk = tenant#key in the intents table.
If a row exists → return the samepaymentIntentId. No second charge object.
If missing → mint pi_…, save it, return it.
Why this matters for the timeout story later:
If you crash *after* create_intent but *before* writing the order, the intent still exists. The sweeper can find it and heal. That is only possible because the mock (like real Stripe) keys intents by the idempotency key.
Local vs AWS:
Local
AWS
Call site
store.create_intent(...) passed into charge()
Same function on DynamoStore
Storage
MemoryStore.intents dict
DynamoDB intents table
Extra
stripe_mock.py Lambda exists for the pack; happy path calls the store method directly
Same store method from Charge Lambda
Interview line: “Gateway side effects are keyed by Idempotency-Key. Retries must not mint a second intent.”
---
Step 6 — Order row + mark key completed (official record)
Why two writes:
Orders table — the business ledger (“order ord_… succeeded for $25”).
Idempotency key row — the retry cache (status=completed + full JSON body).
What a later retry does: Reads this row and returns responseBody with x-idempotent-replay: true. It does not call Mock Stripe again. It does not mint a second order.
Order of operations in code:put_order → complete_key. After this moment, the checkout is “done” for retries.
Interview line: “Completed means: ledger written, and the exact HTTP answer is cached on the key for replay.”
---
Step 7 — Enqueue webhook (tell the rest of the world)
Why: Real Stripe does not only return HTTP to your API. It also pushes payment_intent.succeeded so email, ledger sync, fraud, or analytics can react. Your charge handler must not do all of that inline on the user’s request.
What gets enqueued:
text
{
event_id: evt_… ← unique id for THIS delivery attempt’s event
type: payment_intent.succeeded
payment_intent_id: pi_…
order_id: ord_…
tenant_id: demo
}
Local lab:MemoryStore.enqueue appends to an in-memory list (store.queue).
AWS lab:DynamoStore.enqueue calls sqs.send_message on the webhook queue.
Important: Enqueue happens after complete. The user-facing charge is already safe. The webhook is “notify others,” not “create the charge.”
---
Steps 8–9 — Worker dedupe + client 201
Worker (`worker.py` / `process_event`):
Read event_id from the message.
put_webhook(event_id) — first write wins.
If SQS (or the local loop) delivers again → duplicate: true → ignore. No second “send receipt” side effect.
“Hash the body. Claim the key before the gateway. One intent per key. Write the order and cache the 201. Enqueue the webhook with an event id. Retries replay — they do not charge again.”
Story: The phone never got the 201, so it retries with the same key and the same body.
Step by step
Client POSTs again with the same Idempotency-Key and same amount.
claim_key finds the row already exists (created=false).
Hash matches. Status is `completed`.
Lambda returns the cached JSON. No second PaymentIntent. No second order.
Response: 201 + x-idempotent-replay: true.
Sequence diagram — replay
Interview line: “Same key + same body = replay. The side effect already happened.”
---
Flow 3 — Timeout path (the interview trap)
There are two crash drills. Both return 504 to the client and leave the key in `processing`. What the sweeper does next depends on whether the gateway already created an intent.
3A — Crash *after claim*, *before* gateway
Header: X-Lab-Crash-After-Claim: 1
What happened: You reserved the key, then died. No money moved. No PaymentIntent.
Step
What you see
First POST
504 — row stuck processing
Immediate retry same key
409 in flight
Sweeper runs
No intent found → mark `failed`
Later retry same key
Replay of the failed response (not a new charge)
3B — Crash *after* gateway (money may already have moved)
Header: X-Lab-Crash-After-Gateway: 1
What happened: Intent exists in the mock Stripe table. The client still only saw 504. This is the scary UNKNOWN case.
Step
What you see
First POST
504 — intent exists, row still processing
Immediate retry same key
409 in flight
Sweeper runs
Finds intent → heal → completed with same payment_intent_id
Later retry same key
201 + "healed": true — same IDs
Interview line: “Client got UNKNOWN. I retry the same Idempotency-Key. Reconciliation looks up the gateway. If the intent exists, I complete; if not, I fail. I never mint a new key.”
COMMON MISTAKE: A new UUID after the 504. That is a second claim_key and a second charge. At 1,200/s with 2% retries, that is ≈ 24 double-charge attempts per second.
---
Flow 4 — In flight (409 while another request holds the key)
Story: Two tabs, or a retry that arrives while the first request is still talking to Stripe.
Request A claimed processing and is still working.
Request B uses the same key.
B sees processing → 409 “request in flight — retry the same key.”
B must not start a second gateway call.
---
Flow 5 — Same key, different body (409)
Story: Reuse the key but change the amount (bug or attacker).
First request claimed with hash of $25.
Second request sends $50 with the same key.
Hash mismatch → 409 “same Idempotency-Key with a different body.”
Do not charge $50 under the $25 key.
---
Flow 6 — Store down (503 fail closed)
Story: DynamoDB (or Aurora in production) is unreachable.
You cannot record the attempt.
Return 503. Do not call the payment gateway.
Interview line: “If I cannot write the idempotency row, I fail closed. Charging without a record is how you double-bill.”
---
Flow 7 — Webhook worker (event_id dedupe)
Story: SQS can deliver the same message twice. That must not create two “succeeded” side effects downstream.
Happy path enqueues one message with event_id.
Worker calls put_webhook(event_id). First write wins.
Duplicate delivery → duplicate: true → ignore.
---
What to say on the whiteboard (60 seconds)
text
1. Client always sends Idempotency-Key for a logical checkout.
2. I claim processing in the key store BEFORE the gateway.
3. Same key + same body + completed → replay cached 201.
4. Same key + processing → 409 in flight.
5. Timeout → UNKNOWN → retry SAME key → sweeper/reconciler checks gateway intent.
6. Store down → 503. Never charge without a record.
7. PayRail numbers: 93/s avg, 1,200/s BFCM, 2% retries ≈ 24 dup attempts/s.
Path on this portal
Path
Where
Pass when
A Portal
This overview + architecture + charge.py
You can point at claim / replay / 409 / sweeper
B Local
Unzip → pytest → local_server.py → demo.sh
9 passed, then PASS + 409
C AWS
Lab 701 — Test on AWS
health ok, crash drill 201 healed, then destroy
Stay in Lab 701 — PayRail AWS in the left nav.
Read the flows above until you can redraw them from memory.
Open Lab 701 — Test and demo and follow A → B (C is optional).
Open Build PayRail and read charge.py in the source browser.
Download sd-payrail-lab.zip when you start Path B.
This is a working AWS lab. Deploy it, prove a timeout retry does not double-charge, then destroy it the same day.
Production at Stripe/merchant scale often uses Aurora + ECS. This lab uses DynamoDB + Lambda so a student account stays under ~$2 if you clean up today. The state machine is the same.
What you build
Path
What it is
lambda/charge.py
POST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.py
SQS consumer — dedupe event_id
lambda/sweeper.py
Heal rows left processing after a crash
lambda/webhook.py
POST /webhooks/stripe replay
terraform/
Supported deploy path
scripts/local_server.py
Same API on :8080 with no AWS
scripts/demo.sh
Same key twice → same order_id
tests/
8 pytest cases, no AWS
Prerequisites
Python 3.11+
For AWS: Terraform ≥ 1.5, an account that can create IAM, Lambda, API Gateway, DynamoDB, SQS, EventBridge, KMS
curl
Unique prefix such as yourinitials-payrail
1. Prove it locally (no AWS)
bash
cd labs/payrail-idempotency
python3 -m pytest tests/ -v
python3 scripts/local_server.py
In another terminal:
bash
./scripts/demo.sh
You should see PASS: same order_id and payment_intent_id on retry and HTTP 409 when the amount changes.
That leaves the key in processing (504). A retry with the same key returns 409 in flight. Wait ~1 minute for the sweeper, or invoke the sweeper function. Then the same key returns the healed 201.
Validation
Same Idempotency-Key → same order_id and payment_intent_id
DynamoDB orders does not grow on retry
Same key, different amount_cents → 409
Missing key → 400
Store down (local: store.down = True) → 503 fail closed
SQS DLQ depth is 0 after a happy-path charge
CloudWatch log groups /aws/lambda/{prefix}-charge show the request
Cleanup
bash
cd terraform
terraform destroy
Interview talking points
After a timeout you are in UNKNOWN — do not assume failure and do not mint a new key
Unique claim on (tenant, key); replay returns the cached body
Request hash rejects same key + different body
Fail closed if the idempotency store is down
Webhooks are at-least-once; dedupe event_id
Sweeper + reconciliation are the backstop, not hope
PayRail numbers in this sprint: 93/s average, 1,200/s Black Friday, p99 < 400 ms, 2% retries → 24 duplicate attempts/s without the key
Test and demo path
Test and demo path
Lab 701 — Test and demo path
Lab id:BUILD-SD-701
Time: 20 minutes locally, plus 15–25 minutes if you deploy to AWS
Cost: $0 locally. Under $2 on AWS if you terraform destroy the same day.
Today we prove that a second POST with the same retry key returns the same order id. Then we say that out loud.
The idea: Path A is the whiteboard story. Path B is the terminal demo. Path C is optional AWS — and you destroy the same day.
Why we learn this
Interviewers believe what you can show. A local demo.sh that prints PASS and 409 is stronger than saying “idempotent” with no proof.
Where to click on the sprint portal
You are already in Learn → Lab 701 — PayRail AWS. Stay in this section.
Step
Portal lesson
What you do
0
Lab 701 — PayRail overview
Why the lab exists. Download sd-payrail-lab.zip.
1
This lesson
Follow Path A → B → C below. Do not skip Path B.
2
Lab 701 — PayRail architecture
Memorize claim / replay / 409 / 503.
3
Lab 701 — Build PayRail
Open charge.py in the source browser. Same files as the zip.
When a step is honest, mark Lab tracking · BUILD-SD-701 as in progress, then complete.
---
Path A — Understand it on the portal (no laptop)
Do this first. You can demo the *idea* even if AWS is down.
On PayRail overview, read the one-sentence promise and the diagram.
On PayRail architecture, say the state machine out loud:
text
missing key → 400
store down → 503 fail closed
completed → cached 201 (replay) ← this is the demo
processing → 409 in flight
same key + new body → 409
On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
Open How the code maps to the interview (extra on this section). Point at the four rows.
COMMON MISTAKE: Minting a new Idempotency-Key after the 504. That is a second charge. Say: “I am in UNKNOWN. I retry the same key.”
---
Path C — AWS deploy (optional, same day)
Open the next lesson: Lab 701 — Test on AWS. That is the full apply → health → demo.sh → crash drill → destroy script.
Short version:
bash
cd terraform
cp terraform.tfvars.example terraform.tfvars # set your name_prefix
terraform init
terraform apply
cd ..
./scripts/aws_test.sh
cd terraform && terraform destroy
“PayRail is 8 million charges a day, about 93 per second, 1,200 per second on Black Friday. Two percent retries without a key is 24 duplicate attempts per second. I claim (tenant, Idempotency-Key) before I call the gateway. Same key and body replay the cached order_id. Same key and a different body is 409. If the store is down I fail closed — 503 — I do not charge. After a timeout I am in UNKNOWN: I retry the same key; a sweeper is the backstop. I will not mint a new UUID.”
---
Mark the lab complete when
[ ] Path A: you can point at claim / replay / 409 in charge.py on the portal
[ ] Path B: pytest is 9 passed and demo.sh prints PASS and 409
[ ] You can explain the crash drill without creating a second key
[ ] If you ran Path C: terraform destroy finished
How the code maps to the interview
How the code maps to the interview
How PayRail code maps to the interview
Read this on the portal. You do not have to unzip first to understand the design.
In one sentence: The same Idempotency-Key must return the same order_id. A new UUID after a timeout is a second charge.
PayRail assumptions used in the sprint: 8M charges/day ≈ 93/s, Black Friday 1,200/s, 2% retries ≈ 24 duplicate attempts/s without a key.
The four answers you must be able to point at
Interview sentence
Function / file
What happens
“I claim the key before I call the gateway.”
claim_key in lab_store.py / dynamo_store.py
First writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”
charge() in charge.py
If completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”
charge() after the hash check
request_hash is SHA-256 of {amount_cents, currency}.
claim_key creates a processing row (or returns the existing one).
Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
An order_id is minted once, stored, and cached on the key row.
A webhook event is enqueued. The worker dedupes on event_id.
Timeout path (the interview trap)
X-Lab-Crash-After-Claim: 1 returns 504 and leaves the row `processing`.
A retry with the same key sees processing → 409 in flight (client should wait / retry the same key).
The sweeper (sweeper.py) looks for a gateway intent:
- Intent exists → complete the key (the money already moved).
- No intent → mark failed. Do not invent a second charge.
COMMON MISTAKE: Minting a new Idempotency-Key because the first call timed out. That is a second claim_key and a second order.
Why DynamoDB in the student lab
Production mapping you say out loud: ALB + ECS + Aurora. The lab uses HTTP API + Lambda + DynamoDB so a same-day destroy stays under $2. The *state machine* is what you are learning, not the SKU names.
Files to open in the source browser on Build PayRail
charge.py — claim / replay / 409 / 503
lab_store.py — in-memory version of the same API (pytest + local server)
dynamo_store.py — the AWS version (attribute_not_exists claim)
sweeper.py — heal stuck processing
worker.py — event_id dedupe
terraform/main.tf — what apply builds
Lab 701 — Test and demo20 min
Lab 701 — Test and demo
Lab 701 — Test and demo path
Lab id:BUILD-SD-701
Time: 20 minutes locally, plus 15–25 minutes if you deploy to AWS
Cost: $0 locally. Under $2 on AWS if you terraform destroy the same day.
Today we prove that a second POST with the same retry key returns the same order id. Then we say that out loud.
The idea: Path A is the whiteboard story. Path B is the terminal demo. Path C is optional AWS — and you destroy the same day.
Why we learn this
Interviewers believe what you can show. A local demo.sh that prints PASS and 409 is stronger than saying “idempotent” with no proof.
Where to click on the sprint portal
You are already in Learn → Lab 701 — PayRail AWS. Stay in this section.
Step
Portal lesson
What you do
0
Lab 701 — PayRail overview
Why the lab exists. Download sd-payrail-lab.zip.
1
This lesson
Follow Path A → B → C below. Do not skip Path B.
2
Lab 701 — PayRail architecture
Memorize claim / replay / 409 / 503.
3
Lab 701 — Build PayRail
Open charge.py in the source browser. Same files as the zip.
When a step is honest, mark Lab tracking · BUILD-SD-701 as in progress, then complete.
---
Path A — Understand it on the portal (no laptop)
Do this first. You can demo the *idea* even if AWS is down.
On PayRail overview, read the one-sentence promise and the diagram.
On PayRail architecture, say the state machine out loud:
text
missing key → 400
store down → 503 fail closed
completed → cached 201 (replay) ← this is the demo
processing → 409 in flight
same key + new body → 409
On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
Open How the code maps to the interview (extra on this section). Point at the four rows.
COMMON MISTAKE: Minting a new Idempotency-Key after the 504. That is a second charge. Say: “I am in UNKNOWN. I retry the same key.”
---
Path C — AWS deploy (optional, same day)
Open the next lesson: Lab 701 — Test on AWS. That is the full apply → health → demo.sh → crash drill → destroy script.
Short version:
bash
cd terraform
cp terraform.tfvars.example terraform.tfvars # set your name_prefix
terraform init
terraform apply
cd ..
./scripts/aws_test.sh
cd terraform && terraform destroy
“PayRail is 8 million charges a day, about 93 per second, 1,200 per second on Black Friday. Two percent retries without a key is 24 duplicate attempts per second. I claim (tenant, Idempotency-Key) before I call the gateway. Same key and body replay the cached order_id. Same key and a different body is 409. If the store is down I fail closed — 503 — I do not charge. After a timeout I am in UNKNOWN: I retry the same key; a sweeper is the backstop. I will not mint a new UUID.”
---
Mark the lab complete when
[ ] Path A: you can point at claim / replay / 409 in charge.py on the portal
[ ] Path B: pytest is 9 passed and demo.sh prints PASS and 409
[ ] You can explain the crash drill without creating a second key
[ ] If you ran Path C: terraform destroy finished
Test the stack on AWS
Test the stack on AWS
Lab 701 — Test the stack on AWS
Lab id:BUILD-SD-701 · Path C
Time: 15–25 minutes after unzip
Cost: under $2 if you terraform destroy the same day.
Today we deploy the lab in your own AWS account, prove a retry does not create a second order, then delete the stack.
The idea: Real charge_url in your account. Same state machine as Path B. Alwaysterraform destroy before you leave.
Why we learn this
This is not the BayLearn Portal account. You deploy into the student account you use for labs.
Production you say in the interview: ALB + ECS + Aurora + Stripe. This lab is HTTP API + Lambda + DynamoDB + a Stripe mock so teardown stays cheap. The state machine is the same.
---
Before you start
On your laptop:
Python 3.11+ (Path B already done)
Terraform ≥ 1.5 (terraform version)
AWS CLI v2 (aws --version)
An IAM user or role that can create IAM roles, Lambda, HTTP API, DynamoDB, SQS, EventBridge, KMS, and CloudWatch Logs
A unique prefix such as js-payrail (lowercase, numbers, hyphens, 2–21 characters)
bash
aws sts get-caller-identity
# note Account. You will destroy everything tagged with your prefix today.
The gateway did create an intent; the charge handler then returns 504 on purpose. Retry the same key. Invoke the sweeper (or wait ~1 minute for EventBridge).
claim_key creates a processing row (or returns the existing one).
Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
An order_id is minted once, stored, and cached on the key row.
A webhook event is enqueued. The worker dedupes on event_id.
Timeout path (the interview trap)
X-Lab-Crash-After-Claim: 1 returns 504 and leaves the row `processing`.
A retry with the same key sees processing → 409 in flight (client should wait / retry the same key).
The sweeper (sweeper.py) looks for a gateway intent:
- Intent exists → complete the key (the money already moved).
- No intent → mark failed. Do not invent a second charge.
COMMON MISTAKE: Minting a new Idempotency-Key because the first call timed out. That is a second claim_key and a second order.
Why DynamoDB in the student lab
Production mapping you say out loud: ALB + ECS + Aurora. The lab uses HTTP API + Lambda + DynamoDB so a same-day destroy stays under $2. The *state machine* is what you are learning, not the SKU names.
Files to open in the source browser on Build PayRail
charge.py — claim / replay / 409 / 503
lab_store.py — in-memory version of the same API (pytest + local server)
dynamo_store.py — the AWS version (attribute_not_exists claim)
sweeper.py — heal stuck processing
worker.py — event_id dedupe
terraform/main.tf — what apply builds
Failure drill
Failure drill
Failure drill — crash after claim
This is the interview timeout.
Claim the idempotency row (processing).
Die before the gateway response is stored.
Client is in UNKNOWN.
Retry the sameIdempotency-Key.
Sweeper or in-flight 409 until healed.
bash
# After terraform apply
URL="$(terraform output -raw charge_url)"
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-H "X-Lab-Crash-After-Claim: 1" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 504
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 409 in flight
# wait up to 1 minute for EventBridge sweeper, then:
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 201 healed or still 409 if the mock intent was never created
Locally, POST /lab/sweep runs the sweeper immediately.
Do not mint a new key because the first call “failed.” That is how you double-charge.
Troubleshooting
Troubleshooting
Troubleshooting
Symptom
Likely cause
Fix
terraform apply fails on archive_file
Lambda folder missing next to terraform/
Keep lambda/ and terraform/ as siblings from the zip
400 missing key
Forgot Idempotency-Key
Header is required on every mutating call
409 different body
Reused a key for a new amount
New logical checkout → new UUID
409 in flight
Crash drill or slow gateway
Wait for sweeper (~1 min on AWS) or retry later with the same key
503
Store down
Fail closed. Do not charge.
Demo hits localhost and fails
local_server.py not running and no Terraform state
Start the local server orterraform apply first
Worker never writes webhook rows
SQS KMS key does not allow Lambda
Use the lab Terraform; do not swap in a generic CMK without grants
orders count > 1 after retry
You changed the key
The key is the operation. A new key is a new charge.
Cost: under $2 if you terraform destroy the same day.
Today we deploy the lab in your own AWS account, prove a retry does not create a second order, then delete the stack.
The idea: Real charge_url in your account. Same state machine as Path B. Alwaysterraform destroy before you leave.
Why we learn this
This is not the BayLearn Portal account. You deploy into the student account you use for labs.
Production you say in the interview: ALB + ECS + Aurora + Stripe. This lab is HTTP API + Lambda + DynamoDB + a Stripe mock so teardown stays cheap. The state machine is the same.
---
Before you start
On your laptop:
Python 3.11+ (Path B already done)
Terraform ≥ 1.5 (terraform version)
AWS CLI v2 (aws --version)
An IAM user or role that can create IAM roles, Lambda, HTTP API, DynamoDB, SQS, EventBridge, KMS, and CloudWatch Logs
A unique prefix such as js-payrail (lowercase, numbers, hyphens, 2–21 characters)
bash
aws sts get-caller-identity
# note Account. You will destroy everything tagged with your prefix today.
The gateway did create an intent; the charge handler then returns 504 on purpose. Retry the same key. Invoke the sweeper (or wait ~1 minute for EventBridge).
[ ] terraform destroy finished and the prefix is gone from Lambda/DynamoDB
Failure drill
Failure drill
Failure drill — crash after claim
This is the interview timeout.
Claim the idempotency row (processing).
Die before the gateway response is stored.
Client is in UNKNOWN.
Retry the sameIdempotency-Key.
Sweeper or in-flight 409 until healed.
bash
# After terraform apply
URL="$(terraform output -raw charge_url)"
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-H "X-Lab-Crash-After-Claim: 1" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 504
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 409 in flight
# wait up to 1 minute for EventBridge sweeper, then:
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 201 healed or still 409 if the mock intent was never created
Locally, POST /lab/sweep runs the sweeper immediately.
Do not mint a new key because the first call “failed.” That is how you double-charge.
Cleanup
Cleanup
Cleanup
bash
cd terraform
terraform destroy
If a table delete hangs, wait — DynamoDB deletes are usually seconds. Do not leave the EventBridge rule (rate(1 minute)) running overnight; that is the main idle cost besides a few Lambda-minutes.
Today we walk the same charge rules as Stripe, on smaller AWS pieces so you can deploy and tear down in an afternoon.
The idea: Claim the key, charge once, replay a completed key, return 409 when another request is in flight. The sweeper is the backstop after a crash.
Why we learn this
In the interview you draw ALB + ECS + Aurora. In this lab you run HTTP API + Lambda + DynamoDB. The state machine is what you memorize — not the brand names.
PayRail AWS lab
Start on your laptop first. One Python process holds every role:
PayRail local lab deployment
Local → AWS map
PayRail AWS demo — every service
See the full architecture notes in the lab pack. The source browser on this lesson opens charge.py, lab_store.py, dynamo_store.py, worker.py, and sweeper.py — same files as the zip. Teacher walkthrough of local boxes, AWS services, and happy-path internals: Lab 701 overview.
State machine (memorize)
text
missing key → 400
store down → 503 fail closed
completed → cached 201 (replay)
processing → 409 in flight
new + hash clash → 409 different body
else → claim → gateway → ledger → completed
After a timeout the client is in UNKNOWN. Retry the same Idempotency-Key. Reconciliation (sweeper) is the backstop.
SQS + EventBridge every minute so the drill is visible
The state machine is what you defend in the interview. The AWS services are sized for a $2 afternoon.
PayRail AWS lab
Charge path
Client sends Idempotency-Key (UUID per logical checkout, reused on retry).
Charge Lambda hashes the body.
Conditional PutItem claims processing. Loser reads the winner.
If completed — return cached JSON. No second intent.
If processing — 409 in flight.
Call the mock gateway (same key → same payment_intent_id).
Write orders row. Mark key completed with the response.
Enqueue payment_intent.succeeded to SQS.
Timeout zone
If the process dies after step 3 and before 7, the client sees 504 / UNKNOWN. Retry the same key. Do not generate a new UUID. The sweeper looks up the mock intent and completes or fails the row.
Why DynamoDB is an honest lab choice
PayRail peak 1,200/s is well inside DynamoDB. Aurora is the right production default when you want SQL reporting on the ledger. Say that out loud. Do not pretend this lab is your 5k QPS multi-region payment platform.
Security
KMS on DynamoDB and SQS
Least-privilege IAM on named tables and the queue
No public buckets, no sk_live_ in source
24h TTL on idempotency keys (Stripe default window)
How the code maps to the interview
How the code maps to the interview
How PayRail code maps to the interview
Read this on the portal. You do not have to unzip first to understand the design.
In one sentence: The same Idempotency-Key must return the same order_id. A new UUID after a timeout is a second charge.
PayRail assumptions used in the sprint: 8M charges/day ≈ 93/s, Black Friday 1,200/s, 2% retries ≈ 24 duplicate attempts/s without a key.
The four answers you must be able to point at
Interview sentence
Function / file
What happens
“I claim the key before I call the gateway.”
claim_key in lab_store.py / dynamo_store.py
First writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”
charge() in charge.py
If completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”
charge() after the hash check
request_hash is SHA-256 of {amount_cents, currency}.
claim_key creates a processing row (or returns the existing one).
Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
An order_id is minted once, stored, and cached on the key row.
A webhook event is enqueued. The worker dedupes on event_id.
Timeout path (the interview trap)
X-Lab-Crash-After-Claim: 1 returns 504 and leaves the row `processing`.
A retry with the same key sees processing → 409 in flight (client should wait / retry the same key).
The sweeper (sweeper.py) looks for a gateway intent:
- Intent exists → complete the key (the money already moved).
- No intent → mark failed. Do not invent a second charge.
COMMON MISTAKE: Minting a new Idempotency-Key because the first call timed out. That is a second claim_key and a second order.
Why DynamoDB in the student lab
Production mapping you say out loud: ALB + ECS + Aurora. The lab uses HTTP API + Lambda + DynamoDB so a same-day destroy stays under $2. The *state machine* is what you are learning, not the SKU names.
Files to open in the source browser on Build PayRail
charge.py — claim / replay / 409 / 503
lab_store.py — in-memory version of the same API (pytest + local server)
dynamo_store.py — the AWS version (attribute_not_exists claim)
sweeper.py — heal stuck processing
worker.py — event_id dedupe
terraform/main.tf — what apply builds
Read the lab source
Same files as the zip. Open one at a time — map the function to the interview sentence.
charge.py
python
"""POST /v1/charges — Stripe-style idempotency for PayRail."""
from __future__ import annotations
import json
import os
import uuid
from typing import Any, Callable
from lab_store import MemoryStore, StoreDown, request_hash
_STORE = None
def get_store():
global _STORE
if _STORE is not None:
return _STORE
if os.environ.get("KEYS_TABLE"):
from dynamo_store import DynamoStore
_STORE = DynamoStore()
else:
_STORE = MemoryStore()
return _STORE
def _headers(event: dict) -> dict[str, str]:
raw = event.get("headers") or {}
return {str(k).lower(): str(v) for k, v in raw.items()}
def _body(event: dict) -> dict[str, Any]:
raw = event.get("body") or "{}"
if event.get("isBase64Encoded"):
import base64
raw = base64.b64decode(raw).decode("utf-8")
if not isinstance(raw, dict):
payload = json.loads(raw or "{}")
else:
payload = raw
return payload
def _jsonable(obj):
if isinstance(obj, dict):
return {k: _jsonable(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_jsonable(v) for v in obj]
try:
from decimal import Decimal
if isinstance(obj, Decimal):
return int(obj) if obj % 1 == 0 else float(obj)
except Exception:
pass
return obj
def _resp(code: int, payload: dict, extra_headers: dict | None = None) -> dict:
headers = {"content-type": "application/json"}
if extra_headers:
headers.update(extra_headers)
return {"statusCode": code, "headers": headers, "body": json.dumps(_jsonable(payload))}
def charge(
headers: dict[str, str],
body: dict[str, Any],
store,
stripe: Callable[..., dict],
crash_after_claim: bool = False,
) -> dict:
key = (headers.get("idempotency-key") or "").strip()
tenant = (headers.get("x-tenant-id") or "demo").strip() or "demo"
if not key:
return _resp(400, {"error": "Idempotency-Key header is required"})
amount = body.get("amount_cents")
currency = str(body.get("currency") or "").lower()
if not isinstance(amount, int) or amount <= 0:
return _resp(400, {"error": "amount_cents must be a positive integer"})
if currency != "usd":
return _resp(400, {"error": "currency must be usd in this lab"})
payload = {"amount_cents": amount, "currency": currency}
req_hash = request_hash(payload)
try:
claim = store.claim_key(tenant, key, req_hash)
except StoreDown:
return _resp(503, {"error": "idempotency store unavailable — fail closed"})
row = claim["row"] or {}
if not claim["created"]:
if row.get("requestHash") and row["requestHash"] != req_hash:
return _resp(409, {"error": "same Idempotency-Key with a different body"})
if row.get("status") == "completed":
cached = row.get("responseBody") or {}
return _resp(int(row.get("responseStatus") or 201), cached, {"x-idempotent-replay": "true"})
if row.get("status") == "processing":
return _resp(409, {"error": "request in flight — retry the same key"})
if row.get("status") == "failed":
cached = row.get("responseBody") or {"error": "previous attempt failed"}
return _resp(int(row.get("responseStatus") or 402), cached, {"x-idempotent-replay": "true"})
if crash_after_claim:
return _resp(504, {"error": "lab crash after claim — row left processing", "hint": "run the sweeper"})
try:
intent = stripe(tenant, key, amount, currency)
except Exception as exc: # noqa: BLE001
err = {"error": "gateway timeout or error", "detail": str(exc)}
store.fail_key(tenant, key, 504, err)
return _resp(504, err)
order_id = "ord_" + uuid.uuid4().hex[:12]
store.put_order(
{
"orderId": order_id,
"tenantId": tenant,
"amountCents": amount,
"currency": currency.upper(),
"paymentIntentId": intent["paymentIntentId"],
"status": "succeeded",
}
)
body_out = {
"order_id": order_id,
"payment_intent_id": intent["paymentIntentId"],
"status": "succeeded",
"amount_cents": amount,
"currency": "USD",
}
store.complete_key(tenant, key, 201, body_out, order_id, intent["paymentIntentId"])
store.enqueue(
{
"event_id": "evt_" + uuid.uuid4().hex[:16],
"type": "payment_intent.succeeded",
"payment_intent_id": intent["paymentIntentId"],
"order_id": order_id,
"tenant_id": tenant,
}
)
return _resp(201, body_out, {"x-idempotent-replay": "false"})
def handler(event, _context):
store = get_store()
route = (event.get("requestContext") or {}).get("http", {}).get("path") or event.get("rawPath") or ""
method = (event.get("requestContext") or {}).get("http", {}).get("method") or event.get("httpMethod") or "POST"
headers = _headers(event)
if method == "GET" and route.endswith("/health"):
return _resp(200, {"ok": True, "service": "payrail-charges"})
if method == "GET" and "/v1/orders/" in route:
order_id = route.rstrip("/").split("/")[-1]
row = store.get_order(order_id)
if not row:
return _resp(404, {"error": "order not found"})
return _resp(200, _jsonable(row))
if method != "POST":
return _resp(405, {"error": "method not allowed"})
body = _body(event)
crash = headers.get("x-lab-crash-after-claim") == "1"
def stripe(tenant, key, amount, currency):
return store.create_intent(tenant, key, amount, currency)
return charge(headers, body, store, stripe, crash_after_claim=crash)
This is a working AWS lab. Deploy it, prove a timeout retry does not double-charge, then destroy it the same day.
Production at Stripe/merchant scale often uses Aurora + ECS. This lab uses DynamoDB + Lambda so a student account stays under ~$2 if you clean up today. The state machine is the same.
What you build
Path
What it is
lambda/charge.py
POST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.py
SQS consumer — dedupe event_id
lambda/sweeper.py
Heal rows left processing after a crash
lambda/webhook.py
POST /webhooks/stripe replay
terraform/
Supported deploy path
scripts/local_server.py
Same API on :8080 with no AWS
scripts/demo.sh
Same key twice → same order_id
tests/
8 pytest cases, no AWS
Prerequisites
Python 3.11+
For AWS: Terraform ≥ 1.5, an account that can create IAM, Lambda, API Gateway, DynamoDB, SQS, EventBridge, KMS
curl
Unique prefix such as yourinitials-payrail
1. Prove it locally (no AWS)
bash
cd labs/payrail-idempotency
python3 -m pytest tests/ -v
python3 scripts/local_server.py
In another terminal:
bash
./scripts/demo.sh
You should see PASS: same order_id and payment_intent_id on retry and HTTP 409 when the amount changes.
That leaves the key in processing (504). A retry with the same key returns 409 in flight. Wait ~1 minute for the sweeper, or invoke the sweeper function. Then the same key returns the healed 201.
Validation
Same Idempotency-Key → same order_id and payment_intent_id
DynamoDB orders does not grow on retry
Same key, different amount_cents → 409
Missing key → 400
Store down (local: store.down = True) → 503 fail closed
SQS DLQ depth is 0 after a happy-path charge
CloudWatch log groups /aws/lambda/{prefix}-charge show the request
Cleanup
bash
cd terraform
terraform destroy
Interview talking points
After a timeout you are in UNKNOWN — do not assume failure and do not mint a new key
Unique claim on (tenant, key); replay returns the cached body
Request hash rejects same key + different body
Fail closed if the idempotency store is down
Webhooks are at-least-once; dedupe event_id
Sweeper + reconciliation are the backstop, not hope
PayRail numbers in this sprint: 93/s average, 1,200/s Black Friday, p99 < 400 ms, 2% retries → 24 duplicate attempts/s without the key
Test and demo path
Test and demo path
Lab 701 — Test and demo path
Lab id:BUILD-SD-701
Time: 20 minutes locally, plus 15–25 minutes if you deploy to AWS
Cost: $0 locally. Under $2 on AWS if you terraform destroy the same day.
Today we prove that a second POST with the same retry key returns the same order id. Then we say that out loud.
The idea: Path A is the whiteboard story. Path B is the terminal demo. Path C is optional AWS — and you destroy the same day.
Why we learn this
Interviewers believe what you can show. A local demo.sh that prints PASS and 409 is stronger than saying “idempotent” with no proof.
Where to click on the sprint portal
You are already in Learn → Lab 701 — PayRail AWS. Stay in this section.
Step
Portal lesson
What you do
0
Lab 701 — PayRail overview
Why the lab exists. Download sd-payrail-lab.zip.
1
This lesson
Follow Path A → B → C below. Do not skip Path B.
2
Lab 701 — PayRail architecture
Memorize claim / replay / 409 / 503.
3
Lab 701 — Build PayRail
Open charge.py in the source browser. Same files as the zip.
When a step is honest, mark Lab tracking · BUILD-SD-701 as in progress, then complete.
---
Path A — Understand it on the portal (no laptop)
Do this first. You can demo the *idea* even if AWS is down.
On PayRail overview, read the one-sentence promise and the diagram.
On PayRail architecture, say the state machine out loud:
text
missing key → 400
store down → 503 fail closed
completed → cached 201 (replay) ← this is the demo
processing → 409 in flight
same key + new body → 409
On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
Open How the code maps to the interview (extra on this section). Point at the four rows.
COMMON MISTAKE: Minting a new Idempotency-Key after the 504. That is a second charge. Say: “I am in UNKNOWN. I retry the same key.”
---
Path C — AWS deploy (optional, same day)
Open the next lesson: Lab 701 — Test on AWS. That is the full apply → health → demo.sh → crash drill → destroy script.
Short version:
bash
cd terraform
cp terraform.tfvars.example terraform.tfvars # set your name_prefix
terraform init
terraform apply
cd ..
./scripts/aws_test.sh
cd terraform && terraform destroy
“PayRail is 8 million charges a day, about 93 per second, 1,200 per second on Black Friday. Two percent retries without a key is 24 duplicate attempts per second. I claim (tenant, Idempotency-Key) before I call the gateway. Same key and body replay the cached order_id. Same key and a different body is 409. If the store is down I fail closed — 503 — I do not charge. After a timeout I am in UNKNOWN: I retry the same key; a sweeper is the backstop. I will not mint a new UUID.”
---
Mark the lab complete when
[ ] Path A: you can point at claim / replay / 409 in charge.py on the portal
[ ] Path B: pytest is 9 passed and demo.sh prints PASS and 409
[ ] You can explain the crash drill without creating a second key
[ ] If you ran Path C: terraform destroy finished
Test the stack on AWS
Test the stack on AWS
Lab 701 — Test the stack on AWS
Lab id:BUILD-SD-701 · Path C
Time: 15–25 minutes after unzip
Cost: under $2 if you terraform destroy the same day.
Today we deploy the lab in your own AWS account, prove a retry does not create a second order, then delete the stack.
The idea: Real charge_url in your account. Same state machine as Path B. Alwaysterraform destroy before you leave.
Why we learn this
This is not the BayLearn Portal account. You deploy into the student account you use for labs.
Production you say in the interview: ALB + ECS + Aurora + Stripe. This lab is HTTP API + Lambda + DynamoDB + a Stripe mock so teardown stays cheap. The state machine is the same.
---
Before you start
On your laptop:
Python 3.11+ (Path B already done)
Terraform ≥ 1.5 (terraform version)
AWS CLI v2 (aws --version)
An IAM user or role that can create IAM roles, Lambda, HTTP API, DynamoDB, SQS, EventBridge, KMS, and CloudWatch Logs
A unique prefix such as js-payrail (lowercase, numbers, hyphens, 2–21 characters)
bash
aws sts get-caller-identity
# note Account. You will destroy everything tagged with your prefix today.
The gateway did create an intent; the charge handler then returns 504 on purpose. Retry the same key. Invoke the sweeper (or wait ~1 minute for EventBridge).
claim_key creates a processing row (or returns the existing one).
Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
An order_id is minted once, stored, and cached on the key row.
A webhook event is enqueued. The worker dedupes on event_id.
Timeout path (the interview trap)
X-Lab-Crash-After-Claim: 1 returns 504 and leaves the row `processing`.
A retry with the same key sees processing → 409 in flight (client should wait / retry the same key).
The sweeper (sweeper.py) looks for a gateway intent:
- Intent exists → complete the key (the money already moved).
- No intent → mark failed. Do not invent a second charge.
COMMON MISTAKE: Minting a new Idempotency-Key because the first call timed out. That is a second claim_key and a second order.
Why DynamoDB in the student lab
Production mapping you say out loud: ALB + ECS + Aurora. The lab uses HTTP API + Lambda + DynamoDB so a same-day destroy stays under $2. The *state machine* is what you are learning, not the SKU names.
Files to open in the source browser on Build PayRail
charge.py — claim / replay / 409 / 503
lab_store.py — in-memory version of the same API (pytest + local server)
dynamo_store.py — the AWS version (attribute_not_exists claim)
sweeper.py — heal stuck processing
worker.py — event_id dedupe
terraform/main.tf — what apply builds
Failure drill
Failure drill
Failure drill — crash after claim
This is the interview timeout.
Claim the idempotency row (processing).
Die before the gateway response is stored.
Client is in UNKNOWN.
Retry the sameIdempotency-Key.
Sweeper or in-flight 409 until healed.
bash
# After terraform apply
URL="$(terraform output -raw charge_url)"
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-H "X-Lab-Crash-After-Claim: 1" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 504
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 409 in flight
# wait up to 1 minute for EventBridge sweeper, then:
curl -sS -X POST "$URL" \
-H "content-type: application/json" \
-H "Idempotency-Key: crash-drill" \
-d '{"amount_cents":2500,"currency":"usd"}'
# expect 201 healed or still 409 if the mock intent was never created
Locally, POST /lab/sweep runs the sweeper immediately.
Do not mint a new key because the first call “failed.” That is how you double-charge.
Troubleshooting
Troubleshooting
Troubleshooting
Symptom
Likely cause
Fix
terraform apply fails on archive_file
Lambda folder missing next to terraform/
Keep lambda/ and terraform/ as siblings from the zip
400 missing key
Forgot Idempotency-Key
Header is required on every mutating call
409 different body
Reused a key for a new amount
New logical checkout → new UUID
409 in flight
Crash drill or slow gateway
Wait for sweeper (~1 min on AWS) or retry later with the same key
503
Store down
Fail closed. Do not charge.
Demo hits localhost and fails
local_server.py not running and no Terraform state
Start the local server orterraform apply first
Worker never writes webhook rows
SQS KMS key does not allow Lambda
Use the lab Terraform; do not swap in a generic CMK without grants
orders count > 1 after retry
You changed the key
The key is the operation. A new key is a new charge.
If a table delete hangs, wait — DynamoDB deletes are usually seconds. Do not leave the EventBridge rule (rate(1 minute)) running overnight; that is the main idle cost besides a few Lambda-minutes.
Same files as the zip. Open one at a time — map the function to the interview sentence.
charge.py
python
"""POST /v1/charges — Stripe-style idempotency for PayRail."""
from __future__ import annotations
import json
import os
import uuid
from typing import Any, Callable
from lab_store import MemoryStore, StoreDown, request_hash
_STORE = None
def get_store():
global _STORE
if _STORE is not None:
return _STORE
if os.environ.get("KEYS_TABLE"):
from dynamo_store import DynamoStore
_STORE = DynamoStore()
else:
_STORE = MemoryStore()
return _STORE
def _headers(event: dict) -> dict[str, str]:
raw = event.get("headers") or {}
return {str(k).lower(): str(v) for k, v in raw.items()}
def _body(event: dict) -> dict[str, Any]:
raw = event.get("body") or "{}"
if event.get("isBase64Encoded"):
import base64
raw = base64.b64decode(raw).decode("utf-8")
if not isinstance(raw, dict):
payload = json.loads(raw or "{}")
else:
payload = raw
return payload
def _jsonable(obj):
if isinstance(obj, dict):
return {k: _jsonable(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_jsonable(v) for v in obj]
try:
from decimal import Decimal
if isinstance(obj, Decimal):
return int(obj) if obj % 1 == 0 else float(obj)
except Exception:
pass
return obj
def _resp(code: int, payload: dict, extra_headers: dict | None = None) -> dict:
headers = {"content-type": "application/json"}
if extra_headers:
headers.update(extra_headers)
return {"statusCode": code, "headers": headers, "body": json.dumps(_jsonable(payload))}
def charge(
headers: dict[str, str],
body: dict[str, Any],
store,
stripe: Callable[..., dict],
crash_after_claim: bool = False,
) -> dict:
key = (headers.get("idempotency-key") or "").strip()
tenant = (headers.get("x-tenant-id") or "demo").strip() or "demo"
if not key:
return _resp(400, {"error": "Idempotency-Key header is required"})
amount = body.get("amount_cents")
currency = str(body.get("currency") or "").lower()
if not isinstance(amount, int) or amount <= 0:
return _resp(400, {"error": "amount_cents must be a positive integer"})
if currency != "usd":
return _resp(400, {"error": "currency must be usd in this lab"})
payload = {"amount_cents": amount, "currency": currency}
req_hash = request_hash(payload)
try:
claim = store.claim_key(tenant, key, req_hash)
except StoreDown:
return _resp(503, {"error": "idempotency store unavailable — fail closed"})
row = claim["row"] or {}
if not claim["created"]:
if row.get("requestHash") and row["requestHash"] != req_hash:
return _resp(409, {"error": "same Idempotency-Key with a different body"})
if row.get("status") == "completed":
cached = row.get("responseBody") or {}
return _resp(int(row.get("responseStatus") or 201), cached, {"x-idempotent-replay": "true"})
if row.get("status") == "processing":
return _resp(409, {"error": "request in flight — retry the same key"})
if row.get("status") == "failed":
cached = row.get("responseBody") or {"error": "previous attempt failed"}
return _resp(int(row.get("responseStatus") or 402), cached, {"x-idempotent-replay": "true"})
if crash_after_claim:
return _resp(504, {"error": "lab crash after claim — row left processing", "hint": "run the sweeper"})
try:
intent = stripe(tenant, key, amount, currency)
except Exception as exc: # noqa: BLE001
err = {"error": "gateway timeout or error", "detail": str(exc)}
store.fail_key(tenant, key, 504, err)
return _resp(504, err)
order_id = "ord_" + uuid.uuid4().hex[:12]
store.put_order(
{
"orderId": order_id,
"tenantId": tenant,
"amountCents": amount,
"currency": currency.upper(),
"paymentIntentId": intent["paymentIntentId"],
"status": "succeeded",
}
)
body_out = {
"order_id": order_id,
"payment_intent_id": intent["paymentIntentId"],
"status": "succeeded",
"amount_cents": amount,
"currency": "USD",
}
store.complete_key(tenant, key, 201, body_out, order_id, intent["paymentIntentId"])
store.enqueue(
{
"event_id": "evt_" + uuid.uuid4().hex[:16],
"type": "payment_intent.succeeded",
"payment_intent_id": intent["paymentIntentId"],
"order_id": order_id,
"tenant_id": tenant,
}
)
return _resp(201, body_out, {"x-idempotent-replay": "false"})
def handler(event, _context):
store = get_store()
route = (event.get("requestContext") or {}).get("http", {}).get("path") or event.get("rawPath") or ""
method = (event.get("requestContext") or {}).get("http", {}).get("method") or event.get("httpMethod") or "POST"
headers = _headers(event)
if method == "GET" and route.endswith("/health"):
return _resp(200, {"ok": True, "service": "payrail-charges"})
if method == "GET" and "/v1/orders/" in route:
order_id = route.rstrip("/").split("/")[-1]
row = store.get_order(order_id)
if not row:
return _resp(404, {"error": "order not found"})
return _resp(200, _jsonable(row))
if method != "POST":
return _resp(405, {"error": "method not allowed"})
body = _body(event)
crash = headers.get("x-lab-crash-after-claim") == "1"
def stripe(tenant, key, amount, currency):
return store.create_intent(tenant, key, amount, currency)
return charge(headers, body, store, stripe, crash_after_claim=crash)
You will
Run Lab ARCHITECT-SD-401 on the 16-section canvas
Write assumptions when numbers are missing
URL shortener design25 min
URL shortener design
Guided challenge — URL shortener
Today we design Linkly with D-SCALE on the canvas before we look at a sample picture. Start from 400 million redirects a day, not from a pile of logos.
The idea: Walk the whole method on a small prompt that still has real trade-offs — reads vs writes, uniqueness, deletes, one viral code.
Why we learn this
This is the first time you apply the whole method. Interviewers love this prompt because it is small and still has real trade-offs: reads vs writes, uniqueness, deletes, one viral code.
Linkly thin path, then cache
Reference shape — hide this until you attempt
Do not treat that second picture as the start. Close it. Work the canvas. Then compare.
Walk D-SCALE here (use these assumptions unless they give others)
D. Anyone with the link redirects. Logged-in staff create. Done = 201 on create, 302 on read. Must not lose a paid campaign mapping. Custom slugs optional — say if in scope. Analytics out of the 45-minute core unless they insist.
S. Labeled assumptions (erase if they give telemetry):
Input
Math
Number
400M redirects/day
÷ 86,400
≈ 4,630 GET/s avg
Morning-news peak
× ~8.6
≈ 40,000 GET/s
2M creates/day
÷ 86,400
≈ 23 POST/s
Value size
200 B
mappings stay tiny
Viral code
one key
50,000 GET/s for 10 min
Cache 92% hit
40k × 0.08
3,200 miss/s on KV
Creates do not need a stream. Reads need a cache. One celebrity code is a hot key, not a shard problem.
C. Client → API → stateless app → key-value store. Four boxes. Minute 4 is done.
A.POST /v1/urls{ longUrl } → { code }. GET /{code} → 302 + Location. Key = code. Optional Idempotency-Key on create so a double-click does not mint two codes.
L. The GET path at 40k/s. Secondary: uniqueness on mint; a takedown that must win against a 60s cache.
E. Cache-aside, 60s TTL, invalidate that key on delete. What I give up: a disable may linger until TTL unless you bust the key. You will not 301 if legal takedown matters (browsers cache 301 forever).
Hit-ratio math
Design choices to decide out loud
Choice
Simple default
When to change
Number that decides
Who mints the code
Server random, retry on clash
Client vanity slugs
23 POST/s — clash retries are cheap
301 vs 302
302
301 only if target never changes
Takedown SLA
Deletes
Soft delete + cache bust
Legal = short TTL + purge that key
60s vs “now”
Analytics
Async queue later
They asked for click counts
40k/s must not write a row
Multi-region
One region first
They ask DR
RPO minutes on mappings is often OK
Hot key
Cache + maybe local copy
Viral 50k/s
Sharding does nothing
Common traps
Showing CDN + Kafka + Cassandra in minute two (23 POST/s does not buy a log)
Putting the long URL in a join-heavy schema with no code key
Forgetting GET is the product
Using 301 and then promising instant disable
Sharding because “50k/s on one code”
COMMON MISTAKE: Showing the final design first.
What to say when you submit
I assumed 400 million redirects/day, about 4,630/s average, 40,000/s peak, 23 creates/s, 200-byte values. Thin path is API, app, key-value. First bottleneck is read QPS, so I cache codes at 92% hit and take 3,200 miss/s on the store. I invalidate on delete; I gave up instant global drop if I only have TTL. I will not draw a stream for creates.
Then open the architecture canvas and fill all sixteen sections. Only then compare to the reference diagram.
SCALE CHECK: If they say 10 million/day instead, recompute: ≈ 116/s avg, ~1k/s peak. You may still cache, but you will not invent 20 app copies for sport.
Architecture review checklist
Architecture review checklist
Architecture Review Checklist
[ ] Requirements and assumptions written
[ ] Scale with units (QPS, bytes, retention)
[ ] Thin end-to-end path first
[ ] APIs: idempotency, pagination, errors
[ ] Data: access patterns, keys, lifecycle
[ ] Bottleneck named after each evolution
[ ] Failure: timeout, retry, DLQ, degrade
[ ] Security overlay in one pass
[ ] Observability: one SLI/SLO
[ ] Trade-off named for every extra box
[ ] 2-minute summary ready
Lab 401 brief
Lab 401 brief
Lab 401 — Linkly studio
Today we design a URL shortener on the 16-section canvas *before* we open the reference diagram.
The idea: Design a URL shortener on the 16-section canvas *before* you open the reference diagram.
Why we practice this
Reading “add a cache” is not the interview. Filling the canvas with units is.
Objectives
Walk D-SCALE on Linkly
Put 4,630/s, 40k/s peak, and 23 POST/s on the board
Draw four boxes, then *one* evolution
Name a loser (60s takedown unless you invalidate)
Time
20–25 minutes.
Steps
Read the URL shortener challenge. Hide the reference picture.
Open the live canvas on Architecture canvas.
Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
Fill sections 1–7 (problem through baseline) before you decorate.
Fill 8–16. The hop that dies first is the KV at 40k GET/s.
Export Markdown if you want a copy. Mark the lab complete.
Validation
[ ] Scale row has units, not “high scale”
[ ] Baseline is four boxes (no Kafka)
[ ] Evolve is one cache with a hit ratio
[ ] Trade-off names a loser
[ ] Close is two minutes: path, bottleneck, trade-off
Common fails
Logo pile in minute two
Sharding to fix a 50k/s viral code (one key)
301 plus “instant legal disable”
Copying ClinicDocs (202 + queue) onto a redirect path
SCALE CHECK: If they say 10 million/day, recompute (~116/s avg). Do not keep 20 app copies for sport.
Architecture canvas10 min
Architecture canvas
Architecture canvas
Today we fill the sixteen sections so every box has a number or a rule. Then we talk through the canvas from top to bottom.
The idea: A pretty picture with no units is not a design. A filled canvas is the talk you will give.
Why we learn this
If a section is empty, you are not ready to present.
Sixteen sections
Filled Linkly canvas
Instructor comments stay instructor-visible in Portal. They will not appear on your student report.
The sixteen sections (what “done” looks like)
Problem — one sentence a VP would accept
Users / actors — who writes, who reads, who is admin
Scope — in and out (analytics, vanity, multi-region)
Scale — daily, avg QPS, peak, object size, one hot-key
APIs — 2–4 calls with verbs and status codes
Data — entities, primary key, what is *not* in the row
Baseline — users → door → app → store
Bottleneck — 10×, which hop dies first
Evolve — one fix and why
Reliability — timeout, retry, degrade the user can see
Security — auth, TLS, data class
Observe — one SLI / SLO / page
Trade-offs — winner and what you give up
Failures — two concrete stories
10× / 100× — what actually changes
Close — two-minute summary
The live canvas below this lesson is Lab ARCHITECT-SD-401. Autosave is in your browser. Export Markdown if you want a copy. Fill it here — do not stop at reading the table.
More workers on queue age; do not enlarge the upload API
13
202 wins API time. What I give up: the doctor waits up to 60s for search
Same sixteen boxes. Different product. If your ClinicDocs canvas still says “cache the GET,” you copied Linkly.
How to use it in the two challenges
URL shortener: fill Linkly-style numbers. Event platform: fill ClinicDocs- or PulseFeed-style numbers — 12/s is a queue, 150k/s is a feed.
INTERVIEW TIP: Read the canvas top to bottom as your spoken outline. That *is* D-SCALE.
COMMON MISTAKE: A beautiful diagram and an empty Scale row.
Lab 401 brief
Lab 401 brief
Lab 401 — Linkly studio
Today we design a URL shortener on the 16-section canvas *before* we open the reference diagram.
The idea: Design a URL shortener on the 16-section canvas *before* you open the reference diagram.
Why we practice this
Reading “add a cache” is not the interview. Filling the canvas with units is.
Objectives
Walk D-SCALE on Linkly
Put 4,630/s, 40k/s peak, and 23 POST/s on the board
Draw four boxes, then *one* evolution
Name a loser (60s takedown unless you invalidate)
Time
20–25 minutes.
Steps
Read the URL shortener challenge. Hide the reference picture.
Open the live canvas on Architecture canvas.
Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
Fill sections 1–7 (problem through baseline) before you decorate.
Fill 8–16. The hop that dies first is the KV at 40k GET/s.
Export Markdown if you want a copy. Mark the lab complete.
Validation
[ ] Scale row has units, not “high scale”
[ ] Baseline is four boxes (no Kafka)
[ ] Evolve is one cache with a hit ratio
[ ] Trade-off names a loser
[ ] Close is two minutes: path, bottleneck, trade-off
Common fails
Logo pile in minute two
Sharding to fix a 50k/s viral code (one key)
301 plus “instant legal disable”
Copying ClinicDocs (202 + queue) onto a redirect path
SCALE CHECK: If they say 10 million/day, recompute (~116/s avg). Do not keep 20 app copies for sport.
You will
Run Lab ARCHITECT-SD-501 — do not copy the Linkly answers
Keep TicketDrop as optional practice
Event platform design30 min
Event platform design
Advanced challenge — event processing platform
Today we design a system that takes in work, says “we got it,” and finishes the heavy work later — without making the user wait on the line.
The idea: “One million a day” sounds huge. Divide by 86,400 (seconds in a day). You get about 12 per second. That is a to-do list and a few workers — not a giant company-wide cluster.
1M/day vs ClinicDocs vs TicketDrop
Do the napkin out loud
What they say
Math
What you draw
1,000,000 items a day
÷ 86,400
About 12 per second on a normal day
Busy hour 10×
About 120 per second at the peak
Each item is 50 KB
1 million × 50 KB
About 50 GB a day of data
ClinicDocs: 80,000 PDFs × 3 MB, 8-second scan
About 240 GB a day, about 19 per second, about 152 scans running at once — store the PDF in a file store; only put an id in the to-do list
Tell 12 other systems at peak
120 × 12
1,440 calls a second if you do them all inside one request — do not
Check: About 12 per second means a waiting list of jobs and a few workers. It does not mean “draw every fancy tool you know.”
Not this challenge: TicketDrop (fair ticket sales and seat counts).
Different problem: PulseFeed (lots of people *reading* a feed).
Same rule as PayRail: say yes first, finish later, and use a unique key so a retry does not do the work twice.
Walk D-SCALE in plain words
Letter
Plain English
D — Define
Who sends work? Who needs the result? “Done” means we accepted the work (HTTP 202) and they can check status later. Bad outcome = we said yes, then lost the work. Keep order only inside one group key if they ask — never promise one global order for the whole company.
S — Size
Use the napkin above. Stop when more decimal places will not change a box on the board.
C — Create
Sender → front door → safe waiting list → workers → small status record → other systems that need the result.
A — APIs
POST /v1/events returns an id and “accepted.” GET /v1/events/{id} shows status. Workers are not called by the public. Ask for a unique key on the first POST so a double-send does not create two jobs.
L — Locate
Slow workers (oldest job waits too long), too many outbound calls, or one bad file that blocks a worker.
E — Evolve
Add more workers when the oldest waiting job is too old. After a few failed tries, park the bad job in a failed-jobs folder. Alert if wait time or failed-jobs pile up.
text
Sender → Front door (we got it) → Waiting list → Workers → Status record → Other systems
The front door does not finish every downstream job. It saves the work and a short status. Big files go in a file store; the waiting-list message is only an id, not a whole PDF.
Event platform shape
Good defaults (and when to change)
Choice
Start with
Change when
Waiting list
A simple to-do inbox (the same job may show up twice — plan for that)
They need full history replay for many readers → a diary-style log
Many listeners
Separate workers or a shared announcement
Never call 12 outside systems one-by-one on the user’s request
Order
Same group key stays in order
They demand one order for everything — push back
“Exactly once”
Unique key + update the same status row
Do not claim a magic switch on the waiting list
Big files
File store + pointer
The waiting list cannot hold multi‑MB bodies
Cloud product names (if they ask) are examples only. Draw the plain path first.
Mistakes to avoid
Making the user wait while the whole pipeline finishes
Hearing “a million a day” and drawing a huge stack before dividing by 86,400
Putting the whole PDF in the waiting-list message
No plan for bad jobs or for the same job arriving twice
Copying the Linkly “add a cache” answer onto this pipeline problem
Say this to close
“About 12 per second on average. I say we got it right away, put work on a waiting list, keep big files in a file store, tell other systems with a unique key so retries are safe, and watch how long the oldest job has waited. What I give up is finishing everything before I answer the user.”
Your lab
Fill a new canvas — do not copy the URL-shortener answers.
COMMON MISTAKE: Treating “1,000,000 a day” as “we need a huge cluster” before you divide by 86,400.
Lab 501 brief
Lab 501 brief
Lab 501 — Event studio
Today we design “take the work, finish later” on a new canvas. Do not copy the URL-shortener design.
The idea: One million a day ≈ 12 per second. ClinicDocs is about 19 per second with about 152 scans in flight. TicketDrop is about seats and fairness — not this lab.
Why we practice this
The headline sounds like a giant system. The napkin picks a waiting list, a file store for big files, and workers sized by how long the oldest job has waited.
Goals
Say we got it (HTTP 202) before the heavy work finishes
Put big files in a file store; put only an id on the waiting list
Add workers when wait time grows
Say what you give up (the user does not get “fully done” on the first call)
Thin architecture — waiting room, admit, hold, pay, confirm (four to six boxes)
Inventory-correctness decision — how a hold becomes a sale; what a retry uses as its key
One failure using DETECT → IMPACT → MITIGATE → RECOVER → PREVENT (example: payment timeout after hold)
Scale evolution — 10× demand in the room, not 10× checkout boxes
Named tradeoff (winner and loser)
How you know it is failing — customer symptom, SLI/SLO, alert, dependency vs saturation vs error vs latency
Validation
[ ] Waiting room exists; checkout is not 500k QPS
[ ] In-flight holds can exceed inventory — you said how oversell is prevented
[ ] Retry/duplicate story (idempotency or hold id)
[ ] Failure uses D→I→M→R→P
[ ] Observability answer is user-visible, not “watch CPU”
Common fails
Adding more checkout services instead of admission control
Holds that never expire
Double-sell on retry
Copying ClinicDocs 202+queue as if tickets were PDFs
SCALE CHECK: 3,000/s × 30s ≈ 90,000 in-flight holds vs 80,000 tickets. Inventory, not hop count, is the gate.
You will
Open the bank and filter by a weak skill
Speak 60–90 seconds with one number, then check
Question bankongoing
108 prompts. Ongoing practice. Filter by weak skill, then speak before you reveal. Live sessions use only a small subset.
Q-001 · Requirements · intermediate
What questions should you ask before drawing any boxes?
Q-002 · Requirements · intermediate
How do you prioritize nonfunctional requirements when everything sounds important?
Q-003 · Requirements · senior
The prompt is only a product name. How do you create a 45-minute contract?
Q-004 · Requirements · intermediate
What is the difference between a functional requirement and an implementation?
Q-005 · Requirements · senior
When should you push back on a requirement?
Q-006 · Requirements · intermediate
Why write assumptions on the board?
Q-007 · Requirements · staff
How do requirements differ for a staff/principal interview?
Q-008 · Requirements · intermediate
What does “read-heavy” actually change?
Q-009 · Requirements · senior
How do you handle a prompt that mixes product, platform, and ML concerns?
Q-010 · Requirements · intermediate
What sentence should you say before designing?
Q-011 · Estimation · intermediate
How do you estimate QPS from DAU?
Q-012 · Estimation · intermediate
When is estimation useful, and when should you stop?
Q-013 · Estimation · senior
How do you estimate storage for a URL shortener?
Q-014 · Estimation · intermediate
How do you estimate bandwidth?
Q-015 · Estimation · senior
The interviewer gives 1M events/day. What else must you ask?
Q-016 · Estimation · intermediate
Why convert everything to per-second?
Q-017 · Estimation · staff
How do you use estimates to talk about cost without a price sheet?
Q-018 · Estimation · intermediate
How do you estimate cache size?
Q-019 · Estimation · senior
Peak is 20× average. What does that do to the design?
Q-020 · Estimation · intermediate
Walk through a URL-shortener estimate with 100M creates/month, 10:1 reads, 500-byte records, 5-year retention.
Q-021 · APIs · intermediate
How do you design an idempotent write API?
Q-022 · APIs · intermediate
Cursor vs offset pagination — when do you pick each?
Q-023 · APIs · senior
Why might URL creation use POST, and when would you accept PUT?
Q-024 · APIs · intermediate
How do you version a public API?
Q-025 · APIs · senior
How do you prevent abuse on a public write API?
Q-026 · APIs · intermediate
What belongs in a redirect API vs a management API?
Q-027 · APIs · staff
How do you design APIs for a multi-tenant platform?
Q-028 · APIs · intermediate
When is a batch API better than N chatty calls?
Q-029 · APIs · senior
How do you expose long-running work over HTTP?
Q-030 · APIs · intermediate
What does rate limiting belong on — gateway, service, or both?
Q-031 · Data · intermediate
SQL vs NoSQL — how do you choose in an interview?
Q-032 · Data · senior
What creates a hot partition?
Q-033 · Data · senior
When would you shard?
Q-034 · Data · intermediate
What is an access pattern, in one sentence?
Q-035 · Data · intermediate
Primary key vs secondary index — what is the interview distinction?
Q-036 · Data · senior
How do you model a many-to-many follow graph?
Q-037 · Data · intermediate
What is a data lifecycle in a design?
Q-038 · Data · staff
How do you migrate a live schema without a dual-write essay?
Q-039 · Data · senior
When would you add a search index beside the source of truth?
Q-040 · Data · intermediate
Why put blobs in object storage and metadata in a database?
Q-041 · Data · senior
What is a write-heavy access pattern that fools people into NoSQL?
Q-042 · Data · intermediate
How do you prevent a hot short code from melting the database?
Q-043 · Data · staff
How do you reason about multi-region data placement?
Q-044 · Data · intermediate
What is denormalization’s cost?
Q-045 · Data · senior
How do you design for GDPR erase on a distributed system?
Q-046 · Caching · intermediate
What is cache-aside?
Q-047 · Caching · intermediate
What causes a cache stampede?
Q-048 · Caching · senior
Compare write-through vs write-behind.
Q-049 · Caching · intermediate
Where can a cache live?
Q-050 · Caching · senior
How do you invalidate a cached object that is also on a CDN?
Q-051 · Caching · intermediate
What eviction policies should you mention?
Q-052 · Caching · senior
How do you keep a cache from serving deleted or banned content?
Q-053 · Caching · intermediate
Why might a cache make availability worse?
Q-054 · Caching · staff
How do you reason about cache consistency across regions?
Q-055 · Caching · intermediate
Read-through vs cache-aside?
Q-056 · Messaging · intermediate
Queue vs pub/sub — how do you choose?
Q-057 · Messaging · intermediate
How do you handle duplicate messages?
Q-058 · Messaging · senior
What is a DLQ for, and what is it not?
Q-059 · Messaging · senior
How do you apply backpressure?
Q-060 · Messaging · intermediate
At-most-once vs at-least-once vs exactly-once?
Q-061 · Messaging · senior
When do you want a log/stream instead of a queue?
Q-062 · Messaging · intermediate
Why do producers need a durable accept path?
Q-063 · Messaging · staff
How do you preserve per-user ordering without a global lock?
Q-064 · Messaging · senior
How do you detect a poison message?
Q-065 · Messaging · intermediate
What does a consumer retry look like?
Q-066 · Reliability · intermediate
Retry vs DLQ — how do they work together?
Q-067 · Reliability · intermediate
What is graceful degradation?
Q-068 · Reliability · intermediate
Why add jitter to backoff?
Q-069 · Reliability · senior
What is a circuit breaker doing?
Q-070 · Reliability · senior
What is a bulkhead?
Q-071 · Reliability · intermediate
Why are timeouts mandatory?
Q-072 · Reliability · staff
How do you design disaster recovery, not just HA?
Q-073 · Reliability · senior
How do you find single points of failure on a whiteboard?
Q-074 · Reliability · intermediate
What is idempotency in reliability terms?
Q-075 · Reliability · senior
How do you design rate limiting as a reliability feature?
Q-076 · Reliability · intermediate
Token bucket vs leaky bucket vs sliding window?
Q-077 · Reliability · staff
What SLI/SLO/error-budget story is enough in an interview?
Q-078 · Reliability · intermediate
What security items should a candidate mention without being asked?
Q-079 · Reliability · senior
How do you make retries safe for payments?
Q-080 · Reliability · intermediate
Why health checks can lie?
Q-081 · Distributed Systems · intermediate
What is eventual consistency, with an example?
Q-082 · Distributed Systems · intermediate
What is replication lag, and why does it bite?
Q-083 · Distributed Systems · senior
How should you talk about CAP in 2026 interviews?
Q-084 · Distributed Systems · senior
What is consistent hashing useful for?
Q-085 · Distributed Systems · intermediate
Primary/replica vs multi-primary?
Q-086 · Distributed Systems · senior
Hash vs range vs directory sharding?
Q-087 · Distributed Systems · staff
What operational complexity does sharding add?
Q-088 · Distributed Systems · intermediate
Read-your-writes vs monotonic reads?
Q-089 · Distributed Systems · senior
How do you scale writes besides sharding?
Q-090 · Distributed Systems · intermediate
Why are stateless services easier to scale?
Q-091 · Communication & Trade-offs · intermediate
How do you defend a technology choice?
Q-092 · Communication & Trade-offs · intermediate
What do you do when the interviewer changes requirements?
Q-093 · Communication & Trade-offs · senior
How do you narrate while drawing?
Q-094 · Communication & Trade-offs · intermediate
What is over-engineering in an interview?
Q-095 · Communication & Trade-offs · staff
How do you talk about organizational/service boundaries?
Q-096 · Communication & Trade-offs · senior
SQL vs cache vs queue — how do you explain the trio?
Q-097 · Communication & Trade-offs · intermediate
How do you close a 45-minute interview?
Q-098 · Communication & Trade-offs · senior
The interviewer looks unconvinced. What do you do?
Q-099 · Communication & Trade-offs · intermediate
What is a bottleneck, and how do you find the next one?
Q-100 · Communication & Trade-offs · staff
How do you evolve a design over years, not minutes?
Q-101 · Requirements · senior
Which NFRs most often change a chat design?
Q-102 · Estimation · senior
How do you estimate a news-feed fan-out?
Q-103 · APIs · senior
How do you design a feature-flag evaluation API?
Q-104 · Data · staff
How do you model multi-tenant metadata vs tenant payload isolation?
Q-105 · Caching · senior
What is a thundering herd after a deploy?
Q-106 · Messaging · staff
How do you design replay for an event platform?
Q-107 · Reliability · staff
What is an error budget conversation with a PM?
Q-108 · Distributed Systems · staff
How do you reason about clocks in distributed design?
You will
Talk through a new prompt under time
Leave with a score that does not predict hiring
Mock interview brief5 min
Mock interview brief
Mock interview brief
Today we treat the clock as part of the design.
The idea: Forty-five minutes on a new prompt. The score is for practice. It does not predict hiring.
45 minutes
The clock
text
0–5 Requirements actors, done, fail, scope
5–10 Estimation daily / 86,400, peak, size
10–20 High-level four boxes, 2–4 APIs, key
20–30 Deep dive one hop with a number
30–38 Scale / reliability 10×, timeout, degrade
38–43 Trade-offs what you give up
43–45 Two-minute close path, bottleneck, trade-off
The instructor may pause the timer. You should not pause to “research.”
NOTE: Instructor private comments never appear on your copy. The number does not predict hiring.
Mock interview45 min
Mock interview
Mock interview — how to take it
Today we take the Full Mock like the real room: scope, numbers, one deep hop, two-minute close.
The idea: Forty-five minutes on an unfamiliar scenario (M-01–M-10). You talk. The instructor scores the 9-dimension rubric. This is practice — not a hiring forecast.
Before you start
Cheat sheet in your head — not a second screen of notes
Water, marker or notepad
Know your two weakest skills so you watch for them
Know 86,400 as a method. If their numbers differ, erase and recompute
Written bank essays are not this mock. Open the Full Mock when you are ready to talk under the clock.
The 45 minutes (one pass)
text
0–5 Requirements who, what, done, fail → then scale
5–10 Estimation daily ÷ 86,400, peak, size — stop when a box will not change
10–20 High-level thin path, 2–4 APIs, the key
20–30 Deep dive ONE hop with a QPS or in-flight number
30–38 Scale / failure 10×, timeout, what the user sees
38–43 Trade-off I picked X because of Y; I give up Z
43–45 Close path, bottleneck, trade-off — then stop
Minute 40 and still drawing logos? Skip to trade-off and close.
Say: “I will treat this like [X] unless you object.”
After
Read the released report. Private instructor notes stay hidden. Build the 7-day plan from your two lowest rubric lines and two weakest readiness skills.
COMMON MISTAKE: Minutes 20–40 adding boxes instead of defending one hop with a number.
Written interview rehearsal20 min
Written interview rehearsal
Written interview rehearsal
Today we practice six architecture questions in writing. This is not the Full Mock.
The idea: Type spoken-style answers when you cannot run a 45-minute spoken design.
Why we practice this
The Full Mock (Module 6) is a timed unfamiliar scenario with phases, notes, and the 9-dimension System Design rubric.
You will
Write the two weakest skills down
Walk the 45-minute guide once before Monday
Feedback and interview plan10 min
Feedback and interview plan
Feedback and 7-day plan
Today we turn your assessment and mock gaps into one week you can actually follow.
The idea: Two weak skills → seven short sessions out loud. The certificate means you finished the course. A score here does not predict hiring.
Why this page exists
A mock without a plan is just a grade. By Monday you should know what to practice and for how long — not reread the whole sprint.
Seven days
What the report gives you
Your instructor releases: strengths, improvements, topics to review, and next steps.
Private instructor notes never appear on your copy.
You need only four inputs for the week:
Two weakest readiness skills
Two weakest mock rubric lines
Map each to a bank category. Do not invent a seventh “add Kafka” day.
Your week (fill the blanks)
Day
Focus
Do this
Done when
1
Readiness gap A
Five bank questions out loud in that category
Each answer has one number or labeled assumption
2
Readiness gap B
Five more, same rule
You can name one mistake you almost made
3
Mock gap A
Teach one Day-1 answer to a wall (60–90s, no notes)
Clear without memorizing a napkin that does not match the prompt
4
Mock gap B
One medium design on a fresh canvas (or TicketDrop compact)
Units on the scale line; one bottleneck
5
Unfamiliar shape
One item from the 25 practice problems — design before probes
Thin path + what you give up
6
Endurance
45-minute mock or written rehearsal
Clock on the table; notes saved
7
Close
Opening sentence + two-minute close once out loud
“Thin path, first bottleneck, one trade-off”
If the interview is sooner than seven days: Days 1–3 tonight, timed mock tomorrow, Day 7 the morning of.
Pick the drill for the gap
If this was weak…
Practice on…
Estimation
Changed-telemetry, then one napkin with units
Data / APIs
Key + API first (Linkly code, ClinicDocs pointer, PayRail key)
Scalability
PulseFeed read:write or RideHail ping vs trip
Reliability
PayRail same-key after timeout; TicketDrop hold expiry
Trade-offs
One sentence: I picked X because of Y; I give up Z
BayLearn Certificate of Completion — System Design Interview Sprint.
Completion only — not a professional accreditation, not a hiring forecast.
INTERVIEW TIP: Day 7 is the close. Path, bottleneck, one trade-off — then stop talking.
Final checklist
Final checklist
Final interview prep checklist
Today we tick through what you need ready before you walk in — including one number per story.
The idea: If you can tick these without notes, you are ready.
D-SCALE
Six workloads
What these six products are — use-cases in depth
Read the product story and the diagrams before you memorize QPS. Same six stories all weekend. Labeled assumptions for rehearsal — not leaked telemetry. If the interviewer gives different numbers, erase yours and recompute.
1. Linkly · short links
Read-heavy lookup
A news-and-ads company needs short links for articles and paid campaigns. Marketing staff mint a short code. Anyone who opens that code — a reader, a social app, a bot — is redirected to the long URL. The product is the redirect, not a URL database.
Newsrooms and ad ops cannot paste 200-character tracking URLs into SMS, print, or social. The short code is the distribution primitive. Revenue sits on those mappings staying up: if a paid campaign code 404s, the spend is wasted. Analytics dashboards are a later product. In 45 minutes you are paid to keep GET /{code} correct and fast.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly thin path, then cache-aside on the 40k/s hop
Hit-ratio math: 40k GET/s becomes 3,200 miss/s at 92% hit
Who uses it
Anonymous readers (the GET), logged-in marketing staff (the POST), crawlers, and bots that will hammer creates if you do not rate-limit the write path.
In 45 minutes
Create + redirect. Optional custom slug if they insist. Out of scope: Click analytics, QR campaigns, a public directory of all links, multi-region active-active in minute five.
What people do
Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
A front-page article goes viral. One code absorbs tens of thousands of GET/s. That is a hot key, not a reason to shard the cluster.
Done means
201 on create, 302 on read. The mapping is durable across a box death.
Cannot happen
Lose a paid campaign mapping. Return 301 if takedown matters (browsers cache 301 forever).
Walk D-SCALE on this product
Letter
What you write on the board
D
Anyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
GET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
E
Cache-aside 92% → 3,200 miss/s. Loser: 60s takedown unless we invalidate that key.
APIs
POST /v1/urls { longUrl } → 201 { code } (Idempotency-Key so a double-click does not mint two codes)
GET /{code} → 302 Location
DELETE /v1/urls/{code} → 204, then invalidate that cache key
Data model
Primary key is code. Value is the long URL plus a disabled flag. No joins. Analytics events, if they exist at all, are a later async path — not on the 40k/s GET.
First bottleneck
The KV hop on GET at ~40,000/s (and 50k/s on one viral code).
A takedown can linger until TTL unless you bust that one key. You gave up “instant global disable” if you only have TTL.
Why we teach this shape
Reads are the product (~40k GET/s peak). Creates are ~23/s — that does not buy a stream. One viral code is a hot key. Cache-aside with a named invalidation story is the first evolve.
Common traps
Drawing Kafka, search, or four regions before a number needs them
Sharding to “fix” one hot code — every GET still hits that key
301 instead of 302 when legal disable matters
Labeled napkin
400M redirects/day ≈ 4,630 GET/s avg · ~40k GET/s peak · 2M creates/day ≈ 23 POST/s · 200 B values · one viral code can hit 50k GET/s · 92% cache hit → 3,200 miss/s
What to say: Anyone with the link redirects. Staff create. I cache GET. I will not draw Kafka for 23 creates a second.
2. PulseFeed · home feed
Fan-out / read:write ~150:1
A social app where logged-in people open a home feed of posts from accounts they follow. Authors publish. Most users are quiet. One celebrity with 12 million followers can break a naive fan-out-on-write. You are designing the feed, not the whole social network.
Retention is “open the app, see people I follow.” An empty or two-second home is churn. Celebrity posts are marketing events, not the same write path as your neighbor. Ads, stories, live, and DMs each have their own interviews. In 45 minutes you own publish and home.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
Fan-out on write vs fan-out on read, and why hybrid exists
Who uses it
Logged-in readers, ordinary authors, and one celebrity whose single post is 12 million timeline writes if you push on publish.
In 45 minutes
Publish + home feed. Out of scope: Stories, ads, live video, DMs, search, a full follow-graph product.
What people do
An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
A reader likes a post. The count can lag — this is not a card-capture path.
A celebrity posts. You pull that post at read time (or precompute a thin pointer), you do not write 12 million rows on the request.
Done means
201 on publish. The feed is fast enough to open. Fan-out may still be in flight.
Cannot happen
An empty home because you joined the follow graph on every GET. A celebrity publish that synchronously writes 12 million timeline rows.
Walk D-SCALE on this product
Letter
What you write on the board
D
Logged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
POST /v1/posts/{id}/likes (eventual count is fine)
Data model
Post store (id → body, author, time) is the source of truth. Follow graph is edges, not a join on GET. Timeline cache holds precomputed post ids for normal users. Celebrity ids are fetched at read time and merged.
First bottleneck
Home-feed reads at ~150k/s, and the celebrity key if you fan-out-on-write.
Evolve
Cache built timelines 10–30s. Push to normal users asynchronously. Pull celebrity posts on read. Ranking can degrade to chronological.
What you give up
A like count or a celebrity post can lag a few hundred ms to a few seconds. Ranking down means an unranked feed, not a 500.
Why we teach this shape
Publish is modest (~185/s). Feed reads dominate (~28k/s avg, ~150k/s peak). Hybrid fan-out exists because celebrities are a different shape from normal users. Replicas help likes; they do not multiply write capacity.
Common traps
Treating “Instagram” as the spec and stacking stories, ads, and live
SQL join of 12 million follow edges on every Home GET
Sharding by userId and expecting it to fix an 80k/s celebrity profile
What to say: I will design publish and a home feed. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on one publish without a hybrid.
3. RideHail · live map
Two speeds: pings vs trips
Riders request a car. Drivers are on a live map so the app can show nearby supply and match a trip. After the ride, someone gets paid. Location pings and trip checkout are two products that share a brand — they do not share a store.
Marketplace liquidity is seeing cars move. A stale map makes riders think there is no supply. Charging twice is a trust and regulatory failure. Those are different SLOs, so they are different stores. Pricing ML, incentives, and a forever ping warehouse are other interviews.
RideHail use-case: live map vs trip/pay as two products
75k location overwrites/s versus 17 trip starts/s
Who uses it
Riders requesting a trip, ~300k drivers at evening peak, dispatch, and payments after drop-off.
In 45 minutes
Latest driver location + request/match a trip. Out of scope: Full pricing ML, driver incentives, a city-scale warehouse of every ping forever, multi-city active-active.
What people do
A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
Payment runs after drop-off on the trip store — never by appending a charge onto the ping table.
Done means
The map shows nearby drivers. A trip start is a committed record. The rider is not charged twice.
Cannot happen
Charge the rider twice. Append every ping forever (~1.3 TB/day). Put the ledger on the ping table.
Walk D-SCALE on this product
Letter
What you write on the board
D
Rider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
Ping ingest → latest-location store. Trip API → transactional store.
A
PUT location by driverId. GET nearby by cell. POST /trips.
L
Append-forever ping volume, or one hot downtown cell.
E
Overwrite + TTL. Loser: no forever breadcrumb on the hot path.
APIs
PUT /v1/drivers/{id}/location { lat, lng, ts } (overwrite)
GET /v1/drivers/nearby?cell= → ~20 cars
POST /v1/trips { pickup, dest } → 201 { tripId }
POST /v1/trips/{id}/complete then charge on the trip ledger
Data model
Location store: key = driverId, value = latest point + coarse geohash, TTL 15–30s. Trip store: transactional row for rider, driver, fare, state. Never one table for both.
First bottleneck
75k location writes/s if you append, and a downtown geo cell at 17:30 if you shard only by cell.
Evolve
Overwrite latest. Keep a 15-minute ring for replay. Warehouse overnight. Subdivide hot cells or cap density. Trip path stays SQL-ish.
What you give up
You do not have a forever breadcrumb of a rider. ETA can degrade to raw map if the ETA service is down.
Why we teach this shape
75k overwrite writes/s for latest point. Trip starts are ~17/s and can be transactional. Change the data model (overwrite, not append) before you buy nodes. A downtown geo cell can still be a hot key.
Common traps
One “real-time database” for pings and money
SQL UPDATE of 75k/s latest-point rows as the first design
Keeping every ping “for analytics” in the serving path
Labeled napkin
300k drivers at peak · ping every 4s → 75k writes/s · 1.5M trips/day ≈ 17/s · payload ~200 B · keep ~15 min of pings (~3.4 GB ring) · warehouse the rest overnight
What to say: Pings and payments are two products. I overwrite latest location. I will not put the ledger on the ping table.
4. PayRail · card charges
Correctness over slogans
Merchants charge cards. A shopper taps pay. The processor authorizes, then captures. Finance exports a ledger. Fraud looks at batches later. The interview is “do not double-charge,” not “draw a payments mesh.”
A merchant cannot take cards unless retries and Black Friday noon are boring. Double capture is a lawsuit and a trust event, not a 500 you can retry later. Finance needs a ledger they can export. Fraud is a batch consumer — it does not sit on the 400 ms authorize path.
PayRail use-case: one tap, a timeout, the same key, one ledger row
Idempotency-Key path and the 24 double-charges/s math
Who uses it
Cardholder, merchant, finance export, fraud batch, and mobile clients that retry when the 400 ms budget times out.
In 45 minutes
Idempotent authorize/capture and a ledger row. Out of scope: A full issuing bank, rewards, every FX corridor, a new card network, instant worldwide strong consistency on every read.
What people do
Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
The phone times out after the write succeeded. The same key is retried. You return the original charge.
Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
Finance exports captured rows. Fraud reads a replica or a nightly batch. GET-after-capture for the shopper hits the primary.
Done means
201 + chargeId. One ledger row. Duplicate POST with the same key is the same charge.
Cannot happen
Two $49 captures for one tap. Blind retry without a key. Read-your-writes from a lagging replica on GET-after-capture.
Walk D-SCALE on this product
Letter
What you write on the board
D
Cardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
API → authorize service → ledger primary. Email is off the path.
A
POST /charges + Idempotency-Key. Unique chargeId. State machine.
L
Downstream timeout and duplicate taps.
E
Key + one writer. Loser: no “email sent” as success.
APIs
POST /v1/charges Idempotency-Key: … → 201 { chargeId, state }
POST /v1/charges/{id}/capture (same key rules)
GET /v1/charges/{id} after write → primary (read-your-writes)
Data model
Unique chargeId plus unique idempotency key (scoped to merchant, TTL ~24h). State machine: pending → authorized → captured | voided. Ledger line is written in the same commit as the state change.
First bottleneck
Downstream bank latency inside a 400 ms p99, and duplicate POSTs if the key is missing.
Evolve
Idempotency store + single writer for capture. Timeouts 300–400 ms. Bulkhead authorize threads from receipt-email sockets. Reporting on replicas.
What you give up
You do not email-on-success as the commit. You accept that finance reports can lag the primary by seconds.
Why we teach this shape
Average ~93/s is easy. Black Friday 1,200 simple writes/s still often fits one well-run primary. 2% retries = 24 potential double-charges/s without a key. Replicas do not multiply write capacity.
Common traps
“Exactly-once” as a slogan with no key
Caching the authorize result
Sharding at minute five because 8 million sounds large
Sending GET-after-capture to a replica
Labeled napkin
8M charges/day ≈ 93/s · Black Friday noon 1,200 authorize/s · p99 < 400 ms · 2% client retries → +24/s duplicates if you are not idempotent
What to say: Done is a ledger row, not an email. I require an Idempotency-Key. I will not shard in minute five for 1,200 simple writes/s.
5. ClinicDocs · hospital PDFs
Pipeline, not internet-scale
Clinics upload patient documents (PDFs, ~3 MB). A scanner must inspect each file before anyone downloads it. Doctors want the clean object searchable within a minute. This is ingest-and-retrieve for documents — not an electronic health record.
Hospitals receive referrals, imaging reports, and consents as PDFs. They cannot block the upload request on an 8-second malware scan, and they cannot put ransomware on the patient portal. Data class is PHI: no bytes in logs, no public origin, short-lived signed downloads. Search is a derived index with lag — not the official record.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
PUT presigned landing URL (bytes never through the app if you can avoid it)
GET /v1/files/{id} → metadata + status
GET /v1/files/{id}/download → 302 to a short-lived signed clean URL
Data model
SQL (or equivalent) for fileId, patientId, status, checksum, actor. Object store for landing vs clean prefixes. Search index is derived and may lag. Audit log of fetches.
First bottleneck
Scan time × peak arrivals (152 in-flight), not HTTP QPS. Year-five bytes if you never lifecycle.
Evolve
202 + queue + N workers on queue age. Separate landing and clean. Signed URLs. Lifecycle to cold storage.
What you give up
Upload is not “file ready.” Search can lag the official object. You will not serve landing “to be helpful.”
Why we teach this shape
80k files/day is 0.93/s average and ~19/s peak — a queue and ~152 in-flight scanners, not “internet scale.” Bytes go to object storage. Metadata can be boring SQL. Autoscale on queue age, name the 2–5 min warm-up.
What to say: This is a pipeline-time problem. Upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
6. TicketDrop · on-sale
Burst + fairness + inventory
A concert goes on sale at 10:00:00.000. There are 80,000 tickets and about 500,000 people already in a waiting room. Bots will try to skip the line. The product is a fair chance to buy a real seat — not a checkout API that 500,000 clients hit at once.
A promoter sold a finite inventory. Half a million people want it at the same millisecond. Fairness (lottery or FIFO) is a product choice you must name. Oversell is a lawsuit and a venue night that cannot exist. A box sized for 10:00 and idle 364 days/year is the expensive design. The waiting room is cheaper than hope.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
Waiting-room numbers: admit 3k/s, 90k in-flight holds, inventory still gates
Who uses it
Fans, bot farms, box office. Inventory is a scarce uniquely numbered seat — not a digital good you can reprint.
In 45 minutes
Waiting room, hold, pay, inventory decrement once. Out of scope: Season tickets, dynamic pricing ML, a social feed of who got in, 365-day always-on flash sales as the first design.
What people do
Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
Retries use the same hold id. Sold-out stops admits and clears the room. Nobody gets a 500 that looks like “try again for a new seat.”
Done means
Inventory decremented once. The fan has a seat or a clear miss. Oversell is zero.
Cannot happen
Sell 80,001 seats. Let 500k hit checkout. Retry checkout without the same hold id.
Walk D-SCALE on this product
Letter
What you write on the board
D
Fans, bots, box office. Fair chance + no oversell. Season tickets out.
Waiting room → admit → hold → pay. Checkout is closed before 10:00.
A
Room status, POST hold, POST checkout on holdId.
L
500k QPS if the room is missing; hot event row if inventory is one lock.
E
Room + hold + inventory gate. Loser: instant Buy for everyone.
APIs
GET /v1/room/status (poll; per-user limit)
POST /v1/holds → 201 { holdId, seat, expires }
POST /v1/holds/{id}/checkout Idempotency-Key / same holdId
POST /v1/holds/{id}/release on expire
Data model
Seat (or GA counter) with a unique constraint / atomic decrement. Hold row: holdId, seat, user, expiry. Payment references holdId. Waiting-room token is not inventory.
First bottleneck
500k browsers if they reach checkout, then lock contention on a hot eventId if you decrement one row.
Evolve
Waiting room + admit rate + per-seat or sharded counters + hold TTL + stop-admits on sell-out.
What you give up
Some fans wait. Some lose the lottery. You gave up “everyone clicks Buy at 10:00 and we sort it out.”
Why we teach this shape
If 500k hit checkout you invented a 500k QPS event. Admit ~3k/s and a 30s checkout ⇒ ~90k in-flight holds — still above 80k tickets, so inventory is the gate. A waiting room is not a rate-limit trivia question; it is a hold.
Common traps
Autoscaling checkout boxes to 500k and calling it architecture
Rate-limiting by IP in a stadium NAT
Retry that decrements again
Treating the waiting room as decoration
Labeled napkin
80k tickets · 500k in the room at 09:59:58 · checkout ~30 s · admit ~3k/s → ~90k in-flight holds, still more than inventory, so inventory gates
What to say: I will not take 500k checkouts at 10:00. The waiting room admits a survivable rate. Inventory is the gate. Retry the same hold id.
The night before
[ ] Opening sentence ready: “Before I design, I will clarify requirements and assumptions.”
Instructor may pause the timer. If you are still drawing at 43, stop and summarize.
You will
Pick a problem and design on paper or canvas first
Reveal guidance only after you have a thin path
25 practice problemsongoing
25 practice problems
25 System Design practice problems
Today we practice unfamiliar prompts — twenty-five shapes, one method, real numbers.
The idea: Design first with D-SCALE and a napkin. Reveal interviewer guidance only after a thin path. The deep answer needs a second confirm — napkin math, components to draw, a deep architecture diagram, and a numbered sequence explained step by step.
How to use each problem
Read title, prompt, and constraints.
State labeled assumptions with units. Divide by 86,400. Apply a peak factor.
Explain claim_key and attribute_not_exists out loud
Map each pytest to a failure mode
Appendix overview5 min
Appendix overview
Appendix — PayRail code (read this with Lab 701)
Today we open the real PayRail source so you can point at code in an interview, not only at boxes on a napkin.
The idea: Design without code is half an interview. Saying “idempotent charges” is cheap. Pointing at claim_key before the gateway, then replay vs 409 vs 503, is what hiring managers remember.
Read this appendix withLab 701 overview. The overview teaches the story. These pages teach the lines.
---
Why this appendix exists
In the room you will draw PayRail at Black Friday load. Someone will ask: *Where do you lock the key? What does the client see on retry? What if the store is down?*
Those answers live in a few short Python files. You do not need to memorize every line. You need to know which file proves which sentence, then open that file and walk it.
---
Map of files → interview sentence
File
Interview sentence it proves
lambda/charge.py
“I claim before I call the gateway. Same key + same body = replay. Different body = 409. Store down = fail closed.”
lambda/lab_store.py
“The lock is insert-if-absent on tenant#key. One PaymentIntent per key. Queue + stuck rows for heal.”
lambda/dynamo_store.py
“Distributed claim is conditional insert (attribute_not_exists). Same methods as memory — different backend.” *(AWS example only.)*
lambda/sweeper.py
“Stuck processing heals if an intent exists; otherwise we fail the key — never mint a new key after timeout.”
lambda/worker.py
“Webhooks are at-least-once; we dedupe on event_id.”
lambda/webhook.py
“Accept fast (202), enqueue, process later.”
lambda/stripe_mock.py
“Gateway is idempotent on (tenant, key) — one pi_…, not one per retry.”
scripts/local_server.py
“One process plays every role: HTTP front door + charge + queue drain + sweep.”
tests/test_idempotency.py
“Each test is a failure mode you must not break.”
Vendor-neutral first: in the interview you can still say load balancer + app fleet + relational DB + real card gateway. This lab trains the state machine. DynamoDB / Lambda / SQS are example only so students can destroy the stack the same day.
---
How to study
Open the appendix page for that file.
Read the teacher explanation (tables + short snippets).
Open the same source in the lab pack / extras browser and skim the real lines.
Say the interview sentence out loud once.
Do not copy-paste into the whiteboard. Point and narrate.
That last number is why Idempotency-Key is not optional. Without it, BFCM retries become a second charge factory.
---
What to say (30 seconds)
I store one row per tenant + Idempotency-Key. First writer claims processing before the gateway. Completed keys replay the cached body. Same key with a different body is 409. Store unavailable is 503 — fail closed. Timeouts leave processing; a sweeper heals from the gateway intent or marks failed. I never mint a new key because the first call timed out.
COMMON MISTAKE: Drawing boxes and never naming the claim → gateway → complete order. Interviewers smell vaporware.
claim_key creates a processing row (or returns the existing one).
Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
An order_id is minted once, stored, and cached on the key row.
A webhook event is enqueued. The worker dedupes on event_id.
Timeout path (the interview trap)
X-Lab-Crash-After-Claim: 1 returns 504 and leaves the row `processing`.
A retry with the same key sees processing → 409 in flight (client should wait / retry the same key).
The sweeper (sweeper.py) looks for a gateway intent:
- Intent exists → complete the key (the money already moved).
- No intent → mark failed. Do not invent a second charge.
COMMON MISTAKE: Minting a new Idempotency-Key because the first call timed out. That is a second claim_key and a second order.
Why DynamoDB in the student lab
Production mapping you say out loud: ALB + ECS + Aurora. The lab uses HTTP API + Lambda + DynamoDB so a same-day destroy stays under $2. The *state machine* is what you are learning, not the SKU names.
Files to open in the source browser on Build PayRail
charge.py — claim / replay / 409 / 503
lab_store.py — in-memory version of the same API (pytest + local server)
dynamo_store.py — the AWS version (attribute_not_exists claim)
This is a working AWS lab. Deploy it, prove a timeout retry does not double-charge, then destroy it the same day.
Production at Stripe/merchant scale often uses Aurora + ECS. This lab uses DynamoDB + Lambda so a student account stays under ~$2 if you clean up today. The state machine is the same.
What you build
Path
What it is
lambda/charge.py
POST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.py
SQS consumer — dedupe event_id
lambda/sweeper.py
Heal rows left processing after a crash
lambda/webhook.py
POST /webhooks/stripe replay
terraform/
Supported deploy path
scripts/local_server.py
Same API on :8080 with no AWS
scripts/demo.sh
Same key twice → same order_id
tests/
8 pytest cases, no AWS
Prerequisites
Python 3.11+
For AWS: Terraform ≥ 1.5, an account that can create IAM, Lambda, API Gateway, DynamoDB, SQS, EventBridge, KMS
curl
Unique prefix such as yourinitials-payrail
1. Prove it locally (no AWS)
bash
cd labs/payrail-idempotency
python3 -m pytest tests/ -v
python3 scripts/local_server.py
In another terminal:
bash
./scripts/demo.sh
You should see PASS: same order_id and payment_intent_id on retry and HTTP 409 when the amount changes.
That leaves the key in processing (504). A retry with the same key returns 409 in flight. Wait ~1 minute for the sweeper, or invoke the sweeper function. Then the same key returns the healed 201.
Validation
Same Idempotency-Key → same order_id and payment_intent_id
DynamoDB orders does not grow on retry
Same key, different amount_cents → 409
Missing key → 400
Store down (local: store.down = True) → 503 fail closed
SQS DLQ depth is 0 after a happy-path charge
CloudWatch log groups /aws/lambda/{prefix}-charge show the request
Cleanup
bash
cd terraform
terraform destroy
Interview talking points
After a timeout you are in UNKNOWN — do not assume failure and do not mint a new key
Unique claim on (tenant, key); replay returns the cached body
Request hash rejects same key + different body
Fail closed if the idempotency store is down
Webhooks are at-least-once; dedupe event_id
Sweeper + reconciliation are the backstop, not hope
PayRail numbers in this sprint: 93/s average, 1,200/s Black Friday, p99 < 400 ms, 2% retries → 24 duplicate attempts/s without the key
Appendix — Charge25 min
Appendix — Charge
Appendix — charge.py (POST /v1/charges)
Today we walk every branch of the charge handler. This is the file you point at when you say “claim before gateway.”
The idea: One function, charge(), owns the state machine. Clients only see HTTP codes. Every branch below names the code and why.
Routes health, get order, POST charge + lab crash headers
---
Store selection — get_store
python
# L15–25
def get_store():
global _STORE
if _STORE is not None:
return _STORE
if os.environ.get("KEYS_TABLE"):
from dynamo_store import DynamoStore
_STORE = DynamoStore()
else:
_STORE = MemoryStore()
return _STORE
Interview line: Same charge() logic locally and in the cloud; only the store backend swaps. In the room you can still say Aurora / Postgres for production.
---
Helpers (skim)
Function
Job
_headers
Lowercase header names so Idempotency-Key and idempotency-key both work
_body
Parse JSON body; decode base64 if the gateway sent it that way
_jsonable
Turn Dynamo Decimal into int/float before json.dumps
_resp(code, payload, extra_headers?)
Always returns { statusCode, headers, body } — what Lambda / local server send
# L76–86
key = (headers.get("idempotency-key") or "").strip()
tenant = (headers.get("x-tenant-id") or "demo").strip() or "demo"
if not key:
return _resp(400, {"error": "Idempotency-Key header is required"})
amount = body.get("amount_cents")
currency = str(body.get("currency") or "").lower()
if not isinstance(amount, int) or amount <= 0:
return _resp(400, {"error": "amount_cents must be a positive integer"})
if currency != "usd":
return _resp(400, {"error": "currency must be usd in this lab"})
Branch
HTTP
Why
Missing / blank key
400
No key → no idempotency story
Bad amount_cents
400
Must be positive int
Currency not usd
400
Lab constraint
Tenant defaults to "demo" if the header is missing. Hash is only over { amount_cents, currency } — not the key itself.
Do not call the gateway if you cannot record the attempt
Interview line: Fail closed. Charging without a row is how you double-bill after a blip.
claim["created"] is True only for the first writer. Everyone else gets created: False and the existing row.
---
Replay / conflict when claim was not created
python
# L96–107
row = claim["row"] or {}
if not claim["created"]:
if row.get("requestHash") and row["requestHash"] != req_hash:
return _resp(409, {"error": "same Idempotency-Key with a different body"})
if row.get("status") == "completed":
cached = row.get("responseBody") or {}
return _resp(int(row.get("responseStatus") or 201), cached, {"x-idempotent-replay": "true"})
if row.get("status") == "processing":
return _resp(409, {"error": "request in flight — retry the same key"})
if row.get("status") == "failed":
cached = row.get("responseBody") or {"error": "previous attempt failed"}
return _resp(int(row.get("responseStatus") or 402), cached, {"x-idempotent-replay": "true"})
Row state
Same body?
HTTP
Header
Why
Any
Hash mismatch
409
—
Same key must mean same request
completed
Yes
201 (or cached status)
x-idempotent-replay: true
Safe retry — same order
processing
Yes
409
—
In flight; client should retry same key later
failed
Yes
cached (often 402 / 504)
x-idempotent-replay: true
Replay the failure; do not invent a new charge
Interview trap: A timeout then a *new* UUID is a second claim_key → second order. Say: “retry the same key.”
---
Lab crash after claim (504, leave processing)
python
# L109–110
if crash_after_claim:
return _resp(504, {"error": "lab crash after claim — row left processing", "hint": "run the sweeper"})
Branch
HTTP
Why
crash_after_claim=True
504
Simulates die after lock, before gateway. Row stays processing. No order.
Set via header X-Lab-Crash-After-Claim: 1 in the handler (see below). Sweeper later: no intent → mark failed.
Second POST with same key + body never reaches this block — it returns at the replay branch with 201 and replay: true, same order_id.
---
All client HTTP codes in one place
Code
When
400
Missing key; bad amount; currency ≠ usd
201
First success, or completed replay
409
Hash mismatch, or still processing
402 / cached
Failed-key replay (default if status missing)
503
Store down — fail closed
504
Lab crash headers, or gateway exception (then fail_key)
404
Order GET miss (handler)
405
Non-POST on charge path (handler)
200
Health / order found (handler)
---
handler() — routing
python
# L160–193
def handler(event, _context):
store = get_store()
route = ... path ...
method = ... method ...
headers = _headers(event)
if method == "GET" and route.endswith("/health"):
return _resp(200, {"ok": True, "service": "payrail-charges"})
if method == "GET" and "/v1/orders/" in route:
order_id = route.rstrip("/").split("/")[-1]
row = store.get_order(order_id)
if not row:
return _resp(404, {"error": "order not found"})
return _resp(200, _jsonable(row))
if method != "POST":
return _resp(405, {"error": "method not allowed"})
body = _body(event)
crash = headers.get("x-lab-crash-after-claim") == "1"
crash_gw = headers.get("x-lab-crash-after-gateway") == "1"
def stripe(tenant, key, amount, currency):
return store.create_intent(tenant, key, amount, currency)
return charge(headers, body, store, stripe,
crash_after_claim=crash, crash_after_gateway=crash_gw)
Route
Method
HTTP outcomes
…/health
GET
200
…/v1/orders/{id}
GET
200 or 404
anything else
not POST
405
charge (POST)
POST
whatever charge() returns
Crash flags are lab only. Production has no “please die after claim” header — you use them to practice sweeper heal.
---
What to say (point at this file)
I hash the body, claim tenant#key as processing, then call the gateway. If the row already exists, I replay completed, conflict on hash or in-flight, or replay failed. Store down is 503. I never charge without a claim.
COMMON MISTAKE: Calling Stripe first, then writing the idempotency row. A crash between them double-charges on retry.
Both bump updatedAt. Sweeper uses updatedAt to find stuck processing rows.
---
Orders
Method
Job
put_order(order)
Store by orderId
get_order(order_id)
Lookup for GET
order_count()
Tests assert “exactly one charge”
The order is the ledger. The idempotency row caches the HTTP response so retries do not invent a second ledger line.
---
Webhook dedupe — put_webhook
python
# L105–112
def put_webhook(self, event_id, payload) -> bool:
"""Return True if this is the first delivery."""
...
if event_id in self.webhooks:
return False
self.webhooks[event_id] = dict(payload)
return True
Return
Meaning
True
First time — process side effects
False
Duplicate delivery — no-op
Worker uses this. Queues are at-least-once; your table must be exactly-once *for effects*.
---
Queue — enqueue / dequeue
python
# L114–120
def enqueue(self, message):
with self.lock:
self.queue.append(dict(message))
def dequeue(self):
with self.lock:
return self.queue.pop(0) if self.queue else None
Local server drains this every 0.2s. On AWS the same enqueue becomes SQS send_message *(example only)*. DynamoStore.dequeue returns None — workers read from the queue service instead.
Interview line: The gateway is also keyed by idempotency. Retries after “crash after gateway” must reuse the same pi_…, not create a second capture.
---
stuck_processing — sweeper fuel
python
# L139–142
def stuck_processing(self, older_than_ms):
cutoff = now_ms() - older_than_ms
with self.lock:
return [
dict(r) for r in self.keys.values()
if r.get("status") == "processing" and r.get("updatedAt", 0) <= cutoff
]
Rows left processing after a crash header stay here until the sweeper runs. Default sweeper age in code is 8 seconds (STUCK_MS); local /lab/sweep uses older_than_ms=1 so demos heal immediately.
---
What to say
My store keys on tenant#key. First insert wins and sets processing. Complete caches the 201; fail caches the error. Intents are one per key so heal is safe. Webhooks dedupe on event_id.
COMMON MISTAKE: Treating the queue as exactly-once. The queue is at-least-once; the webhook table makes effects idempotent.
Today we see the AWS-backed store. Same method names as MemoryStore. Different durability and locking.
The idea: The interview answer is the state machine. The lab backend is DynamoDB so you can destroy it the same day. In the room you can still say ALB + ECS + Aurora (or any load balancer + app fleet + relational DB).
Source: labs/payrail-idempotency/lambda/dynamo_store.py. *(AWS example only.)*
---
Why this file exists
Local / pytest
Lab on AWS (example)
What you say in interview
MemoryStore
DynamoStore
Same claim / complete / fail / intent / webhook API
Lab cleanup; not part of the interview state machine
Interview translation (vendor-neutral): “I use a conditional insert / unique constraint on (tenant, idempotency_key) so only one worker proceeds to the gateway.”
You do not have to say DynamoDB. You do have to say the claim is atomic and fail-closed on store errors.
---
Complete / fail
Same fields as memory: status, cached responseStatus / responseBody, order id, payment intent id, updatedAt. Implemented with update_item instead of mutating a dict.
Charge does not care. Replay logic lives in charge.py.
Same contract as memory: True = first delivery, False = duplicate.
---
Queue
python
# L105–113
def enqueue(self, message):
if not self.queue_url:
return
self.sqs.send_message(QueueUrl=self.queue_url, MessageBody=json.dumps(message))
def dequeue(self):
return None
Local
AWS example
queue.append / pop(0)
SQS send; Worker Lambda reads Records
dequeue used by local drain loop
Unused here — return None
---
create_intent under contention
python
# L115–137
existing = self.intents.get_item(Key={"pk": pk}).get("Item")
if existing:
return existing
...
try:
self.intents.put_item(Item=intent, ConditionExpression="attribute_not_exists(pk)")
return intent
except ClientError as exc:
if ConditionalCheckFailedException:
return self.intents.get_item(...)["Item"]
Race-safe: two retries after crash still share one paymentIntentId.
---
stuck_processing
Scans keys where status = processing and updatedAt <= cutoff. Fine for a lab table. In an interview you might say “secondary index / query by status and age” — same idea, better ops.
---
What to say in the room
Lab uses a document store with conditional writes for a cheap same-day destroy. Production PayRail I’d put behind a load balancer, run the charge service on a fleet, and store idempotency rows in a relational DB with a unique key — same claim before gateway.
COMMON MISTAKE: Memorizing DynamoDB APIs as the design. Interviewers want the state machine and fail-closed story, not SKU names.
Today we cover the files that finish the story after the happy path: crashes, webhooks, and the mock gateway.
The idea: Timeouts leave rows in processing. You heal from the gateway intent — or mark failed. You never mint a new Idempotency-Key. Webhooks are accepted fast and deduped on event_id.
Sources under labs/payrail-idempotency/lambda/: sweeper.py, worker.py, webhook.py, stripe_mock.py.
---
Map
File
Job
Interview sentence
sweeper.py
Find old processing rows; heal or fail
“Stuck claims resolve from gateway truth.”
worker.py
Process queue messages; dedupe
“At-least-once delivery, exactly-once effects.”
webhook.py
HTTP accept → enqueue
“202 Accepted; work async.”
stripe_mock.py
Thin wrapper on create_intent
“Gateway keyed by tenant + key.”
---
sweeper.py — heal vs fail
python
# L8
STUCK_MS = 8_000
Default: only rows older than 8 seconds. Local demo /lab/sweep passes older_than_ms=1 so you do not wait.
sweep(store, older_than_ms=STUCK_MS)
Step
What it does
1
store.stuck_processing(older_than_ms)
2
For each row, look up intent by pk = tenant#key
3
Intent exists → ensure order, complete_key(…, 201, body with healed=True, …)
4
No intent → fail_key(…, 504, {"error": "sweeper: no gateway intent found"})
5
Return {"healed": [...], "count": N}
python
# L23–49 (shape)
if intent:
order_id = row.get("orderId") or ("ord_heal_" + key[:8])
body = { ..., "healed": True }
if not row.get("orderId"):
store.put_order({ ..., "healed": True })
store.complete_key(tenant, key, 201, body, order_id, intent["paymentIntentId"])
healed.append({"key": key, "status": "completed"})
else:
store.fail_key(tenant, key, 504, {"error": "sweeper: no gateway intent found"})
healed.append({"key": key, "status": "failed"})
Crash lab header
Intent?
Sweeper result
Later same-key POST
After claim
No
failed / 504 cached
Replay failure (x-idempotent-replay: true)
After gateway
Yes
completed / heal
201 replay, same payment_intent_id
Intent lookup works for both backends:
Memory: store.intents is a dict → .get(pk)
Dynamo: table resource → .get_item(Key={"pk": pk}) *(AWS example only)*
On AWS a timer can invoke this. Locally you POST /lab/sweep.
Interview line: After a client timeout I retry the same key (409 while processing). A sweeper or reconciliation job closes the row from gateway truth.
---
worker.py — event_id dedupe
python
# L10–15
def process_event(store, payload):
event_id = payload.get("event_id") or payload.get("id")
if not event_id:
raise ValueError("webhook missing event_id")
first = store.put_webhook(event_id, payload)
return {"event_id": event_id, "duplicate": not first}
Case
put_webhook
Result
First delivery
True
duplicate: False
Redelivery
False
duplicate: True
Missing id
—
Raises ValueError
handler (SQS-shaped event)
python
# L18–24
def handler(event, _context):
store = get_store()
results = []
for record in event.get("Records") or []:
payload = json.loads(record["body"])
results.append(process_event(store, payload))
return {"ok": True, "results": results}
Local drain calls process_event directly — no SQS envelope. Same dedupe function.
Interview line: Queues retry. My webhook table makes side effects idempotent on event_id.
---
webhook.py — accept and enqueue
python
# L10–17
def handler(event, _context):
store = get_store()
payload = _body(event)
event_id = payload.get("event_id") or payload.get("id")
if not event_id:
return _resp(400, {"error": "event_id required"})
store.enqueue(payload)
return _resp(202, {"accepted": True, "event_id": event_id})
Branch
HTTP
Why
No event_id / id
400
Cannot dedupe later
OK
202
Accepted; worker processes async
Does not write the webhook table here. Enqueue only. Dedupe happens in the worker. That split matches “fast ACK, slow work.”
Charge also enqueues a payment_intent.succeeded event on happy path — same queue, same worker path.
---
stripe_mock.py — thin gateway
python
# L5–14
def handler(event, _context):
store = get_store()
tenant = event.get("tenantId") or "demo"
key = event.get("idempotencyKey") or ""
amount = int(event.get("amountCents") or 0)
currency = event.get("currency") or "usd"
if not key:
return _resp(400, {"error": "idempotencyKey required"})
return store.create_intent(tenant, key, amount, currency)
Branch
Result
Missing key
400 via _resp
OK
Dict from create_intent (the intent object; charge’s inline stripe callable returns this same shape)
In unit tests and local charge, Stripe is not this Lambda — it is store.create_intent passed into charge(). This handler exists for the AWS mock path *(example only)*. Either way: one PI per `(tenant, key)`.
---
Crash → sweeper cheat sheet
Client POST + crash header
│
▼
claim → processing
│
┌────┴────┐
│ │
after after
claim gateway
│ │
no PI PI exists
│ │
▼ ▼
sweeper sweeper
fail complete (heal)
504 201 + same pi_
Never: new UUID after 504. That is a second charge at 1,200/s × 2% retries.
---
What to say
Timeouts leave processing. Reconciliation looks at the gateway: intent present → complete with the same PI; absent → fail the key. Webhooks return 202 and dedupe on event_id in the worker.
COMMON MISTAKE: “Client got 504, so generate a new Idempotency-Key.” That bypasses the claim and double-charges.
Same files as the zip. Open one at a time — map the function to the interview sentence.
sweeper.py
python
"""Heal rows stuck in processing (crash after claim)."""
from __future__ import annotations
from charge import get_store
STUCK_MS = 8_000
def sweep(store, older_than_ms: int = STUCK_MS) -> dict:
healed = []
for row in store.stuck_processing(older_than_ms):
tenant = row["tenantId"]
key = row["idempotencyKey"]
pk = store.pk(tenant, key)
intent = None
if hasattr(store, "intents"):
if isinstance(getattr(store, "intents"), dict):
intent = store.intents.get(pk)
else:
intent = store.intents.get_item(Key={"pk": pk}).get("Item")
if intent:
order_id = row.get("orderId") or ("ord_heal_" + key[:8])
body = {
"order_id": order_id,
"payment_intent_id": intent["paymentIntentId"],
"status": "succeeded",
"amount_cents": int(intent.get("amountCents") or 0),
"currency": "USD",
"healed": True,
}
if not row.get("orderId"):
store.put_order(
{
"orderId": order_id,
"tenantId": tenant,
"amountCents": int(intent.get("amountCents") or 0),
"currency": "USD",
"paymentIntentId": intent["paymentIntentId"],
"status": "succeeded",
"healed": True,
}
)
store.complete_key(tenant, key, 201, body, order_id, intent["paymentIntentId"])
healed.append({"key": key, "status": "completed"})
else:
store.fail_key(tenant, key, 504, {"error": "sweeper: no gateway intent found"})
healed.append({"key": key, "status": "failed"})
return {"healed": healed, "count": len(healed)}
def handler(event, _context):
return sweep(get_store())
Appendix — Local and tests20 min
Appendix — Local and tests
Appendix — Local server and tests
Today we see how one process plays every role, and how each pytest catches a real bug.
The idea: Local lab = same state machine as the cloud diagram, zero cloud bill. Tests encode the interview failure modes. If you break the code, a named test fails.
Interview: Gateway already took money; heal must reuse the intent.
---
test_sweeper_heals_stuck_processing
Steps
Asserts
Break this and you get…
Crash after claim, then manually create_intent
—
Simulates intent that appeared without complete
Age row, sweep
count == 1
Stuck forever
Replay charge
201, healed or succeeded
Never leaves processing
Interview: Reconciliation closes the row from gateway truth.
---
How tests map to napkin load
At 1,200/s with 2% retries you get ~24 duplicate attempts per second. Every one of those must hit the replay / 409 / heal paths these tests lock in — not a second claim_key.
---
What to say
I run the same charge function locally with an in-memory store and a drain thread. Pytest proves no double charge, hash conflicts, fail-closed, in-flight 409, webhook dedupe, and sweeper heal. That is the interview state machine in executable form.
COMMON MISTAKE: Demo only the happy 201. Interviewers ask about the 504 path next.