Skip to content

Capstone: three design walkthroughs

Phase 7 · Designing AI systems · 29 min read

What you'll be able to do

  • Apply one ten-step method to a new system and produce a design with numbers, failure modes, and stated trade-offs.
  • Estimate QPS, storage, bandwidth, GPU capacity, error budgets, and monthly cost, and show the arithmetic.
  • Review a design critically: ask the questions a skeptical reviewer would ask, and propose credible alternatives.

The design method

This lesson adds no new theory: it applies one method to three systems. Every traffic figure, price, and throughput below is a hypothetical assumption; in a real design, replace each with data or a load test.

  1. Requirements and constraints: functional behavior, scale, latency, consistency, availability, cost, privacy.
  2. Estimates: napkin math for QPS, storage, bandwidth, and GPU or CPU capacity. Write the formula, then the numbers.
  3. API and data model: the interface and the main entities, including keys and versions.
  4. Architecture: a diagram annotated with rates and sizes.
  5. Deep dive: the riskiest component, in detail.
  6. Failure modes: what breaks, how you notice, what happens next.
  7. Scaling path: which number breaks first at 10x.
  8. Operations: SLOs, metrics, deploy and rollback.
  9. Security and privacy.
  10. Cost and trade-offs: including what you chose not to do.

The same ten steps form a one-page design review checklist. A design is ready when each row has evidence, and a reviewer treats a missing row as a finding.

Step Question to answer Done when Red flag
1 Requirements What must be true, for whom, at what scale? Targets are numbers, assumptions are labeled "Fast", "scalable", "secure" with no figures
2 Estimates Which resource runs out first? Formulas with units and a result Numbers appear only in the conclusion
3 API and data What are the keys, versions, idempotency rules? Requests and rows can be written down Entities with no owner or key
4 Architecture What are the paths and who calls whom? Diagram annotated with rates and sizes Boxes with no numbers
5 Deep dive What is most likely to hurt us? One component explained to the mechanism Every component described equally shallowly
6 Failure modes What fails, how do we detect it, what do users see? At least 3 with detection and mitigation "We use retries" as the whole answer
7 Scaling What breaks at 10x? A named bottleneck and the change it forces "Add more servers"
8 Operations How do we know it works, and ship safely? SLO, error budget, canary, rollback Deploy with no way back
9 Security and privacy Who can see what, and how do we prove it? Isolation tests, retention, audit Security as a final paragraph
10 Cost and trade-offs What does it cost, and what did we reject? Monthly figure, largest line, "not doing" list Only the chosen design is mentioned

Two habits make the method work. Give each stage of a request a latency budget, but measure the whole request under load, because stage percentiles do not add up to the end-to-end percentile. And put numbers on the arrows that matter (requests per second, bytes, tokens), which makes capacity claims checkable.

Walkthrough 1: a multi-tenant RAG question-answering service

The system: 200 business tenants connect their documents, and employees get streamed answers with citations. Every document has an access control list (ACL) that says who may read it. Designing a RAG system covers retrieval itself.

Requirements and estimates

Requirement Target (assumed)
Users 50,000 seats, 20,000 daily active, 10 questions each per day
Corpus 2,000,000 documents, 10 chunks each, growing 30% per year
Latency p95 time to first token under 1.5 s
Freshness An edited document is searchable within 5 minutes (p95)
Revocation and deletion Unusable for answers within 60 s of the change reaching the platform; cross-tenant leaks: zero tolerated
Availability 99.5% monthly (error budget 0.005 x 43,200 = 216 minutes)
queries/day  = 20,000 x 10 = 200,000
avg QPS      = 200,000 / 86,400 = 2.31
peak QPS     = 2.31 x 5 = 11.6          (work-hour concentration)
answers out  = 11.6 x 300 tokens x 4 B x 8 = about 0.11 Mbps

chunks       = 2,000,000 x 10 = 20,000,000
bytes/chunk  = 3,072 vector (768 x 4 B) + 2,048 text + 512 meta = 5,632
2-year chunks= 20M x 1.3^2 = 33.8M
storage      = 33.8M x 5,632 x 3 replicas = 571 GB
vector RAM   = 33.8M x 3,072 = 103.8 GB per replica; / 4 shards = 26.0 GB
               (x1.5 assumed index overhead = 39 GB: fits a 64 GB node)
nodes        = 4 shards x 3 replicas = 12

LLM tokens   = 3,500 in (6 chunks x 500 + 500 prompt) + 300 out
per day      = 200,000 x 3,500 = 700M in; 200,000 x 300 = 60M out
LLM cost     = 700 x $1 + 60 x $4 = $940/day ($ per 1M) = $28,200/month
ingest       = 3%/day x 2M docs = 60,000 docs = 600,000 chunks
             = 300M tokens/day = 3,472 tokens/s
             = 17% of one GPU at 20,000 tokens/s
full re-embed= 20M x 500 = 10B tokens / 20,000 = 500,000 s = 5.8 days, 1 GPU
infra        = 12 nodes x $0.50 x 730 + 2 GPUs (embed, rerank) x $3 x 730
             = $4,380 + $4,380 = $8,760/month
subtotal     = $28,200 + $8,760 = $36,960/month

Peak retrieval is about 12 QPS, yet we run 12 nodes, because memory (104 GB of vectors) and availability (3 replicas) set the count. The LLM bill is 76% of the subtotal, which still excludes the database, queue, and network transfer.

Stage p95 budget (ms)
Gateway, auth 30
Group lookup (cached) 10
Query embedding 40
Filtered search 80
Rerank 150
Live document and permission check 30
Prompt assembly 20
LLM time to first token 600
Sum of budgets 960

The stage budgets sum to 960 ms, leaving 540 ms of planning headroom under 1,500 ms. This does not prove the SLO: measure end-to-end p95 under the expected load.

API, data model, architecture

POST /v1/ask takes a question and returns streamed tokens plus citations {doc_id, chunk_id, version}. The tenant comes from the verified token, never from the request body. A chunk record holds tenant_id, doc_id, doc_version, chunk_idx, vector, text, acl_group_ids, updated_at. Its unique key is (tenant_id, doc_id, doc_version, chunk_idx), which makes re-ingestion idempotent. A relational database is the source of truth for documents, current versions, deletions, and ACLs; the index is a derived copy.

Design review 1, ingest: change events update the metadata DB first, then a keyed queue feeds chunk, embed and upsert.
Design review 1, query: tenant from the verified token, hybrid retrieval on a sharded index, rerank, a live permission check, then the LLM.

Deep dive and failure modes

The riskiest component is permission-safe retrieval, because its failure is a data breach.

  1. Tenant scope. Document IDs are only unique within a tenant. Without tenant_id in the key, one tenant's upsert can replace another's chunk. Every read, update, and delete requires the same tenant key, and the index client refuses calls without it. A test stores identical document IDs in two tenants and checks that neither can see, overwrite, or delete the other's.
  2. Pre-filter. The search filters on the user's group IDs (cached 30 s), so top-k slots are not wasted on forbidden chunks.
  3. Live check before prompt assembly. For the final 6 chunks, ask the source of truth whether each document still exists, whether this version is current, and whether this user may read it now. Drop any chunk that fails. If the check errors or times out, fail closed: no unchecked content reaches the prompt, and the user is told no answer is available. Unbatched this is 6 x 11.6 = 69 lookups per second; batched, 11.6 calls.
  4. No answer cache at launch. If one is added, key it by tenant, group set, index version, and prompt version, invalidate on deletion and revocation, and serve a hit only after every document that fed its prompt passes the live check (Caching and CDNs).

The check reads document state from the primary and uses group membership at most 30 s old, which keeps enforcement inside 60 s. Delay between the customer's wiki and our platform is a separate number to agree on. Chat history needs the same rule: re-check old citations before feeding an earlier answer back to the model, or leave it out.

This has two costs. An edited document disappears from answers until its new version is indexed, because the old version fails the check. And the metadata database is now on the query path, so it needs replicas and its downtime spends the 216-minute budget.

Failure Detect Mitigate
Embedding service down Ingest queue age over 5 min; embed errors Queue retains events, retry with backoff; queries fall back to keyword search, marked degraded
Stale index Canary document written each minute; alert if not searchable in 5 min Scale ingest workers; citations show version
Permission leak Canary documents that nobody may read; cross-tenant eval probes Zero tolerance: page, disable the path, review audit log
Metadata database unavailable Live-check errors and timeouts Fail closed; promote only a synchronous replica, so no committed revocation is lost
LLM provider outage or rate limit Error rate, 429 count Timeout, one retry with jitter, fallback model, or return checked snippets only
Poison document Parse errors Dead-letter queue; do not block the partition
Physical deletion lags Age of oldest unprocessed delete Access already blocked by the live check; remove index entries within 1 hour; nightly sweep

Evals and rollout. A golden set of 300 questions (assumed) with labeled source chunks scores recall at 6, citation correctness, faithfulness, and refusal on unanswerable questions; leak probes are separate and pass or fail. As in Evals as tests, CI blocks a change if recall drops more than 2 points against main or any probe returns a forbidden chunk. A new embedding model or chunker builds a second index alongside the first, followed by shadow traffic, then 5%, 25%, and 100% of tenants, a business day per stage.

Scale, operations, security, cost

At 10x queries (116 QPS), the LLM bill is $282,000 a month, so cost and provider rate limits are the likely first walls. At 10x corpus, vectors are 1,038 GB per replica: 40 shards x 3 = 120 nodes, the cue for quantization or disk-based indexes (Partitioning). Operations: SLOs on time to first token, freshness, and revocation latency; per-stage dashboards; cost per tenant; the index version in every log line. Security (Security basics): retrieved documents are untrusted input that may contain instructions, so this path gets no tools with side effects; logs keep metadata, not question text, unless a tenant opts in. Cost: the $36,960 subtotal is about $0.006 per question (6M questions a month). Not doing: fine-tuning on tenant data, per-tenant indexes, multi-region, or an answer cache at launch.

Critique

A skeptical reviewer asks Brief answer
What if the filter code has a bug? Token-derived tenant, tenant in every key, live check, and leak probes in CI and production; the layers must not share one filter function
How fresh is it, and how do you know? 5-minute target, measured by a canary document
Why not put every document into a long context? 2M documents do not fit; token cost grows with context; permissions still need filtering
What happens when you change the embedding model? 5.8 days on one GPU (about 1.45 on four), so build a second index and flip an alias
How do you know answers are right? Golden set, faithfulness checks, and online thumbs-down rate
Why accept a refusal when the check is down? A missed answer is recoverable; a leaked document is not
Alternative Trade-off
One index per tenant (silo) Stronger isolation and easier deletion; 200 mostly small indexes waste memory and multiply operations
Keyword search plus rerank, no vectors Simpler, cheaper, easier to explain; weaker on paraphrased questions

Walkthrough 2: a model-serving platform

Eight product teams share a platform serving an 8B-class LLM, a ranker, and a fraud model. Teams ship weekly, and finance wants cost per team. Serving models and LLMs covers the mechanisms.

Requirements and estimates

Requirement Target (assumed)
LLM load 1,728,000 requests/day, 3x peak-to-average, 600 input and 250 output tokens
Classical load 400 QPS at peak (ranker 300, fraud 100), 5 ms CPU each
Latency LLM time to first token p95 under 1.0 s; classical p99 under 50 ms
Availability LLM 99.9%, classical 99.95% (monthly)
Zone loss Utilization targets still hold at peak with one of 3 zones gone
Fairness No team can starve another; per-team cost reports
avg QPS      = 1,728,000 / 86,400 = 20
peak QPS     = 20 x 3 = 60
decode load  = 60 x 250 = 15,000 output tokens/s
bandwidth    = 60 x 850 tokens x 4 B x 8 = about 1.6 Mbps
must survive = 15,000 / (2,500 x 0.6) = 10 GPUs
bought       = 2 zones must hold 10, so 5 per zone x 3 = 15 GPUs
utilization  = 15,000 / (15 x 2,500) = 40%; after zone loss 10 GPUs = 60%
error budget = 0.001 x 43,200 = 43.2 min (LLM)
               0.0005 x 43,200 = 21.6 min (classical)

KV per token = 2 x 32 layers x 8 KV heads x 128 dim x 2 B = 131,072 B
one request  = 850 tokens x 131,072 = 111.4 MB
concurrency  = (60 / 10 GPUs) x (250 / 30 tokens/s) = 50 per GPU
KV memory    = 50 x 111.4 MB = 5.6 GB
free memory  = 80 GB GPU - 16 GB weights = 64 GB, before overheads
32,000 tokens= 4.19 GB each, so at most 15 per GPU

classical    = 400 x 0.005 s = 2 cores busy; at 50% target = 4 cores
bought       = 2 cores per zone x 3 = 6 (4 remain after a zone loss)

cost         = 15 x $3 x 730 = $32,850/month, GPUs only
requests     = 1,728,000 x 30 = 51.84M; $0.63 per 1,000
autoscaled   = (6 GPUs x 16 h + 15 GPUs x 8 h) / 24 = 9 average
             = 9 x $3 x 730 = $19,710 ($0.38 per 1,000, 40% less)

The 2,500 output tokens per second per GPU is an assumed effective figure at the request mix, prefill included; load-test it for each model version. Autoscaling also assumes that demand stays under 5,000 tokens/s during the 16 off-peak hours: that needs 4 GPUs after a zone loss, so a floor of 6.

API, data model, architecture

Clients call POST /v1/chat (streaming) or POST /v1/models/{name}:predict with a per-team key scoped to model names. The registry stores immutable versions keyed by (name, version), with artifact_hash, owner_team, quota_class; the aliases prod and canary point at versions. Each request produces a usage record: team, model_version, input_tokens, output_tokens, latency.

Design review 2: a gateway enforces quotas, a router sends LLM calls to a GPU pool and small models to CPUs, and usage feeds metering.

Deep dive and failure modes

The riskiest component is the admission controller in front of the LLM pool. Request cost varies enormously (850 versus 32,000 tokens is about 38x), so the router balances on tokens in flight, not request count (Load balancing). Long prompts may be limited by key-value (KV) cache memory; benchmark prefill, decode, memory, and time to first token for the actual request mix. The estimate of 15 long prompts per GPU is an upper bound, because the runtime and activations also use memory. A request is admitted only if prompt tokens plus maximum new tokens fit the GPU's remaining KV budget.

Fairness uses token-based limits (Rate limiting). Each team is guaranteed 1,500 output tokens per second (8 x 1,500 = 12,000). The other 3,000 of the 15,000 form a burst pool shared by weighted fair queuing, interactive ahead of batch. For classical models, the expected arrivals in a 5 ms batching window are 0.5 for fraud and 1.5 for the ranker; benchmark batch-size distribution, throughput, and added p99 latency before enabling dynamic batching.

Failure Detect Mitigate
GPU node dies mid-stream Health checks, stream errors Router retries only before the first token; after that the client retries
Zone loss Healthy-GPU count per zone 10 GPUs carry peak at 60%; pause rollouts
Bad model version Canary error, latency, and quality probes Flip the alias back; keep the old version warm during rollout
One team floods the pool Per-team tokens/s Quota, 429 with Retry-After, queue batch work
Long-prompt memory exhaustion KV budget utilization, queue wait Admission control by tokens; cap context per quota class
Scale-up too slow Pending replicas, queue wait Floor of 6 GPUs; scale before the daily peak; react to queue depth and tokens in flight, not CPU

Scale, operations, security, cost

At 10x, load is 600 QPS and 150,000 tokens per second. The 100 GPUs that run at 60% are the unprotected minimum ($219,000 a month); surviving a zone loss takes 150, 50 per zone: 150 x $3 x 730 = $328,500 a month. GPU supply and cost become the problem before the router does. Operations (Observability and SLOs): SLIs are time to first token, error rate, queue wait, and tokens per second per team; releases follow CI/CD. At peak, a 1% canary gets 36 requests a minute, slow to compare; 5% gets 180, enough to compare latency and errors much sooner, while quality still needs offline evals and mirrored traffic. Give rollouts spare GPUs, or they consume the zone margin. Security: per-team keys, no prompt text in logs, metering stores counts only. Cost attribution charges each team its reserved quota plus metered burst tokens, and shares idle capacity in proportion to reservations. Not doing: multi-region active-active, per-team dedicated GPUs, or scale-to-zero for the interactive pool.

Critique

A skeptical reviewer asks Brief answer
Why not call a hosted API? Valid; compare per-token price, data-handling limits, and rate limits with the full self-hosted cost, of which GPUs alone are $0.38 to $0.63 per 1,000 requests
Why 60% utilization? Queueing delay grows sharply near saturation (Latency and throughput)
How do you know 2,500 tokens/s? You do not yet; load-test each model version
How do you catch a quality regression with no errors? Eval gate before the canary, then online proxy metrics against baseline
Are team guarantees real off-peak? Not fully: 6 GPUs give 9,000 tokens/s at 60%, under 12,000. Accept scale-up lag, or raise the floor to 12 to hold them through a zone loss
What stops a team claiming interactive priority? Priority is tied to the API key, audited, and given a lower quota
Alternative Trade-off
Hosted-API gateway only No GPU operations; per-token cost, provider limits, data-privacy review
Dedicated GPUs per team Simple isolation; with equal shares, surviving a zone loss takes 3 GPUs per team, 24 in total, $52,560 a month, 60% more than the shared 15

Walkthrough 3: an event-driven feature pipeline

A marketplace app produces click and purchase events. The pipeline computes a streaming feature (clicks_last_1h) and a daily batch feature (purchases_last_30d), serves both to the ranker from Walkthrough 2, and builds training sets from history (Data and ML pipelines).

Requirements and estimates

Requirement Target (assumed)
Events 2,000,000 daily users x 50 events, 500 bytes each, 4x peak
Freshness Streaming features visible online within 60 s (p95)
Correctness Retries and replays must not inflate values; online vs batch mismatch under 0.5%
Late data Mobile clients can deliver events hours or days late
Reads Ranker: 300 QPS x 21 keys (the user plus 20 candidate items)
events/day   = 2,000,000 x 50 = 100,000,000
avg rate     = 100M / 86,400 = 1,157/s;  peak = x 4 = 4,630/s
bandwidth    = 4,630 x 500 x 8 / 1e6 = 18.5 Mbps
log storage  = 100M x 500 B = 50 GB/day; x 7 days x 3 replicas = 1,050 GB
lake         = 50 GB/day / 4 (assumed Parquet ratio) = 12.5 GB/day
             = 4.56 TB/year
partitions   = 4,630 / 500 events/s per consumer = 9.3; choose 48 (about 5x)
dedupe IDs   = 100M x 16 B = 1.6 GB for 24 h, before store overhead
             = 33 MB per partition
online reads = 300 x 21 = 6,300/s
online store = 20M registered users x 1 KB x 2 replicas = 40 GB
backfill     = 100M x 365 = 36.5B events / 1M per s = 36,500 s = 10.1 h
cost         = 12 workers x $0.20 x 730 + 4 batch nodes x $0.50 x 730
               + 4,562 GB x $0.02
             = $1,752 + $1,460 + $91 = $3,303/month (subtotal)

API, data model, architecture

An event has event_id, user_id, type, event_time, and schema_version; a producer retry resends it unchanged. A feature value is stored under (feature_name, version, entity_id) with its window_end and computed-at time. The topic is keyed by user_id, so a user's events and their copies reach the same partition, in log order (Partitioning).

Design review 3: one event log feeds a streaming job for the online store and a lake for batch rebuilds; served features become training data.

Deep dive and failure modes

The riskiest part is correctness under replay and lateness. Delivery from the log is at-least-once (Queues, pub/sub and streams), so a consumer can crash after updating its state but before committing its offset, then process the batch again. An upsert alone does not help: if the state counts an event twice, the job faithfully writes the wrong total. The design needs three rules (Delivery guarantees and idempotency):

  1. Save event IDs and aggregates atomically, in one transaction or checkpoint, and ignore a repeated event_id.
  2. Write the computed value, keyed by feature, entity, and window, never an increment. Rewriting it repairs a write lost in the crash.
  3. Refuse, in the stream path, any event whose event_time is more than 24 hours old, and keep each ID at least until then.

The guarantee is scoped: within the dedupe retention window, a repeated event_id is ignored, and the sink writes a deterministic window value. The 7-day log outlives the IDs, so older replays and backfills are rebuilt from the raw lake, deduplicating by event_id across all records for the affected windows. Test both a crash between state update and offset commit and a replay older than 24 hours.

For freshness, the job writes updated values every few seconds instead of waiting for a window to close. A watermark 10 minutes behind the newest event time seen decides what is too late (reject future timestamps, or one bad clock drags it forward). Late events go to a late topic for the daily batch job. If 2% were late, 2M events a day would miss the live path: clicks_last_1h simply lacks them, while batch corrects offline history and 30-day features. The log has three replicas and acknowledges a write only after at least two in-sync replicas have it (Replication).

Training/serving skew comes from different code, different data (late events), and time leakage in training joins. Share one feature definition between both paths, build training sets with point-in-time joins (the value as of each label's timestamp), train on the logged served features where you have them, and compare a nightly batch recompute with online values for a sample.

Failure Detect Mitigate
Consumer crash Consumer lag, restarts Restore checkpoint, replay from committed offset; dedupe and value upserts
Replay older than 24 h Count of events refused for age Rebuild windows from the lake, deduplicated
Poison event Parse error rate Dead-letter topic, keep processing
Producer duplicates Duplicate rate Dedupe on event_id; the batch path does the same
Hot user (bot traffic) Per-partition skew Per-key rate guard; divert excess for later review
Schema change breaks parsing Compatibility check in CI Schema registry, compatible changes only
Online store down Read errors Defaults plus a missing flag the model was trained to handle

A backfill for a new feature reads the lake (about 10.1 hours for a year) into the offline store only. Refreshing the online store for 20M users at 5,000 writes per second would take 4,000 s, about 67 minutes. That rate is a placeholder: choose the throttle from a load test with live reads and stream writes running, so the read SLO holds.

Scale, operations, security, cost

At 10x, peak is 46,300 events per second, 964 per partition, about twice the assumed consumer speed. Try faster consumers first, because repartitioning keyed state is a project of its own. If registered users also grow 10x, the online store reaches 400 GB; plan to shard it. Operations: SLIs are freshness, consumer lag, watermark delay, dead-letter depth, and mismatch rate. An SLO of "freshness on target in 99% of minutes" allows 0.01 x 43,200 = 432 bad minutes a month. Ship a changed feature as a new version computed in shadow, compare, then switch the model, keeping the old version for rollback. Security: pseudonymous IDs, access control per feature table, and a deletion log with scheduled rewrites of affected lake files. Cost: $3,303 a month covers only the listed workers, batch nodes, and one year of lake data; price brokers, the online store, and network transfer before quoting a total. Not doing: exactly-once delivery end to end, a real-time training loop, or model inference in the stream.

Critique

A skeptical reviewer asks Brief answer
How do you know there is no double counting? Within 24 h: atomic dedupe state and value upserts. Older: rebuild from deduplicated raw data. Both are tested, and nightly reconciliation watches production
What about an event that arrives two days late? The stream refuses it; the batch path recomputes the affected windows
Why 48 partitions? 9.3 consumers needed now; 48 leaves about 5x; changing later is costly
How do you prevent label leakage? Point-in-time joins and training on logged served features
What if the online store is down? Default values and a missing flag; the ranker degrades but works
Can a backfill hurt production? Offline by default; any online refresh is throttled and load-tested
Alternative Trade-off
Hourly batch features only Far simpler, less skew; values are up to an hour old plus job time, which misses the 60 s target
Streaming only, replay for backfills One code path; a year in the log is 18.25 TB x 3 = 54.75 TB uncompressed, versus 4.56 TB compressed in the lake before its own redundancy

How to keep learning

Read postmortems (the Google SRE books discuss the practice) and ask which step of the method was weak: an unstated assumption, an untested failure mode, a missing rollback. Run small systems: watch lag on a Postgres replica, feed a consumer a poison message, load-test an endpoint until it fails. Contribute to open source, starting with documentation, bug reproductions, and small fixes. Ask a peer to review one of your designs with the checklist above.

This table is also the course map. For each phase, check that you can do both columns.

Phase Can you explain... Can you build... Lessons
1 Working like an engineer Processes, exit codes, branches, why tests fail A tested Python package with a bisected bug fix Terminal, Git, Testing
2 Web and APIs What happens in an HTTP call; authentication versus authorization An authenticated API with errors and pagination Networking, API design
3 Data and state An index, a transaction, a query plan, B-tree versus LSM A schema with a justified index Indexes, Datastores
4 Concurrency and performance The GIL, queueing, percentiles A profiled and measured speedup Concurrency, Profiling
5 Shipping and operating An image, a canary, an SLO, a secret A containerized service with CI and a rollback Docker, CI/CD
6 Distributed systems Replication lag, partitions, retries, idempotency A retry-safe consumer with a failover plan Replication, Timeouts and retries
7 Designing AI systems Evals as gates, RAG failure modes, serving capacity A reviewed design doc with numbers RAG, Evals

For AI engineers

For AI engineers

A document Q&A notebook becomes Walkthrough 1 when a second customer uploads data the first must never see. A fine-tuned model becomes Walkthrough 2 when three teams call it at once. A pandas feature becomes Walkthrough 3 when it must be served within a minute and match the training set. Write the design doc, with estimates, before the service.

Common mistakes

  • Diagrams without numbers: without rates, sizes, or budgets, nobody can check whether the capacity is enough.
  • Ignoring failure modes: a design that only describes the happy path has not finished step 6.
  • Over-engineering for scale not required: at 12 QPS, Walkthrough 1 needs shards for memory, not for throughput; let the numbers say which.
  • Skipping evals, security, or cost: a quality regression, a permission leak, or a bill far above plan can sink a system whose servers are healthy.
  • Not stating trade-offs: every choice rejects an alternative; write down what you are not doing and why.
  • Copying a famous architecture: a design that fits another company's requirements may be wrong for yours.

Check yourself

In Walkthrough 1, peak retrieval is about 12 QPS but the design uses 12 vector nodes. Is it over-engineered?

Not on these assumptions. Memory and availability set the node count. 33.8M vectors at 3,072 bytes are 103.8 GB per replica, split into 4 shards of about 26 GB before index overhead, and 3 replicas give failover: 4 x 3 = 12 nodes.

A document is deleted at 10:00. Its index entry, with an ACL that still grants access, survives until 10:40. A permitted user asks about it at 10:02. What must happen?

The search may still return the chunk, but the live check before prompt assembly finds that the document no longer exists and drops it. If the check itself fails, the service fails closed. The one-hour target covers only physical cleanup of the index; access must stop within 60 seconds.

A colleague proposes 12 GPUs for Walkthrough 2: 10 needed plus 2 spares, 4 per zone. Why does that miss the requirement?

Losing a zone leaves 8 GPUs, or 20,000 raw tokens per second, so 15,000 of demand runs them at 75%, above the 60% target. The two surviving zones must hold all 10, which means 5 per zone and 15 in total.

Team A starts sending 32,000-token prompts and other teams see latency spikes, while GPU compute utilization looks moderate. What do you suspect, and how do you respond?

KV-cache memory is a likely limit: one such request needs about 4.19 GB against 111 MB for a typical one, so at most 15 fit per GPU. Confirm with KV usage, queue wait, and prefill timing. Then admit by tokens against a memory budget, apply per-team token quotas, and cap context length per quota class.

A feature job saves its state, then crashes before committing its offset. Why is the replay safe, and why is replaying the same events three days later a different case?

The event IDs were saved atomically with the counts, so the replayed events are recognized, and the sink receives the same computed value again. Three days later the 24-hour IDs may be gone, so the stream cannot tell old from new. It refuses those events, and the batch path rebuilds the windows from the raw data with deduplication.

Lab

In code/capstone-design-reviews/ you build the capacity math (including zone-loss GPU sizing and cost). You also build two safety mechanisms: a tenant-safe, fail-closed retrieval gate and a replay-safe feature counter. Finally, check_design_doc is a structural preflight: an empty result never means a design is approved. Copy starter/design_template.md, write your own design for Walkthrough 1 or 3, then review it by hand with the checklist table. solution/example_design.md is a filled example for Walkthrough 2. Run: cd code/capstone-design-reviews && PYTHONPATH=starter python -m pytest tests -q

Go deeper