BayLearnBayAreaLa8s

BayLearn Weekend Interview Sprints

System Design Weekend Interview Sprint

Design It. Scale It. Defend It.

Use D-SCALE to clarify requirements, estimate scale, find bottlenecks, evolve the architecture, and explain every trade-off out loud.

  • 4-Hour Live 1:1
  • D-SCALE Framework
  • Real Design Scenarios
  • Practice Question Bank (100+)
  • Mock Interview + Feedback

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.

What You Leave With

  • Interview Readiness Score
  • Top Strengths and Gaps
  • Reusable Interview Framework
  • Real Scenario Practice
  • Mock Interview Score
  • Personalized Feedback
  • Question Bank
  • 7-Day Preparation Plan

Preview the 7-day plan

Four-hour agenda

  1. Hour 1

    Core concepts and interview patterns

  2. Hour 2

    Architecture / coding scenarios

  3. Hour 3

    Hands-on interview challenges

  4. Hour 4

    Mock interview and feedback

Sample interview questions

  • Design a URL shortener for 100M new links per day.
  • How do you estimate QPS and storage before drawing boxes?
  • Where would you place the cache, and what is the invalidation story?
  • How do you explain consistency trade-offs under interview time pressure?

Can you explain these confidently?

Meet Your Interview Coach

Himanshu Bhadra

Enterprise Architect | Cloud | AI | Distributed Systems | Technical Leadership

Learn by designing, building and explaining.

Availability

Private 1:1 · Book on request

Private 1:1 sessions are scheduled after you book. No public cohort dates are listed yet.

Formats: Group Sprint and Private 1:1 Sprint when scheduled.

Book a Free 15-Minute Interview Strategy Call

FAQ

Can I master the topic in four hours?
No. The Sprint is focused interview preparation for people who already have relevant fundamentals or experience.
What happens in the four hours?
Targeted review, scenario practice, hands-on or architecture exercises, and a mock interview with feedback.
Is it live 1:1?
For the premium format, yes. Other delivery modes may be offered separately.
Can I share my job description?
Yes, so preparation can be better aligned to the target role.
Do you guarantee I will pass?
No. BayLearn improves preparation and readiness but does not guarantee hiring outcomes.
What if my interview is next week?
That is the primary use case for the Weekend Interview Sprint.
What if I need more depth?
Use a BayLearn Professional Program for deeper 8–16 week training.
What is the refund policy?
Refund terms are a draft and are not a current offer. They depend on the format you buy. Read the draft at /refund-policy/ before you enroll or book.

Need more than a weekend?

Professional Programs are 8–16 week paths with labs and capstones. Use a Sprint to get interview-ready, then a program if you need deeper mastery.

Explore Professional Programs

Curriculum

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 on Linkly — six sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
D-SCALE
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.

Open the course overview next, then Module 0.

Start here

Start here

Course overview — System Design Interview Sprint

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)

  1. Readiness assessment + debrief — pick two priority gaps
  2. D-SCALE + one capacity napkin (Lab 301)
  3. Two to four spoken prompts from those gaps (not a Module 2/3 tour)
  4. One design challenge: Linkly, ClinicDocs, or TicketDrop
  5. Real 45-minute mock on an unfamiliar prompt
  6. 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 on Linkly — six sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
D-SCALE order
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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

  1. Take a 15-question diagnostic and see seven skill scores (directional, not a hiring forecast)
  2. Learn D-SCALE
  3. Treat building blocks as *selection problems* (ongoing unless the live room needs one)
  4. Run Lab 301, then one live challenge; keep the other canvases for ongoing
  5. Optionally deploy PayRail (701)
  6. Practice from the 108-question bank and the 25-problem set
  7. Run a scored 45-minute scenario mock (not six unrelated essays)
  8. 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 the 15 questions score Seven skills the 15 questions score Requirements Scale Data Architecture Reliability Trade-offs Talk Write down the two weakest. That is the study list. The band does not predict hiring. It tells you where to practice.
Seven skills
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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:

SkillWhat it checksA strong answer sounds like
RequirementsScope before you draw“Paid mapping cannot be lost. Analytics is out.”
ScaleDaily → QPS with units“100M/86,400 ≈ 1,157/s — now I ask about the write shape.”
DataAPIs and keys before the brand“Key = code. Bytes live in object storage.”
ArchitectureThin path, then one box“API, app, KV — then a cache because reads dominate.”
ReliabilityTimeout, retry, what the user sees“If ranking is down, chronological feed.”
Trade-offsWhat you give up“We cache; takedown may linger 60s.”
CommunicationAssumptions 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

ScoreLabelWhat it meansWhat to do next
0–40%FoundationMethod firstD-SCALE + napkin math only
41–60%DevelopingPieces, no glueReplay Linkly on the canvas
61–75%Interview CapableYou can startDrill the two weakest skills
76–90%Ready for Timed PracticeClock is the next gapTimed design + mock
91–100%AdvancedTeach itStaff 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

  1. Close other tabs.
  2. Answer from first principles — do not open the cheat sheet the first time.
  3. Finish all 15. Partial saves do not give a band.
  4. Write the two weakest skills on paper.
  5. 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 the 15 questions score Seven skills the 15 questions score Requirements Scale Data Architecture Reliability Trade-offs Talk Write down the two weakest. That is the study list. The band does not predict hiring. It tells you where to practice.
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.

  1. Draw CDN, cache, shard the photos table, then ask questions if time remains.
  2. Ask who the users are, which 2–3 features are in scope, and what “done” means in 45 minutes.
  3. List every Instagram feature so the design is complete.
  4. 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 — six sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
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 interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.

LetterWhat you write
DAnyone with the link redirects. Logged-in staff create. Done = 201 create, 302 read. Must not lose a paid campaign mapping.
SAssume 400M GET/day ≈ 4,630/s, peak 40,000/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LThe GET path at 40k/s.
ECache-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.

Nonfunctional: availability, latency, durability, consistency, throughput, security, privacy, cost, geographic distribution.

Reusable prompts:

  1. Who is the user, and what is the unit of work?
  2. Which 2–3 features are in scope for 45 minutes?
  3. What does success mean — API accepted, or pipeline complete?
  4. What failure is unacceptable?
  5. What scale should I assume if you do not give numbers?

If they refuse to answer, write assumptions.

COMMON MISTAKE: Treating the product name as a specification.

STAFF-LEVEL EXPECTATION: Negotiate impossible SLOs and name organizational ownership of failure.

S — Size the System

Lightweight estimation, not a spreadsheet.

Estimate: DAU/MAU, peak concurrent users, reads/sec, writes/sec, peak QPS, payload size, daily/annual storage, bandwidth, cache working set.

text

Average QPS = Daily Requests / 86,400
Peak QPS    = Average QPS × Peak Factor
Daily Storage = Writes per Day × Average Object Size

Open the Capacity Estimator. Use a preset, then say the units out loud.

SCALE CHECK: If average and peak differ by ~10×, prefer queues and autoscaling over a box sized for peak.

C — Create High-Level Design

Start simple:

text

Users → DNS / CDN → Load Balancer → Application Services → Cache → Database

Then add a box only when a requirement or a number says you need it.

INTERVIEW TIP: Start simple → identify bottleneck → evolve architecture.

Do not draw Kafka, Redis, Kubernetes, microservices, or sharding without a reason.

A — Analyze Data & APIs

APIs: resources, HTTP methods, idempotency, pagination, auth, versioning, rate limiting.

Data: only important entities, primary keys, secondary indexes, access patterns, hot keys, lifecycle.

The deep lesson is the same six products as high-level design, for the contract: Data and APIs.

ARCHITECTURE DECISION: Design storage around access patterns.

L — Locate Bottlenecks

After each evolution, name the hop that saturates first: a hot key, a primary’s write QPS, a cache stampede, a slow consumer.

E — Evolve & Explain Trade-offs

I picked a queue because peak is 8× average. What I give up is synchronous end-to-end success on the user request.

Open the Trade-off matrix.

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:

  1. Who changes a box?
  2. What two features are in scope?
  3. What does done mean?
  4. What failure is unacceptable?
  5. 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.
D — five questions before any box D — five questions before any box 1. Who? users / actors 2. What? 2–3 features 3. Done? success 4. Fail? cannot lose 5. Scale? assume Write assumptions if they will not answer then design to those numbers The product name is not a spec. Instagram is not a design.
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.

Jump: Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop

1. Linkly · short links

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.
Linkly — write the five answers before any box Linkly — write the five answers before any box 1 Who? Readers (GET) Staff (POST) Crawlers + bots Bots change POST 2 In scope? Create + redirect Optional slug Analytics out Swap, do not stack 3 Done? 201 + code 302 on GET Work is 1 ms No 301 if takedown 4 Cannot fail Lose paid mapping 301 cached forever Forces durable KV + invalidate 5 Scale 400M GET/day ≈ 4,630/s avg Peak ~40k/s Creates ≈ 23/s Say this (write ASSUMPTION if they shrug) Anyone with the link redirects. Staff create. Done is 201 and 302. Must not lose a paid code. I assume 400 million GET/day unless you correct me. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
Linkly D-board: who, scope, done, failure, labeled scale

1. Who?

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.
PulseFeed — write the five answers before any box PulseFeed — write the five answers before any box 1 Who? Logged-in readers Ordinary authors One 12M celebrity Celeb changes writes 2 In scope? Publish + home Not ads / live / DMs Likes may lag Swap, do not stack 3 Done? 201 on publish Home is fast Fan-out later Not 12M sync writes 4 Cannot fail Empty home on GET Sync 12M fan-out Forces hybrid + cached timeline 5 Scale 80M DAU Posts ≈ 185/s Reads peak 150k/s Ratio ≈ 150:1 Say this (write ASSUMPTION if they shrug) I design publish and home for 80 million DAU. Ads and live are out. Likes can lag. I will not fan-out 12 million writes on publish. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
PulseFeed D-board: who, scope, done, failure, labeled scale

1. Who?

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.

5. What scale should we assume?

On the board: ASSUMPTION: 80M DAU, 16M posts/day ≈ 185/s, ~30 feed opens/user/day ≈ 28k reads/s, peak ~150k/s, read:write ≈ 150:1.

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.
RideHail — write the five answers before any box RideHail — write the five answers before any box 1 Who? Rider + driver Dispatch Payments later Two SLOs 2 In scope? Latest location Request / match Pricing ML out No forever pings 3 Done? Map shows nearby Trip row commits Pay after drop-off 4s stale is OK 4 Cannot fail Charge twice Ledger on pings Append 1.3 TB/day Two stores 5 Scale 300k / 4s = 75k writes/s Trips ≈ 17/s Overwrite latest Say this (write ASSUMPTION if they shrug) Pings and payments are two products. I overwrite latest. I will not charge twice. I assume 300k drivers pinging every 4 seconds. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
RideHail D-board: who, scope, done, failure, labeled scale

1. Who?

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.
PayRail — write the five answers before any box PayRail — write the five answers before any box 1 Who? Cardholder Merchant + finance Fraud is batch Retrying phone 2 In scope? Authorize + capture One ledger row Rewards / FX out Email off path 3 Done? 201 + chargeId Same key = same $ Not “email sent” Primary on GET 4 Cannot fail Two $49 captures Retry without key Replica after write Forces the key 5 Scale 8M/day ≈ 93/s Peak 1,200/s p99 < 400 ms 2% → 24 retries/s Say this (write ASSUMPTION if they shrug) Done is a ledger row, not an email. I require an Idempotency-Key. I assume 1,200 authorize/s at noon. I will not shard yet. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
PayRail D-board: who, scope, done, failure, labeled scale

1. Who?

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.
ClinicDocs — write the five answers before any box ClinicDocs — write the five answers before any box 1 Who? Clinic uploader Scan workers Clinician / patient Auditor + PHI 2 In scope? Upload + status Download clean Not a full EHR Search may lag 3 Done? 202 accepted Clean in ≤ 60s Not 201 public Status API 4 Cannot fail Serve landing Bytes in a row DB PHI in logs Private origin 5 Scale 80k/day ≈ 0.93/s Peak ~19/s 3 MB · 240 GB/day 8s → 152 in flight Say this (write ASSUMPTION if they shrug) This is a pipeline, not internet scale. Upload returns 202. Scan is behind a queue. Serving landing is unacceptable. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
ClinicDocs D-board: who, scope, done, failure, labeled scale

1. Who?

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.

5. What scale should we assume?

On the board: ASSUMPTION: 80k files/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, scan 8s → ~152 in-flight, ~88 TB/year.

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.
TicketDrop — write the five answers before any box TicketDrop — write the five answers before any box 1 Who? Fans Bot farms Box office Seats are scarce 2 In scope? Room + hold + pay Decrement once Season tickets out Checkout closed 3 Done? Inventory once Seat or clear miss 200 ≠ decrement Same hold id 4 Cannot fail Oversell 80,001 500k at checkout Retry new hold Inventory gates 5 Scale 80k tickets 500k in the room Admit ~3k/s Checkout ~30s Say this (write ASSUMPTION if they shrug) I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate. Retry the same hold id. The product name is not a spec. Two minutes of D saves twenty minutes of Kafka-for-23-writes/s.
TicketDrop D-board: who, scope, done, failure, labeled scale

1. Who?

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.

Cards under the diagram walk all five questions on each teaching product: Linkly, PulseFeed, RideHail, PayRail, ClinicDocs, TicketDrop. Write the answers on the board.

The five questions (why they exist)

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:

DriverExampleBox it changes
LatencyLinkly p99 GET < 200 msCache, region
Pipeline timeClinicDocs clean ≤ 60sQueue + workers
ConsistencyPayRail no double captureSingle writer + key
Data classClinicDocs PHIPrivate origin, no PDF in logs
FairnessTicketDropWaiting 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:

  1. What is the average QPS — daily requests divided by 86,400?
  2. What is the peak — average times a peak factor?
  3. 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.
S — three real napkin sheets (units on the board) S — three real napkin sheets (units on the board) Linkly redirects 400,000,000 / 86,400 ≈ 4,630 GET/s average × 8.6 peak ≈ 40,000/s Value ≈ 200 B Hot 1% of codes = most hits Cache first, not 40k DB/s ClinicDocs pipeline 80,000 / 86,400 ≈ 0.93/s 70% in 8h ≈ 1.9/s 10× peak ≈ 19/s 3 MB × 80k = 240 GB/day 8s scan × 19/s ≈ 152 inflight Queue + N workers, not one box RideHail pings 300,000 drivers / 4s = 75,000 writes/s peak 200 B × 75k ≈ 15 MB/s ≈ 1.3 TB/day if you keep all Keep latest point, not history TTL / overwrite by driverId Stop rule 1,157 vs 1,200 does not change a box. 12/s vs 12,000/s does. 75k writes/s is a different store than 23 creates/s. Always say 86,400, object size, and peak factor. Label the sheet ASSUMPTION.
Three real napkin sheets
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.

MathNumberWhat it changes
400e6 / 86,400≈ 4,630 GET/s averageAlready more than a casual single-node demo
Peak × 8.6 (morning news)≈ 40,000 GET/sCache or you melt the KV
2e6 / 86,400≈ 23 POST/sCreates do not need a stream
400e6 × 200 B≈ 80 GB/day of readsReads, not storage; mappings stay tiny
One viral code50,000 GET/s for 10 minOne key. Sharding does not help

You say: “Reads are the product. I cache. I will not draw Kafka for 23 creates a second.”

ClinicDocs (hospital PDFs)

Assumption: 80,000 files/day, 3 MB average, doctors want search in 60 seconds, scanner takes 8 seconds.

MathNumberWhat it changes
80,000 / 86,4000.93/s averageThis is not “internet scale”
70% in an 8-hour clinic day≈ 1.9/s (56k / 28,800)Still small
10× burst when clinics open≈ 19/sQueue, not a bigger API box
80k × 3 MB240 GB/dayObject store, not a row store
365 × 240 GB≈ 88 TB/yearLifecycle / cold storage
19/s × 8 s scan≈ 152 in-flightWorker count, not a logo

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.

MathNumberWhat it changes
300,000 / 4 s75,000 writes/sA different store than trip checkout
75k × 200 B≈ 15 MB/s ≈ 1.3 TB/day if you keep every pingYou must overwrite latest point
1.5e6 / 86,400≈ 17 trip starts/sThat path can be transactional
Keep 15 minutes of pings75k × 200 B × 225 ≈ 3.4 GB ringWarehouse 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.

MathNumberWhat it changes
16e6 / 86,400≈ 185 writes/sPublish is modest
80e6 × 30 / 86,400≈ 27,800 feed reads/sReads dominate
Peak morning × 5.4≈ 150,000 reads/sCache + precompute
Read:write≈ 150:1Fan-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.

MathNumberWhat it changes
8e6 / 86,400≈ 93/s averageEasy if you are not silly
Peak1,200/sStill one well-run primary *if* the query is simple
2% retries+24/s duplicatesWithout 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

  1. Scroll to Capacity napkin on this lesson (same widget also sits on Size the system).
  2. Run Linkly. Write avg QPS, peak QPS, and miss QPS (92% hit) on paper.
  3. Run ClinicDocs. Write daily bytes, peak files/s, and in-flight scanners.
  4. Run PayRail. Say whether 1,200/s forces a shard.
  5. 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 computeFormulaWhy it matters
Average QPSdaily volume / 86,400Shared scale with the interviewer
Peak QPSaverage × peak factorThe box you provision for
Write QPSwrites per day / 86,400Separate from read QPS
Daily byteswrites × object sizeDatabase vs object store
Yearly bytesdaily bytes × 365Lifecycle, not one disk
In-flightpeak QPS × work secondsQueue depth / holds / scanners
Cache miss QPSpeak × (1 − hit%)What actually hits origin

Stop when another decimal will not change a box.

Expected napkin (labeled assumptions)

ProductHeadlineWhat you should see
Linkly400M GET/day, 200 B, 92% hit~4,630/s avg, ~40k/s peak, ~3,200 miss/s
ClinicDocs80k × 3 MB, 8s scan240 GB/day, ~19/s peak, ~152 in-flight
PayRail8M/day, peak ×13~93/s avg, ~1,200/s peak
RideHail300k × ping/4s75k writes/s — overwrite, do not append
PulseFeed16M posts, ~2.4B feed reads~150:1 read:write — fan-out or cache the timeline
TicketDrop500k in the room, admit 3k/sWaiting 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:

  1. What is the thin path — users, door, app, store?
  2. Which hop is busy, and what number proves it?
  3. 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

WordMeaning
QPSHow many requests per second
Front door / APIWhere the user’s request enters
Store of recordThe official copy of the data
CacheA fast copy used to take load off the official store
QueueA waiting line so slow work does not block the user
What you give upThe cost of the box you added
Gold boxOn implementation boards: the official store, or the runtime piece a number buys
Dashed arrowReply, or work that happens later (email, fan-out, scan) — not “done”
SequenceWho talks to whom, in order. Top banners are trust boundaries
Second line on a boxAn AWS example. Other clouds and datastores are valid
PlacementWhere a box runs: public subnet, private subnet, or regional managed
Two AZsTwo buildings. If one dies, the other still serves
RPOHow much data you may lose if a region dies
RTOHow long until you serve again
SLOThe promise you page on (one journey)
Hot keyOne id that takes all the traffic — sharding that id does nothing

How to draw (every product)

  1. People on the left (who uses this).
  2. One request across the middle. If it is really two products (RideHail map vs trip), draw two pictures.
  3. The official store on the right.
  4. Write the busy number on the hottest arrow.
  5. 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.

Jump: Building blocks · 8-minute script · Second region

Jump: Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop

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:

  1. What two or four APIs do we expose — verb, path, success, failure?
  2. What is the lookup key, and is it a hot key?
  3. 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

WordMeaning
Lookup keyWhat you look the official row up by
IdempotencySame retry key returns the same row
CursorA continuation token, not a page number
201The official row exists
202Accepted. Work happens later
302Redirect I can still turn off
301Browser caches forever — Linkly disable dies
Gold boxOfficial row, or the contract that stops a double write

How to write A (every product)

  1. Two or four APIs: verb, path, success code, failure code, who may call it.
  2. Name the lookup key. One hot-key sentence.
  3. Write the QPS (or bytes, or in-flight work) on that key.
  4. 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.

Jump: Matrix · Blank sheet · Codes · Retry · Method

Jump: Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: Data and APIs one-pager

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

Product2 APIsKeyHot keyStore instinctReplay
LinklyGET /{code} 302 · POST /v1/urls 201codeviral code 50k/sKV + cacheoptional key / hash(url+owner)
PulseFeedPOST /v1/posts 201 · GET /feed?cursor=postId · Home userIdcelebrity authorids cache, not a joinoptional client key
RideHailPUT /location · POST /tripsdriverId vs tripIddowntown celltwo storesPUT replace · pay key
PayRailPOST /charges + header · GET by idmerchant + key · chargeIdnot a shard storyone primarysame key → same chargeId
ClinicDocsPOST 202 · signed GET when cleanfileIdnone at 19/sSQL pointer + objectsoverwrite landing
TicketDropstatus · POST /holds · checkoutholdId · seatone show lockcached status ≠ inventorysame holdId · 410 gone

Codes

CodeMeansUse
201Official row existsPost, charge, code, hold
202Accepted, work laterClinicDocs upload
302Redirect I can turn offLinkly. Never 301
409In flight, same keyPayRail processing
410Gone. Stop.TicketDrop sold out
429Mint limiterBots / 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:

  1. At the peak we wrote under S, which hop saturates first?
  2. What one fix unsticks that hop?
  3. 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

WordMeaning
LFirst hop to die at the peak you wrote under S
EOne evolve plus what you give up
Gold boxStore of record, or the piece a number buys
What you give upSeconds, dollars, or staleness — not a vibe
202Accepted. Work happens later. Not “done”
Hit ratioA number. Miss QPS = peak × (1 − hit)

How to walk L then E

  1. Finger on a hop. “If traffic is the peak we wrote under S, which box saturates first?”
  2. Add one fix that unsticks that hop — cache, queue, key, split, waiting room.
  3. Say what you give up, with units.
  4. 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.*

Jump: Locate · L→E · Blank sheet · Six products · 60s script

Jump: Database · Communication · Consistency · Compute · Cache · Replication · Processing · Reads · APIs · Delivery · Drills

Printable: Trade-off matrix one-pager

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.

DecisionABDiscussion
DatabaseSQLNoSQL / KVTransactions and relations vs access-pattern scale
CommunicationSyncAsyncEnd-to-end errors vs buffering and retries
ConsistencyStrongEventualCorrectness vs availability and lag
ComputeMonolithMicroservicesOne failure domain vs independent scale
CacheNoneCacheFreshness vs origin offload (hit ratio is a number)
ReplicationSingle regionMulti-regionHA in-region vs DR / locality
ProcessingImmediateQueueUser waits vs load leveling
ReadsPrimary onlyRead replicasRead-your-writes vs read scale with lag
APIsOffset pagesCursorsJump-to-page vs a moving list
DeliveryAt-most-onceAt-least-onceLoss 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 sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
D-SCALE on Linkly
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.

Six assumptions (erase if they give telemetry)

WorkloadThe number you writeFirst box it implies
Linkly400M GET/day → 4,630/s, peak 40k/s, 23 POST/sCache, not a stream
PulseFeed16M posts/day → 185/s; feeds 28k/s (peak 150k/s)Fan-out / cache, not write shards first
RideHail300k drivers × ping/4s → 75k writes/sOverwrite latest, do not append
PayRail8M/day → 93/s, BFCM 1,200/s, p99 < 400 msIdempotency, one primary
ClinicDocs80k × 3 MB → 240 GB/day, ~19/s, scan 8s → ~152 in-flight202 + queue + object store
TicketDrop80k seats, 500k in room, admit ~3k/sWaiting room, not 500k checkout QPS

45-minute reminder

45 minutes — what should be on the board 45 minutes — what should be on the board 0–5 D Actors, done, fail Analytics out Paid mapping stays 5–10 S 400M → 4,630/s Peak 40k/s 23 POST/s · 200 B 10–20 C+A API → app → KV GET /{code} key = code 20–30 L 40k/s on KV Cache 92% 3,200 miss/s 30–38 Timeout 80ms Cache down? Degrade + shed 38–45 Loser: 60s Two-minute close If the prompt is ClinicDocs, minute 8 is 240 GB/day and 152 in-flight — not 40k GET/s. If they say peak is 20×, erase and recompute. Do not add logos after minute 40. The clock is part of the design. Leave five minutes to close.
Clock with Linkly beats

Do not still be drawing new logos at minute 40.

INTERVIEW TIP: Write D-SCALE in the corner. Tick each letter. Write 86,400 under S.

COMMON MISTAKE: A seventh letter called “add Kafka.”

One-page cheat sheet

One-page cheat sheet

System Design Interview Cheat Sheet

BayLearn · System Design Interview Sprint

  • Scope 2–3 features. Write assumptions.
  • Average QPS = daily requests / 86,400. Peak = average × peak factor.
  • Draw users → edge → app → cache → store. Add queues only for spikes or slow work.
  • Storage follows access patterns. SQL vs NoSQL is a requirement, not a slogan.
  • Cache-aside is the default read optimization. You still owe invalidation.
  • Assume at-least-once. Make handlers idempotent. DLQ after a retry budget.
  • Timeouts + jittered backoff + circuit breaker + degradation.
  • 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 — six sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
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)

LetterOne breath with a number
DAnyone redirects. Staff create. Do not lose a paid mapping. Analytics out.
S400M/86,400 ≈ 4,630 GET/s, peak 40k/s, 23 POST/s, 200 B
CUsers, door, app, KV. No extras yet
APOST /v1/urls, GET /{code}, key = code
LAt 40k/s the KV dies first
ECache 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.

Lab: Lab 302 — Changed telemetry (LAB-SD-302) — use the live widget on that lesson.

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.

AssumptionValue
ProductShort links for a regional publisher
Redirects / day90 million
Creates / day8 million
Average mapping size80 bytes
Peak storyMorning homepage, interviewer says “about 3× average unless you justify another factor”
Prior architecture you are allowed to rememberAPI → app → KV + optional cache (from Lab 401). You must validate it against these numbers.

What you must produce

  1. Average GET rate (requests / second) with units
  2. Peak factor you will use, and why
  3. Read / write ratio
  4. First bottleneck
  5. Does the previous thin architecture still hold? Yes/no + one sentence
  6. What you would change, if anything
  7. 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:

  1. How people find the site (the address book).
  2. Whether a saved copy nearby actually helps.
  3. How often that copy is enough (a percent) — and why, if that percent is low.
  4. 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

WordPlain meaning
DNSThe internet address book. You type a name, you get an address
DoorThe address DNS gave you — the app, the CDN, or the load balancer. Say which
Three clocksDNS timer = old door. CDN timer = saved copy nearby. 301 / browser = that phone remembers
Three doorsDNS finds one door. CDN = saved copy nearby. Load balancer = the front desk inside
CDNA saved copy nearby — like a photo already on your phone so you don’t re-download every time
HitYou already have the file nearby. Fast
MissFetch from the main server / original files. Then keep a copy for next time
Cache keyWhat makes two requests “the same file.” Extra junk in the URL can ruin the percent
OriginOriginal files / main server. Keep it locked
Signed URLA ticket that expires
302A redirect I can still turn off
301Browsers remember forever. Linkly cannot turn that off

How to walk this (every product)

  1. Name the door (DNS, not the load balancer) and which TTL you mean.
  2. Ask: is this the same file for everyone? If yes, a saved copy nearby may help.
  3. Say the hit percent. If the file is large, also say how much traffic still hits the main server.
  4. If the hit percent is low, say why — often a bad cache key — before you keep the CDN.
  5. Say what you will not cache (money, login, dirty files, live location pings).
  6. 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.

Jump: Two jobs · Address book · TTL · Three clocks · New door · Nearby door · Three doors

Jump: The percent · Pipes · Bad key · Herd · Refuse list · Main server · New ticket · Blank sheet · 60s script

Jump: Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: DNS and CDN one-pager

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.

WordPlain meaning
DNSAddress book. Name → address
Three clocksDNS TTL = old door. CDN TTL = saved copy nearby. 301 = that phone
Three doorsDNS = one door. CDN = saved copy nearby. Load balancer = front desk
Hit / missAlready have it nearby / fetch from main server
Cache keyWhat makes two requests the same copy. ?utm= can ruin the percent
OriginOriginal files / main server. Lock it
301Browsers 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

ProductCDN?TTL instinctNever cache
LinklyMaybe the 30260s, never 301Mapping in DNS
PulseFeedPhotos yesHours + new filenamePrivate Home
RideHailTiles maybeOne city doorLive location
PayRailNo on moneyAPI door 60sCapture / authorize
ClinicDocsClean + ticketMinutesLanding files, open bucket
TicketDropPoster yesVersioned artHold / “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

WordPlain meaning
Traffic directorThe load balancer. It sends each person to the next free helper (server copy)
HelperOne server copy
PairTwo traffic directors. If you have only one and it dies, nobody gets in
Layer 4Cannot read URL details. It sees the connection, not the path
Layer 7Can read the path. It unwraps HTTPS to do that. Use this for our APIs
HealthyThe helper can still do the real job — the database is up, not just “the process is running”
Sticky / glueAlways the same helper (fragile if that helper is down)
Front-door rulesThe 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 timersDatabase, then the app, then the user’s client. The inside one should finish first
RetryRetry a simple read once. Do not let the traffic director send a payment twice
DrainLet current requests finish, then take the copy out
Fail closedIf every copy is sick, stop and show an error. Don’t guess
Warm-upA new copy needs a few minutes before it is ready
Spare copyPlan so one copy can be down and you still keep up

How to walk this (every product)

  1. How many copies? Peak requests per second ÷ what one copy can handle. If one down is too much for the rest, add a spare.
  2. Run two traffic directors. DNS found the address; it is too slow to be the backup.
  3. Health must check the database. If all copies fail, return 503, not 429, and don’t send traffic anyway.
  4. 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.
  5. The gateway adds front-door rules. It is not PayRail’s money and not TicketDrop’s seats.
  6. The database timer should finish first. Retry a read once. Never let the traffic director retry a payment.
  7. 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.

Jump: Two jobs · Traffic director · A pair · L4 vs L7 · Real health · How many · No glue · Long connections · Front-door rules · 429 vs 503 · Three timers · No hidden retry · Drain

Jump: Blank sheet · 60s script · Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: Load balancing one-pager

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.

WordPlain meaning
Traffic directorLoad balancer — next free helper
HelperOne server copy
PairTwo traffic directors, not one box
L4 / L7Cannot read URL details / can read the path
HealthyHelper can still do the real job (DB up)
StickyAlways the same helper (fragile if down)
Front-door rulesGateway: login, rate limits, size — not the money ledger
429 vs 503Please wait vs nobody can help
Three timersDatabase, then app, then client. Inside one first
RetryRetry a simple read once. Don’t retry a payment
DrainWait 30–60s, then take the copy out
Fail closedIf every copy is sick → 503
Spare copyPlan 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

ProductCopiesHealthSticky?Front doorDon’t do this
Linkly20 at 40k/sKey store upNo429 on createSession in one copy
PulseFeedMany readersFeed pathNo on Home429 on publishLoad balancer as photo CDN
RideHailPings ≠ tripsPer pathLong calls: say itLogin on tripOne pool for both
PayRailFewer, 1,200/sLedger upNoRetry key + 60/minTraffic director retries payment
ClinicDocsSmall APIAPI onlyNoUpload ticketPDF through JSON
TicketDropMany pollsStatus ≠ seatNo cart in memory1 poll / 2sLoad 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

WordPlain meaning
One appOne deployable unit. Monolith is honest if it is the only app
ModulesFolders inside one app. Same deploy today, easy to extract later
Separate appsSplit because scale or failure differs — 75k pings vs 17 trips — or a stable team boundary
Too many appsNeeds a platform team. Not the first cut
Short functionOften a 15s limit. Runs for one job, then stops
Always-on serverA container. Stays up. Better for 8s work that may grow to 90s
Live requestThe user is staring at a spinner
Background jobThey can leave (scan, receipt)
EventOne fact many apps may read
Official recordMoney, seats, or mappings. Usually one commit
Shared databaseStill one system if “services” share it
API contractMust stay boring to split teams
Hold + expireIf two apps must agree: reserve with a clock, then give it back
Two knobsTwo scale controls. ClinicDocs API on QPS, workers on queue age
Chain of waiting callsFake split. Home waits on rank waits on ads…

How to walk this (every product)

  1. What is the simplest one app? One deploy, or modules inside one deploy.
  2. 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.
  3. 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.
  4. Where is the official record? One commit, or hold-then-expire. Do not invent a shared transaction across apps.
  5. Is the database shared? If yes, you did not really split.
  6. How does it run? Short function vs always-on server. Say the timeout. Same boxes either way.
  7. 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.

Jump: Start simple · One app · Modules · Three reasons · Too many apps · Short vs always-on · Live vs background · Waiting chain · Two knobs · Official record · Hold · Shared DB · Contract · No session glue · 15s limit

Jump: Blank sheet · 60s script · Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: Application services one-pager

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.

WordPlain meaning
One appOne deployable unit (monolith is honest)
ModulesFolders inside one app
Separate appsSplit when scale or failure differs (or stable team boundary)
Short function / always-onOften 15s limit / container that stays up
Live / backgroundUser is waiting / they can leave
Official recordMoney, seats, or mappings in one place
Shared databaseStill one system
API contractMust stay boring to split teams
Hold + expireReserve with a clock if two apps must agree
Two knobsTwo scale controls; can share one repo
Waiting chainFake 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

ProductShapeSplit?TalkOfficial record / DBDon’t do this
LinklyOne appLater if deploys fightLiveOne mapTwo companies for GET vs POST
PulseFeedWrite + built HomeIf hops growBackground + copyFeed is a copy12-hop live chain
RideHailTwo apps75k vs 17Cheap ping; strict tripTwo databasesOne fate for both
PayRailModules, one recordEmail onlyLive $49; background mailOne ledgerBlock capture on SMTP
ClinicDocsTwo knobs, one repoProcess, not company202 + backgroundMetadata vs bytes8s on HTTP; 15s function for 90s
TicketDropOne record or holdOnly if pay is elsewhereHold clockSeats are the gateForty 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:

  1. Hit percent — how often the quick saved lookup helps.
  2. Miss QPS — how hard the official record still works.
  3. Stampede — what happens when one hot key expires (whole class refreshes grades at once).
  4. 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

WordPlain meaning
Quick saved lookupThe cache. Fast, maybe stale, maybe gone. Not the official record
Official recordThe database. Misses land here
HitFound the lookup
Miss QPSPeak × (1 − hit ratio). This is what the official record must survive
LayerBrowser, CDN, app RAM, shared cache, DB buffer. Name which
Cache-asideApp asks lookup → miss → official record → fill → return. Good default
Read-throughThe cache layer loads the official record. Retries can hide here
Write-throughWrite hits lookup and official record together. Safer, slower writes
Write-behindWrite the lookup; official record later. Fast. Can lose money
TTLHow long the saved copy is allowed to live
JitterRandomize TTL so keys do not die as a herd
StampedeWhole class refreshes grades at once — one hot key expires; thousands miss together
InvalidateDelete the saved lookup on write or DELETE
Hot setThe small slice that actually moves hit %. LRU drops the rest
LabelThe cache key. Private data needs userId

How to walk this (every product)

  1. What is copied, and which layer? CDN vs this cache vs app RAM.
  2. Miss QPS = peak × (1 − hit). Does the official record still live?
  3. Pattern: cache-aside unless the copy must match before you return. Never write-behind for money.
  4. TTL as a number. Jitter. Delete the key on write. Stampede: lock or serve stale 2s.
  5. Key: public vs userId. Maybe cache “not found” for junk.
  6. Hot set size. Do not cache 100% of cold keys.
  7. If the cache dies: fall through, watch QPS, shed or serve stale. The cache was never the official record.
  8. 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.

Jump: Quick saved lookup · Miss QPS · Which layer · Cache-aside · Through · Write-behind · TTL · Jitter · Stampede · Delete the saved lookup · The label · Hot set · Cache dead · Refuse

Jump: Blank sheet · 60s script · Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: Cache patterns one-pager

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.

WordPlain meaning
Quick saved lookupCache — fast, maybe stale
Official recordDatabase. Misses land here
Miss QPSPeak × (1 − hit). Linkly 40k × 8% = 3,200/s
Cache-asideAsk lookup → miss → record → fill → return
Write-throughWrite lookup and record together
Write-behindWrite lookup, record later — not for money
TTL + jitterHow long the saved copy may live; do not expire as a herd
StampedeWhole class refreshes grades at once; lock or serve stale 2s
InvalidateDelete the saved lookup on write
Hot setSmall 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

ProductWhatHit / missTTLDon’t do this
LinklyRedirect map92% → 3,200 miss/s60s + delete key301; cache as the map
PulseFeedBuilt Home (userId)Reads from copy10–30sLikes as a ledger; photos in Redis
RideHailPing store already 30sSkip second lookupOverwrite is the clock1.3 TB/day in Redis
PayRailProfile / token onlyCapture: no cacheShort on profileWrite-behind $49
ClinicDocsStatus onlyTinyFew secondsPHI / PDF in Redis
TicketDropPoll “wait” maybeSeats: no cacheVery short if at allStale “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 the store from the lookup, not the logo Pick the store from the lookup, not the logo SQL / relational joins · transactions · flexible queries NoSQL / key-value or document known key · high throughput · denormalize Ask: what is the primary key? do we need a transaction? a join? a search? NoSQL is not automatically more scalable. A well-indexed SQL primary can go far.
Pick from the lookup
More shards do not fix one celebrity key More shards do not fix one celebrity key PulseFeed celeb 1 post → 12M followers or 1 profile GET at 80k/s Hash(userId) All 80k/s land on one shard other 99 shards idle Fix 1 — cache Cache the profile 92%+ hit TTL 5–15s Fix 2 — split key photo vs count or local cache on every app When you do shard Shard PayRail by merchantId or chargeId once a single primary cannot take ~1k–3k complex writes/s. Name who owns the map. Reshard is a project, not a checkbox. If one key is the fire, adding nodes is rearranging furniture.
Hot key

Two questions first

  1. How do we look this up? One key? Range? Join? Full-text?
  2. 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.

PathAccessQPS (assumption)Store instinctWhy not the other
Linkly redirectcode → url40k GET/s (cached to 3.2k)KVJoins do not exist
PayRail chargeinsert + unique key1,200/s peakSQL or transactional KVNeed unique + state machine
PulseFeed follow graphmany edges185 posts/s, huge readsGraph *or* two tables + cacheDo not join 12M rows on GET
ClinicDocs metadatafileId, patientId19/sSQLBoring is correct
ClinicDocs bytesblob 3 MB57 MB/s peakObject store240 GB/day in rows is pain
RideHail latestdriverId overwrite75k/sIn-memory / specialized KVSQL UPDATE 75k/s is a fight
TicketDrop inventorydecrement seatburstSQL row or atomic counterRace = 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:

ShapeOften comfortableTime to rethink
Single SQL primary, simple writeshundreds–low thousands/sPayRail 1,200/s is in-range; 20k/s complex joins are not
Single KV node, 200 B getstens–hundreds of thousands/sLinkly 40k uncached is the danger; cached 3.2k is calm
Object store PUTsthousands/s with parallelismClinicDocs 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 trueStart with
GET by primary key, huge QPSKV + cache
Orders + money must commitRelational
Feed “latest N for user”KV / time-ordered table + cache
Users type wordsSeparate search index
3 MB blobsObject store + pointer
Analytics for five yearsWarehouse, 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:

  1. Which shape is this — to-do inbox, group announcement, or scrollable history?
  2. How many jobs are sitting in the inbox right now? (That is QPS × time.)
  3. 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.

Common mix-ups we will clear up:

  • 202 means “we got it,” not “we finished.”
  • In-flight = peak QPS × time. ClinicDocs 19/s × 8s ≈ 152. At 90s ≈ 1,710.
  • 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

WordPlain meaning
To-do inboxQueue. One job. Workers take turns
Group announcementPub/sub. One update, everyone gets it
Scrollable historyStream / log. Catch up / replay
User waitsLive request. No buffer (Linkly 302, PayRail capture)
Background jobAsync. User can leave the page
202We got it. Not we finished
In-flightPeak QPS × processing time. How many jobs sit in the inbox
At-least-onceThe same job can show up twice. Default
Unique keySame order id / receipt — retry does not double-do
Claimed timeVisibility timeout. Job stays claimed for N seconds. Longer than the job
Failed-jobs folderDLQ. After 3–5 tries, park poison. Alarm on depth
AgeHow long the oldest job has waited
Ledger then inboxSave the official record / DB row, then drop the inbox job
SkipNo broker on a 2 ms path, and no 1.3 TB ping history

How to walk this (every product)

  1. Shape: to-do inbox, group announcement, scrollable history, or user waits?
  2. In-flight = QPS × time. Does a 15s stall still fit?
  3. 202 vs finished. Who is waiting?
  4. Twice: assume at-least-once. Name the unique key. Claimed > job. DLQ after 3–5. Alarm on age.
  5. Order per key, not global. Replay only if you named the day count.
  6. Official record first, then enqueue.
  7. 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.

Jump: Three shapes · To-do inbox · Group announcement · Scrollable history · In-flight · 202 · Twice · The key · Claimed time · DLQ · Age · Order · Ledger then inbox · Skip

Jump: Blank sheet · 60s script · Linkly · PulseFeed · RideHail · PayRail · ClinicDocs · TicketDrop · Drills

Printable: Messaging one-pager

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.

WordPlain meaning
To-do inboxQueue. Workers take turns
Group announcementPub/sub. Everyone gets the same update
Scrollable historyStream. Order per key. Replay is a project
User waitsLive request. No buffer
Background jobAsync. User can leave
In-flightPeak QPS × time. ClinicDocs 19 × 8s ≈ 152
202We got it, not we finished
At-least-onceDefault. Same job can show up twice
Unique keySame order id / receipt. PayRail 1,200/s × 2% ≈ 24 replays/s
Claimed timeVisibility > job. 8s scan → 30–60s
Failed-jobs folderDLQ. 3–5 tries, then park. Alarm
AgeOldest job. Depth lies
Ledger then inboxSave 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

ProductShapeIn-flightTwiceDon’t do this
LinklyUser waits; no broker23/s × 2 ms < 1N/A on 302Kafka on create or GET
PulseFeedAnnounce; history if replayNot 12M inlinePost idFan-out-on-write 12M homes
RideHailOverwrite ping75k last-pointLast write wins1.3 TB/day ping history
PayRailUser waits $49; inbox mailMail 1,200 × 0.2s ≈ 240Idempotency-KeySMTP on authorize
ClinicDocsTo-do inbox scan19 × 8s ≈ 152fileId8s on HTTP; 15s stall at 90s
TicketDropRoom + inbox confirm10:00 burstHold / email key500k 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 live in object storage. Search is an index, not the record. Bytes live in object storage. Search is an index, not the record. Upload Object store the bytes Metadata DB id · owner · status Search index lags · not official Download pointer index later Do not put PDFs in the database. Do not treat search as the system of record.
Bytes vs index
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
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

AssumptionNumber
80,000 × 3 MB240 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

ThingWhere
3 MB PDF / 400 KB photoObject store
status, owner, ACLMetadata DB
Full-text findSearch index (lags)
Linkly mappingKV row
Card PANNever 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 interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.
Basic scalable web architecture Basic scalable web architecture 1 Users 2 DNS / CDN 3 Load balancer 4 App services 5 Cache 6 Database 1 Users 2 DNS/CDN 3 Load balancer 4 App 5 Cache 6 Database
Baseline

One-line why (with the workload that proves it)

BlockWhy it existsNumber / ruleTypical cost
DNSFind the doorTTL 60s ≈ 1 min failover24h TTL sticks
CDNCacheable bytes near the userPulseFeed photo 90% hitExtra hop at 20% hit; never cache PayRail POST
Load balancerHealthy, stateless copiesLinkly 20 copies × 2k/sSticky RAM at 40k/s
AppRulesStateless; bytes not on diskSnowflake boxes
CacheHot copies + TTL + miss path92% hit → 3,200 miss/sStale takedown
SQL / NoSQLAccess pattern + transactionsPayRail ledger vs Linkly codeWrong store = painful queries
Queue / stream / pub/subAsync, fan-out, or replayClinicDocs 19/s × 8s = 152Duplicates; no sync “done”
Object storeBytes. DB holds the pointer240 GB/day, 88 TB/yearPublic buckets, files in the DB
SearchLagging indexSearchable in 60sTreating 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).

Scale up one box. Scale out many copies. Scale up one box. Scale out many copies. Small box Bigger box vertical Copy Copy Copy up Until a real limit: CPU, disk, or blast radius Scale out when copies are interchangeable. State belongs in a store.
Scale up vs out
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
RideHail two speeds

Vertical scaling (scale up)

More CPU, RAM, disk on one box.

Honest when: PayRail 93/s average, even 1,200/s simple commits; ClinicDocs metadata 19/s; Linkly creates 23/s.

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

Product1×10×First move
Linkly GET4,630/s46,000/sMore cache + copies; watch miss QPS
PayRail93/s930/sStill often one primary; then read replicas for reporting
ClinicDocs files0.93/s9.3/sMore workers, same API
RideHail drivers30k300kPing path already designed for overwrite; do not append
TicketDrop8k tickets80kWaiting 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.

Replicas add read QPS — they add lag. Name both. Replicas add read QPS — they add lag. Name both. Primary PayRail writes 1,200/s peak source of truth Replica A lag 20–80 ms feed / search OK not the ledger Replica B cross-AZ +1–3 ms cross-region 50–150 ms or more copy copy Read-your-writes User just captured a charge Next GET must hit primary or pass a version token PulseFeed likes Eventual is fine Show ≈ if you must Do not stall the page Not HA Replicas ≠ more write capacity Sharding is how you grow writes. Replication is how you grow reads and survive a box.
Lag is a number
More shards do not fix one celebrity key More shards do not fix one celebrity key PulseFeed celeb 1 post → 12M followers or 1 profile GET at 80k/s Hash(userId) All 80k/s land on one shard other 99 shards idle Fix 1 — cache Cache the profile 92%+ hit TTL 5–15s Fix 2 — split key photo vs count or local cache on every app When you do shard Shard PayRail by merchantId or chargeId once a single primary cannot take ~1k–3k complex writes/s. Name who owns the map. Reshard is a project, not a checkbox. If one key is the fire, adding nodes is rearranging furniture.
Hot key
Database replication Database replication write read read App Primary Replica A Replica B Writes to primary. Replica lag is a feature you must name.
Replication
Sharding Sharding Router Shard 1 Shard 2 Shard 3 Shard key comes from access patterns. Cross-shard queries hurt.
Sharding

Replication

One primary takes writes. Replicas copy.

PathReplica OK?Lag you name
PayRail GET after captureNo — read-your-writes on primary0 on that path
PulseFeed like countYes100–500 ms fine
Linkly redirectYes if cache miss20–80 ms in-region
ClinicDocs staff reportYesSeconds OK
Cross-region replicaReporting, not ledger50–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.

Consistent hashing (conceptual) Consistent hashing (conceptual) maps to Key Node A Node B Node C Adding a node moves only a fraction of keys. Virtual nodes reduce hot spots.
Ring

How to choose

PainFirst moveNumber
Reads heavyCache + replicasLinkly 40k GET/s
Writes exceed one primaryShard or a managed sharded storeAfter you prove it
One key is hotCache / split key80k/s celeb
Range scans by timeCareful with hash-onlyReports

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.

Same company, three consistency stories Same company, three consistency stories PayRail ledger Partition → refuse debit Better a 503 than two $49 One primary for writes RPO target: 0 on captured PulseFeed likes Partition → still increment Reconcile later User sees ≈ 12.4k Page must not wait RideHail name change Read-your-writes You see “Alex” now Rider can lag 2s Not a ledger Do not say “we are AP” or “we are CP.” Say what the human notices if two copies cannot talk. CAP is a user story. Physics: you cannot be strongly consistent and 10 ms worldwide.
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.

Eventual. Copies catch up. Likes, view counts, search.

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 Circuit breaker open Caller Breaker Dependency Fallback Closed → Open (fail fast) → Half-open probe.
Circuit breaker
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
Duplicates
Multi-region architecture Multi-region architecture Users Geo DNS Region A Region B Locality and resilience vs cost, lag, and conflict resolution.
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.

ProductRTO instinctRPO instinct
PayRail captured charges15–60 min (business)0 (or accept explicit $ risk)
Linkly mappings1–2 hMinutes (async copy)
PulseFeed timeline cacheRebuildCache can die
ClinicDocs objectsHoursObject 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.

Reliability download

Reliability download

Reliability Pattern Guide

Timeout · Retry · Exponential backoff · Jitter · Circuit breaker · Bulkhead · DLQ · Idempotency · Graceful degradation.

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 — 100 tokens, refill 10/s, burst is a feature Token bucket — 100 tokens, refill 10/s, burst is a feature Honest mobile app 10 taps in 1s after a retry bucket had 100 tokens allowed — refill 10/s PayRail checkout Scripted attacker 2,000/s from one key bucket empty in 0.05s then 429 + Retry-After edge + per-user TicketDrop room Admit 3,000/s global per-user 1 poll / 2s IP is a bad key NAT hides a stadium Fixed-window trap 100/min reset: 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 fixed window. Edge = coarse flood. Service = per-user fairness. Ledger limits ≠ feed limits.
Token bucket vs attacker vs room
Rate limiting Rate limiting allow Client Gateway Limiter Service Edge coarse limits + per-key token buckets.
Limiter at the edge
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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

ProductWhat you protectLimit you sayKey
Linkly createKV uniqueness + abuse30 POST/min per useruser id
Linkly redirectApp + cache, not the limiterVery high; cache is the real shieldoptional per-IP for scrapers
PulseFeed postWrite path 185/s global5 posts/min per useruser id
PulseFeed feed150k GET/s peakSoft; cache firstdo not IP-limit a campus
PayRail authorizeBank + 400 ms p9920/min per card/merchantmerchant + instrument
RideHail ping75k writes/s already designedDrop extra pings, keep latestdriver id
ClinicDocs upload19/s peak, 3 MB10 files/min per clinictenant id
TicketDropInventory, not HTTPAdmit ~3,000/s; poll 1 / 2swaiting-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.

Rate-limit download

Rate-limit download

Rate Limiting Guide

  • Token bucket: controlled bursts + refill. Interview default.
  • Leaky bucket: smooths to a constant rate.
  • Fixed window: simple, bursty at edges.
  • Sliding window: fairer, more state.

Edge = coarse protection. Service = per-user / per-tenant fairness. Return 429 + Retry-After.

Observability and security6 min

Observability and security

Observability and security — deep dive

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 user journey — SLI, SLO, what you page on One user journey — SLI, SLO, what you page on Linkly redirect SLI: GET /{code} success and p99 < 200 ms SLO: 99.9% in 30 days Page on SLO burn + 5xx PayRail authorize SLI: capture persisted p99 < 400 ms Page on error rate and idempotency conflicts ClinicDocs pipeline SLI: clean within 60s Page on queue age > 3 min Not on worker CPU 70% Logs: request id, code prefix, latency. Never the full PDF, card PAN, or GPS breadcrumb history. Alert on symptoms a human feels. CPU is a cause, not a page.
One journey, one SLO
Multi-region architecture Multi-region architecture Users Geo DNS Region A Region B Locality and resilience vs cost, lag, and conflict resolution.
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)
JourneySLISLO you can sayPage on
Linkly redirectGET /{code} success and p99 < 200 ms99.9% in 30 daysSLO burn, 5xx, hit ratio < 80%
PayRail authorizeCapture persisted, p99 < 400 ms99.95% capturedError rate, duplicate-key conflicts
ClinicDocs cleanFile searchable in 60 s99% within 60 sQueue age > 3 min, DLQ > 50
RideHail mapFresh ping age < 8 s (2 missed pings)99% of visible driversWrite lag, drop rate
TicketDrop admitWaiting-room fairness, hold expirySeats never oversoldHold 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 classExtra control you name
Linkly public GETOpen redirect check; takedown + cache bust
PulseFeed PIIRetention on DMs; no raw location in logs
PayRail moneyLeast privilege, audit, Idempotency-Key, no PAN in logs
ClinicDocs PHIPrivate origin, signed URL 5 min, landing bucket hostile until scan, ACL from metadata DB not from search
TicketDropAuth 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 one box. Scale out many copies. Scale up one box. Scale out many copies. Small box Bigger box vertical Copy Copy Copy up Until a real limit: CPU, disk, or blast radius Scale out when copies are interchangeable. State belongs in a store.
Scale up vs out
Same company, three consistency stories Same company, three consistency stories PayRail ledger Partition → refuse debit Better a 503 than two $49 One primary for writes RPO target: 0 on captured PulseFeed likes Partition → still increment Reconcile later User sees ≈ 12.4k Page must not wait RideHail name change Read-your-writes You see “Alex” now Rider can lag 2s Not a ledger Do not say “we are AP” or “we are CP.” Say what the human notices if two copies cannot talk. CAP is a user story. Physics: you cannot be strongly consistent and 10 ms worldwide.
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

  1. Scroll to Capacity napkin on this lesson (same widget also sits on Size the system).
  2. Run Linkly. Write avg QPS, peak QPS, and miss QPS (92% hit) on paper.
  3. Run ClinicDocs. Write daily bytes, peak files/s, and in-flight scanners.
  4. Run PayRail. Say whether 1,200/s forces a shard.
  5. 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 computeFormulaWhy it matters
Average QPSdaily volume / 86,400Shared scale with the interviewer
Peak QPSaverage × peak factorThe box you provision for
Write QPSwrites per day / 86,400Separate from read QPS
Daily byteswrites × object sizeDatabase vs object store
Yearly bytesdaily bytes × 365Lifecycle, not one disk
In-flightpeak QPS × work secondsQueue depth / holds / scanners
Cache miss QPSpeak × (1 − hit%)What actually hits origin

Stop when another decimal will not change a box.

Expected napkin (labeled assumptions)

ProductHeadlineWhat you should see
Linkly400M GET/day, 200 B, 92% hit~4,630/s avg, ~40k/s peak, ~3,200 miss/s
ClinicDocs80k × 3 MB, 8s scan240 GB/day, ~19/s peak, ~152 in-flight
PayRail8M/day, peak ×13~93/s avg, ~1,200/s peak
RideHail300k × ping/4s75k writes/s — overwrite, do not append
PulseFeed16M posts, ~2.4B feed reads~150:1 read:write — fan-out or cache the timeline
TicketDrop500k in the room, admit 3k/sWaiting 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

  1. Read the URL shortener challenge. Hide the reference picture.
  2. Open the live canvas on Architecture canvas.
  3. Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
  4. Fill sections 1–7 (problem through baseline) before you decorate.
  5. Fill 8–16. The hop that dies first is the KV at 40k GET/s.
  6. 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)

Time

25–30 minutes.

Steps

  1. Read Event platform design.
  2. Open the live canvas on that lesson (different save from Linkly).
  3. Pick ClinicDocs (80k × 3 MB, 8-second scan) *or* 1M items a day.
  4. Fill sections 1–7 — include a safe waiting list.
  5. Fill 8–16 — the pain is usually slow workers or too many outbound calls, not “upload speed.”
  6. Mark complete. Do not paste the Linkly cache answer.

Checklist

  • [ ] You divided the headline by 86,400
  • [ ] First response is 202 (“accepted”), not “fully searchable”
  • [ ] The waiting-list message is not a whole PDF
  • [ ] You named retries / failed-jobs and “same key twice”
  • [ ] You can say why TicketDrop is a different problem

Check: 1,000,000 / 86,400 ≈ 12 per second. File size, time, and inventory decide the boxes.

TicketDrop flash-sale25 min

TicketDrop flash-sale

TicketDrop flash-sale challenge

Today we design TicketDrop with D-SCALE on the board — waiting room, admit rate, and inventory as the gate.

The idea: A compact 20–30 minute design for traffic, correctness, and concurrency pressure.

Why we learn this

Selectable as the LIVE challenge when those are the gaps. Otherwise practice it on your own.

Lab: Lab 551 — TicketDrop (ARCHITECT-SD-551) — use the live widget on this lesson.

Numbers on the widget are teaching / interviewer assumptions.

Use DETECT → IMPACT → MITIGATE → RECOVER → PREVENT on the failure row.

Lab 701 — PayRail AWS (BUILD-SD-701)60 min

Lab 701 — PayRail AWS (BUILD-SD-701)

Hands-on AWS lab — PayRail idempotent charges

Lab id: BUILD-SD-701

Today we deploy a charge API like Stripe into your AWS account. We prove a timeout retry does not charge twice. Then we delete the stack the same day.

The idea: Same Idempotency-Key → same order_id. A new key is a second charge. Tear down before you leave.

Source: PAKS — Stripe Payment Idempotency

Why we learn this

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 — every piece on your laptop before AWS PayRail local lab — every piece on your laptop before AWS ONE PROCESS on your laptop — python3 scripts/local_server.py No AWS · No Docker · No Terraform · Everything below lives in this one Python process until you quit 1 Your terminal curl / demo.sh pytest Idempotency-Key 2 HTTP server http.server :8080 127.0.0.1 only routes in box 6 3 charge.py hash → claim create_intent order + complete enqueue 4 Worker thread daemon every 0.2s dequeue → process_event same as Worker λ 5 MemoryStore (lab_store.py) — DynamoDB + SQS + Stripe stand-in Shared by charge, worker thread, and POST /lab/sweep. Cleared when you stop the process. keys{} pk = tenant#key status + hash cached 201 orders{} orderId amount paymentIntentId intents{} Mock Stripe one pi_ per key create_intent() webhooks{} event_id first-wins dedupe table worker writes queue[] in-memory SQS enqueue appends thread pops 6 HTTP routes on :8080 GET /health · GET /v1/orders/{id} · POST /v1/charges POST /lab/sweep · POST /webhooks/stripe 7 sweeper.py (on demand) POST /lab/sweep runs it now No EventBridge timer locally Same charge.py as AWS. Only the store changes: MemoryStore here → DynamoDB + SQS on AWS.
PayRail local lab deployment
What each box is
#ComponentFile / thingJob
1Your terminalcurl, demo.sh, pytestClient. Sends Idempotency-Key.
2HTTP serverscripts/local_server.py · 127.0.0.1:8080Front door. Same job as API Gateway later.
3Charge logiclambda/charge.pyHash, claim, call Mock Stripe, write order, enqueue. Same file on AWS.
4Worker threaddaemon in local_server.py every 0.2sDrains the in-memory queue. Same job as Worker Lambda.
5akeys{}MemoryStoreIdempotency rows (processing / completed).
5borders{}MemoryStoreOfficial ledger rows.
5cintents{}MemoryStoreMock Stripe — one pi_… per key.
5dwebhooks{}MemoryStoreevent_id dedupe table.
5equeue[]MemoryStoreIn-memory stand-in for SQS.
6HTTP routeson :8080/health, /v1/charges, /v1/orders/{id}, /lab/sweep, /webhooks/stripe
7Sweeperlambda/sweeper.py via POST /lab/sweepHeal 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 same Idempotency-Key against the local server. You should see the same payment_intent_id / order_id — not a second charge.

Replay Payment Intent IDs locally
Local → AWS map (same state machine)
Local lab → AWS lab — what each piece becomes Local lab → AWS lab — what each piece becomes Read left to right. Same state machine. Different boxes. Local — Path B One Python process on 127.0.0.1:8080 Zero cloud cost · stop = wipe store AWS — Path C Your account · terraform apply / destroy Under $2 if you destroy today 1 HTTPServer :8080 API Gateway HTTP API 2 charge.py (same file) Charge Lambda 3 MemoryStore.keys + orders DynamoDB keys + orders tables 4 MemoryStore.intents DynamoDB intents (Mock Stripe) 5 MemoryStore.queue[] SQS webhook queue 6 Worker thread every 0.2s Worker Lambda triggered by SQS 7 POST /lab/sweep EventBridge 1 min → Sweeper Lambda 8 curl / demo.sh / pytest Same tools · URL from terraform output Learn Path B first. On the interview board say ALB + ECS + Aurora — this lab trains the state machine.
Local lab maps to AWS lab
LocalBecomes on AWS
HTTPServer :8080API Gateway HTTP API
charge.py in-processCharge Lambda
MemoryStore.keys + ordersDynamoDB tables
MemoryStore.intentsDynamoDB intents (Mock Stripe)
MemoryStore.queue[]SQS
Worker threadWorker Lambda
POST /lab/sweepEventBridge 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.

PayRail AWS demo — every service terraform apply creates PayRail AWS demo — every service terraform apply creates YOUR AWS ACCOUNT — terraform apply in labs/payrail-idempotency/terraform Same charge.py as local. Destroy the same day. Typical cost under $2. No live Stripe secret. 1 Client curl / demo.sh Idempotency-Key charge_url 2 API Gateway HTTP POST /v1/charges GET /health GET /orders/{id} POST /webhooks/stripe 3 Charge λ charge.handler timeout 15s hash · claim · intent 4 Webhook λ webhook.handler POST /webhooks/stripe Stripe-style accept 5 DynamoDB (PAY_PER_REQUEST · KMS encrypted) Four tables — same jobs as MemoryStore.keys / orders / intents / webhooks on Path B idemp-keys pk = tenant#key TTL 24h processing / completed orders hash key orderId ledger row amount + pi_ id stripe-intents Mock Stripe one pi_ per key create_intent() webhook-events hash key eventId first-wins dedupe Worker writes here 6 Async path — SQS + Worker · 7 Reconciliation — EventBridge + Sweeper SQS webhooks KMS encrypted visibility 60s Charge λ sends SQS DLQ maxReceive 3 poison messages alarm in prod Worker λ worker.handler SQS event source batch=1 · conc=5 EventBridge + Sweeper λ rate(1 minute) sweeper.handler heal stuck processing 8 KMS + IAM CMK alias …-payrail encrypt DDB + SQS one Lambda role 9 CloudWatch Logs each Lambda log group demo / crash drill store down → 503 10 Terraform outputs charge_url · health_url table + queue names destroy same day Interview board still says ALB + ECS + Aurora + real Stripe. This stack trains the same state machine under $2.
PayRail AWS demo deployment
#AWS serviceTerraform / handlerJob
1Your terminalcurl / demo.shClient against charge_url
2API Gateway HTTP APIaws_apigatewayv2_apiFront door: charges, health, orders, webhooks
3Charge Lambdacharge.handler · 15sHash, claim, Mock Stripe intent, order, enqueue
4Webhook Lambdawebhook.handlerAccepts POST /webhooks/stripe
5aDynamoDB …-idemp-keyspk = tenant#key · TTL 24hIdempotency rows
5bDynamoDB …-orderspk = orderIdOfficial ledger
5cDynamoDB …-stripe-intentsMock StripeOne pi_… per key
5dDynamoDB …-webhook-eventspk = eventIdWebhook dedupe
6SQS webhooks + DLQvisibility 60s · maxReceive 3Async notify path
6bWorker Lambdaworker.handler · SQS triggerevent_id first-wins
7EventBridge rate(1 minute) → Sweeper Lambdasweeper.handlerHeal stuck processing
8KMS + IAM roleencrypt DDB/SQS · least privilegeSecurity
9CloudWatch Logsper LambdaDemo / crash drill output
10Terraform outputscharge_url, table namesWhat demo.sh uses

Compact reminder (same flow, fewer labels):

PayRail AWS lab — same state machine as Stripe, student-account size PayRail AWS lab — same state machine as Stripe, student-account size 1 Client Idempotency-Key timeout = UNKNOWN 2 HTTP API POST /v1/charges GET /health 3 Charge λ claim processing hash body 4 DynamoDB keys + orders mock intents 5 SQS + worker event_id dedupe DLQ ×3 Timeout drill Crash after claim → 504 Retry SAME key → 409 in flight Sweeper (1 min) heals or fails New UUID = a second $25 Production mapping ALB + ECS + Aurora at 5k/s This lab: Lambda + DynamoDB PayRail 93/s, BFCM 1,200/s Fail closed if keys table is down Source: PAKS Stripe Payment Idempotency. No live sk_live_ in the lab.
PayRail AWS lab

text

Client → API Gateway → Charge Lambda → DynamoDB (keys + orders + intents)
                                      → SQS → Worker (event_id dedupe)
EventBridge (every 1 min) → Sweeper

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
StepNameWhat it protects
1–2Accept requestBad input never reaches money
3Hash the bodySame key cannot mean two different amounts
4Claim the keyOnly one request may call the gateway for this checkout
5Mock StripeOne PaymentIntent per key — the bank side effect
6Order + completeOfficial PayRail ledger + cached answer for retries
7Enqueue webhookDownstream systems hear “succeeded” once (with dedupe)
8–9Worker + 201Event stored; client gets IDs
Steps 1–2 (short)
  1. Client sends POST /v1/charges with Idempotency-Key, X-Tenant-Id, and { amount_cents, currency }.
  2. 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 the code does:

text

payload = { amount_cents, currency }
request_hash = SHA-256( JSON with sorted keys )

Example: { "amount_cents": 2500, "currency": "usd" } → one fixed hex string.

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:

EnvironmentMechanism
Local labMemoryStore lock + “if key exists, return it”
AWS labDynamoDB PutItem with attribute_not_exists(pk) — loser gets ConditionalCheckFailed and reads the winner

Return value of `claim_key`:

ResultMeaningNext action
created: trueYou own this attemptContinue to Mock Stripe
created: false + completedAlready doneReplay cached 201
created: false + processingSomeone else is mid-flight409 in flight
created: false + hash mismatchSame key, different amount409

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)`:

  1. Lookup pk = tenant#key in the intents table.
  2. If a row exists → return the same paymentIntentId. No second charge object.
  3. 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:

LocalAWS
Call sitestore.create_intent(...) passed into charge()Same function on DynamoStore
StorageMemoryStore.intents dictDynamoDB intents table
Extrastripe_mock.py Lambda exists for the pack; happy path calls the store method directlySame 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:

  1. Orders table — the business ledger (“order ord_… succeeded for $25”).
  2. Idempotency key row — the retry cache (status=completed + full JSON body).

What `complete_key` stores on the key:

text

status          = completed
responseStatus  = 201
responseBody    = { order_id, payment_intent_id, status, amount… }
orderId         = ord_…
paymentIntentId = pi_…

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`):

  1. Read event_id from the message.
  2. put_webhook(event_id) — first write wins.
  3. If SQS (or the local loop) delivers again → duplicate: true → ignore. No second “send receipt” side effect.

Client response:

text

HTTP 201
x-idempotent-replay: false
{
  order_id,
  payment_intent_id,
  status: succeeded,
  amount_cents,
  currency
}

---

How the local lab runs the same happy path

You do not need AWS to learn steps 3–7. Path B uses one process:

text

python3 scripts/local_server.py
→ http://127.0.0.1:8080
PieceLocal stand-inSame code idea
APIHTTPServer on :8080API Gateway
ChargePOST /v1/charges → charge()Charge Lambda
Key / order / intent / webhook tablesMemoryStore dictsDynamoDB tables
Mock Stripestore.create_intentIntents table
SQSstore.queue listSQS queue
WorkerBackground thread every 0.2s calls dequeue → process_eventWorker Lambda
SweeperPOST /lab/sweepEventBridge → Sweeper

Same `charge.py`. Local and AWS only swap the store (MemoryStore vs DynamoStore).

Try it after unzip:

bash

# terminal 1
python3 scripts/local_server.py

# terminal 2
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H 'content-type: application/json' \
  -H 'Idempotency-Key: lesson-happy-1' \
  -H 'X-Tenant-Id: demo' \
  -d '{"amount_cents":2500,"currency":"usd"}'
# → 201, one order_id, one payment_intent_id

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H 'content-type: application/json' \
  -H 'Idempotency-Key: lesson-happy-1' \
  -H 'X-Tenant-Id: demo' \
  -d '{"amount_cents":2500,"currency":"usd"}'
# → 201, SAME ids, x-idempotent-replay: true

---

Full happy-path sequence (AWS-shaped names)

Interview close for happy path:

“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.”

---

Flow 2 — Idempotent replay (same key, already done)

Story: The phone never got the 201, so it retries with the same key and the same body.

Step by step
  1. Client POSTs again with the same Idempotency-Key and same amount.
  2. claim_key finds the row already exists (created=false).
  3. Hash matches. Status is `completed`.
  4. Lambda returns the cached JSON. No second PaymentIntent. No second order.
  5. 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.

StepWhat you see
First POST504 — row stuck processing
Immediate retry same key409 in flight
Sweeper runsNo intent found → mark `failed`
Later retry same keyReplay 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.

StepWhat you see
First POST504 — intent exists, row still processing
Immediate retry same key409 in flight
Sweeper runsFinds intent → heal → completed with same payment_intent_id
Later retry same key201 + "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.

  1. Request A claimed processing and is still working.
  2. Request B uses the same key.
  3. B sees processing → 409 “request in flight — retry the same key.”
  4. 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).

  1. First request claimed with hash of $25.
  2. Second request sends $50 with the same key.
  3. Hash mismatch → 409 “same Idempotency-Key with a different body.”
  4. Do not charge $50 under the $25 key.

---

Flow 6 — Store down (503 fail closed)

Story: DynamoDB (or Aurora in production) is unreachable.

  1. You cannot record the attempt.
  2. Return 503. Do not call the payment gateway.
  3. 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.

  1. Happy path enqueues one message with event_id.
  2. Worker calls put_webhook(event_id). First write wins.
  3. 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

PathWherePass when
A PortalThis overview + architecture + charge.pyYou can point at claim / replay / 409 / sweeper
B LocalUnzip → pytest → local_server.py → demo.sh9 passed, then PASS + 409
C AWSLab 701 — Test on AWShealth ok, crash drill 201 healed, then destroy
  1. Stay in Lab 701 — PayRail AWS in the left nav.
  2. Read the flows above until you can redraw them from memory.
  3. Open Lab 701 — Test and demo and follow A → B (C is optional).
  4. Open Build PayRail and read charge.py in the source browser.
  5. Download sd-payrail-lab.zip when you start Path B.

Full README: lab pack.

Architecture deep dive: PayRail lab architecture.

Code map: code walkthrough.

Typical cost: under $2 if you destroy today.

COMMON MISTAKE: Minting a new UUID because the first call timed out. That is a second charge.

Go deeper on the code

Open the Appendix — PayRail code for line-by-line walkthroughs of every lab file.

Download the full lab (all code)

PayRail source, Terraform, local server, and pytest. Read charge.py here, then deploy in your AWS account and destroy the same day.

Download sd-payrail-lab.zip

You will

  • Follow Lab 701 — Test and demo (Path A portal, Path B local, Path C optional AWS)
  • pytest 9 passed, then demo.sh PASS + 409
  • Path C: Lab 701 — Test on AWS, then terraform destroy the same day

Lab 701 — PayRail overview10 min

Lab 701 — PayRail overview

Hands-on AWS lab — PayRail idempotent charges

Lab id: BUILD-SD-701

Today we deploy a charge API like Stripe into your AWS account. We prove a timeout retry does not charge twice. Then we delete the stack the same day.

The idea: Same Idempotency-Key → same order_id. A new key is a second charge. Tear down before you leave.

Source: PAKS — Stripe Payment Idempotency

Why we learn this

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 — every piece on your laptop before AWS PayRail local lab — every piece on your laptop before AWS ONE PROCESS on your laptop — python3 scripts/local_server.py No AWS · No Docker · No Terraform · Everything below lives in this one Python process until you quit 1 Your terminal curl / demo.sh pytest Idempotency-Key 2 HTTP server http.server :8080 127.0.0.1 only routes in box 6 3 charge.py hash → claim create_intent order + complete enqueue 4 Worker thread daemon every 0.2s dequeue → process_event same as Worker λ 5 MemoryStore (lab_store.py) — DynamoDB + SQS + Stripe stand-in Shared by charge, worker thread, and POST /lab/sweep. Cleared when you stop the process. keys{} pk = tenant#key status + hash cached 201 orders{} orderId amount paymentIntentId intents{} Mock Stripe one pi_ per key create_intent() webhooks{} event_id first-wins dedupe table worker writes queue[] in-memory SQS enqueue appends thread pops 6 HTTP routes on :8080 GET /health · GET /v1/orders/{id} · POST /v1/charges POST /lab/sweep · POST /webhooks/stripe 7 sweeper.py (on demand) POST /lab/sweep runs it now No EventBridge timer locally Same charge.py as AWS. Only the store changes: MemoryStore here → DynamoDB + SQS on AWS.
PayRail local lab deployment
What each box is
#ComponentFile / thingJob
1Your terminalcurl, demo.sh, pytestClient. Sends Idempotency-Key.
2HTTP serverscripts/local_server.py · 127.0.0.1:8080Front door. Same job as API Gateway later.
3Charge logiclambda/charge.pyHash, claim, call Mock Stripe, write order, enqueue. Same file on AWS.
4Worker threaddaemon in local_server.py every 0.2sDrains the in-memory queue. Same job as Worker Lambda.
5akeys{}MemoryStoreIdempotency rows (processing / completed).
5borders{}MemoryStoreOfficial ledger rows.
5cintents{}MemoryStoreMock Stripe — one pi_… per key.
5dwebhooks{}MemoryStoreevent_id dedupe table.
5equeue[]MemoryStoreIn-memory stand-in for SQS.
6HTTP routeson :8080/health, /v1/charges, /v1/orders/{id}, /lab/sweep, /webhooks/stripe
7Sweeperlambda/sweeper.py via POST /lab/sweepHeal 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 same Idempotency-Key against the local server. You should see the same payment_intent_id / order_id — not a second charge.

Replay Payment Intent IDs locally
Local → AWS map (same state machine)
Local lab → AWS lab — what each piece becomes Local lab → AWS lab — what each piece becomes Read left to right. Same state machine. Different boxes. Local — Path B One Python process on 127.0.0.1:8080 Zero cloud cost · stop = wipe store AWS — Path C Your account · terraform apply / destroy Under $2 if you destroy today 1 HTTPServer :8080 API Gateway HTTP API 2 charge.py (same file) Charge Lambda 3 MemoryStore.keys + orders DynamoDB keys + orders tables 4 MemoryStore.intents DynamoDB intents (Mock Stripe) 5 MemoryStore.queue[] SQS webhook queue 6 Worker thread every 0.2s Worker Lambda triggered by SQS 7 POST /lab/sweep EventBridge 1 min → Sweeper Lambda 8 curl / demo.sh / pytest Same tools · URL from terraform output Learn Path B first. On the interview board say ALB + ECS + Aurora — this lab trains the state machine.
Local lab maps to AWS lab
LocalBecomes on AWS
HTTPServer :8080API Gateway HTTP API
charge.py in-processCharge Lambda
MemoryStore.keys + ordersDynamoDB tables
MemoryStore.intentsDynamoDB intents (Mock Stripe)
MemoryStore.queue[]SQS
Worker threadWorker Lambda
POST /lab/sweepEventBridge 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.

PayRail AWS demo — every service terraform apply creates PayRail AWS demo — every service terraform apply creates YOUR AWS ACCOUNT — terraform apply in labs/payrail-idempotency/terraform Same charge.py as local. Destroy the same day. Typical cost under $2. No live Stripe secret. 1 Client curl / demo.sh Idempotency-Key charge_url 2 API Gateway HTTP POST /v1/charges GET /health GET /orders/{id} POST /webhooks/stripe 3 Charge λ charge.handler timeout 15s hash · claim · intent 4 Webhook λ webhook.handler POST /webhooks/stripe Stripe-style accept 5 DynamoDB (PAY_PER_REQUEST · KMS encrypted) Four tables — same jobs as MemoryStore.keys / orders / intents / webhooks on Path B idemp-keys pk = tenant#key TTL 24h processing / completed orders hash key orderId ledger row amount + pi_ id stripe-intents Mock Stripe one pi_ per key create_intent() webhook-events hash key eventId first-wins dedupe Worker writes here 6 Async path — SQS + Worker · 7 Reconciliation — EventBridge + Sweeper SQS webhooks KMS encrypted visibility 60s Charge λ sends SQS DLQ maxReceive 3 poison messages alarm in prod Worker λ worker.handler SQS event source batch=1 · conc=5 EventBridge + Sweeper λ rate(1 minute) sweeper.handler heal stuck processing 8 KMS + IAM CMK alias …-payrail encrypt DDB + SQS one Lambda role 9 CloudWatch Logs each Lambda log group demo / crash drill store down → 503 10 Terraform outputs charge_url · health_url table + queue names destroy same day Interview board still says ALB + ECS + Aurora + real Stripe. This stack trains the same state machine under $2.
PayRail AWS demo deployment
#AWS serviceTerraform / handlerJob
1Your terminalcurl / demo.shClient against charge_url
2API Gateway HTTP APIaws_apigatewayv2_apiFront door: charges, health, orders, webhooks
3Charge Lambdacharge.handler · 15sHash, claim, Mock Stripe intent, order, enqueue
4Webhook Lambdawebhook.handlerAccepts POST /webhooks/stripe
5aDynamoDB …-idemp-keyspk = tenant#key · TTL 24hIdempotency rows
5bDynamoDB …-orderspk = orderIdOfficial ledger
5cDynamoDB …-stripe-intentsMock StripeOne pi_… per key
5dDynamoDB …-webhook-eventspk = eventIdWebhook dedupe
6SQS webhooks + DLQvisibility 60s · maxReceive 3Async notify path
6bWorker Lambdaworker.handler · SQS triggerevent_id first-wins
7EventBridge rate(1 minute) → Sweeper Lambdasweeper.handlerHeal stuck processing
8KMS + IAM roleencrypt DDB/SQS · least privilegeSecurity
9CloudWatch Logsper LambdaDemo / crash drill output
10Terraform outputscharge_url, table namesWhat demo.sh uses

Compact reminder (same flow, fewer labels):

PayRail AWS lab — same state machine as Stripe, student-account size PayRail AWS lab — same state machine as Stripe, student-account size 1 Client Idempotency-Key timeout = UNKNOWN 2 HTTP API POST /v1/charges GET /health 3 Charge λ claim processing hash body 4 DynamoDB keys + orders mock intents 5 SQS + worker event_id dedupe DLQ ×3 Timeout drill Crash after claim → 504 Retry SAME key → 409 in flight Sweeper (1 min) heals or fails New UUID = a second $25 Production mapping ALB + ECS + Aurora at 5k/s This lab: Lambda + DynamoDB PayRail 93/s, BFCM 1,200/s Fail closed if keys table is down Source: PAKS Stripe Payment Idempotency. No live sk_live_ in the lab.
PayRail AWS lab

text

Client → API Gateway → Charge Lambda → DynamoDB (keys + orders + intents)
                                      → SQS → Worker (event_id dedupe)
EventBridge (every 1 min) → Sweeper

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
StepNameWhat it protects
1–2Accept requestBad input never reaches money
3Hash the bodySame key cannot mean two different amounts
4Claim the keyOnly one request may call the gateway for this checkout
5Mock StripeOne PaymentIntent per key — the bank side effect
6Order + completeOfficial PayRail ledger + cached answer for retries
7Enqueue webhookDownstream systems hear “succeeded” once (with dedupe)
8–9Worker + 201Event stored; client gets IDs
Steps 1–2 (short)
  1. Client sends POST /v1/charges with Idempotency-Key, X-Tenant-Id, and { amount_cents, currency }.
  2. 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 the code does:

text

payload = { amount_cents, currency }
request_hash = SHA-256( JSON with sorted keys )

Example: { "amount_cents": 2500, "currency": "usd" } → one fixed hex string.

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:

EnvironmentMechanism
Local labMemoryStore lock + “if key exists, return it”
AWS labDynamoDB PutItem with attribute_not_exists(pk) — loser gets ConditionalCheckFailed and reads the winner

Return value of `claim_key`:

ResultMeaningNext action
created: trueYou own this attemptContinue to Mock Stripe
created: false + completedAlready doneReplay cached 201
created: false + processingSomeone else is mid-flight409 in flight
created: false + hash mismatchSame key, different amount409

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)`:

  1. Lookup pk = tenant#key in the intents table.
  2. If a row exists → return the same paymentIntentId. No second charge object.
  3. 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:

LocalAWS
Call sitestore.create_intent(...) passed into charge()Same function on DynamoStore
StorageMemoryStore.intents dictDynamoDB intents table
Extrastripe_mock.py Lambda exists for the pack; happy path calls the store method directlySame 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:

  1. Orders table — the business ledger (“order ord_… succeeded for $25”).
  2. Idempotency key row — the retry cache (status=completed + full JSON body).

What `complete_key` stores on the key:

text

status          = completed
responseStatus  = 201
responseBody    = { order_id, payment_intent_id, status, amount… }
orderId         = ord_…
paymentIntentId = pi_…

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`):

  1. Read event_id from the message.
  2. put_webhook(event_id) — first write wins.
  3. If SQS (or the local loop) delivers again → duplicate: true → ignore. No second “send receipt” side effect.

Client response:

text

HTTP 201
x-idempotent-replay: false
{
  order_id,
  payment_intent_id,
  status: succeeded,
  amount_cents,
  currency
}

---

How the local lab runs the same happy path

You do not need AWS to learn steps 3–7. Path B uses one process:

text

python3 scripts/local_server.py
→ http://127.0.0.1:8080
PieceLocal stand-inSame code idea
APIHTTPServer on :8080API Gateway
ChargePOST /v1/charges → charge()Charge Lambda
Key / order / intent / webhook tablesMemoryStore dictsDynamoDB tables
Mock Stripestore.create_intentIntents table
SQSstore.queue listSQS queue
WorkerBackground thread every 0.2s calls dequeue → process_eventWorker Lambda
SweeperPOST /lab/sweepEventBridge → Sweeper

Same `charge.py`. Local and AWS only swap the store (MemoryStore vs DynamoStore).

Try it after unzip:

bash

# terminal 1
python3 scripts/local_server.py

# terminal 2
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H 'content-type: application/json' \
  -H 'Idempotency-Key: lesson-happy-1' \
  -H 'X-Tenant-Id: demo' \
  -d '{"amount_cents":2500,"currency":"usd"}'
# → 201, one order_id, one payment_intent_id

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H 'content-type: application/json' \
  -H 'Idempotency-Key: lesson-happy-1' \
  -H 'X-Tenant-Id: demo' \
  -d '{"amount_cents":2500,"currency":"usd"}'
# → 201, SAME ids, x-idempotent-replay: true

---

Full happy-path sequence (AWS-shaped names)

Interview close for happy path:

“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.”

---

Flow 2 — Idempotent replay (same key, already done)

Story: The phone never got the 201, so it retries with the same key and the same body.

Step by step
  1. Client POSTs again with the same Idempotency-Key and same amount.
  2. claim_key finds the row already exists (created=false).
  3. Hash matches. Status is `completed`.
  4. Lambda returns the cached JSON. No second PaymentIntent. No second order.
  5. 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.

StepWhat you see
First POST504 — row stuck processing
Immediate retry same key409 in flight
Sweeper runsNo intent found → mark `failed`
Later retry same keyReplay 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.

StepWhat you see
First POST504 — intent exists, row still processing
Immediate retry same key409 in flight
Sweeper runsFinds intent → heal → completed with same payment_intent_id
Later retry same key201 + "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.

  1. Request A claimed processing and is still working.
  2. Request B uses the same key.
  3. B sees processing → 409 “request in flight — retry the same key.”
  4. 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).

  1. First request claimed with hash of $25.
  2. Second request sends $50 with the same key.
  3. Hash mismatch → 409 “same Idempotency-Key with a different body.”
  4. Do not charge $50 under the $25 key.

---

Flow 6 — Store down (503 fail closed)

Story: DynamoDB (or Aurora in production) is unreachable.

  1. You cannot record the attempt.
  2. Return 503. Do not call the payment gateway.
  3. 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.

  1. Happy path enqueues one message with event_id.
  2. Worker calls put_webhook(event_id). First write wins.
  3. 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

PathWherePass when
A PortalThis overview + architecture + charge.pyYou can point at claim / replay / 409 / sweeper
B LocalUnzip → pytest → local_server.py → demo.sh9 passed, then PASS + 409
C AWSLab 701 — Test on AWShealth ok, crash drill 201 healed, then destroy
  1. Stay in Lab 701 — PayRail AWS in the left nav.
  2. Read the flows above until you can redraw them from memory.
  3. Open Lab 701 — Test and demo and follow A → B (C is optional).
  4. Open Build PayRail and read charge.py in the source browser.
  5. Download sd-payrail-lab.zip when you start Path B.

Full README: lab pack.

Architecture deep dive: PayRail lab architecture.

Code map: code walkthrough.

Typical cost: under $2 if you destroy today.

COMMON MISTAKE: Minting a new UUID because the first call timed out. That is a second charge.

Go deeper on the code

Open the Appendix — PayRail code for line-by-line walkthroughs of every lab file.

README

README

Lab BUILD-SD-701 — PayRail Stripe-style idempotency

Source scenario: PAKS — Stripe Payment Idempotency

text

Client → API Gateway → Charge Lambda
       → DynamoDB (idempotency_keys + orders + stripe mock)
       → SQS → Worker Lambda (webhook event_id dedupe)
       → EventBridge 1 min → Sweeper Lambda (stuck processing)

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

PathWhat it is
lambda/charge.pyPOST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.pySQS consumer — dedupe event_id
lambda/sweeper.pyHeal rows left processing after a crash
lambda/webhook.pyPOST /webhooks/stripe replay
terraform/Supported deploy path
scripts/local_server.pySame API on :8080 with no AWS
scripts/demo.shSame 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.

2. Deploy to AWS

bash

cd terraform
cp terraform.tfvars.example terraform.tfvars
# edit name_prefix
terraform init
terraform apply

Note charge_url. Then:

bash

../scripts/demo.sh

demo.sh uses Terraform outputs when .terraform exists.

3. Failure drill (ambiguous timeout)

bash

curl -sS -X POST "$(terraform output -raw charge_url)" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-1" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'

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

  1. Same Idempotency-Key → same order_id and payment_intent_id
  2. DynamoDB orders does not grow on retry
  3. Same key, different amount_cents → 409
  4. Missing key → 400
  5. Store down (local: store.down = True) → 503 fail closed
  6. SQS DLQ depth is 0 after a happy-path charge
  7. 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.

StepPortal lessonWhat you do
0Lab 701 — PayRail overviewWhy the lab exists. Download sd-payrail-lab.zip.
1This lessonFollow Path A → B → C below. Do not skip Path B.
2Lab 701 — PayRail architectureMemorize claim / replay / 409 / 503.
3Lab 701 — Build PayRailOpen 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.

  1. On PayRail overview, read the one-sentence promise and the diagram.
  2. 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
  1. On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
  2. Open How the code maps to the interview (extra on this section). Point at the four rows.
  3. Download sd-payrail-lab.zip when you are ready to run Path B.

You can stop here for a whiteboard-only session. Path B is what you show if you have a terminal.

---

Path B — Local demo (required, no AWS)

Watch the local replay first on Lab 701 overview (Watch: local replay), then run the same steps here.

Unzip on your machine. The folder must look like this:

text

payrail-idempotency/
  lambda/          charge.py, lab_store.py, dynamo_store.py, …
  scripts/         local_server.py, demo.sh
  tests/           test_idempotency.py
  terraform/
  requirements-dev.txt
B1. Tests (8 must pass)

bash

cd payrail-idempotency
python3 -m pip install -q -r requirements-dev.txt
python3 -m pytest tests/ -v

Expected last line: `9 passed`.

TestWhat it proves
test_replay_same_key_does_not_double_chargeSame key → same order_id, x-idempotent-replay: true, one order row
test_new_key_creates_new_orderA new key is a second charge
test_same_key_different_body_conflict409, still one order
test_missing_key_is_400Header required
test_in_flight_returns_409Crash after claim → 504, retry → 409
test_store_down_fails_closed503, no charge
test_webhook_dedupeSame event_id is ignored
test_crash_after_gateway_then_sweeper_replays_same_intentGateway charged, process died; sweeper heals; same payment_intent_id
test_sweeper_heals_stuck_processingSweeper completes a stuck row; replay is 201
B2. Start the local API

bash

python3 scripts/local_server.py

Leave it running. You should see:

text

PayRail local lab on http://127.0.0.1:8080

Health check (other terminal):

bash

curl -sS http://127.0.0.1:8080/health

Expected: {"ok": true}.

B3. Happy-path demo (this is the recording)

bash

chmod +x scripts/demo.sh
./scripts/demo.sh

demo.sh posts twice with the same key, then once with a different amount.

Expected:

  1. First POST → 201 and an order_id like ord_… plus payment_intent_id like pi_…
  2. Second POST → 201, same order_id and payment_intent_id, header x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Third POST (amount 9900) → HTTP 409
  5. Console: Demo succeeded.

If you want to see it with curl yourself (same as the script):

bash

KEY="demo-$(date +%s)"
URL="http://127.0.0.1:8080/v1/charges"

# first charge
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# retry — must replay
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# same key, new amount — must 409
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":9900,"currency":"usd"}'
B4. Timeout drill (the interview trap)

Still on :8080. Use a new key for each drill.

Crash before the gateway (no money moved). Sweeper marks failed. Replay stays failed. Zero orders.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 failed replay — still no second charge

Crash after the gateway (intent exists). Sweeper heals. Replay is 201 with the same payment_intent_id.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 — intent created, row still processing

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 201 healed — same payment_intent_id

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

Cleanup · Troubleshooting

---

What to say while you demo (30 seconds)

“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 sentenceFunction / fileWhat happens
“I claim the key before I call the gateway.”claim_key in lab_store.py / dynamo_store.pyFirst writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”charge() in charge.pyIf completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”charge() after the hash checkrequest_hash is SHA-256 of {amount_cents, currency}.
“Store down → fail closed.”StoreDown → 503Do not charge if you cannot record the attempt.

Happy path (first POST)

  1. Client sends Idempotency-Key + X-Tenant-Id + { amount_cents, currency }.
  2. charge() hashes the body.
  3. claim_key creates a processing row (or returns the existing one).
  4. Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
  5. An order_id is minted once, stored, and cached on the key row.
  6. 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

  1. charge.py — claim / replay / 409 / 503
  2. lab_store.py — in-memory version of the same API (pytest + local server)
  3. dynamo_store.py — the AWS version (attribute_not_exists claim)
  4. sweeper.py — heal stuck processing
  5. worker.py — event_id dedupe
  6. 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.

StepPortal lessonWhat you do
0Lab 701 — PayRail overviewWhy the lab exists. Download sd-payrail-lab.zip.
1This lessonFollow Path A → B → C below. Do not skip Path B.
2Lab 701 — PayRail architectureMemorize claim / replay / 409 / 503.
3Lab 701 — Build PayRailOpen 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.

  1. On PayRail overview, read the one-sentence promise and the diagram.
  2. 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
  1. On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
  2. Open How the code maps to the interview (extra on this section). Point at the four rows.
  3. Download sd-payrail-lab.zip when you are ready to run Path B.

You can stop here for a whiteboard-only session. Path B is what you show if you have a terminal.

---

Path B — Local demo (required, no AWS)

Watch the local replay first on Lab 701 overview (Watch: local replay), then run the same steps here.

Unzip on your machine. The folder must look like this:

text

payrail-idempotency/
  lambda/          charge.py, lab_store.py, dynamo_store.py, …
  scripts/         local_server.py, demo.sh
  tests/           test_idempotency.py
  terraform/
  requirements-dev.txt
B1. Tests (8 must pass)

bash

cd payrail-idempotency
python3 -m pip install -q -r requirements-dev.txt
python3 -m pytest tests/ -v

Expected last line: `9 passed`.

TestWhat it proves
test_replay_same_key_does_not_double_chargeSame key → same order_id, x-idempotent-replay: true, one order row
test_new_key_creates_new_orderA new key is a second charge
test_same_key_different_body_conflict409, still one order
test_missing_key_is_400Header required
test_in_flight_returns_409Crash after claim → 504, retry → 409
test_store_down_fails_closed503, no charge
test_webhook_dedupeSame event_id is ignored
test_crash_after_gateway_then_sweeper_replays_same_intentGateway charged, process died; sweeper heals; same payment_intent_id
test_sweeper_heals_stuck_processingSweeper completes a stuck row; replay is 201
B2. Start the local API

bash

python3 scripts/local_server.py

Leave it running. You should see:

text

PayRail local lab on http://127.0.0.1:8080

Health check (other terminal):

bash

curl -sS http://127.0.0.1:8080/health

Expected: {"ok": true}.

B3. Happy-path demo (this is the recording)

bash

chmod +x scripts/demo.sh
./scripts/demo.sh

demo.sh posts twice with the same key, then once with a different amount.

Expected:

  1. First POST → 201 and an order_id like ord_… plus payment_intent_id like pi_…
  2. Second POST → 201, same order_id and payment_intent_id, header x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Third POST (amount 9900) → HTTP 409
  5. Console: Demo succeeded.

If you want to see it with curl yourself (same as the script):

bash

KEY="demo-$(date +%s)"
URL="http://127.0.0.1:8080/v1/charges"

# first charge
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# retry — must replay
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# same key, new amount — must 409
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":9900,"currency":"usd"}'
B4. Timeout drill (the interview trap)

Still on :8080. Use a new key for each drill.

Crash before the gateway (no money moved). Sweeper marks failed. Replay stays failed. Zero orders.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 failed replay — still no second charge

Crash after the gateway (intent exists). Sweeper heals. Replay is 201 with the same payment_intent_id.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 — intent created, row still processing

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 201 healed — same payment_intent_id

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

Cleanup · Troubleshooting

---

What to say while you demo (30 seconds)

“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. Always terraform 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.

Unzip sd-payrail-lab.zip if you have not already:

text

payrail-idempotency/
  lambda/
  scripts/     demo.sh  aws_test.sh  local_server.py
  terraform/
  tests/

---

C1. Apply the stack

bash

cd payrail-idempotency/terraform
cp terraform.tfvars.example terraform.tfvars

Edit terraform.tfvars:

hcl

region      = "us-west-2"
name_prefix = "yourinitials-payrail"

bash

terraform init
terraform apply

Type yes. Wait until it finishes (usually 2–4 minutes).

Copy these outputs — you will use them in every later command:

bash

terraform output

You must see charge_url and health_url starting with https:// and *.execute-api.us-west-2.amazonaws.com. Also note sweeper_function and orders_table.

---

C2. Health check

bash

curl -sS "$(terraform output -raw health_url)"

Expected:

json

{"ok": true, "service": "payrail-charges"}

If this fails, wait 20 seconds (API Gateway auto-deploy) and retry. Still failing: troubleshooting.

---

C3. Happy-path demo (this is the recording)

From the lab root (payrail-idempotency/), not from terraform/:

bash

chmod +x scripts/demo.sh scripts/aws_test.sh
./scripts/demo.sh

demo.sh reads charge_url from Terraform state when it is a real https:// URL.

Expected (same as local Path B, against API Gateway):

  1. First POST → 201, order_id (ord_…), payment_intent_id (pi_…), x-idempotent-replay: false
  2. Retry same Idempotency-Key → 201, same IDs, x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Same key, amount_cents: 9900 → HTTP 409
  5. Console: Demo succeeded.
  6. If AWS CLI works: orders table COUNT= at least 1

Manual curl (optional — same as the script):

bash

cd terraform
URL="$(terraform output -raw charge_url)"
KEY="demo-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

---

C4. Timeout drill on AWS

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).

bash

cd terraform
URL="$(terraform output -raw charge_url)"
SWEEPER="$(terraform output -raw sweeper_function)"
KEY="aws-crash-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 504

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 409  request in flight

sleep 9
aws lambda invoke --function-name "$SWEEPER" /tmp/payrail-sweep.json
cat /tmp/payrail-sweep.json
# {"healed":[{"key":"aws-crash-…","status":"completed"}],"count":1}

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 201  same payment_intent_id, "healed": true

One command that runs C2–C4 after apply:

bash

cd payrail-idempotency
./scripts/aws_test.sh

Expected last line: AWS Path C succeeded.

COMMON MISTAKE: A new Idempotency-Key after the 504. That is a second charge. Say: “UNKNOWN — retry the same key; the sweeper is the backstop.”

---

C5. What to look at in the AWS console (optional)

WhereWhat you should see
API Gateway → your {prefix}-payrail HTTP APIRoutes POST /v1/charges, GET /health
Lambda → {prefix}-chargeCloudWatch: the two POSTs and the crash header
DynamoDB → {prefix}-idemp-keysOne item demo#{key}, status=completed
DynamoDB → {prefix} orders tableOne row for the happy-path key, not two
SQS DLQDepth 0 after the happy path
EventBridge rule {prefix}-payrail-sweeprate(1 minute)

---

C6. Destroy the same day

bash

cd terraform
terraform destroy

Type yes. Confirm the account is clean:

bash

PREFIX=yourinitials-payrail
aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`${PREFIX}\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`${PREFIX}\`)]"

Both should be empty of this lab. Full notes: cleanup.

---

Mark Path C complete when

  • [ ] curl on health_url returns ok
  • [ ] ./scripts/demo.sh prints PASS and 409 against the https://…execute-api… URL
  • [ ] Crash-after-gateway → 504 → 409 → sweeper → 201 same payment_intent_id
  • [ ] terraform destroy finished and the prefix is gone from Lambda/DynamoDB

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 sentenceFunction / fileWhat happens
“I claim the key before I call the gateway.”claim_key in lab_store.py / dynamo_store.pyFirst writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”charge() in charge.pyIf completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”charge() after the hash checkrequest_hash is SHA-256 of {amount_cents, currency}.
“Store down → fail closed.”StoreDown → 503Do not charge if you cannot record the attempt.

Happy path (first POST)

  1. Client sends Idempotency-Key + X-Tenant-Id + { amount_cents, currency }.
  2. charge() hashes the body.
  3. claim_key creates a processing row (or returns the existing one).
  4. Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
  5. An order_id is minted once, stored, and cached on the key row.
  6. 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

  1. charge.py — claim / replay / 409 / 503
  2. lab_store.py — in-memory version of the same API (pytest + local server)
  3. dynamo_store.py — the AWS version (attribute_not_exists claim)
  4. sweeper.py — heal stuck processing
  5. worker.py — event_id dedupe
  6. terraform/main.tf — what apply builds

Failure drill

Failure drill

Failure drill — crash after claim

This is the interview timeout.

  1. Claim the idempotency row (processing).
  2. Die before the gateway response is stored.
  3. Client is in UNKNOWN.
  4. Retry the same Idempotency-Key.
  5. 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

SymptomLikely causeFix
terraform apply fails on archive_fileLambda folder missing next to terraform/Keep lambda/ and terraform/ as siblings from the zip
400 missing keyForgot Idempotency-KeyHeader is required on every mutating call
409 different bodyReused a key for a new amountNew logical checkout → new UUID
409 in flightCrash drill or slow gatewayWait for sweeper (~1 min on AWS) or retry later with the same key
503Store downFail closed. Do not charge.
Demo hits localhost and failslocal_server.py not running and no Terraform stateStart the local server or terraform apply first
Worker never writes webhook rowsSQS KMS key does not allow LambdaUse the lab Terraform; do not swap in a generic CMK without grants
orders count > 1 after retryYou changed the keyThe key is the operation. A new key is a new charge.

CloudWatch: /aws/lambda/{prefix}-charge, -worker, -sweeper.

Lab 701 — Test on AWS25 min

Lab 701 — Test 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. Always terraform 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.

Unzip sd-payrail-lab.zip if you have not already:

text

payrail-idempotency/
  lambda/
  scripts/     demo.sh  aws_test.sh  local_server.py
  terraform/
  tests/

---

C1. Apply the stack

bash

cd payrail-idempotency/terraform
cp terraform.tfvars.example terraform.tfvars

Edit terraform.tfvars:

hcl

region      = "us-west-2"
name_prefix = "yourinitials-payrail"

bash

terraform init
terraform apply

Type yes. Wait until it finishes (usually 2–4 minutes).

Copy these outputs — you will use them in every later command:

bash

terraform output

You must see charge_url and health_url starting with https:// and *.execute-api.us-west-2.amazonaws.com. Also note sweeper_function and orders_table.

---

C2. Health check

bash

curl -sS "$(terraform output -raw health_url)"

Expected:

json

{"ok": true, "service": "payrail-charges"}

If this fails, wait 20 seconds (API Gateway auto-deploy) and retry. Still failing: troubleshooting.

---

C3. Happy-path demo (this is the recording)

From the lab root (payrail-idempotency/), not from terraform/:

bash

chmod +x scripts/demo.sh scripts/aws_test.sh
./scripts/demo.sh

demo.sh reads charge_url from Terraform state when it is a real https:// URL.

Expected (same as local Path B, against API Gateway):

  1. First POST → 201, order_id (ord_…), payment_intent_id (pi_…), x-idempotent-replay: false
  2. Retry same Idempotency-Key → 201, same IDs, x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Same key, amount_cents: 9900 → HTTP 409
  5. Console: Demo succeeded.
  6. If AWS CLI works: orders table COUNT= at least 1

Manual curl (optional — same as the script):

bash

cd terraform
URL="$(terraform output -raw charge_url)"
KEY="demo-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

---

C4. Timeout drill on AWS

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).

bash

cd terraform
URL="$(terraform output -raw charge_url)"
SWEEPER="$(terraform output -raw sweeper_function)"
KEY="aws-crash-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 504

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 409  request in flight

sleep 9
aws lambda invoke --function-name "$SWEEPER" /tmp/payrail-sweep.json
cat /tmp/payrail-sweep.json
# {"healed":[{"key":"aws-crash-…","status":"completed"}],"count":1}

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 201  same payment_intent_id, "healed": true

One command that runs C2–C4 after apply:

bash

cd payrail-idempotency
./scripts/aws_test.sh

Expected last line: AWS Path C succeeded.

COMMON MISTAKE: A new Idempotency-Key after the 504. That is a second charge. Say: “UNKNOWN — retry the same key; the sweeper is the backstop.”

---

C5. What to look at in the AWS console (optional)

WhereWhat you should see
API Gateway → your {prefix}-payrail HTTP APIRoutes POST /v1/charges, GET /health
Lambda → {prefix}-chargeCloudWatch: the two POSTs and the crash header
DynamoDB → {prefix}-idemp-keysOne item demo#{key}, status=completed
DynamoDB → {prefix} orders tableOne row for the happy-path key, not two
SQS DLQDepth 0 after the happy path
EventBridge rule {prefix}-payrail-sweeprate(1 minute)

---

C6. Destroy the same day

bash

cd terraform
terraform destroy

Type yes. Confirm the account is clean:

bash

PREFIX=yourinitials-payrail
aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`${PREFIX}\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`${PREFIX}\`)]"

Both should be empty of this lab. Full notes: cleanup.

---

Mark Path C complete when

  • [ ] curl on health_url returns ok
  • [ ] ./scripts/demo.sh prints PASS and 409 against the https://…execute-api… URL
  • [ ] Crash-after-gateway → 504 → 409 → sweeper → 201 same payment_intent_id
  • [ ] 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.

  1. Claim the idempotency row (processing).
  2. Die before the gateway response is stored.
  3. Client is in UNKNOWN.
  4. Retry the same Idempotency-Key.
  5. 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.

Confirm:

bash

aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`YOURPREFIX\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`YOURPREFIX\`)]"

Both should be empty of this lab's resources.

Troubleshooting

Troubleshooting

Troubleshooting

SymptomLikely causeFix
terraform apply fails on archive_fileLambda folder missing next to terraform/Keep lambda/ and terraform/ as siblings from the zip
400 missing keyForgot Idempotency-KeyHeader is required on every mutating call
409 different bodyReused a key for a new amountNew logical checkout → new UUID
409 in flightCrash drill or slow gatewayWait for sweeper (~1 min on AWS) or retry later with the same key
503Store downFail closed. Do not charge.
Demo hits localhost and failslocal_server.py not running and no Terraform stateStart the local server or terraform apply first
Worker never writes webhook rowsSQS KMS key does not allow LambdaUse the lab Terraform; do not swap in a generic CMK without grants
orders count > 1 after retryYou changed the keyThe key is the operation. A new key is a new charge.

CloudWatch: /aws/lambda/{prefix}-charge, -worker, -sweeper.

Lab 701 — PayRail architecture15 min

Lab 701 — PayRail architecture

PayRail lab architecture — deep dive

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 — same state machine as Stripe, student-account size PayRail AWS lab — same state machine as Stripe, student-account size 1 Client Idempotency-Key timeout = UNKNOWN 2 HTTP API POST /v1/charges GET /health 3 Charge λ claim processing hash body 4 DynamoDB keys + orders mock intents 5 SQS + worker event_id dedupe DLQ ×3 Timeout drill Crash after claim → 504 Retry SAME key → 409 in flight Sweeper (1 min) heals or fails New UUID = a second $25 Production mapping ALB + ECS + Aurora at 5k/s This lab: Lambda + DynamoDB PayRail 93/s, BFCM 1,200/s Fail closed if keys table is down Source: PAKS Stripe Payment Idempotency. No live sk_live_ in the lab.
PayRail AWS lab

Start on your laptop first. One Python process holds every role:

PayRail local lab — every piece on your laptop before AWS PayRail local lab — every piece on your laptop before AWS ONE PROCESS on your laptop — python3 scripts/local_server.py No AWS · No Docker · No Terraform · Everything below lives in this one Python process until you quit 1 Your terminal curl / demo.sh pytest Idempotency-Key 2 HTTP server http.server :8080 127.0.0.1 only routes in box 6 3 charge.py hash → claim create_intent order + complete enqueue 4 Worker thread daemon every 0.2s dequeue → process_event same as Worker λ 5 MemoryStore (lab_store.py) — DynamoDB + SQS + Stripe stand-in Shared by charge, worker thread, and POST /lab/sweep. Cleared when you stop the process. keys{} pk = tenant#key status + hash cached 201 orders{} orderId amount paymentIntentId intents{} Mock Stripe one pi_ per key create_intent() webhooks{} event_id first-wins dedupe table worker writes queue[] in-memory SQS enqueue appends thread pops 6 HTTP routes on :8080 GET /health · GET /v1/orders/{id} · POST /v1/charges POST /lab/sweep · POST /webhooks/stripe 7 sweeper.py (on demand) POST /lab/sweep runs it now No EventBridge timer locally Same charge.py as AWS. Only the store changes: MemoryStore here → DynamoDB + SQS on AWS.
PayRail local lab deployment
Local lab → AWS lab — what each piece becomes Local lab → AWS lab — what each piece becomes Read left to right. Same state machine. Different boxes. Local — Path B One Python process on 127.0.0.1:8080 Zero cloud cost · stop = wipe store AWS — Path C Your account · terraform apply / destroy Under $2 if you destroy today 1 HTTPServer :8080 API Gateway HTTP API 2 charge.py (same file) Charge Lambda 3 MemoryStore.keys + orders DynamoDB keys + orders tables 4 MemoryStore.intents DynamoDB intents (Mock Stripe) 5 MemoryStore.queue[] SQS webhook queue 6 Worker thread every 0.2s Worker Lambda triggered by SQS 7 POST /lab/sweep EventBridge 1 min → Sweeper Lambda 8 curl / demo.sh / pytest Same tools · URL from terraform output Learn Path B first. On the interview board say ALB + ECS + Aurora — this lab trains the state machine.
Local → AWS map
PayRail AWS demo — every service terraform apply creates PayRail AWS demo — every service terraform apply creates YOUR AWS ACCOUNT — terraform apply in labs/payrail-idempotency/terraform Same charge.py as local. Destroy the same day. Typical cost under $2. No live Stripe secret. 1 Client curl / demo.sh Idempotency-Key charge_url 2 API Gateway HTTP POST /v1/charges GET /health GET /orders/{id} POST /webhooks/stripe 3 Charge λ charge.handler timeout 15s hash · claim · intent 4 Webhook λ webhook.handler POST /webhooks/stripe Stripe-style accept 5 DynamoDB (PAY_PER_REQUEST · KMS encrypted) Four tables — same jobs as MemoryStore.keys / orders / intents / webhooks on Path B idemp-keys pk = tenant#key TTL 24h processing / completed orders hash key orderId ledger row amount + pi_ id stripe-intents Mock Stripe one pi_ per key create_intent() webhook-events hash key eventId first-wins dedupe Worker writes here 6 Async path — SQS + Worker · 7 Reconciliation — EventBridge + Sweeper SQS webhooks KMS encrypted visibility 60s Charge λ sends SQS DLQ maxReceive 3 poison messages alarm in prod Worker λ worker.handler SQS event source batch=1 · conc=5 EventBridge + Sweeper λ rate(1 minute) sweeper.handler heal stuck processing 8 KMS + IAM CMK alias …-payrail encrypt DDB + SQS one Lambda role 9 CloudWatch Logs each Lambda log group demo / crash drill store down → 503 10 Terraform outputs charge_url · health_url table + queue names destroy same day Interview board still says ALB + ECS + Aurora + real Stripe. This stack trains the same state machine under $2.
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.

Walk every arrow with pictures: Lab 701 overview — happy path internals (steps 3–7), Mock Stripe, webhook, local lab.

PayRail numbers to say while you demo

ItemNumber
Average authorize93/s (8M/day)
Black Friday1,200/s
p99 budget< 400 ms
2% retries without a key24 duplicate attempts/s
Key TTL24 hours (Stripe default)

Mapping to the interview whiteboard

You drawLab equivalent
ALB + ECSHTTP API + Lambda
Aurora idempotency_keysDynamoDB pk = tenant#key
Stripe PaymentIntentMock intents table
SQS webhooksSQS + worker
Hourly reconEventBridge every 1 minute so the drill is visible

Architecture

Architecture

PayRail lab architecture

Source: PAKS Stripe Payment Idempotency

What this lab is (and is not)

Production (interview whiteboard)This student lab
CloudFront → WAF → ALB → ECS FargateHTTP API → Lambda
Aurora PostgreSQL idempotency_keysDynamoDB pk = tenant#key
Secrets Manager + api.stripe.comIn-account Stripe mock table (no live secret)
SQS webhooks + EventBridge hourly reconSQS + 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 — same state machine as Stripe, student-account size PayRail AWS lab — same state machine as Stripe, student-account size 1 Client Idempotency-Key timeout = UNKNOWN 2 HTTP API POST /v1/charges GET /health 3 Charge λ claim processing hash body 4 DynamoDB keys + orders mock intents 5 SQS + worker event_id dedupe DLQ ×3 Timeout drill Crash after claim → 504 Retry SAME key → 409 in flight Sweeper (1 min) heals or fails New UUID = a second $25 Production mapping ALB + ECS + Aurora at 5k/s This lab: Lambda + DynamoDB PayRail 93/s, BFCM 1,200/s Fail closed if keys table is down Source: PAKS Stripe Payment Idempotency. No live sk_live_ in the lab.
PayRail AWS lab

Charge path

  1. Client sends Idempotency-Key (UUID per logical checkout, reused on retry).
  2. Charge Lambda hashes the body.
  3. Conditional PutItem claims processing. Loser reads the winner.
  4. If completed — return cached JSON. No second intent.
  5. If processing — 409 in flight.
  6. Call the mock gateway (same key → same payment_intent_id).
  7. Write orders row. Mark key completed with the response.
  8. 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 sentenceFunction / fileWhat happens
“I claim the key before I call the gateway.”claim_key in lab_store.py / dynamo_store.pyFirst writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”charge() in charge.pyIf completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”charge() after the hash checkrequest_hash is SHA-256 of {amount_cents, currency}.
“Store down → fail closed.”StoreDown → 503Do not charge if you cannot record the attempt.

Happy path (first POST)

  1. Client sends Idempotency-Key + X-Tenant-Id + { amount_cents, currency }.
  2. charge() hashes the body.
  3. claim_key creates a processing row (or returns the existing one).
  4. Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
  5. An order_id is minted once, stored, and cached on the key row.
  6. 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

  1. charge.py — claim / replay / 409 / 503
  2. lab_store.py — in-memory version of the same API (pytest + local server)
  3. dynamo_store.py — the AWS version (attribute_not_exists claim)
  4. sweeper.py — heal stuck processing
  5. worker.py — event_id dedupe
  6. 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)

Lab 701 — Build PayRail (BUILD-SD-701)35 min

Lab 701 — Build PayRail (BUILD-SD-701)

Lab BUILD-SD-701 — PayRail Stripe-style idempotency

Source scenario: PAKS — Stripe Payment Idempotency

text

Client → API Gateway → Charge Lambda
       → DynamoDB (idempotency_keys + orders + stripe mock)
       → SQS → Worker Lambda (webhook event_id dedupe)
       → EventBridge 1 min → Sweeper Lambda (stuck processing)

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

PathWhat it is
lambda/charge.pyPOST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.pySQS consumer — dedupe event_id
lambda/sweeper.pyHeal rows left processing after a crash
lambda/webhook.pyPOST /webhooks/stripe replay
terraform/Supported deploy path
scripts/local_server.pySame API on :8080 with no AWS
scripts/demo.shSame 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.

2. Deploy to AWS

bash

cd terraform
cp terraform.tfvars.example terraform.tfvars
# edit name_prefix
terraform init
terraform apply

Note charge_url. Then:

bash

../scripts/demo.sh

demo.sh uses Terraform outputs when .terraform exists.

3. Failure drill (ambiguous timeout)

bash

curl -sS -X POST "$(terraform output -raw charge_url)" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-1" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'

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

  1. Same Idempotency-Key → same order_id and payment_intent_id
  2. DynamoDB orders does not grow on retry
  3. Same key, different amount_cents → 409
  4. Missing key → 400
  5. Store down (local: store.down = True) → 503 fail closed
  6. SQS DLQ depth is 0 after a happy-path charge
  7. 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.

StepPortal lessonWhat you do
0Lab 701 — PayRail overviewWhy the lab exists. Download sd-payrail-lab.zip.
1This lessonFollow Path A → B → C below. Do not skip Path B.
2Lab 701 — PayRail architectureMemorize claim / replay / 409 / 503.
3Lab 701 — Build PayRailOpen 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.

  1. On PayRail overview, read the one-sentence promise and the diagram.
  2. 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
  1. On Build PayRail, open charge.py. Find claim_key, then the replay branch (x-idempotent-replay: true), then the 409 hash clash.
  2. Open How the code maps to the interview (extra on this section). Point at the four rows.
  3. Download sd-payrail-lab.zip when you are ready to run Path B.

You can stop here for a whiteboard-only session. Path B is what you show if you have a terminal.

---

Path B — Local demo (required, no AWS)

Watch the local replay first on Lab 701 overview (Watch: local replay), then run the same steps here.

Unzip on your machine. The folder must look like this:

text

payrail-idempotency/
  lambda/          charge.py, lab_store.py, dynamo_store.py, …
  scripts/         local_server.py, demo.sh
  tests/           test_idempotency.py
  terraform/
  requirements-dev.txt
B1. Tests (8 must pass)

bash

cd payrail-idempotency
python3 -m pip install -q -r requirements-dev.txt
python3 -m pytest tests/ -v

Expected last line: `9 passed`.

TestWhat it proves
test_replay_same_key_does_not_double_chargeSame key → same order_id, x-idempotent-replay: true, one order row
test_new_key_creates_new_orderA new key is a second charge
test_same_key_different_body_conflict409, still one order
test_missing_key_is_400Header required
test_in_flight_returns_409Crash after claim → 504, retry → 409
test_store_down_fails_closed503, no charge
test_webhook_dedupeSame event_id is ignored
test_crash_after_gateway_then_sweeper_replays_same_intentGateway charged, process died; sweeper heals; same payment_intent_id
test_sweeper_heals_stuck_processingSweeper completes a stuck row; replay is 201
B2. Start the local API

bash

python3 scripts/local_server.py

Leave it running. You should see:

text

PayRail local lab on http://127.0.0.1:8080

Health check (other terminal):

bash

curl -sS http://127.0.0.1:8080/health

Expected: {"ok": true}.

B3. Happy-path demo (this is the recording)

bash

chmod +x scripts/demo.sh
./scripts/demo.sh

demo.sh posts twice with the same key, then once with a different amount.

Expected:

  1. First POST → 201 and an order_id like ord_… plus payment_intent_id like pi_…
  2. Second POST → 201, same order_id and payment_intent_id, header x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Third POST (amount 9900) → HTTP 409
  5. Console: Demo succeeded.

If you want to see it with curl yourself (same as the script):

bash

KEY="demo-$(date +%s)"
URL="http://127.0.0.1:8080/v1/charges"

# first charge
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# retry — must replay
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

# same key, new amount — must 409
curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":9900,"currency":"usd"}'
B4. Timeout drill (the interview trap)

Still on :8080. Use a new key for each drill.

Crash before the gateway (no money moved). Sweeper marks failed. Replay stays failed. Zero orders.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-before" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 failed replay — still no second charge

Crash after the gateway (intent exists). Sweeper heals. Replay is 201 with the same payment_intent_id.

bash

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 504 — intent created, row still processing

curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 409 in flight

curl -sS -X POST http://127.0.0.1:8080/lab/sweep
curl -sS -X POST http://127.0.0.1:8080/v1/charges \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# 201 healed — same payment_intent_id

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

Cleanup · Troubleshooting

---

What to say while you demo (30 seconds)

“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. Always terraform 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.

Unzip sd-payrail-lab.zip if you have not already:

text

payrail-idempotency/
  lambda/
  scripts/     demo.sh  aws_test.sh  local_server.py
  terraform/
  tests/

---

C1. Apply the stack

bash

cd payrail-idempotency/terraform
cp terraform.tfvars.example terraform.tfvars

Edit terraform.tfvars:

hcl

region      = "us-west-2"
name_prefix = "yourinitials-payrail"

bash

terraform init
terraform apply

Type yes. Wait until it finishes (usually 2–4 minutes).

Copy these outputs — you will use them in every later command:

bash

terraform output

You must see charge_url and health_url starting with https:// and *.execute-api.us-west-2.amazonaws.com. Also note sweeper_function and orders_table.

---

C2. Health check

bash

curl -sS "$(terraform output -raw health_url)"

Expected:

json

{"ok": true, "service": "payrail-charges"}

If this fails, wait 20 seconds (API Gateway auto-deploy) and retry. Still failing: troubleshooting.

---

C3. Happy-path demo (this is the recording)

From the lab root (payrail-idempotency/), not from terraform/:

bash

chmod +x scripts/demo.sh scripts/aws_test.sh
./scripts/demo.sh

demo.sh reads charge_url from Terraform state when it is a real https:// URL.

Expected (same as local Path B, against API Gateway):

  1. First POST → 201, order_id (ord_…), payment_intent_id (pi_…), x-idempotent-replay: false
  2. Retry same Idempotency-Key → 201, same IDs, x-idempotent-replay: true
  3. Console: PASS: same order_id and payment_intent_id on retry
  4. Same key, amount_cents: 9900 → HTTP 409
  5. Console: Demo succeeded.
  6. If AWS CLI works: orders table COUNT= at least 1

Manual curl (optional — same as the script):

bash

cd terraform
URL="$(terraform output -raw charge_url)"
KEY="demo-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'

---

C4. Timeout drill on AWS

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).

bash

cd terraform
URL="$(terraform output -raw charge_url)"
SWEEPER="$(terraform output -raw sweeper_function)"
KEY="aws-crash-$(date +%s)"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -H "X-Lab-Crash-After-Gateway: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 504

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 409  request in flight

sleep 9
aws lambda invoke --function-name "$SWEEPER" /tmp/payrail-sweep.json
cat /tmp/payrail-sweep.json
# {"healed":[{"key":"aws-crash-…","status":"completed"}],"count":1}

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Tenant-Id: demo" \
  -d '{"amount_cents":2500,"currency":"usd"}'
# HTTP 201  same payment_intent_id, "healed": true

One command that runs C2–C4 after apply:

bash

cd payrail-idempotency
./scripts/aws_test.sh

Expected last line: AWS Path C succeeded.

COMMON MISTAKE: A new Idempotency-Key after the 504. That is a second charge. Say: “UNKNOWN — retry the same key; the sweeper is the backstop.”

---

C5. What to look at in the AWS console (optional)

WhereWhat you should see
API Gateway → your {prefix}-payrail HTTP APIRoutes POST /v1/charges, GET /health
Lambda → {prefix}-chargeCloudWatch: the two POSTs and the crash header
DynamoDB → {prefix}-idemp-keysOne item demo#{key}, status=completed
DynamoDB → {prefix} orders tableOne row for the happy-path key, not two
SQS DLQDepth 0 after the happy path
EventBridge rule {prefix}-payrail-sweeprate(1 minute)

---

C6. Destroy the same day

bash

cd terraform
terraform destroy

Type yes. Confirm the account is clean:

bash

PREFIX=yourinitials-payrail
aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`${PREFIX}\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`${PREFIX}\`)]"

Both should be empty of this lab. Full notes: cleanup.

---

Mark Path C complete when

  • [ ] curl on health_url returns ok
  • [ ] ./scripts/demo.sh prints PASS and 409 against the https://…execute-api… URL
  • [ ] Crash-after-gateway → 504 → 409 → sweeper → 201 same payment_intent_id
  • [ ] terraform destroy finished and the prefix is gone from Lambda/DynamoDB

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 sentenceFunction / fileWhat happens
“I claim the key before I call the gateway.”claim_key in lab_store.py / dynamo_store.pyFirst writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”charge() in charge.pyIf completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”charge() after the hash checkrequest_hash is SHA-256 of {amount_cents, currency}.
“Store down → fail closed.”StoreDown → 503Do not charge if you cannot record the attempt.

Happy path (first POST)

  1. Client sends Idempotency-Key + X-Tenant-Id + { amount_cents, currency }.
  2. charge() hashes the body.
  3. claim_key creates a processing row (or returns the existing one).
  4. Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
  5. An order_id is minted once, stored, and cached on the key row.
  6. 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

  1. charge.py — claim / replay / 409 / 503
  2. lab_store.py — in-memory version of the same API (pytest + local server)
  3. dynamo_store.py — the AWS version (attribute_not_exists claim)
  4. sweeper.py — heal stuck processing
  5. worker.py — event_id dedupe
  6. terraform/main.tf — what apply builds

Failure drill

Failure drill

Failure drill — crash after claim

This is the interview timeout.

  1. Claim the idempotency row (processing).
  2. Die before the gateway response is stored.
  3. Client is in UNKNOWN.
  4. Retry the same Idempotency-Key.
  5. 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

SymptomLikely causeFix
terraform apply fails on archive_fileLambda folder missing next to terraform/Keep lambda/ and terraform/ as siblings from the zip
400 missing keyForgot Idempotency-KeyHeader is required on every mutating call
409 different bodyReused a key for a new amountNew logical checkout → new UUID
409 in flightCrash drill or slow gatewayWait for sweeper (~1 min on AWS) or retry later with the same key
503Store downFail closed. Do not charge.
Demo hits localhost and failslocal_server.py not running and no Terraform stateStart the local server or terraform apply first
Worker never writes webhook rowsSQS KMS key does not allow LambdaUse the lab Terraform; do not swap in a generic CMK without grants
orders count > 1 after retryYou changed the keyThe key is the operation. A new key is a new charge.

CloudWatch: /aws/lambda/{prefix}-charge, -worker, -sweeper.

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.

Confirm:

bash

aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`YOURPREFIX\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`YOURPREFIX\`)]"

Both should be empty of this lab's resources.

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)

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 — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache
URL shortener URL shortener Client LB URL service Cache URL DB Redirect path must stay thin. Analytics is optional and async.
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):

InputMathNumber
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 size200 Bmappings stay tiny
Viral codeone key50,000 GET/s for 10 min
Cache 92% hit40k × 0.083,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).

Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
Hit-ratio math

Design choices to decide out loud

ChoiceSimple defaultWhen to changeNumber that decides
Who mints the codeServer random, retry on clashClient vanity slugs23 POST/s — clash retries are cheap
301 vs 302302301 only if target never changesTakedown SLA
DeletesSoft delete + cache bustLegal = short TTL + purge that key60s vs “now”
AnalyticsAsync queue laterThey asked for click counts40k/s must not write a row
Multi-regionOne region firstThey ask DRRPO minutes on mappings is often OK
Hot keyCache + maybe local copyViral 50k/sSharding 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

  1. Read the URL shortener challenge. Hide the reference picture.
  2. Open the live canvas on Architecture canvas.
  3. Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
  4. Fill sections 1–7 (problem through baseline) before you decorate.
  5. Fill 8–16. The hop that dies first is the KV at 40k GET/s.
  6. 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.

Architecture canvas — write these, then draw Architecture canvas — write these, then draw 1 Problem 2 Users 3 Scope 4 Scale 5 APIs 6 Data 7 Baseline 8 Bottleneck 9 Evolve 10 Reliability 11 Security 12 Observe 13 Trade-offs 14 Failures 15 10× 16 Close A filled canvas beats a pretty diagram with no numbers.
Sixteen sections
Architecture canvas — Linkly filled with units (steal the shape) Architecture canvas — Linkly filled with units (steal the shape) 1–3 Scope Short links for news/ads GET anyone · POST staff Out: vanity, analytics 4 Scale 400M/day ≈ 4,630/s Peak 40k/s · 23 POST/s Viral one key 50k/s 5–6 API + data POST /v1/urls → 201 GET /{code} → 302 key = code, 200 B 7 Baseline Client → API → app → KV four boxes 8–9 Bottleneck KV dies at 40k/s Cache-aside 92% 3,200 miss/s 10 Reliability KV get timeout 80ms Retry GET once Cache down → serve KV 11–12 Sec / SLO Auth on POST p99 < 200ms, 99.9% Page 5xx + hit ratio 13–16 Close Loser: 60s takedown 10× = more cache Not Kafka for POSTs Empty Scale row = not ready to present Fill 1–7 before you decorate. Fill 8–16 after you name the hop. ClinicDocs on this canvas must say 240 GB/day and 152 in-flight — not 40k GET/s. Read top to bottom. That is the 45-minute talk.
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)

  1. Problem — one sentence a VP would accept
  2. Users / actors — who writes, who reads, who is admin
  3. Scope — in and out (analytics, vanity, multi-region)
  4. Scale — daily, avg QPS, peak, object size, one hot-key
  5. APIs — 2–4 calls with verbs and status codes
  6. Data — entities, primary key, what is *not* in the row
  7. Baseline — users → door → app → store
  8. Bottleneck — 10×, which hop dies first
  9. Evolve — one fix and why
  10. Reliability — timeout, retry, degrade the user can see
  11. Security — auth, TLS, data class
  12. Observe — one SLI / SLO / page
  13. Trade-offs — winner and what you give up
  14. Failures — two concrete stories
  15. 10× / 100× — what actually changes
  16. 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.

Open Lab 401 — Linkly studio in this Course Player.

Worked example — Linkly filled (copy the shape, not the brand)

#You write
1Short links for articles and ads. Anyone with the code redirects.
2Readers (GET), staff (POST), legal (disable).
3In: create, redirect, disable. Out: vanity, click analytics, QR.
4400M GET/day ≈ 4,630/s, peak 40k/s, 23 POST/s, 200 B, viral 50k/s on one code.
5POST /v1/urls → 201 {code}. GET /{code} → 302. DELETE /{code} → 204.
6code → {url, owner, expires, disabled}. Key = code. No click rows on the GET path.
7Client → API → app → KV.
8KV on the GET path at 40k/s.
9Cache-aside, 92% hit → 3,200 miss/s.
10KV get timeout 80 ms. Retry GET once. If cache down, serve from KV and accept higher p99.
11Auth on POST. Open-redirect allow-list. Public GET is OK.
12SLI: redirect success and p99 < 200 ms. SLO 99.9%. Page 5xx + hit ratio.
13Cache wins latency. What I give up: takedown may linger 60s unless we invalidate that key.
14Viral code 50k/s — cache holds. Cache cluster death — fall through to KV, shed bots.
1510× GET → more cache nodes. 100× → still not Kafka for 230 POST/s.
16Thin path, 40k/s hop, cache + 60s staleness.

Fill 1–7 before you decorate. Fill 8–16 after you have a bottleneck.

Second pass — ClinicDocs on the same canvas (do not copy Linkly)

#Different answer
480k files/day, 3 MB → 240 GB/day, ~19/s peak, scan 8s → ~152 in-flight
5POST /v1/files → 202 {id}. GET /v1/files/{id} status. Search is another API.
7Client → API → landing bucket + metadata row → queue → scanners → clean bucket
8Scanner time, not QPS
9More workers on queue age; do not enlarge the upload API
13202 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

  1. Read the URL shortener challenge. Hide the reference picture.
  2. Open the live canvas on Architecture canvas.
  3. Use the napkin if you want to recompute. Default assumption: 400M redirects/day.
  4. Fill sections 1–7 (problem through baseline) before you decorate.
  5. Fill 8–16. The hop that dies first is the KV at 40k GET/s.
  6. 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.

Same ‘event’ word — three different designs Same ‘event’ word — three different designs Ingest bus · 1M/day 1,000,000 / 86,400 ≈ 12/s Peak 10× ≈ 120/s 50 KB → ~50 GB/day 202 + queue + workers Not a 40-service mesh ClinicDocs · pipeline 80k × 3 MB = 240 GB/day ~19/s peak · scan 8s ~152 in-flight scanners Bytes in object store Queue message = file id TicketDrop · on-sale 500k in the room at 10:00 Admit ~3,000/s Hold 30s → 90k in-flight Inventory is the gate Do not ‘process later’ Divide by 86,400 before you name a broker. PulseFeed is a third cousin: 185 post/s but 150k feed reads/s. The bus is not the feed. Headline counts lie. Payload, time, and inventory decide the boxes.
1M/day vs ClinicDocs vs TicketDrop

Do the napkin out loud

What they sayMathWhat you draw
1,000,000 items a day÷ 86,400About 12 per second on a normal day
Busy hour 10×About 120 per second at the peak
Each item is 50 KB1 million × 50 KBAbout 50 GB a day of data
ClinicDocs: 80,000 PDFs × 3 MB, 8-second scanAbout 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 peak120 × 121,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

LetterPlain English
D — DefineWho 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 — SizeUse the napkin above. Stop when more decimal places will not change a box on the board.
C — CreateSender → front door → safe waiting list → workers → small status record → other systems that need the result.
A — APIsPOST /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 — LocateSlow workers (oldest job waits too long), too many outbound calls, or one bad file that blocks a worker.
E — EvolveAdd 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-processing platform Event-processing platform Producer Ingest Buffer Processors Metadata Consumers Ingest → durable buffer → processors → metadata → consumers.
Event platform shape

Good defaults (and when to change)

ChoiceStart withChange when
Waiting listA 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 listenersSeparate workers or a shared announcementNever call 12 outside systems one-by-one on the user’s request
OrderSame group key stays in orderThey demand one order for everything — push back
“Exactly once”Unique key + update the same status rowDo not claim a magic switch on the waiting list
Big filesFile store + pointerThe 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.

Open Lab 501 — Event studio.

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)

Time

25–30 minutes.

Steps

  1. Read Event platform design.
  2. Open the live canvas on that lesson (different save from Linkly).
  3. Pick ClinicDocs (80k × 3 MB, 8-second scan) *or* 1M items a day.
  4. Fill sections 1–7 — include a safe waiting list.
  5. Fill 8–16 — the pain is usually slow workers or too many outbound calls, not “upload speed.”
  6. Mark complete. Do not paste the Linkly cache answer.

Checklist

  • [ ] You divided the headline by 86,400
  • [ ] First response is 202 (“accepted”), not “fully searchable”
  • [ ] The waiting-list message is not a whole PDF
  • [ ] You named retries / failed-jobs and “same key twice”
  • [ ] You can say why TicketDrop is a different problem

Check: 1,000,000 / 86,400 ≈ 12 per second. File size, time, and inventory decide the boxes.

TicketDrop flash-sale25 min

TicketDrop flash-sale

TicketDrop flash-sale challenge

Today we design TicketDrop with D-SCALE on the board — waiting room, admit rate, and inventory as the gate.

The idea: A compact 20–30 minute design for traffic, correctness, and concurrency pressure.

Why we learn this

Selectable as the LIVE challenge when those are the gaps. Otherwise practice it on your own.

Lab: Lab 551 — TicketDrop (ARCHITECT-SD-551) — use the live widget on this lesson.

Numbers on the widget are teaching / interviewer assumptions.

Use DETECT → IMPACT → MITIGATE → RECOVER → PREVENT on the failure row.

Lab 551 brief

Lab 551 brief

Lab 551 — TicketDrop flash-sale

Today we design a fair admit path, scarce inventory, and recovery from expiry and retries — without inventing a 500,000 QPS checkout.

The idea: Admit people fairly, hold scarce inventory correctly, and recover from expiry and retries — without inventing a 500,000 QPS checkout.

Why we practice this

Flash-sale interviews reward fairness and inventory truth, not a fake mega-QPS checkout. Practice the waiting room and the gate out loud.

Teaching assumptions (interviewer-provided)

AssumptionValue
On-sale inventory80,000 tickets
People in the waiting room at 09:59:58500,000
Waiting-room admit rate3,000/s (labeled; you may change it if you say why)
Checkout think-time30 seconds
Client retries on timeout2%

If 500k hit checkout at once, you invented a 500k QPS event. Inventory is the gate.

What you must produce

  1. Three key requirements (fairness / no oversell / user-visible hold)
  2. Capacity napkin — admit rate, in-flight holds (admit × 30s), vs 80k tickets
  3. Thin architecture — waiting room, admit, hold, pay, confirm (four to six boxes)
  4. Inventory-correctness decision — how a hold becomes a sale; what a retry uses as its key
  5. One failure using DETECT → IMPACT → MITIGATE → RECOVER → PREVENT (example: payment timeout after hold)
  6. Scale evolution — 10× demand in the room, not 10× checkout boxes
  7. Named tradeoff (winner and loser)
  8. 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 — what should be on the board 45 minutes — what should be on the board 0–5 D Actors, done, fail Analytics out Paid mapping stays 5–10 S 400M → 4,630/s Peak 40k/s 23 POST/s · 200 B 10–20 C+A API → app → KV GET /{code} key = code 20–30 L 40k/s on KV Cache 92% 3,200 miss/s 30–38 Timeout 80ms Cache down? Degrade + shed 38–45 Loser: 60s Two-minute close If the prompt is ClinicDocs, minute 8 is 240 GB/day and 152 in-flight — not 40k GET/s. If they say peak is 20×, erase and recompute. Do not add logos after minute 40. The clock is part of the design. Leave five minutes to close.
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.”

How to take it in the room: Mock interview.

Example board (Linkly-shaped prompt)

MinuteOn the board
3Anyone redirects. Staff create. Do not lose paid mappings. Analytics out.
8400M/day ≈ 4,630/s, peak 40k/s, 23 POST/s
15API → app → KV. GET /{code}, POST /v1/urls
25Cache 92% → 3,200 miss/s. Viral 50k/s is a hot key.
35KV timeout 80 ms. Cache down → serve KV, shed bots.
41Give up: 60s takedown unless we invalidate. No 301.
44Thin path, 40k/s hop, cache + 60s staleness.

ClinicDocs-shaped? Minute 8 is 240 GB/day and ~152 in-flight, not 40k GET/s.

How probes change

LevelWhat they add
IntermediateHelp on numbers; stay on one product
SeniorPeak 20×; a dependency is down
Staff / PrincipalMulti-tenant, compliance, “delete a box”

Reference solutions stay hidden until scoring.

Weights (1–5 → 0–100)

DimensionWeight
Requirements10%
Estimation8%
API / Data10%
Architecture18%
Scalability12%
Reliability12%
Trade-offs12%
Security / Observability6%
Communication12%

Architecture is large because a thin path plus one evolution beats a logo pile. Communication is large because they hire someone they can follow.

1 vs 5 examples: Scorecard.

INTERVIEW TIP: Write D-SCALE in the corner and tick. The clock is part of the design.

Scorecard

Scorecard

Mock interview scorecard

Today we learn what a 1 vs a 5 sounds like so you can study the right gap.

The idea: Use the score to pick next week’s drills — not to guess if you will get an offer.

Same prompt — what a 1 vs a 5 sounds like Same prompt — what a 1 vs a 5 sounds like 1 — logo pile ‘We will use Kafka, Cassandra, four regions, and Kubernetes.’ No QPS. No key. No loser. Still drawing boxes at minute 40. 5 — units on the board ‘400M/86,400 ≈ 4,630/s, peak 40k/s.’ Four boxes, then one cache. 92% hit → 3,200 miss/s. Loser: 60s takedown unless we bust the key. Architecture is 18% of the mock. Communication is 12%. The mural without numbers loses both. The rubric rewards the thin path plus one evolution. It does not predict hiring.
What 1 vs 5 sounds like

1 vs 5 (with numbers)

Line1 looks like5 looks like
RequirementsDrew immediately“Disable is in. Analytics is out. Losing a paid mapping is unacceptable.”
Estimation“High scale”“400M/86,400 ≈ 4,630/s, peak 40k/s. Stop.”
API / DataNo contractGET /{code} → 302. Key = code.
ArchitectureLogo pileFour boxes, then one cache because 40k/s.
Scalability“We scale out”“10× GET → more cache. 23 POST/s stays put.”
ReliabilityHappy path only“KV timeout 80 ms. Cache down → serve KV, shed bots.”
Trade-offs“It depends”“Cache for 40k/s. I give up 60s takedown unless we invalidate.”
Sec / obsNever mentioned“SLO 99.9% p99 < 200 ms. Auth on POST.”
CommunicationMute or rambleChecks in, invites correction, closes in two minutes.

Weights are on the brief. Architecture 18%, Communication 12%.

Same prompt, two candidates

A draws Kafka and four regions in minute two. No QPS. Fashionable logos → weak Estimation and Architecture.

B writes 4,630/s and 40k/s, four boxes, cache at 92% hit, names the 60s takedown cost → strong Estimation, Architecture, Trade-offs.

The rubric rewards B.

After the mock: 7-day plan.

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.

Full clock examples and probe levels: Mock brief.

What a 1 vs a 5 sounds like: Scorecard.

If the prompt is unfamiliar

Map it, then use this prompt’s numbers:

Sounds likeTreat as
Redirect / slug / QRLinkly
Timeline / celebrityPulseFeed
Live map / presenceRideHail
Charge / wallet / ledgerPayRail
Upload / scan / searchClinicDocs
On-sale / inventoryTicketDrop

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 from the two weakest skills Seven days from the two weakest skills Day 1 Skill A Day 2 Skill B Day 3 Redo A Day 4 Medium Day 5 Advanced Day 6 Timed Day 7 Close Ten mastered questions beat one silent read of the whole bank Practice out loud. Silent scrolling does not survive a whiteboard.
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:

  1. Two weakest readiness skills
  2. Two weakest mock rubric lines

Map each to a bank category. Do not invent a seventh “add Kafka” day.

Your week (fill the blanks)

DayFocusDo thisDone when
1Readiness gap AFive bank questions out loud in that categoryEach answer has one number or labeled assumption
2Readiness gap BFive more, same ruleYou can name one mistake you almost made
3Mock gap ATeach one Day-1 answer to a wall (60–90s, no notes)Clear without memorizing a napkin that does not match the prompt
4Mock gap BOne medium design on a fresh canvas (or TicketDrop compact)Units on the scale line; one bottleneck
5Unfamiliar shapeOne item from the 25 practice problems — design before probesThin path + what you give up
6Endurance45-minute mock or written rehearsalClock on the table; notes saved
7CloseOpening 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…
EstimationChanged-telemetry, then one napkin with units
Data / APIsKey + API first (Linkly code, ClinicDocs pointer, PayRail key)
ScalabilityPulseFeed read:write or RideHail ping vs trip
ReliabilityPayRail same-key after timeout; TicketDrop hold expiry
Trade-offsOne sentence: I picked X because of Y; I give up Z
Security / observabilityOne journey SLO; what must never hit the logs

For how to use the bank out loud: Question bank.

Night-before ticks: Final checklist.

Certificate

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 on Linkly — six sentences with units D-SCALE on Linkly — six sentences with units D · Define Anyone with the link 201 create · 302 redirect Do not lose paid traffic S · Size 400M GET/day 4,630/s avg · 40k/s peak 23 POST/s · 200 B values C · Create HLD API → app → key-value Four boxes on the board No queue yet A · APIs & data POST /v1/urls → 201 GET /{code} → 302 Primary key = code L · Bottleneck GET path is the hot hop 40k/s would melt one KV Cache-aside next E · Trade-off Cache ~92% hit 60s TTL with jitter Loser: instant purge Open, then write this on the board “Before I design I will clarify. I assume 400 million redirects/day, 4,630/s average, 40,000/s peak, 200-byte values. Thin path is API → app → key-value. First bottleneck is reads. I add a cache, accept a 60s takedown window, and I will not draw Kafka for 23 creates/s.” Tick the letters. The numbers are the design.
D-SCALE
Six interview workloads — memorize the shape, not the brand Six interview workloads — memorize the shape, not the brand Linkly · short links 400M redirects/day ≈ 4,630/s avg · 40k/s peak Creates 2M/day ≈ 23/s Viral code can hit 50k/s PulseFeed · home feed 80M DAU · 16M posts/day Writes ≈ 185/s Feed reads ≈ 28k/s avg Peak reads ≈ 150k/s (≈150:1) RideHail · live map 300k drivers at peak Ping every 4s → 75k writes/s Trips 1.5M/day ≈ 17/s Reads are nearby drivers PayRail · charges 8M charges/day ≈ 93/s Black Friday peak 1,200/s p99 authorize < 400 ms Duplicate charge = fail ClinicDocs · PDFs 80k files/day · 3 MB 240 GB/day · 20/s peak Scan 8s → ~160 in flight Search in 60s after upload TicketDrop · on-sale 80k tickets · 500k in room All want 10:00:00.000 Checkout ~30s Need a waiting-room queue Say this: these are labeled assumptions, not leaked telemetry If the interviewer gives different numbers, erase yours and recompute. The method stays. Use the same six stories in every lesson so the numbers stay honest.
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 — news desk ships a short code; the internet follows it Linkly — news desk ships a short code; the internet follows it 1 Marketing staff Mint a code for an article or a paid campaign 2M creates/day ≈ 23/s Rate-limit bots here 2 Mapping store code → long URL ~200 bytes Must survive a crash Paid codes are revenue 3 Anyone with the link Reader, SMS, social app, crawler GET /{code} → 302 Location 400M/day ≈ 4,630/s average Morning news peak ≈ 40,000/s POST GET Thin path (minute 4) Client → API → app → KV Four boxes. Creates are easy. Do not draw a stream yet. First evolve Cache-aside on GET 92% hit → 3,200 miss/s Invalidate on disable Loser: 60s takedown lag Viral article One code, 50k GET/s Hot key — not a shard Cache + stampede lock Sharding that key fails What the product is Short links are the distribution primitive for news and ads. The interview is the redirect path staying up — not a URL catalog. Lose a paid mapping and the campaign is gone. Say: anyone with the link redirects; staff create; I cache GET; 23 POST/s does not buy Kafka.
Linkly use-case: staff mint a code, anyone with the link redirects, one viral key is the fire
Linkly — start thin, then evolve the 40k/s hop Linkly — start thin, then evolve the 40k/s hop 1 Users phones / bots 2 API GET /{code} 3 App stateless 4 KV store code → url 40k/s dies here Users API App Cache 92% 36.8k/s hits KV 3.2k/s misses comfortable Trade-off you must say We cache hot codes for 60s. A takedown can linger until TTL unless we invalidate that key. We will not 301 if legal disable matters. Minute 4 picture is four boxes. Minute 20 picture adds one cache. Not Kafka.
Linkly thin path, then cache-aside on the 40k/s hop
Cache — hit ratio is a number, not a logo Cache — hit ratio is a number, not a logo 1 Request 40,000 GET/s peak Linkly redirect 2 Cache 92% hit → 36,800/s 8% miss → 3,200/s 3 Store of record Only the 3,200/s misses Fits one well-run KV If no cache 40,000/s on DB That is the outage miss Viral stampede One news code expires 5,000 clients miss together Lock-on-miss or serve stale 2s Jitter TTL 50–70s PayRail — do not cache this Authorize result is money Write-behind can lose a capture Cache tokens / session only Ledger path skips the cache Size the cache Hot 1% of 200M codes × 300 B ≈ 0.6 GB. That fits RAM. Caching 100% of cold codes is a waste. Say hit ratio, miss QPS, TTL, and stampede. “Add Redis” is not a design.
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
  1. Staff POST a long URL (optional custom slug). Service mints a code and returns 201.
  2. A reader, SMS client, or social app GET /{code} and receives 302 Location to the article or campaign.
  3. Legal or marketing disables a code. The next GET must stop serving that campaign — browsers must not cache a 301 forever.
  4. 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

LetterWhat you write on the board
DAnyone with the link redirects. Staff create. Done = 201 / 302. Must not lose a paid mapping.
S400M GET/day ≈ 4,630/s, peak ~40k/s, 2M POST/day ≈ 23/s, 200-byte values.
CClient → API → stateless app → key-value store.
APOST /v1/urls, GET /{code}. Key = code.
LGET path at 40k/s; secondary = uniqueness on mint and takedown vs cache.
ECache-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).
Evolve
Cache-aside, ~92% hit, 60s TTL, invalidate on DELETE. App copies stay stateless.
What you give up
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 — Home is a read product; a celebrity is a different machine PulseFeed — Home is a read product; a celebrity is a different machine Quiet author 200 followers Publish → 201 Fan-out-on-write is cheap 185 posts/s globally Celebrity 12 million followers One post ≠ 12M writes on the request path Pull at read time Reader opens Home ~30 opens / user / day 80M DAU → ~28k reads/s avg Morning peak ~150k reads/s p99 a few hundred ms In 45 minutes Publish + home feed Out: stories, ads, live, DMs Likes may lag Hybrid fan-out Push to normal timelines after 201 (async) Pull celebrity posts when the reader arrives Trap Join follow graph on GET or sync-write 12M rows Empty home = churn What the product is Retention is “open the app, see people I follow.” You design publish + home — not Instagram. Read:write is about 150:1. One celebrity key can melt a shard. Say: publish and home only. Likes can lag. I will not fan-out 12 million writes on one publish.
PulseFeed use-case: quiet authors vs a celebrity, and Home as a read product
PulseFeed — 150:1 reads, so you do not write the feed on the request PulseFeed — 150:1 reads, so you do not write the feed on the request Publish 185 posts/s POST /posts Post store id → body, author source of truth Fan-out worker async after 202 or fan-out on read Home feed read 28k/s avg · 150k/s peak cache + precomputed Fan-out on write (celebrity pain) Push post id to 12M follower timelines 12M writes for one publish Too slow for a mega-account Hybrid: push normal, pull celebs Fan-out on read Build feed at read time from following graph + recent posts Heavier reads, cheap writes Cache the built timeline 10–30s 80M DAU assumption. Pick hybrid and name the celebrity exception.
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
  1. An author publishes. HTTP returns 201. Fan-out to follower timelines may finish later.
  2. A reader opens Home and sees recent posts from people they follow (p99 under a few hundred ms).
  3. A reader likes a post. The count can lag — this is not a card-capture path.
  4. 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

LetterWhat you write on the board
DLogged-in readers + authors. Features = publish + home. Ads/live out. Likes may lag.
S16M posts/day ≈ 185/s. 80M × 30 opens ≈ 28k feed reads/s, peak ~150k/s. 150:1.
CPublish API → post store. Feed API → timeline cache / merge.
APOST /posts, GET /feed?cursor=. Do not join the follow graph on GET.
LRead QPS and the 12M-follower publish.
EHybrid fan-out + cached timeline. Loser: celebrity freshness / like lag.

APIs

  • POST /v1/posts { body } → 201 { postId }
  • GET /v1/feed?cursor= → 200 { items, nextCursor }
  • 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

Labeled napkin

80M DAU · 16M posts/day ≈ 185 writes/s · ~30 feed opens/user/day ≈ 28k reads/s avg · peak ~150k reads/s · celebrity 12M followers · read:write ≈ 150:1

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 — the live map and the trip are two products in one app RideHail — the live map and the trip are two products in one app Hot path — map 300k drivers at 17:30 Ping lat/lng every 4s 75,000 overwrite writes/s Rider sees nearby cars Stale by 4s is OK Do not mix stores Pings: latest point only key = driverId TTL 15–30s + geo cell Append = 1.3 TB/day Slow path — trip 1.5M trips/day ≈ 17/s Request → match → hold Transactional row Pay after drop-off Actors Rider, driver app Dispatch, payments Not a city warehouse in the 45-minute core Nearby read Query a geo cell return ~20 cars Do not scan 300k rows Downtown cell can melt Cannot happen Charge the rider twice Ledger on the ping table Keep every breadcrumb What the product is Liquidity is seeing cars move. Trust is not charging twice. Those SLOs are different, so the stores are different. Change the data model (overwrite) before you buy nodes. Say: pings and payments are two products. I overwrite latest. I will not put the ledger on the ping table.
RideHail use-case: live map vs trip/pay as two products
RideHail — 75k location writes/s is a different system than trip checkout RideHail — 75k location writes/s is a different system than trip checkout Driver phone 300k online ping every 4s 200 B payload Ingest + buffer 75k writes/s overwrite by driverId do not append forever Latest location key = driverId TTL 15–30s geo index for nearby Rider map read nearby 20 stale 4s is OK not a ledger Trip start (17/s) — strong path Rider + driver + fare hold Use a transactional store Do not put this on the ping table If you store every ping forever 75k × 200 B × 86,400 ≈ 1.3 TB/day Keep last point + 15 min ring History goes to a warehouse later Two products, two stores. Mixing them is the common miss.
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
  1. A driver app pings lat/lng every 4 seconds so the live map stays current. The store overwrites latest point by driverId.
  2. A rider opens the map, sees ~20 nearby cars from a geo cell, and requests a trip.
  3. Dispatch matches a driver. The trip is a transactional record (rider, driver, fare hold).
  4. 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

LetterWhat you write on the board
DRider, 300k drivers, dispatch, pay-after-trip. Map + match in scope. Pricing ML out.
S300k / 4s = 75k writes/s. 1.5M trips/day ≈ 17/s. 200 B pings.
CPing ingest → latest-location store. Trip API → transactional store.
APUT location by driverId. GET nearby by cell. POST /trips.
LAppend-forever ping volume, or one hot downtown cell.
EOverwrite + 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 — one tap, two HTTP calls, one $49 PayRail — one tap, two HTTP calls, one $49 1 Shopper Taps Pay Phone can timeout Retries the same tap 2 Idempotency-Key Client-generated Same key ~10 min First write wins 3 Authorize 93/s average Black Friday 1,200/s p99 < 400 ms 4 Ledger row chargeId unique pending → captured This is “done” Timeout after success Authorize wrote the row. 201 never reached the phone. Retry + same key → original. Retry + no key → second $49. Math that changes the box 2% of 1,200/s = 24 retries/s Without a key that is 24 double-captures per second. Replicas do not add write QPS. What the product is Merchants need a processor that survives retries and Black Friday noon. The interview is correctness: one ledger row per tap. Email, rewards, and FX corridors are not the 45-minute product. Say: done is a ledger row, not an email. I require an Idempotency-Key. I will not shard at minute five.
PayRail use-case: one tap, a timeout, the same key, one ledger row
PayRail — the same click can hit you twice; money cannot PayRail — the same click can hit you twice; money cannot Client User taps Pay retries on timeout Idempotency-Key Same key 10 min First write wins Authorize 93/s avg · 1,200/s peak p99 < 400 ms Ledger row chargeId unique state: pending→captured Timeout after authorize succeeded 1) Client never got the 201. 2) Client retries with the same key. 3) You return the original charge — not a second $49. Without the key: 1,200/s × 2% ≈ 24 double-charges/s. At-least-once + idempotency. Do not say exactly-once unless you can explain the key.
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
  1. Merchant or app POST /charges with an Idempotency-Key. Authorize returns 201 + chargeId.
  2. The phone times out after the write succeeded. The same key is retried. You return the original charge.
  3. Capture moves money. The ledger row is the source of truth — not “receipt email sent.”
  4. 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

LetterWhat you write on the board
DCardholder, merchant, finance. Done = ledger row. Two captures is unacceptable.
S8M/day ≈ 93/s. Peak 1,200/s. 2% retries = 24/s. p99 < 400 ms.
CAPI → authorize service → ledger primary. Email is off the path.
APOST /charges + Idempotency-Key. Unique chargeId. State machine.
LDownstream timeout and duplicate taps.
EKey + 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 — a clinic day of PDFs, not a social network ClinicDocs — a clinic day of PDFs, not a social network Clinic upload 80k files/day ≈ 0.93/s average ~19/s when open 3 MB PDF 202 + landing Accepted, not clean Hostile bucket No public URL PHI stays private Queue + scan ~8 seconds / file 19/s × 8s ≈ 152 in flight Scale workers Clean object Object store 240 GB/day ~88 TB/year DB holds pointer Clinician Signed URL Search in ≤ 60s Index may lag SoR is the file If you scan on the HTTP request p99 becomes 8s+ Phones retry the upload You DDoS your own API Always 202 + status poll Not an EHR No scheduling or billing No e-prescribe or charting Upload · status · clean get Auditor sees who fetched What the product is Hospitals receive referrals and reports as PDFs. The interview is pipeline time and PHI — not internet scale. 19 files/s is a queue. 240 GB/day is an object store. Say: upload returns 202. Scan is behind a queue. I will not call 19 files/s internet scale.
ClinicDocs use-case: clinic day upload, private landing, scan, clean download
ClinicDocs — 80k PDFs/day is a pipeline, not internet scale ClinicDocs — 80k PDFs/day is a pipeline, not internet scale Upload 20/s peak presigned PUT 201 ≠ scanned Landing hostile bucket 3 MB objects not downloadable Queue age alarm visibility > 8s Scanner 8s × 20/s ≈ 160 in flight scale workers Clean + metadata search index lags 60s SLA is the pipeline not the HTTP timeout Storage 80k × 3 MB = 240 GB/day × 365 ≈ 88 TB/year object store + lifecycle DB holds pointer + status Scan on the upload request? p99 becomes 8s+ phones retry you DDoS yourself Always 202 + status poll 240 GB/day lives in object storage. Search is an index of clean objects.
Pipeline numbers: 19/s peak, 152 in-flight, 240 GB/day
Who uses it
Clinic uploaders, malware-scan workers, clinicians, a patient portal, and an auditor who will ask who fetched a file.
In 45 minutes
Upload, status, download clean. Out of scope: A full EHR, e-prescribe, scheduling, billing, real-time collaboration on the PDF.
What people do
  1. A clinic uploads a PDF (often via a presigned PUT). HTTP returns 202 accepted with a job id — not 201 with a public URL.
  2. Workers pull from a queue, scan (~8 s), and write a clean object. The landing bucket stays private and is never served.
  3. A clinician or patient downloads the clean file via a short-lived signed URL.
  4. Search becomes useful within ~60 seconds. If search is down, the detail page still works (metadata + signed URL).
Done means
202 on upload. Clean object ready in ≤ 60 seconds. Status API tells you when.
Cannot happen
Serve an unscanned landing-bucket file. Put 240 GB/day of bytes in a row store. PHI in logs or a public bucket.

Walk D-SCALE on this product

LetterWhat you write on the board
DClinic, scanner, clinician, auditor. Upload / status / clean download. PHI. Not an EHR.
S80k/day ≈ 0.93/s, peak ~19/s, 3 MB, 240 GB/day, 8s × 19 ≈ 152 in-flight.
CUpload API → landing → queue → workers → clean + metadata.
APOST 202, GET status, signed GET download. Key = fileId.
LIn-flight scanners and yearly object growth.
EQueue + workers + lifecycle. Loser: sync “file ready” on upload.

APIs

  • POST /v1/files → 202 { fileId, status: accepted }
  • 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.

Common traps

  • Calling 80,000 files/day internet scale
  • Scanning on the upload request so phones retry
  • PDFs in Postgres
  • A public bucket because “doctors need it fast”

Labeled napkin

80k files/day · 3 MB · 240 GB/day · ~19/s peak · scan 8s → ~152 in-flight · search in 60s · ~88 TB/year · lifecycle / cold storage

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 — 10:00 is crowd control, not a checkout API TicketDrop — 10:00 is crowd control, not a checkout API 09:59:58 ~500,000 fans already in the room Bots will jump the line Checkout is still closed Waiting room Admit ~3,000/s Lottery or FIFO Poll every 2–5s Not 500k QPS Hold + pay Hold a seat 30–90s Checkout ~30s Retry the hold id Never a new decrement Inventory 80,000 seats This is the gate Oversell = 0 Then stop admits If 500k hit checkout You invented a 500k QPS event A box sized for 10:00 sits idle 364 days per year The room is cheaper than hope Fairness is the product A real seat or a clear miss Per-user poll limits IP is a bad key (stadium NAT) Hold id is the retry token What the product is A promoter sold 80k seats. Half a million people want them at 10:00. You are designing a fair chance to buy a real seat. Not a storefront that survives 500k POSTs. Say: I will not take 500k checkouts at 10:00. The room admits a survivable rate. Inventory is the gate.
TicketDrop use-case: 500k in the room, admit, hold, inventory as the gate
TicketDrop — 500k people, 80k tickets, one clock tick TicketDrop — 500k people, 80k tickets, one clock tick 500k browsers refresh at 09:59:58 without a room this is 500k QPS Waiting room admit 2–4k/s lottery or FIFO poll every 2–5s Checkout hold 90s 80k inventory idempotent pay Sold out stop admits clear room no thundering herd Numbers to say If 500k hit checkout, you melt. Admit 3,000/s × 30s checkout ≈ 90,000 in-flight holds. Still above 80k tickets — inventory is the gate, not hope. The waiting room is the architecture. Fairness is a product choice. The queue is not optional at this shape.
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
  1. Before 10:00, fans sit in a waiting room. Checkout is closed. Poll every 2–5 seconds, not a refresh storm.
  2. The room admits people at a rate checkout and inventory can survive (~3,000/s), not 500,000 QPS.
  3. An admitted fan holds a specific seat (or a general-admission slot) for ~30–90 seconds and pays.
  4. 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

LetterWhat you write on the board
DFans, bots, box office. Fair chance + no oversell. Season tickets out.
S80k seats, 500k in room, admit ~3k/s, checkout 30s → ~90k holds, inventory gates.
CWaiting room → admit → hold → pay. Checkout is closed before 10:00.
ARoom status, POST hold, POST checkout on holdId.
L500k QPS if the room is missing; hot event row if inventory is one lock.
ERoom + 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.”
  • [ ] Four clarifying questions: who, what, done, fail (then scale)
  • [ ] 86,400 memorized; you can do daily → QPS out loud
  • [ ] Linkly: 4,630/s avg, 40k/s peak, 23 POST/s, cache 92% → 3,200 miss/s
  • [ ] ClinicDocs: 240 GB/day, ~19/s, ~152 in-flight, 202 + queue
  • [ ] PayRail: 93/s, BFCM 1,200/s, p99 < 400 ms, Idempotency-Key
  • [ ] PulseFeed: ~150:1 read:write, celeb 12M — do not fan-out-on-write blindly
  • [ ] RideHail: 75k pings/s, overwrite latest, trips are 17/s elsewhere
  • [ ] TicketDrop: waiting room, admit ~3k/s, inventory is the gate
  • [ ] One simple baseline: users → door → app → store
  • [ ] One cache story (aside, TTL, miss, stampede)
  • [ ] One queue story (accepted vs finished, idempotent, DLQ)
  • [ ] One failure story (degrade mode the user can see)
  • [ ] One trade-off sentence: I picked X because of this number (or this rule). What I give up is Z.
  • [ ] Two-minute close rehearsed once out loud
  • [ ] Sleep. Do not reread the entire bank

In the room

Write D-SCALE in the corner. Tick. Watch the clock. Leave five minutes to close.

45 minutes — what should be on the board 45 minutes — what should be on the board 0–5 D Actors, done, fail Analytics out Paid mapping stays 5–10 S 400M → 4,630/s Peak 40k/s 23 POST/s · 200 B 10–20 C+A API → app → KV GET /{code} key = code 20–30 L 40k/s on KV Cache 92% 3,200 miss/s 30–38 Timeout 80ms Cache down? Degrade + shed 38–45 Loser: 60s Two-minute close If the prompt is ClinicDocs, minute 8 is 240 GB/day and 152 in-flight — not 40k GET/s. If they say peak is 20×, erase and recompute. Do not add logos after minute 40. The clock is part of the design. Leave five minutes to close.
Clock

If they give different numbers, erase yours and recompute. The method stays.

If your mind goes blank

Say an assumption. Draw the thin path. Ask which hop they want to deep-dive. That is enough to restart.

INTERVIEW TIP: You do not need a perfect diagram. You need a clear method and units on the board.

45-minute guide

45-minute guide

45-Minute Interview Time Guide

text

0–5     Requirements
5–10    Estimation
10–20   High-level design
20–30   Deep dive
30–38   Scale / reliability
38–43   Trade-offs
43–45   Summary

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

  1. Read title, prompt, and constraints.
  2. State labeled assumptions with units. Divide by 86,400. Apply a peak factor.
  3. Walk D → S → C → A → L → E out loud.
  4. Reveal interviewer guidance — probes, mistakes, bottlenecks.
  5. Only then reveal the deep answer: napkin → components (what to use) → architecture → sequence steps with numbers.
  6. Compare. Mark attempted.

These are P-01–P-25 in the player — practice, not twenty-five scored labs.

Live instructors usually assign one problem in the 7-day plan — a different shape than the coaching challenge and the Full Mock.

Problem list download

Problem list download

25 System Design Problems

BayLearn · System Design Interview Sprint

P-01 — URL Shortener

INTERMEDIATE

Design a URL shortening service similar to TinyURL.

Functional: Create short URL; Redirect short URL; Optional custom alias; Optional expiration

Nonfunctional: Low redirect latency; High availability; Durable mappings; Read-heavy; Abuse prevention

P-02 — Pastebin

INTERMEDIATE

Design a pastebin-like service for text snippets with optional expiration and public/unlisted links.

Functional: Create paste; Read paste by id; Expire; Optional custom path

Nonfunctional: Low read latency; Durability until expiry; Abuse/spam controls

P-03 — Rate Limiter

INTERMEDIATE

Design a rate limiter that protects APIs per user, IP, and API key.

Functional: Allow/deny decision; Multiple policies; 429 + Retry-After

Nonfunctional: Very low latency; High availability; Fairness under burst

P-04 — Notification Service

INTERMEDIATE

Design a notification service that sends email, SMS, and push from many product teams.

Functional: Enqueue notification; Templates; Preferences; Delivery status

Nonfunctional: At-least-once; Backpressure; Per-channel rate limits

P-05 — File Upload Service

INTERMEDIATE

Design a service that accepts large file uploads and makes them available for download.

Functional: Resumable upload; Complete; Download via signed URL; Virus scan optional

Nonfunctional: Multi-GB files; Integrity; Access control

P-06 — Image Hosting

INTERMEDIATE

Design an image hosting service with thumbnails and global reads.

Functional: Upload; Multiple renditions; Public or private URLs

Nonfunctional: Read-heavy; Global latency; Cost-aware egress

P-07 — Key-Value Store

INTERMEDIATE

Design a distributed key-value store with get/put and optional TTL.

Functional: Get; Put; TTL; Replication

Nonfunctional: High availability; Horizontal scale; Tunable consistency

P-08 — Web Crawler

INTERMEDIATE

Design a polite web crawler that fetches pages and stores them for later indexing.

Functional: Seed URLs; Fetch; Extract links; Store content; Politeness

Nonfunctional: Scale to millions of URLs; Avoid bans; Freshness

P-09 — Chat / Messaging System

SENIOR

Design a chat/messaging system for 1:1 and small groups with online presence.

Functional: Send/receive; History; Presence; Media optional

Nonfunctional: Low latency; At-least-once with idempotent display; Ordering per conversation

P-10 — News Feed

SENIOR

Design a news feed for a social network.

Functional: Publish post; Read home feed; Follow graph

Nonfunctional: Read-heavy; Freshness vs cost; Celebrity accounts

P-11 — Video Streaming

SENIOR

Design a video upload and streaming service.

Functional: Upload; Process renditions; Play

Nonfunctional: Startup time; Global CDN; DRM optional

P-12 — Ride Sharing

SENIOR

Design a ride-hailing matching system.

Functional: Request ride; Match driver; Track; Complete

Nonfunctional: Low match latency; Geo queries; Surge

P-13 — Food Delivery

SENIOR

Design a food-delivery platform.

Functional: Browse; Order; Dispatch courier; Track

Nonfunctional: Marketplace consistency; ETA; Peak dinner

P-14 — Search Autocomplete

SENIOR

Design typeahead search.

Functional: Prefix suggest; Personalize optional; Analytics

Nonfunctional: <100ms; High QPS; Freshness

P-15 — Distributed Job Scheduler

SENIOR

Design a distributed cron/job scheduler.

Functional: Register job; Fire on schedule; Retries

Nonfunctional: Exactly-once appearance; Shard leadership; Catch-up

P-16 — Metrics / Monitoring Platform

SENIOR

Design a metrics ingestion and query platform.

Functional: Ingest; Rollup; Query; Alert

Nonfunctional: High write QPS; Retention tiers; Cardinality

P-17 — Logging Platform

SENIOR

Design a centralized logging platform.

Functional: Ingest logs; Index; Search; Retain

Nonfunctional: Burst buffering; Cost; PII

P-18 — Payment Processing System

SENIOR

Design a payment capture and settlement flow.

Functional: Authorize; Capture; Refund; Ledger

Nonfunctional: Idempotency; Strong consistency; Audit

P-19 — Multi-tenant SaaS Platform

STAFF_PRINCIPAL

Design a multi-tenant SaaS control and data plane.

Functional: Provision tenant; Auth; Isolate data; Meter

Nonfunctional: Noisy neighbor; Tiered isolation; Residency

P-20 — Global API Platform

STAFF_PRINCIPAL

Design a global public API platform.

Functional: Keys; Rate limits; Routing; Versioning

Nonfunctional: Edge latency; Abuse; Regional failover

P-21 — Event Processing Platform

STAFF_PRINCIPAL

Design a platform that ingests and processes up to 1,000,000 events or files per day and distributes results to multiple downstream consumers.

Functional: API/file ingest; Validate; Durable accept; Async process; Fan-out; Replay

Nonfunctional: Backpressure; Idempotency; DR; Audit

P-22 — Enterprise File Transfer Platform

STAFF_PRINCIPAL

Design an enterprise file-transfer platform for partners.

Functional: SFTP/HTTPS ingest; Scan; Route; Audit

Nonfunctional: Compliance; Large files; Partner isolation

P-23 — Feature Flag Platform

STAFF_PRINCIPAL

Design a feature-flag platform.

Functional: Create flag; Target; Evaluate locally; Audit

Nonfunctional: Eval latency; Fail-open/closed; Consistency

P-24 — Distributed Workflow Engine

STAFF_PRINCIPAL

Design a workflow/orchestration engine.

Functional: Define workflow; Start run; Timers; Compensate

Nonfunctional: Exactly-once steps; Long running; Visibility

P-25 — Global Notification Platform

STAFF_PRINCIPAL

Design a global notification platform for many products and regions.

Functional: Send; Fan-out; Preferences; Quiet hours

Nonfunctional: Regional providers; Priority; Compliance

Download the full lab (all code)

PayRail source, Terraform, local server, and pytest. Read charge.py here, then deploy in your AWS account and destroy the same day.

Download sd-payrail-lab.zip

You will

  • Walk charge.py branches with HTTP codes
  • 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 with Lab 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

FileInterview 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

  1. Open the appendix page for that file.
  2. Read the teacher explanation (tables + short snippets).
  3. Open the same source in the lab pack / extras browser and skim the real lines.
  4. Say the interview sentence out loud once.

Do not copy-paste into the whiteboard. Point and narrate.

---

Read order (do not skip)

StepLessonWhy this order
1Appendix — ChargeHappy path + every HTTP branch clients see
2Appendix — Lab storeThe lock, hashes, intents, queue — clearest version
3Appendix — Dynamo storeSame API; distributed claim *(AWS example only)*
4Appendix — Async healSweeper, worker, webhook, Stripe mock
5Appendix — Local and testsHow you run it; what each test catches

---

Napkin reminder (say these numbers)

ScenarioRough rate
Steady: 8M charges/day≈ 93/s
Black Friday peak1,200/s
2% retries without a key≈ 24 duplicate attempts/s

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.

Next: Charge handler line walk.

Code walkthrough (short)

Code walkthrough (short)

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 sentenceFunction / fileWhat happens
“I claim the key before I call the gateway.”claim_key in lab_store.py / dynamo_store.pyFirst writer inserts status=processing. Everyone else sees the existing row.
“Same key + same body = replay.”charge() in charge.pyIf completed, return the cached 201 and x-idempotent-replay: true.
“Same key + different body = 409.”charge() after the hash checkrequest_hash is SHA-256 of {amount_cents, currency}.
“Store down → fail closed.”StoreDown → 503Do not charge if you cannot record the attempt.

Happy path (first POST)

  1. Client sends Idempotency-Key + X-Tenant-Id + { amount_cents, currency }.
  2. charge() hashes the body.
  3. claim_key creates a processing row (or returns the existing one).
  4. Mock Stripe writes one PaymentIntent keyed by tenant#key — not a new intent per retry.
  5. An order_id is minted once, stored, and cached on the key row.
  6. 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

  1. charge.py — claim / replay / 409 / 503
  2. lab_store.py — in-memory version of the same API (pytest + local server)
  3. dynamo_store.py — the AWS version (attribute_not_exists claim)
  4. sweeper.py — heal stuck processing
  5. worker.py — event_id dedupe
  6. terraform/main.tf — what apply builds

Lab README

Lab README

Lab BUILD-SD-701 — PayRail Stripe-style idempotency

Source scenario: PAKS — Stripe Payment Idempotency

text

Client → API Gateway → Charge Lambda
       → DynamoDB (idempotency_keys + orders + stripe mock)
       → SQS → Worker Lambda (webhook event_id dedupe)
       → EventBridge 1 min → Sweeper Lambda (stuck processing)

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

PathWhat it is
lambda/charge.pyPOST /v1/charges — claim key, call gateway mock, cache response
lambda/worker.pySQS consumer — dedupe event_id
lambda/sweeper.pyHeal rows left processing after a crash
lambda/webhook.pyPOST /webhooks/stripe replay
terraform/Supported deploy path
scripts/local_server.pySame API on :8080 with no AWS
scripts/demo.shSame 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.

2. Deploy to AWS

bash

cd terraform
cp terraform.tfvars.example terraform.tfvars
# edit name_prefix
terraform init
terraform apply

Note charge_url. Then:

bash

../scripts/demo.sh

demo.sh uses Terraform outputs when .terraform exists.

3. Failure drill (ambiguous timeout)

bash

curl -sS -X POST "$(terraform output -raw charge_url)" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-1" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'

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

  1. Same Idempotency-Key → same order_id and payment_intent_id
  2. DynamoDB orders does not grow on retry
  3. Same key, different amount_cents → 409
  4. Missing key → 400
  5. Store down (local: store.down = True) → 503 fail closed
  6. SQS DLQ depth is 0 after a happy-path charge
  7. 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.

Source: labs/payrail-idempotency/lambda/charge.py (~193 lines).

---

File map

LinesWhatWhy
15–25get_store()Memory for local/tests; Dynamo when KEYS_TABLE is set *(AWS example only)*
28–65HelpersHeaders, body parse, JSON-safe Decimal, _resp
68–157charge()Claim → replay / 409 / 503 → Stripe → order → enqueue
160–193handler()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)

FunctionJob
_headersLowercase header names so Idempotency-Key and idempotency-key both work
_bodyParse JSON body; decode base64 if the gateway sent it that way
_jsonableTurn Dynamo Decimal into int/float before json.dumps
_resp(code, payload, extra_headers?)Always returns { statusCode, headers, body } — what Lambda / local server send

python

# L61–65
def _resp(code, payload, extra_headers=None):
    headers = {"content-type": "application/json"}
    if extra_headers:
        headers.update(extra_headers)
    return {"statusCode": code, "headers": headers, "body": json.dumps(_jsonable(payload))}

Every client-visible code below comes from _resp.

---

charge() — validation (400)

python

# 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"})
BranchHTTPWhy
Missing / blank key400No key → no idempotency story
Bad amount_cents400Must be positive int
Currency not usd400Lab constraint

Tenant defaults to "demo" if the header is missing. Hash is only over { amount_cents, currency } — not the key itself.

python

# L88–89
payload = {"amount_cents": amount, "currency": currency}
req_hash = request_hash(payload)

---

Claim — and fail closed (503)

python

# L91–94
try:
    claim = store.claim_key(tenant, key, req_hash)
except StoreDown:
    return _resp(503, {"error": "idempotency store unavailable — fail closed"})
BranchHTTPWhy
Store raises StoreDown503Do 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 stateSame body?HTTPHeaderWhy
AnyHash mismatch409—Same key must mean same request
completedYes201 (or cached status)x-idempotent-replay: trueSafe retry — same order
processingYes409—In flight; client should retry same key later
failedYescached (often 402 / 504)x-idempotent-replay: trueReplay 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"})
BranchHTTPWhy
crash_after_claim=True504Simulates 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.

---

Gateway call — success or fail_key (504)

python

# L112–117
try:
    intent = stripe(tenant, key, amount, currency)
except Exception as exc:
    err = {"error": "gateway timeout or error", "detail": str(exc)}
    store.fail_key(tenant, key, 504, err)
    return _resp(504, err)
BranchHTTPWhy
Stripe / mock raises504Key marked failed with that body; later retries replay the failure

In the real handler, stripe is store.create_intent — one PaymentIntent per tenant#key.

---

Lab crash after gateway (504, intent exists)

python

# L119–127
if crash_after_gateway:
    return _resp(
        504,
        {
            "error": "lab crash after gateway — intent exists, row left processing",
            "hint": "run the sweeper to heal",
            "payment_intent_id": intent.get("paymentIntentId"),
        },
    )
BranchHTTPWhy
crash_after_gateway=True504Money path may already have an intent; row still processing; no order yet

Sweeper finds the intent → heal → complete with same payment_intent_id. Header: X-Lab-Crash-After-Gateway: 1.

---

Happy path — order, complete, enqueue (201)

python

# L129–157
order_id = "ord_" + uuid.uuid4().hex[:12]
store.put_order({... "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"})
StepSide effectClient sees
Mint order_idOnce per successful first claimInside 201 body
put_orderLedger rowGET /v1/orders/{id} later
complete_keyRow → completed + cached bodyNext same-key POST replays
enqueueWebhook-style eventWorker dedupes on event_id
Return—201, x-idempotent-replay: false

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

CodeWhen
400Missing key; bad amount; currency ≠ usd
201First success, or completed replay
409Hash mismatch, or still processing
402 / cachedFailed-key replay (default if status missing)
503Store down — fail closed
504Lab crash headers, or gateway exception (then fail_key)
404Order GET miss (handler)
405Non-POST on charge path (handler)
200Health / 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)
RouteMethodHTTP outcomes
…/healthGET200
…/v1/orders/{id}GET200 or 404
anything elsenot POST405
charge (POST)POSTwhatever 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.

Prev: Appendix overview · Next: Memory store

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

charge.py source

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)

Appendix — Lab store20 min

Appendix — Lab store

Appendix — lab_store.py (MemoryStore)

Today we walk the in-memory store. This is the clearest version of the lock. Pytest and the local server both use it.

The idea: Idempotency is not a header alone. It is insert-if-absent on tenant#key, then status transitions: processing → completed or failed.

Source: labs/payrail-idempotency/lambda/lab_store.py.

---

File map

LinesWhatWhy
13–14StoreDownFail-closed signal for charge → 503
17–19request_hashCanonical JSON → SHA-256
26–34MemoryStore.__init__Dicts for keys, orders, webhooks, intents, queue
36–38_checkIf down, raise StoreDown
40–41pktenant#key composite id
49–66claim_keyThe lock
68–88complete_key / fail_keyTerminal states + cached response
90–103OrdersLedger write / read / count
105–112put_webhookFirst event_id wins
114–120enqueue / dequeueIn-memory stand-in for a queue
122–137create_intentOne PaymentIntent per tenant#key
139–142stuck_processingSweeper input

---

StoreDown and fail closed

python

# L13–14
class StoreDown(Exception):
    pass

python

# L36–38
def _check(self) -> None:
    if self.down:
        raise StoreDown("idempotency store unavailable")

Set store.down = True in tests. Charge catches it and returns 503. Interview line: If I cannot record the attempt, I do not charge.

---

request_hash — same key, same body

python

# L17–19
def request_hash(body: dict) -> str:
    canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

Charge hashes { amount_cents, currency }. Same key with a different amount → hash mismatch → 409.

---

What’s inside MemoryStore

Dict / listHoldsInterview role
keysIdempotency rowsClaim / replay
ordersOfficial chargesLedger
intentsMock gateway PIsOne pi_… per key
webhooksSeen event_idsAt-least-once dedupe
queuePending eventsLocal SQS stand-in
lockthreading.LockSafe under local worker thread
downboolLab “store unavailable”

pk(tenant, key) → f"{tenant}#{key}". That string is the uniqueness domain.

---

claim_key — the lock

python

# L49–66
def claim_key(self, tenant, key, req_hash):
    self._check()
    pk = self.pk(tenant, key)
    with self.lock:
        existing = self.keys.get(pk)
        if existing:
            return {"created": False, "row": dict(existing)}
        row = {
            "pk": pk,
            "tenantId": tenant,
            "idempotencyKey": key,
            "requestHash": req_hash,
            "status": "processing",
            "createdAt": now_ms(),
            "updatedAt": now_ms(),
        }
        self.keys[pk] = row
        return {"created": True, "row": dict(row)}
OutcomeMeaning
created: TrueYou own the attempt. Safe to call the gateway.
created: FalseSomeone already claimed. Charge inspects status / hash.

Interview sentence: “I claim the key before I call the gateway.” Point here.

There is no update-if-processing race on first insert: the lock + “exists → return” is the single-writer gate for this process.

---

complete_key and fail_key

python

# L68–78  complete
row["status"] = "completed"
row["responseStatus"] = response_status
row["responseBody"] = response_body
row["orderId"] = order_id
row["paymentIntentId"] = pi

python

# L80–88  fail
row["status"] = "failed"
row["responseStatus"] = response_status
row["responseBody"] = response_body
MethodStatusWhat charge replays later
complete_keycompletedCached 201 body + same order_id
fail_keyfailedCached error (e.g. 504 gateway fail)

Both bump updatedAt. Sweeper uses updatedAt to find stuck processing rows.

---

Orders

MethodJob
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
ReturnMeaning
TrueFirst time — process side effects
FalseDuplicate 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.

---

create_intent — one PI per key

python

# L122–137
def create_intent(self, tenant, key, amount, currency):
    pk = self.pk(tenant, key)
    with self.lock:
        existing = self.intents.get(pk)
        if existing:
            return dict(existing)
        intent = {
            "paymentIntentId": "pi_" + uuid.uuid4().hex[:16],
            "status": "succeeded",
            ...
        }
        self.intents[pk] = intent
        return dict(intent)

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.

Prev: Charge · Next: Dynamo store

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

lab_store.py source

python

"""In-memory store for local tests and the local server. AWS uses DynamoDB in each handler."""

from __future__ import annotations

import hashlib
import json
import threading
import time
import uuid
from typing import Any


class StoreDown(Exception):
    pass


def request_hash(body: dict) -> str:
    canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def now_ms() -> int:
    return int(time.time() * 1000)


class MemoryStore:
    def __init__(self) -> None:
        self.lock = threading.Lock()
        self.down = False
        self.keys: dict[str, dict[str, Any]] = {}
        self.orders: dict[str, dict[str, Any]] = {}
        self.webhooks: dict[str, dict[str, Any]] = {}
        self.intents: dict[str, dict[str, Any]] = {}
        self.queue: list[dict[str, Any]] = []

    def _check(self) -> None:
        if self.down:
            raise StoreDown("idempotency store unavailable")

    def pk(self, tenant: str, key: str) -> str:
        return f"{tenant}#{key}"

    def get_key(self, tenant: str, key: str) -> dict[str, Any] | None:
        self._check()
        with self.lock:
            row = self.keys.get(self.pk(tenant, key))
            return dict(row) if row else None

    def claim_key(self, tenant: str, key: str, req_hash: str) -> dict[str, Any]:
        self._check()
        pk = self.pk(tenant, key)
        with self.lock:
            existing = self.keys.get(pk)
            if existing:
                return {"created": False, "row": dict(existing)}
            row = {
                "pk": pk,
                "tenantId": tenant,
                "idempotencyKey": key,
                "requestHash": req_hash,
                "status": "processing",
                "createdAt": now_ms(),
                "updatedAt": now_ms(),
            }
            self.keys[pk] = row
            return {"created": True, "row": dict(row)}

    def complete_key(self, tenant: str, key: str, response_status: int, response_body: dict, order_id: str, pi: str) -> None:
        self._check()
        pk = self.pk(tenant, key)
        with self.lock:
            row = self.keys[pk]
            row["status"] = "completed"
            row["responseStatus"] = response_status
            row["responseBody"] = response_body
            row["orderId"] = order_id
            row["paymentIntentId"] = pi
            row["updatedAt"] = now_ms()

    def fail_key(self, tenant: str, key: str, response_status: int, response_body: dict) -> None:
        self._check()
        pk = self.pk(tenant, key)
        with self.lock:
            row = self.keys[pk]
            row["status"] = "failed"
            row["responseStatus"] = response_status
            row["responseBody"] = response_body
            row["updatedAt"] = now_ms()

    def put_order(self, order: dict[str, Any]) -> None:
        self._check()
        with self.lock:
            self.orders[order["orderId"]] = dict(order)

    def get_order(self, order_id: str) -> dict[str, Any] | None:
        self._check()
        with self.lock:
            row = self.orders.get(order_id)
            return dict(row) if row else None

    def order_count(self) -> int:
        with self.lock:
            return len(self.orders)

    def put_webhook(self, event_id: str, payload: dict[str, Any]) -> bool:
        """Return True if this is the first delivery."""
        self._check()
        with self.lock:
            if event_id in self.webhooks:
                return False
            self.webhooks[event_id] = dict(payload)
            return True

    def enqueue(self, message: dict[str, Any]) -> None:
        with self.lock:
            self.queue.append(dict(message))

    def dequeue(self) -> dict[str, Any] | None:
        with self.lock:
            return self.queue.pop(0) if self.queue else None

    def create_intent(self, tenant: str, key: str, amount: int, currency: str) -> dict[str, Any]:
        pk = self.pk(tenant, key)
        with self.lock:
            existing = self.intents.get(pk)
            if existing:
                return dict(existing)
            intent = {
                "paymentIntentId": "pi_" + uuid.uuid4().hex[:16],
                "status": "succeeded",
                "amountCents": amount,
                "currency": currency,
                "tenantId": tenant,
                "idempotencyKey": key,
            }
            self.intents[pk] = intent
            return dict(intent)

    def stuck_processing(self, older_than_ms: int) -> list[dict[str, Any]]:
        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]

Appendix — Dynamo store15 min

Appendix — Dynamo store

Appendix — dynamo_store.py (same API, distributed claim)

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 / pytestLab on AWS (example)What you say in interview
MemoryStoreDynamoStoreSame claim / complete / fail / intent / webhook API
Process dict + lockConditional put_itemRow unique on tenant#key
Python list queueSQS send_messageAsync webhook delivery
—Tables from envKEYS_TABLE, ORDERS_TABLE, WEBHOOKS_TABLE, INTENTS_TABLE

Charge never branches on “are we on Dynamo?” except get_store() when KEYS_TABLE is set.

---

File map

LinesMethodSame job as MemoryStore?
15–23__init__Wire tables + SQS client
25–26pkYes — tenant#key
28–33get_keyYes — StoreDown on ClientError
35–55claim_keyYes — distributed via condition
57–83complete_key / fail_keyYes — update_item
85–93OrdersYes
95–103put_webhookYes — conditional on eventId
105–113enqueue / dequeueEnqueue → SQS; dequeue is no-op
115–137create_intentYes — conditional insert
139–146stuck_processingYes — scan filter

---

The distributed claim

python

# L35–55
def claim_key(self, tenant, key, req_hash):
    pk = self.pk(tenant, key)
    ttl = int(time.time()) + 24 * 3600
    item = {
        "pk": pk,
        "tenantId": tenant,
        "idempotencyKey": key,
        "requestHash": req_hash,
        "status": "processing",
        "createdAt": now_ms(),
        "updatedAt": now_ms(),
        "ttl": ttl,
    }
    try:
        self.keys.put_item(Item=item, ConditionExpression="attribute_not_exists(pk)")
        return {"created": True, "row": item}
    except ClientError as exc:
        if exc.response["Error"]["Code"] != "ConditionalCheckFailedException":
            raise StoreDown(str(exc)) from exc
        existing = self.get_key(tenant, key)
        return {"created": False, "row": existing or item}
PieceMeaning
attribute_not_exists(pk)First writer wins across all Lambda copies
Successcreated: True — you own processing
ConditionalCheckFailedExceptionKey already exists → created: False
Any other ClientErrorStoreDown → charge returns 503
ttl 24hLab 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.

---

Webhook dedupe on Dynamo

python

# L95–103
def put_webhook(self, event_id, payload) -> bool:
    item = {"eventId": event_id, **payload}
    try:
        self.webhooks.put_item(Item=item, ConditionExpression="attribute_not_exists(eventId)")
        return True
    except ClientError as exc:
        if exc.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return False
        raise

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
LocalAWS example
queue.append / pop(0)SQS send; Worker Lambda reads Records
dequeue used by local drain loopUnused 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.

Prev: Memory store · Next: Async heal

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

dynamo_store.py source

python

"""DynamoDB backend — same methods as MemoryStore, used in AWS."""

from __future__ import annotations

import os
import time
from typing import Any

import boto3
from botocore.exceptions import ClientError

from lab_store import StoreDown, now_ms


class DynamoStore:
    def __init__(self) -> None:
        self.ddb = boto3.resource("dynamodb")
        self.keys = self.ddb.Table(os.environ["KEYS_TABLE"])
        self.orders = self.ddb.Table(os.environ["ORDERS_TABLE"])
        self.webhooks = self.ddb.Table(os.environ["WEBHOOKS_TABLE"])
        self.intents = self.ddb.Table(os.environ["INTENTS_TABLE"])
        self.sqs = boto3.client("sqs")
        self.queue_url = os.environ.get("WEBHOOK_QUEUE_URL")

    def pk(self, tenant: str, key: str) -> str:
        return f"{tenant}#{key}"

    def get_key(self, tenant: str, key: str) -> dict[str, Any] | None:
        try:
            resp = self.keys.get_item(Key={"pk": self.pk(tenant, key)})
        except ClientError as exc:
            raise StoreDown(str(exc)) from exc
        return resp.get("Item")

    def claim_key(self, tenant: str, key: str, req_hash: str) -> dict[str, Any]:
        pk = self.pk(tenant, key)
        ttl = int(time.time()) + 24 * 3600
        item = {
            "pk": pk,
            "tenantId": tenant,
            "idempotencyKey": key,
            "requestHash": req_hash,
            "status": "processing",
            "createdAt": now_ms(),
            "updatedAt": now_ms(),
            "ttl": ttl,
        }
        try:
            self.keys.put_item(Item=item, ConditionExpression="attribute_not_exists(pk)")
            return {"created": True, "row": item}
        except ClientError as exc:
            if exc.response["Error"]["Code"] != "ConditionalCheckFailedException":
                raise StoreDown(str(exc)) from exc
            existing = self.get_key(tenant, key)
            return {"created": False, "row": existing or item}

    def complete_key(self, tenant: str, key: str, response_status: int, response_body: dict, order_id: str, pi: str) -> None:
        self.keys.update_item(
            Key={"pk": self.pk(tenant, key)},
            UpdateExpression="SET #s = :s, responseStatus = :rs, responseBody = :rb, orderId = :o, paymentIntentId = :p, updatedAt = :u",
            ExpressionAttributeNames={"#s": "status"},
            ExpressionAttributeValues={
                ":s": "completed",
                ":rs": response_status,
                ":rb": response_body,
                ":o": order_id,
                ":p": pi,
                ":u": now_ms(),
            },
        )

    def fail_key(self, tenant: str, key: str, response_status: int, response_body: dict) -> None:
        self.keys.update_item(
            Key={"pk": self.pk(tenant, key)},
            UpdateExpression="SET #s = :s, responseStatus = :rs, responseBody = :rb, updatedAt = :u",
            ExpressionAttributeNames={"#s": "status"},
            ExpressionAttributeValues={
                ":s": "failed",
                ":rs": response_status,
                ":rb": response_body,
                ":u": now_ms(),
            },
        )

    def put_order(self, order: dict[str, Any]) -> None:
        self.orders.put_item(Item=order)

    def get_order(self, order_id: str) -> dict[str, Any] | None:
        resp = self.orders.get_item(Key={"orderId": order_id})
        return resp.get("Item")

    def order_count(self) -> int:
        return int(self.orders.scan(Select="COUNT").get("Count") or 0)

    def put_webhook(self, event_id: str, payload: dict[str, Any]) -> bool:
        item = {"eventId": event_id, **payload}
        try:
            self.webhooks.put_item(Item=item, ConditionExpression="attribute_not_exists(eventId)")
            return True
        except ClientError as exc:
            if exc.response["Error"]["Code"] == "ConditionalCheckFailedException":
                return False
            raise

    def enqueue(self, message: dict[str, Any]) -> None:
        if not self.queue_url:
            return
        import json

        self.sqs.send_message(QueueUrl=self.queue_url, MessageBody=json.dumps(message))

    def dequeue(self) -> dict[str, Any] | None:
        return None

    def create_intent(self, tenant: str, key: str, amount: int, currency: str) -> dict[str, Any]:
        import uuid

        pk = self.pk(tenant, key)
        existing = self.intents.get_item(Key={"pk": pk}).get("Item")
        if existing:
            return existing
        intent = {
            "pk": pk,
            "paymentIntentId": "pi_" + uuid.uuid4().hex[:16],
            "status": "succeeded",
            "amountCents": amount,
            "currency": currency,
            "tenantId": tenant,
            "idempotencyKey": key,
        }
        try:
            self.intents.put_item(Item=intent, ConditionExpression="attribute_not_exists(pk)")
            return intent
        except ClientError as exc:
            if exc.response["Error"]["Code"] == "ConditionalCheckFailedException":
                return self.intents.get_item(Key={"pk": pk})["Item"]
            raise

    def stuck_processing(self, older_than_ms: int) -> list[dict[str, Any]]:
        cutoff = now_ms() - older_than_ms
        resp = self.keys.scan(
            FilterExpression="#s = :p AND updatedAt <= :c",
            ExpressionAttributeNames={"#s": "status"},
            ExpressionAttributeValues={":p": "processing", ":c": cutoff},
        )
        return list(resp.get("Items") or [])

Appendix — Async heal15 min

Appendix — Async heal

Appendix — Async heal (sweeper, worker, webhook, Stripe mock)

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

FileJobInterview sentence
sweeper.pyFind old processing rows; heal or fail“Stuck claims resolve from gateway truth.”
worker.pyProcess queue messages; dedupe“At-least-once delivery, exactly-once effects.”
webhook.pyHTTP accept → enqueue“202 Accepted; work async.”
stripe_mock.pyThin 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)
StepWhat it does
1store.stuck_processing(older_than_ms)
2For each row, look up intent by pk = tenant#key
3Intent exists → ensure order, complete_key(…, 201, body with healed=True, …)
4No intent → fail_key(…, 504, {"error": "sweeper: no gateway intent found"})
5Return {"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 headerIntent?Sweeper resultLater same-key POST
After claimNofailed / 504 cachedReplay failure (x-idempotent-replay: true)
After gatewayYescompleted / heal201 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)*
handler

python

# L53–54
def handler(event, _context):
    return sweep(get_store())

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}
Caseput_webhookResult
First deliveryTrueduplicate: False
RedeliveryFalseduplicate: 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})
BranchHTTPWhy
No event_id / id400Cannot dedupe later
OK202Accepted; 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)
BranchResult
Missing key400 via _resp
OKDict 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.

Prev: Dynamo store · Next: Local server + tests

Read the lab source

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.

Sources: labs/payrail-idempotency/scripts/local_server.py, labs/payrail-idempotency/tests/test_idempotency.py.

---

local_server.py — routes

Listens on 127.0.0.1:8080. Imports charge, sweep, process_event from the lambda/ package.

GET
PathBehaviorHTTP
/health{"ok": true}200
/v1/orders/{id}get_order200 or 404
other—404
POST
PathBehaviorHTTP
/v1/chargescharge(..., store.create_intent, crash flags from headers)whatever charge returns
/webhooks/stripestore.enqueue(body)202 {"accepted": true}
/lab/sweepsweep(store, older_than_ms=1)200 + heal JSON
other—404

Crash headers (same as Lambda handler):

  • X-Lab-Crash-After-Claim: 1
  • X-Lab-Crash-After-Gateway: 1

python

# L61–73  charges path (shape)
if path == "/v1/charges":
    crash = headers.get("x-lab-crash-after-claim") == "1"
    crash_gw = headers.get("x-lab-crash-after-gateway") == "1"
    self._send(charge(headers, body, store, store.create_intent,
                      crash_after_claim=crash, crash_after_gateway=crash_gw))

Note: local webhook 202 body is {"accepted": true} only (no event_id echo). Lambda webhook.py also returns event_id. Same enqueue idea.

---

Background drain loop

python

# L100–107
def drain():
    store = get_store()
    while True:
        msg = store.dequeue()
        if not msg:
            break
        process_event(store, msg)

python

# L117–123
def _worker_loop():
    while True:
        drain()
        time.sleep(0.2)
PieceRole
Daemon thread started in main()Stand-in for Worker Lambda
Every 0.2sDrain memory queue
process_eventSame dedupe as AWS worker

Stop the process → MemoryStore is gone. Fine for Path B.

---

Start command

bash

cd labs/payrail-idempotency
python3 scripts/local_server.py
# → PayRail local lab on http://127.0.0.1:8080

bash

python3 -m pytest tests/test_idempotency.py -q

---

Each test — what failure it catches

test_replay_same_key_does_not_double_charge
AssertsBreak this and you get…
Both POSTs 201Replay path broken
Same order_id and payment_intent_idSecond claim / second order
order_count() == 1Double charge
Replay header x-idempotent-replay: trueMissing replay signal

Interview: Timeout retry must not create a second order.

---

test_new_key_creates_new_order
AssertsBreak this and you get…
Different order_idsKeys incorrectly shared
order_count() == 2Collapsed two customers into one charge

Interview: A new key is a new charge — intentional.

---

test_same_key_different_body_conflict
AssertsBreak this and you get…
Second POST 409Hash check missing
Still one orderBody change silently rewrote money

Interview: Same key + different body is a client bug → conflict.

---

test_missing_key_is_400
AssertsBreak this and you get…
400 without headerCharges without idempotency

Interview: Key required.

---

test_in_flight_returns_409
SetupAssertsBreak this and you get…
crash_after_claim=TrueFirst 504, second 409, order_count() == 0Retry while processing creates a second attempt / order

Interview: In-flight → tell client to retry the same key; do not proceed.

---

test_store_down_fails_closed
SetupAssertsBreak this and you get…
store.down = True503Charging while unable to claim (double-bill risk)

Interview: Fail closed.

---

test_webhook_dedupe
AssertsBreak this and you get…
First duplicate: False, second TrueSide effects run twice
len(webhooks) == 1No dedupe table

Interview: At-least-once queue needs idempotent consumers.

---

test_crash_after_gateway_then_sweeper_replays_same_intent
StepsAssertsBreak this and you get…
Crash after gateway → 504, no order——
Retry → 409 in flight——
Age the row, sweepcount == 1Heal never runs
Retry again201, one order, PI presentNew PI / second order after heal

Interview: Gateway already took money; heal must reuse the intent.

---

test_sweeper_heals_stuck_processing
StepsAssertsBreak this and you get…
Crash after claim, then manually create_intent—Simulates intent that appeared without complete
Age row, sweepcount == 1Stuck forever
Replay charge201, healed or succeededNever 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.

Prev: Async heal · Hub: Appendix overview

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

local_server.py

python

#!/usr/bin/env python3
"""Local PayRail API — no AWS. python3 scripts/local_server.py"""

from __future__ import annotations

import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.parse import urlparse

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "lambda"))

from charge import charge, get_store  # noqa: E402
from sweeper import sweep  # noqa: E402
from worker import process_event  # noqa: E402

HOST = "127.0.0.1"
PORT = 8080


class Handler(BaseHTTPRequestHandler):
    def _send(self, result: dict) -> None:
        self.send_response(int(result["statusCode"]))
        for k, v in (result.get("headers") or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write((result.get("body") or "").encode("utf-8"))

    def do_GET(self):  # noqa: N802
        store = get_store()
        path = urlparse(self.path).path
        if path == "/health":
            self._send(
                {"statusCode": 200, "headers": {"content-type": "application/json"}, "body": json.dumps({"ok": True})}
            )
            return
        if path.startswith("/v1/orders/"):
            order_id = path.rstrip("/").split("/")[-1]
            row = store.get_order(order_id)
            if not row:
                self._send(
                    {"statusCode": 404, "headers": {"content-type": "application/json"}, "body": json.dumps({"error": "not found"})}
                )
                return
            self._send(
                {"statusCode": 200, "headers": {"content-type": "application/json"}, "body": json.dumps(row)}
            )
            return
        self._send({"statusCode": 404, "headers": {"content-type": "application/json"}, "body": json.dumps({"error": "not found"})})

    def do_POST(self):  # noqa: N802
        store = get_store()
        length = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(length).decode("utf-8") if length else "{}"
        body = json.loads(raw or "{}")
        headers = {k.lower(): v for k, v in self.headers.items()}
        path = urlparse(self.path).path
        if path == "/v1/charges":
            crash = headers.get("x-lab-crash-after-claim") == "1"
            self._send(charge(headers, body, store, store.create_intent, crash_after_claim=crash))
            return
        if path == "/webhooks/stripe":
            store.enqueue(body)
            self._send(
                {
                    "statusCode": 202,
                    "headers": {"content-type": "application/json"},
                    "body": json.dumps({"accepted": True}),
                }
            )
            return
        if path == "/lab/sweep":
            self._send(
                {
                    "statusCode": 200,
                    "headers": {"content-type": "application/json"},
                    "body": json.dumps(sweep(store, older_than_ms=1)),
                }
            )
            return
        self._send({"statusCode": 404, "headers": {"content-type": "application/json"}, "body": json.dumps({"error": "not found"})})

    def log_message(self, fmt, *args):
        sys.stderr.write("local_server: " + (fmt % args) + "\n")


def drain() -> None:
    store = get_store()
    while True:
        msg = store.dequeue()
        if not msg:
            break
        process_event(store, msg)


def main() -> None:
    httpd = HTTPServer((HOST, PORT), Handler)
    print(f"PayRail local lab on http://{HOST}:{PORT}")
    print("POST /v1/charges  GET /health  POST /lab/sweep")
    threading.Thread(target=_worker_loop, daemon=True).start()
    httpd.serve_forever()


def _worker_loop() -> None:
    import time

    store = get_store()
    while True:
        drain()
        time.sleep(0.2)


if __name__ == "__main__":
    main()

Pricing

Choose a delivery mode. BayAreaLa8s invoices after you request a session.

This text is a draft. It is not a current BayLearn offer and it does not change existing bookings. Read the draft refund policy

Self-paced

$49

Small group

$129

Live 1:1

$349

Introductory $299

Book Your Interview Sprint

Request a slot. Invoicing is handled by BayAreaLa8s after the request — no Stripe checkout.

Log in or enroll to request a live session time.