Topic: swe-and-system-design

Reading: 25 min, plus 1 in closed details. A map of how production services are built and kept running: one LLM chat product followed from one user to ten million, six walls in the order they arrive, the building block that fixes each, what it costs, and the child page that owns it. Sources are linked inline; data as of October 2026.

The idea in one screen

A production service is one request path through a few layers (servers, data, slow work, failure handling, the model), and every building block on that path fixes one bottleneck at a price you can name; add it only when its bottleneck has arrived.

System design is the craft of keeping a product fast, correct and affordable as more people use it. The running example. A chat assistant powered by a large language model (LLM): people sign in, chat, upload documents and come back to their history. It starts on one machine with one user and grows to ten million registered users. Every child page of this topic uses the same product, so its numbers line up from page to page. Fig. 1 grows it one wall at a time, in the order the walls arrive: the part that breaks turns red, the building block that fixes it arrives green and names the child page that owns it, and the dots are requests on the paths they take.

Fig. 1 · The product grown wall by wall, each fix with its owner

  1. 1 user: everything on one machine. App code, database and a call to a model API share one server, and requests are a trickle. Nothing is wrong yet, so nothing is added yet.
  2. Step 1: too many requests for one server. 600 a second arrive at a server that answers 400 (illustrative), and the line grows without bound. The fix: a load balancer in front of stateless servers, with the state moved into one shared database. Owners: Capacity planning and performance and Building a backend API.
  3. Step 2: the database becomes the bottleneck. 1,000 reads a second against about 600 answered (illustrative). The fix: a cache that answers nine reads in ten, then read replicas. Owners: Topic: databases and Distributed systems fundamentals.
  4. Step 3: slow work leaves the request path. Uploads take tens of seconds and hold the server’s few slots, so chat messages wait behind them. The fix: a queue and workers, the request answered 202 Accepted at once. Owner: Queues, streams and async work.
  5. Step 4: things fail, and the fixes can make it worse. 1 call in 100 to the model provider hangs for a minute (illustrative), and the hung calls use up every slot. The fix: timeouts, retries with backoff and jitter and a breaker, watched against an SLO. Owners: Reliability engineering and Observability.
  6. Step 5: the GPU layer. Reading an 8-billion-parameter model’s weights takes 4.8 ms per token, so one conversation gets at most about 210 tokens a second. The fix: batching (64 conversations share each read, about 13,000 tokens a second) and a model router. Owners: ML system design, Gateways and routing and Topic: inference-and-serving.
  7. Step 6: designing it on purpose. Estimate before building: 10 million messages a day is 231.5 requests a second in the busy hour, 56 GPUs and 2,315 streams open at once, so the model layer is the hard part. Owners: System design case studies and Capacity planning.
  8. Every step: the code under the boxes. Each fix is code someone must change safely later: tests at the right layer, modules that hide their decisions. Owners: Testing and quality and Code design.

The walls' numbers are the illustrative ones of Steps 1 to 4 below, the derived ceilings of Step 5 and the estimate of Step 6, and the map below gives each fix its price; the layout (the request path in the middle, the model in front, slow work behind) is a drawing, not a deployment. A cache makes reads fast and data slightly stale; a queue makes requests fast and results late; a retry rescues one request and can sink the whole system: every green block is a fix with a price.

You need: nothing from other pages. The wire under Step 1 (DNS, TCP, TLS, HTTP) is Topic: protocols, the database under Step 2 is Topic: databases, and the engine under Step 5 is Topic: inference-and-serving; this page needs only their one-line definitions, given where they are used.

New terms (each defined where it first appears, and only these):

Latency, throughput: how long one request takes; how many finish per second.
p50, p99: the latency that 50% or 99% of requests beat.
Stateless: a server that keeps nothing another server would need.
Replica, shard: a full copy of the database; a slice of it.
At-least-once, idempotent: no job is lost, so one can run twice; running twice has the effect of once.
SLO, error budget: the reliability target; the failures it allows.
Prefill, decode: reading the prompt at once; writing the reply one token per step.
Back-of-the-envelope estimate: arithmetic accurate to a factor of two that finds the hard part.

Three tools on this page span every child: the Scale simulator pushes traffic through the whole design and shows which part breaks first, Numbers to know holds the latency, throughput and price figures every page estimates with, and Case files tells real outages and redesigns, each tagged with the step it belongs to.

The map: six walls, the fix for each, its price, and who owns it

Fig. 1 adds these rows one at a time; the table puts them side by side. Read across a row: what breaks, the blocks that fix it, what those blocks give up, and the page that teaches them in depth. The price column is the part that only shows when the pages are side by side: every fix moves the problem somewhere else.

StepWhat breaksBuilding blocksWhat they costOwner
1 One serverMore requests arrive than one machine finishesBigger machine; more machines behind a load balancer; stateless serversMore machines; state moves to one shared databaseCapacity planning and performance (balancing, queueing); Building a backend API (the service itself)
2 DatabaseEvery server waits on one databaseIndex, cache, read replicas, shardsStale reads, replication lag, cross-shard queries; consistencyTopic: databases (indexes, caching, replicas, sharding); Distributed systems fundamentals (consistency, CAP)
3 Slow workLong jobs hold the slots quick requests needQueue and background workersResults arrive later; jobs run twice; backlogs hide overloadQueues, streams and async work
4 FailureSomething is always failing; retries amplify itTimeouts, retries with backoff and jitter, idempotency keys, breakers, shedding, SLOs, telemetryCode that runs only when things are already wrong; extra load; storage for keys and signalsReliability engineering; Observability
5 GPU layerA reply costs seconds of a GPU, not milliseconds of a CPUBatching, prefix caching, model routing, token rate limitsLatency per user for throughput; wrong cached answers; GPUs slow to addML system design; Gateways and routing; Topic: inference-and-serving
6 MethodA fix that takes months, or a design asked for before the system existsRequirements, estimates, API, data model, boxes, deep divesTime up front; estimates are only as good as their stated assumptionsSystem design case studies; Capacity planning and performance (capacity planning)
Every stepThe code itself gets harder to change safelyTests at the right layer; modules that hide their decisionsTime per change; a suite to keep fast and honestTesting and quality; Code design

Two splits that are easy to miss. Idempotency appears in three places: the HTTP key on one request is Service APIs (section 4), a consumer that ignores a second delivery is Queues, and why exactly-once can only be built end to end is Distributed systems fundamentals (section 9). Pools and the GIL: how many connections and cores a service needs is Capacity planning; how one Python service waits (async, threads, workers) and holds a connection inside a handler is Building a backend API; the pooler in front of Postgres is Running Postgres in production.

Step 1 One server, then too many requests for it

One message is a short chain: DNS turns chat.example.com into an address, TCP opens a connection (one round trip), TLS encrypts it (one more in TLS 1.3; reusing an open connection skips both), and an HTTP request such as POST /chats/42/messages reaches a server process, which checks who you are, reads and writes the database (which keeps data safe on disk: the server can crash and restart, the data must never be lost), calls the model and streams the reply. Each hop's typical time is in Numbers to know; the wire itself is Topic: protocols.

Two words measure it all. Latency is how long one request takes; throughput is how many finish per second. Latency is quoted as percentiles (p50 the typical request, p99 the slowest 1 in 100), because an average hides the slow tail.

The wall
Say one server answers 400 requests a second and 600 arrive (illustrative). Every second 200 more arrive than leave, the line grows, and every user's latency grows with it. When work arrives faster than it is finished, waiting does not rise a little, it rises without bound.

Vertical scaling (a bigger machine) needs no code change and is the right first move, but it has a ceiling and stays a single point of failure. Horizontal scaling adds machines behind a load balancer, which hands each request to one of them and stops sending to any that fails its health checks. It has one precondition that changes how code is written: servers must be stateless, so the session moves into the database, a shared cache or a signed token, and any server can answer any request.

The price, across pages
More machines to run, a balancer that must not become the new single point of failure, and every piece of state now in one shared place, the database: Step 2's wall.
Go deeper. Drawn by the owners: Capacity planning, Fig. 1 (the same work, more and more waiting) and Fig. 2 (one simulated run, four ways to split it); Building a backend API, Fig. 2 (one recorded request, stage by stage). Why waiting explodes near full load, percentiles and the tail, and the load-balancing algorithms with a measured comparison: Capacity planning and performance (Queueing theory you actually use; Load balancing). One request through a real FastAPI service, stage by stage, and its health checks and graceful shutdown: Building a backend API (sections 2 and 9). Push the arrival rate past one server yourself in the Scale simulator.

Step 2 The database becomes the bottleneck

The wall
App servers can be added forever; they all talk to one database. Say the servers together send it 1,000 reads a second and it answers about 600 (illustrative): Step 1's law again, and now every server waits on it. Reads far outnumber writes here, so the fixes start with reads, cheapest first.
FixWhat it doesWhat it costsOwner
IndexA sorted structure from a column's values to its rows, so "messages of chat 42" skips the full scanEvery write updates every index; but many "the database is slow" incidents end with one missing indexStorage engines and indexes
CacheCopies of answers in memory; cache-aside checks it first and fills it on a miss. At a 90% hit rate the database sees one read in tenStale reads, bounded by a TTL or fixed by invalidation; a cold cache sends the full load to a database sized for a tenth of itCaching; hit-rate maths and stampedes in Capacity planning
Read replicaA full copy fed by the primary, which takes every write; reads spread over the copiesReplication lag: a user's own message can vanish on refresh unless recent writes are read from the primaryScaling a database
ShardingEach of several databases holds a slice, chosen by a shard key (shard by user)Queries across users ask every shard; resharding moves data; one hot user stays on one shard. Usually the last resortScaling a database; partitioning in Distributed systems fundamentals

What every copy gives up: consistency. Caches and replicas keep several copies, and copies disagree for a moment after every change. Strong consistency (linearisability) means every read sees the latest write, as if there were one copy; eventual consistency means copies converge once writes stop. CAP: while the network between copies is broken, a system either refuses some requests or answers with possibly stale data. PACELC adds the everyday half: when nothing is broken, it trades latency against consistency. In practice the choice is made per piece of data: a paid credit balance must be strongly consistent (never spend the same credit twice); the order of chats in the sidebar can be a second stale.

Go deeper. Drawn by the owners: Capacity planning, Fig. 3 (the database is sized for the misses); Distributed systems fundamentals, Fig. 2 (where a read meets a write). Database families, indexes, transactions, replicas and sharding: Topic: databases. Cache patterns, hit-rate arithmetic and stampedes: Capacity planning and performance (Caching strategy). Replication styles, the consistency ladder, CAP read correctly and PACELC, consensus: Distributed systems fundamentals (sections 3, 5 and 6). Change the hit rate, replicas and shards in the Scale simulator.

Step 3 Slow work leaves the request path

The wall
Uploading a PDF to chat with it means extracting text, cutting it into pieces and computing an embedding for each (a list of numbers standing for its meaning): tens of seconds. Done inside the request, it holds one of the server's few request slots the whole time, and quick messages queue behind it. On a server with 4 slots, 5 uploads among 30 chat messages made chat messages wait up to 3 seconds that should have waited none (illustrative, checked in src/read/recompute.py).

The user does not need the result now; they need to know it is being done. So the handler writes "process document 981" to a message queue and answers 202 Accepted at once, and separate workers do the work in the background: asynchronous processing.

Three consequences follow, and each has an owner. Jobs can run twice: so that nothing is lost, the queue deletes a job only when a worker confirms it (at-least-once delivery), so jobs must be idempotent, and a job that keeps failing goes to a dead-letter queue. A queue can hide overload: the backlog grows while nothing looks broken, so watch the age of the oldest job and apply backpressure (slow producers down, or refuse work with 429). Workers are sized by arithmetic: Little's law, L = λW, says 5 documents a second at 20 seconds each keeps 5 × 20 = 100 jobs in progress, so at least 100 worker slots (illustrative); the same law sizes the model layer in Steps 5 and 6.

The price, across pages
Results arrive later and the product must show progress; failures happen out of sight and need their own alerts; every job must survive running twice. A queue is for work that can be late, never for the reply the user is staring at.
Go deeper. Drawn by the owners: Queues, streams and async work, Fig. 1 (accept now, do later) and Fig. 4 (the work, the ack, and a crash between them). Queues against logs, Kafka, delivery semantics, idempotent consumers, visibility timeouts, dead letters, backpressure, the outbox and sagas, with a nightly batch LLM job as the worked example: Queues, streams and async work. Handing work to a background task inside one service, and what that loses when the process dies: Building a backend API (section 8). Turn the queue on in the Scale simulator.

Step 4 Things fail, and the fixes can make it worse

The wall
At dozens of machines and several outside services, something is always failing. Say 1 request in 100 to the model provider hangs for a minute during a slow hour (illustrative): each hung call holds a slot, slots run out, and one dependency's problem takes the whole product down.

The defences, each a fix with a price, in the order a request meets them:

DefenceWhat it doesHow it backfires
TimeoutA deadline on every call; give up and free the slotToo long and slots pile up; too short and calls that would have succeeded are abandoned
Retry with exponential backoff and jitterTries again after a growing, randomised waitRetries add load exactly when the system struggles: five layers that each try three times multiply the load on the bottom one 243 times (35), a retry storm. Jitter spreads retries out but removes no work; a retry budget or a bounded queue does
Idempotency keyA client-chosen ID per action, so a retried charge returns the stored result instead of charging twiceNeeds storage, an expiry and an atomic claim
Circuit breaker, load shedding, graceful degradationStop calling what is broken; reject excess early; fall back to a smaller model or no searchThe least-tested code you own: it runs only when something is already wrong

A failure that sustains itself after its trigger is gone, usually because retries keep the overload going, is a metastable failure. Reliability engineering measured one on a laptop service: with backoff and full jitter, success stayed at 25%, the same as retrying at once; a retry budget reached 72% and a bounded queue that rejects the excess at once 87%.

How reliable is enough gets a number. An SLI measures the service (the share of messages answered within 10 seconds), an SLO is its target, an SLA the contract built on it, and the gap to perfection is the error budget, spent on shipping. An SLO of 99.9% at 10 million messages a day (Step 6's estimate) allows 10,000 failures a day, about 300,000 in a 30-day month. Seeing whether it holds is observability: logs (one line per event), metrics (numbers over time) and traces (one request followed across every service), joined by one trace ID.

Go deeper. Drawn by the owners: Reliability engineering, Fig. 1 (one provider slowdown, without and with the defences), Fig. 3 (retries at every layer multiply) and Fig. 4 (the measured storm); Observability, Fig. 2 (one trace, two processes). Timeouts and deadlines, retries, the measured retry storm, breakers, bulkheads and shedding, rate-limit algorithms, safe deploys, SLOs and burn rates, incidents, LLM calls and chaos testing: Reliability engineering (sections 3 to 5 and 12). Building the idempotency key on one API: Service APIs (section 4); why exactly-once is end to end: Distributed systems fundamentals (section 9). Logs, metrics, percentiles, traces, OpenTelemetry and alerting on burn rates: Observability. Real outages where retries, caches and timeouts did the damage: Case files.

Step 5 The GPU layer: a backend unlike the others

The wall
A chat reply costs seconds of a GPU. A model writes one token at a time and reads all its weights for each: an 8-billion-parameter model in 16-bit numbers is 16 GB per token, and an H100 reads 3.35 TB/s (NVIDIA), so one conversation gets at most about 210 tokens a second and a 500-token reply takes at least 2.4 seconds (derived: 16 GB ÷ 3.35 TB/s = 4.8 ms per token).

Four properties break the web playbook of Steps 1 to 4:

  • Two phases. Prefill reads the whole prompt at once and is limited by arithmetic; decode writes one token per step and is limited by memory bandwidth, as above.
  • Long-lived responses. Replies are streamed token by token, so each holds a connection open for seconds; Little's law counts them in Step 6.
  • Capacity in big, slow blocks. A 70-billion-parameter model in 16-bit numbers is 140 GB, more than one 80 GB GPU, so one model replica spans several; loading 140 GB at an illustrative 2 GB/s takes 70 seconds before the server even starts, so cold starts take minutes and GPUs cannot be added the moment a spike arrives.
  • Memory per conversation. The KV cache keeps intermediate results for every token so far, in scarce GPU memory, and often limits how many users one GPU serves.

The fixes all do less work per reply. Batching uses one read of the weights for many conversations: with 64 in a batch, the 4.8 ms read yields 64 tokens, a ceiling of about 13,000 tokens a second (derived); continuous batching refills a freed slot at every step instead of waiting for the longest reply. Prefix caching keeps the KV cache of a shared prompt beginning, so what never changes goes first in the prompt; a semantic cache returns a stored answer for a question that merely looks similar, cheap and wrong whenever the answer depends on who asks. A model router sends easy requests to a small model and doubles as Step 4's degradation path. A rate limit per customer, usually a token bucket, must count tokens as well as requests, because one 100,000-token document costs as much as a thousand short questions.

The price, across pages
Batching trades a little latency per user for much more throughput per GPU; caches can serve the wrong answer to the wrong person; routers misjudge difficulty; and GPUs are expensive idle and slow to add, so the fleet size is a bet on tomorrow's traffic, which Step 6 estimates.
Published throughput figures behind these ceilings (depth)

NVIDIA's published performance overview (v0.21 data) reports about 15,000 output tokens a second for Llama 3.1 8B in 8-bit on one H100, 1,000 input and 1,000 output tokens per request, at maximum load (vendor benchmark; see Numbers to know). Continuous batching was introduced by Orca (OSDI 2022); Anyscale's benchmark reported up to 23x the throughput of naive static batching when combined with vLLM's memory management (Anyscale, 2023; a single benchmark by an interested party, so read it as "large", not as a constant).

Go deeper. Drawn by the owners: ML system design, Fig. 4 (one request through the model layer). Designing the service around a model (framing, the data loop, serving shape and latency budgets, drift, the LLM design ladder and its cost) and what running an LLM service adds: ML system design (sections 4, 6 and 7). LLM gateways, routing, fallbacks, token rate limits and budgets: Gateways and routing. Continuous batching, paged KV caches and prefix caching in the engine: Batching, KV cache and scheduling in depth; replica routing, autoscaling and cold starts: LLM serving in production; the whole engine layer: Topic: inference-and-serving. Capacity for an LLM-backed service from the client's side (provider limits, open streams): Capacity planning.

Step 6 Designing it on purpose: the method

The wall
Steps 1 to 5 were reactive. That works until a fix takes months (sharding a live database, buying GPUs), or someone asks for the design before the system exists. Without numbers, a design is a guess drawn in boxes.

The method experienced engineers follow, in roughly this order, which is also what system design interviews expect (Alex Xu compresses it into four phases for 45 minutes: scope 3 to 10 minutes, high-level design 10 to 15, deep dive 10 to 25, wrap-up 3 to 5; ByteByteGo):

Requirements. Functional ones say what the system does; non-functional ones say how well (users, time to first token at p99, the SLO, cost, privacy). The non-functional ones decide the architecture; ask them first.
Estimates. Back-of-the-envelope arithmetic that turns users into requests, tokens, GPUs and bytes, and says which part is hard (below).
API and data model. The endpoints (what is idempotent, what streams, what returns 202) and the tables, each query on an index and carrying the likely shard key.
High-level design, deep dives, trade-offs. The boxes, each justified by a requirement or an estimate; then the two or three parts the estimates flagged; then what breaks at ten times the traffic and what each choice cost.
A fleet sized for the average day is short every evening

Fig. 2 · The estimate step by step, for the average and for the peak

Predict before you step: if the busy hour runs at twice the average, how many hours of the day does a fleet sized for the average fall short? Then switch to the peak-sized fleet and look at the night.

  1. Start from the requirement. Ten million registered users. Everything else is derived from assumptions you say out loud.
  2. Who is actually there: 1,000,000 a day. 10,000,000 × 10%. Only some users come back on a given day; 10% is the assumption here.
  3. How much they do: 10,000,000 messages a day. 1,000,000 × 10. Each message is one request to the model.
  4. Turn a day into a rate: about 116 requests a second. 10,000,000 ÷ 86,400 s = 115.7: modest for app servers and a database.
  5. Traffic is not flat: 231.5 a second in the busy hour. 115.7 × 2. Evenings are busier than nights. Assume the busy hour runs at twice the average, close to what German Wikipedia measures in one time zone (1.92 in September 2026; see the note below).
  6. Convert to model work. At 400 output tokens per reply (with about 1,000 input tokens, the request shape the Scale simulator uses) the model must produce about 46,000 tokens a second on average and 93,000 in the busy hour. The chart shows the day’s shape.
  7. Size the fleet for the average: 24 GPUs. At an assumed 2,000 output tokens a second per GPU, 46,296 ÷ 2,000 rounds up to 24 GPUs, enough for the average.
  8. Count open connections: 2,315. Little’s law again: 231.5 new replies a second, each streaming for 10 seconds, means about 2,315 connections open at once, which every layer from the load balancer down must hold.
  9. Count the bytes: 40 GB a day. 10,000,000 messages × 2 × 2 KB, 14.6 TB a year. Storage is not the hard part; the GPUs are.
  10. Check the whole day: short for 14 of 24 hours. Sized for the average, demand exceeds capacity for 14 of 24 hours: every evening, replies queue and slow down. The average hid the peak.

Every input is an assumption, labelled as such: 10% of users active each day, 10 messages each, 1,000 input and 400 output tokens per reply (the same request shape as the Scale simulator), a busy hour twice the daily average, 2,000 output tokens per second per GPU, replies streaming for 10 seconds, 2 KB of text per message. The daily traffic shape is invented to average exactly 1. Checked in src/read/recompute.py. The results the child pages reuse: 10 million messages a day, about 116 requests a second on average and 231.5 in the busy hour, 56 GPUs for the busy hour with 20% headroom, 2,315 streams open at once.

Where the peak factor and the GPU figure come from (depth)

The busy hour at twice the daily average is a fair figure for a product used in one region: Capacity planning and performance measured Wikipedia's busy hour against its day's average for September 2026 at 1.92 for German, 1.63 for Japanese and 1.24 for the worldwide English site; per second, peaks are much sharper, as Twitter's busiest second in August 2013 ran at 25 times its average (see Case files). The 2,000 output tokens per second per GPU is a round planning number, a little below NVIDIA's maximum-load benchmark row for Llama 3.3 70B in FP8 on two H100s with 1,000 input and 1,000 output tokens per request: 2,209 output tokens/s per GPU (TensorRT-LLM perf overview, commit 8a9c66c, vendor figure, the same row the Scale simulator uses); a service holding latency targets gets less, so measure your own; more figures in Numbers to know. Changing any input changes the answer in proportion, which is the point: the method, not the numbers, is what carries over.

Two lessons fall out of the arithmetic. The model layer dominates: 116 requests a second is a small load for app servers and a database, while the same traffic needs tens of GPUs. And the peak sets the size, not the average: a fleet sized for the average is short of capacity for 14 hours of the day, and one sized for the peak sits more than half idle overnight, which is why autoscaling, night-time batch work and routing to smaller models matter so much.

Machine learning design interviews keep this method and swap part of the middle for the metrics that define success offline and online, the data, the model choice, then serving and monitoring (Chip Huyen's free Machine Learning Systems Design booklet uses this framing). In both, what is judged is whether you quantify and name trade-offs, not how many component names you know.

Go deeper. Drawn by the owners: System design case studies, Figs. 2 to 8 (seven designs, each built step by step). Seven whole designs run through the method, from requirements and live estimates to bottlenecks, and a 45-minute Design drill: System design case studies. Peak factors, headroom, N+1 and cost per request: Capacity planning and performance (Capacity planning). The ML and LLM version of the interview: ML system design (section 8). Run this estimate with your own inputs in the Scale simulator.

Across the steps: how a senior engineer reasons

The habits that use all six steps; each is a question asked before adding anything, and each is taught in depth by the page named.

Start from the invariant, not the component. Write down what must never happen ("never charge twice", "never lose a message") and what may ("the sidebar is a second stale"), then choose consistency and retries per invariant (Distributed systems fundamentals, Reliability engineering).
Do the arithmetic first. Requests, tokens, GPUs, bytes: the numbers say which part is hard (Step 6, System design case studies).
Add a block only when its problem has arrived. A cache before reads hurt or sharding before one machine is full adds cost and failure modes for nothing. A bigger machine and one Postgres go a long way.
Name the cost of every choice. "We cache chat lists for 30 seconds; a renamed chat can show the old name for up to 30 seconds; acceptable." If you cannot say what a choice gives up, you do not yet understand it.
Design for failure as the normal case. Every call gets a timeout; retries get backoff, jitter and a cap; every retried write gets an idempotency key; every queue is bounded; there is a planned worse-but-working mode; and those paths are tested on purpose (Reliability engineering, Testing and quality).
Measure before and after. Percentiles, not averages; an SLO that says when reliability is good enough. Unmeasured "fixes" often move the problem (Observability, Capacity planning).
Prefer reversible decisions, and decide the irreversible ones late. A function can be rewritten tomorrow; a public API, a schema and a shard key are very expensive to change later, so spend your care there (Code design, Service APIs).

The code under every step (drawn as the floor of Fig. 1; Testing and quality, Fig. 1 puts every bug at the lowest net that caught it, Code design, Fig. 1 shows one real handler before and after). Each fix above is code someone must change safely later. Two child pages own that: Testing and quality (which layer of test catches which bug, contract tests for model output, flaky tests, CI gates, and static checks as gates) and Code design (cohesion and coupling, deep modules, dependency direction, refactoring in small tested steps, code review as a craft, and code an LLM agent can change safely). Where they meet: Code design owns static checks and review as craft; Testing and quality owns them as CI gates.

The child pages, in reading order

Ten pages on the same chat product; each uses only what the pages before it taught. Times are the reading time each page's header states (core, plus closed details).

1. Building a backend API: request lifecycle, data layer, async and workers, shutdownThe service behind an API: the request lifecycle, middleware against dependencies, authorising the object in the query, the data layer in a handler, async against threads against workers (measured), configuration and secrets, background hand-off, health checks and graceful shutdown, and an LLM endpoint end to end. 34 min, plus 5 in closed details. Step 1.
2. Distributed systems fundamentals: replication, partitioning, consistency, consensusWhat changes when data lives on more than one machine: partial failure, clocks, replication, quorums, the consistency ladder, CAP and PACELC, Raft, leases and fencing, exactly-once as an end-to-end property, partitioning. 49 min, plus 10. Step 2.
3. Queues, streams and async work: delivery semantics, Kafka, the outbox patternTaking work off the request path: queues against logs, Kafka, delivery semantics, idempotent consumers, visibility timeouts, dead letters, backpressure, the outbox, sagas, cron and workflow engines, a nightly batch LLM job. 42 min, plus 17. Step 3.
4. Reliability engineering: timeouts, retries, circuit breakers, SLOs, incidentsStaying up when dependencies fail: timeouts and deadlines, retries and budgets (a retry storm measured), breakers, shedding, rate-limit algorithms, safe deploys, SLOs and error budgets, incidents, LLM calls, chaos testing. 40 min, plus 8. Step 4.
5. Observability: logs, metrics, traces, alertingSeeing inside a running service, on a real instrumented run: logs, metrics and percentiles, cardinality, traces and context propagation, OpenTelemetry, profiling, one incident debugged, burn-rate alerting. 40 min, plus 8. Step 4.
6. Capacity planning and performance: load balancing, caching, queueing, load testingHow fast and how much: percentiles and the tail, queueing and Little's law, load balancing, cache patterns and stampedes, pools and the GIL, load testing without coordinated omission, capacity planning and cost per request, an LLM-backed service's limits. 41 min, plus 18. Steps 1, 2 and 6.
7. ML system design: LLM and ML servicesDesigning a system around a model: framing and the metric ladder, the data loop and training-serving skew, offline against online evaluation, serving shape and latency budgets, feedback loops and drift, the LLM design ladder and its cost. 29 min, plus 15. Step 5.
8. Testing and quality: unit, property-based, data and model tests, CIKnowing code works while it changes, with real pytest runs: layers, doubles, integration against the real engine, property-based tests, LLM-calling code, data and ML tests, flaky tests, mutation testing, CI and static checks as gates. 45 min, plus 18. Every step.
9. Code design: readable code, abstractions, review, library designKeeping the next change cheap and safe: cohesion and coupling, deep modules, dependency direction, composition, a functional core, error design, refactoring in ten measured steps, code an agent can change, technical debt, library design, review. 42 min, plus 17. Every step.
10. System design case studies: worked designs from requirements to bottlenecksThe capstone: seven whole designs (URL shortener, rate limiter, chat, feed, LLM gateway, RAG service, job scheduler) through Step 6's method, and a 45-minute Design drill. 41 min, plus 28. Step 6, last.