CP·211A
The System, Its Boundaries and the Build Order
The capstone as one serious application, TiffinBox: the user journeys, the non-functional requirements turned into numbers, the boundaries (a modular monolith plus an event-driven edge), the data each part owns, when to call and when to publish, the repository layout, the walking skeleton and the milestone order, the decision records to write, and a lab that measures where a request's time goes as it crosses each layer.
Start here: one system, not twenty projects
The roadmap's capstone says: build one serious application instead of dozens of toy projects. A toy project proves you can use a tool. A serious application proves you can make many tools work together, under load, through failures and changes, which is what employers pay for and what most learning skips.
This volume builds one application, TiffinBox, from end to end. It's the running example of earlier volumes, so you'll recognise it:
- Customers subscribe to a daily lunch tiffin from a home kitchen, choose meals, skip days, pay, and watch the delivery live.
- Kitchens see today's orders, mark them cooked and packed, and manage menus.
- Operations staff issue refunds, manage roles and handle incidents.
- An AI assistant answers questions about menus, allergens and orders from the kitchens' own documents, and can take safe actions such as skipping tomorrow's lunch.
Every requirement in the roadmap's capstone list, from accessible React components to prompt-injection defences, has a place in this one product. Chapters 211B–211H build it layer by layer; chapters 212A–212B break it on purpose.
Where a request's time goes
The lab for this chapter ran a slice of TiffinBox on one machine (nginx in front of a Python API, PostgreSQL with 1 million orders, Redis) and measured one screen, the kitchen's "latest 20 orders" list, built three ways:
| How the list is built | Database round trips | Time inside the API (one request) | Throughput under load | p99 under load |
|---|---|---|---|---|
| one query for orders, then one per customer name ("N+1") | 21 | ~2.2 ms | 732/s | 49 ms |
| one query with a join | 1 | ~0.5 ms | 2,715/s | 24 ms |
| served from the Redis cache | 0 (one Redis call) | ~0.3 ms | 4,173/s | 11 ms |
On one machine, a database round trip costs about 0.1 ms. In the cloud, where the database is in another zone, each one costs 0.5–1 ms, so the N+1 version would spend 10–20 ms just waiting on the network. Architecture is mostly about where you put the boundaries and how many times a request has to cross them.
How deep to go
Volume 17 defines six mastery levels. For this chapter:
| Level | What you can do |
|---|---|
| L1 | Describe TiffinBox's parts and what each does |
| L2 | Build the walking skeleton and deploy it through a pipeline |
| L3 | Explain why the boundaries, data ownership and sync/async choices are where they are |
| L4 | Find where a slow request spends its time across layers, and fix it |
| L5 | Write the requirements, estimates, boundaries and ADRs for a system like this, and defend them |
| L6 | Evolve the architecture as load, team and product change, without a rewrite |
The product: journeys and requirements
User journeys
Requirements start with what people do. Write each journey as steps, then mark the steps that must never fail, the ones that must be fast, and the ones that can be late.
| Journey | Steps | Must never fail | Must be fast | Can be late |
|---|---|---|---|---|
| subscribe | browse kitchens → choose plan → pay → confirmation | payment taken once, subscription created | browsing | welcome email |
| skip a day | open calendar → skip tomorrow → confirmation | skip recorded before the kitchen's cut-off | the click | kitchen's updated count, refund credit |
| track delivery | open order → live map and status | — | first view | position updates (a few seconds is fine) |
| kitchen prep | today's orders → mark cooked/packed | counts correct at cut-off | the list | analytics |
| ask the assistant | "Is the Tuesday sambar nut-free?" → answer with source | never invent allergens | first token | — |
| refund | staff finds order → refunds → audit trail | money moves once; audit entry written | — | customer email |
The last three columns are the architecture in disguise: "must never fail" points at transactions and idempotency, "must be fast" at caching and indexes, "can be late" at events and queues.
Non-functional requirements as numbers
Adjectives like "fast", "reliable" and "secure" can't be tested. Numbers can.
| Requirement | Target | Why this number |
|---|---|---|
| scale | 50,000 subscribers, 30,000 lunches a day, 400 kitchens | a city-scale business; also the size the estimates below use |
| availability (order, skip, pay APIs) | 99.9% of requests per 30 days | about 43 minutes of full outage a month |
| latency | p95 < 300 ms for API reads, < 800 ms for writes, at peak | pages feel instant; payments go through a provider |
| live tracking freshness | position on screen within 5 s of the rider's phone sending it | users notice longer gaps |
| data loss (RPO) | ≤ 5 minutes; zero for payments | payments are reconciled with the provider |
| recovery (RTO) | ≤ 1 hour for a full region rebuild, minutes for a zone | the lunch window is the business |
| AI assistant | ≥ 90% correct on the golden set; zero invented allergen claims; p95 first token < 2 s | allergens are a safety issue |
| security | OWASP ASVS level 2 practices; no secrets in code; all admin actions audited | handles payments and personal data |
| cost | cloud + AI under an agreed monthly budget, cost per order tracked | a small business |
Estimation
Back-of-the-envelope numbers decide what's needed (Volume 12, chapter 122):
- Orders: 30,000 a day, but 80% are placed or changed between 07:00 and 10:30 (the cut-off), so peak writes are roughly 30,000 × 0.8 ÷ 12,600 s ≈ 2 per second on average in that window, with bursts of perhaps 20 per second. That's small: one PostgreSQL primary handles thousands of writes per second.
- Reads: each customer opens the app a few times a day, each screen makes 3–5 API calls: 50,000 × 4 × 4 ≈ 800,000 calls a day, peaking around 100–200 per second. Again, modest.
- Live tracking is the heavy part: 1,500 riders sending positions every 3 s is 500 writes per second during the lunch window, fanned out to the customers watching. That shapes the design more than orders do: positions go to a fast store and a push channel, not the main database.
- AI: if 10% of customers ask one question a day, that's 5,000 questions, each with ~2,000 tokens of context. Cost and latency, not throughput, are the constraints.
- Storage: orders at ~1 KB each are ~11 GB a year: trivial. Rider positions, if kept, are 500 × 3,600 × 2 hours × 365 ≈ 1.3 billion points a year; keep a sample or summaries.
The lesson of the numbers: most of TiffinBox fits one well-run database. The interesting engineering is in correctness (money, skips before cut-off), freshness (tracking), and the AI. That's typical: real systems are rarely limited by raw scale, and over-engineering for scale you don't have is the most common capstone mistake.
Boundaries: a modular monolith with an event-driven edge
The modules
Split by what changes together and who owns the rules (Volume 13, chapters 138–140):
| Module | Owns | Examples of its rules |
|---|---|---|
| Identity | users, roles, sessions (with an external OIDC provider) | who may refund; staff need MFA |
| Catalogue | kitchens, menus, dishes, allergens | a dish's allergens come from the kitchen's declaration |
| Subscriptions | plans, schedules, skips, pauses | skips allowed until the kitchen's cut-off |
| Ordering | daily orders generated from subscriptions | one order per subscription per day |
| Payments | charges, refunds, credits, ledger | money moves exactly once; ledger balances |
| Delivery | riders, assignments, positions, status | status only moves forward |
| Notifications | templates, preferences, deliveries | respect quiet hours; deduplicate |
| Search | the search index (derived data) | rebuilt from source data |
| Assistant | prompts, tools, retrieval index (derived), evaluation | tools act only as the signed-in user |
Each module has a public interface (Java packages with an api sub-package, or Spring Modulith's module rules) and private internals. No module reads another module's tables. Tests enforce it (ArchUnit or Spring Modulith's verification), because a boundary that isn't enforced erodes in months.
What runs where
- The API (one Spring Boot deployable) contains the modules that need transactions and fast synchronous answers: Identity integration, Catalogue, Subscriptions, Ordering, Payments, Delivery status.
- Workers (the same codebase, a different entry point and deployment) consume events: notifications, search indexing, assistant document ingestion, analytics export.
- The tracking gateway (a small separate service) holds the WebSocket or server-sent-event connections and rider position writes, because its load profile (many long-lived connections, high write rate) differs from everything else. It's the one justified extraction on day one.
- The frontend (React and TypeScript) is deployed as static files behind the CDN, talking to the API.
Calling or publishing
The test from the check-yourself: does the caller need the answer to continue?
| Interaction | Style | Why |
|---|---|---|
| Subscriptions → Payments: charge for a new plan | synchronous call (in-process) | the confirmation depends on the result |
| Subscriptions → Ordering: a skip before cut-off | synchronous, same transaction | the kitchen's count must be right at cut-off |
| Ordering → Notifications: "order out for delivery" | event | the order doesn't wait for the email |
| Catalogue → Search: menu changed | event | search is derived data; seconds of lag is fine |
| Catalogue → Assistant: allergen document uploaded | event | ingestion is slow (parsing, embeddings) |
| Payments → Analytics: refund issued | event | reporting is never on the critical path |
| Rider app → Tracking gateway: position | direct write to the gateway | high rate, short-lived data, not business state |
Events leave the API through an outbox written in the same transaction as the change (Volume 5; Volume 18, Phase 8 measured why), so nothing is lost if the process dies between saving and publishing.
Data ownership
- PostgreSQL holds the source of truth for every module, one schema per module, with grants that stop modules reading each other's schemas.
- Redis holds caches and short-lived data (sessions if needed, rate-limit counters, rider positions for the last hour).
- Object storage holds receipts, kitchen documents and menu images.
- The search index and the vector index are derived: they can be rebuilt from PostgreSQL and object storage by replaying events or re-ingesting. Anything derived must be rebuildable, which becomes a failure exercise in chapter 212A.
The repository and the build
One repository (a monorepo) keeps contracts and changes in one place:
tiffinbox/
web/ React + TypeScript app, component library, Playwright tests
api/ Spring Boot modular monolith (modules as packages), Flyway migrations
workers/ event consumers (same build, separate entry points)
tracking/ tracking gateway
contracts/ OpenAPI spec, event schemas (Avro or JSON Schema), versioned
eval/ assistant golden sets and evaluation scripts
infra/ Terraform/OpenTofu modules and environments
deploy/ Kubernetes manifests or Helm charts, Argo CD apps
docs/adr/ architecture decision records
docs/runbooks/ one per alert
The contracts/ folder is the heart: the frontend's API client is generated from the OpenAPI spec, consumers' event classes from the schemas, and CI fails if a change breaks compatibility.
The build order
Milestone 0: the walking skeleton
Before any feature: one page that lists kitchens, from one table, through the API, deployed by the pipeline to a real environment, with a trace, a dashboard and an alert. It sounds trivial; it forces every hard decision early (repository, build, container, cluster, DNS, TLS, identity, telemetry) while there's little to rework.
The milestones
| Milestone | Delivers | Proves |
|---|---|---|
| M0 walking skeleton | kitchens list end to end, deployed, observed | the path to production works |
| M1 identity and catalogue | sign-in with OIDC, roles, menus with allergens | security from the start |
| M2 subscriptions and payments | subscribe, skip with cut-off, pay with idempotency keys | correctness for money and time |
| M3 kitchen and delivery | kitchen dashboard, rider status, live tracking | realtime and a second deployable |
| M4 events | outbox, Kafka, notifications, search indexing, replay | asynchronous correctness |
| M5 assistant | RAG over kitchen documents, tools for safe actions, evaluation | AI held to engineering standards |
| M6 hardening | threat model, scanning, audit log, canary, rollback, SLOs | production readiness |
| M7 failure exercises | the twenty incidents of chapter 212 | it survives and you can explain why |
Every milestone ends deployed, with its tests, telemetry and runbooks: there's no "integration phase" at the end.
Decisions to write down
Write an ADR (Volume 13, chapter 142) for each decision someone could reasonably have made differently:
- Modular monolith with one extracted service (tracking gateway).
- PostgreSQL as the single source of truth; one schema per module.
- Outbox + Kafka for events; at-least-once delivery with idempotent consumers.
- OIDC with an external identity provider; tokens in an HTTP-only session cookie via a backend-for-frontend, not in browser storage.
- Server-sent events (or WebSockets) for live tracking, and why not polling (chapter 211B's lab).
- Search with PostgreSQL full-text first; a search engine only if relevance or scale demands it (chapter 211D's lab).
- Model-provider abstraction with fallback, and what the assistant may and may not do.
- Kubernetes on a managed cloud service; infrastructure as code; GitOps delivery.
- SLOs and the error-budget policy.
- Data retention: what is kept, for how long, and why.
Definition of done for the capstone
- Every user journey works end to end in production-like infrastructure, with automated tests at the right levels.
- Every requirement in the table above has a measurement that shows it is met (or an ADR accepting that it isn't, with a plan).
- Every alert has a runbook; every runbook has been followed by someone other than its author.
- The twenty failure exercises have been run, each with a written detect–mitigate–recover–prevent answer.
- A newcomer can clone the repository and run the whole system locally with one command, and deploy a change through the pipeline on their first day.
Common traps
- Building for scale you don't have (sharding, many microservices) while correctness is untested.
- Integration at the end: layers built separately, joined in a painful final month.
- Shared tables between modules, which turn the monolith into a ball of mud.
- Requirements as adjectives: no numbers, no way to know when you're done.
- Undocumented decisions: six months later nobody knows why anything is the way it is.
Lab: where a request's time goes
Setup. One lab machine with 2 CPUs. PostgreSQL 16 with cp_customers (100,000 rows) and cp_orders (1,000,000 rows, indexed on (kitchen_id, placed_at desc)). Redis 7. A FastAPI app under uvicorn (2 workers, httptools, uvloop) with a connection pool of 8 per worker, behind nginx with upstream keep-alive. Three versions of the kitchen's "latest 20 orders with customer names" endpoint:
- N+1: one query for the 20 orders, then one query per order for the customer's name.
- join: one query joining orders to customers.
- cached: the join's result stored in Redis for 30 s.
Each endpoint reports its internal timing in a Server-Timing header. Load came from wrk (2 threads, 16 connections, 10 s) on the same machine, so the load generator competes for the same CPUs. Treat the numbers as relative.
Single requests (no load)
| Endpoint | Server-Timing (typical) |
|---|---|
| N+1 | orders query ~0.4–0.6 ms, then 20 customer queries ~1.7–2.1 ms in total |
| join | one query ~0.5 ms |
| cached (hit) | Redis read ~0.3 ms |
Under load
| Path | Throughput | p50 | p99 |
|---|---|---|---|
/health directly to the app |
11,412/s | 1.35 ms | 4.8 ms |
/health through nginx |
9,294/s | 1.63 ms | 4.6 ms |
| N+1 through nginx | 732/s | 20.5 ms | 49.5 ms |
| join through nginx | 2,715/s | 5.4 ms | 23.9 ms |
| cached through nginx | 4,173/s | 3.6 ms | 10.9 ms |
What it shows
- The proxy hop is cheap (~0.3 ms at p50 here). Layers that add a network hop aren't the problem by themselves.
- Round trips multiply. The N+1 endpoint's 21 queries each cost little, but together they held a pooled connection and a worker thread ~4× longer, so throughput fell to about a quarter of the join's. With the database across a network, each round trip would add 0.5–1 ms more: about 10–20 ms per request just waiting.
- The cache helps less than you might expect over a good query (4,173 vs 2,715/s): the remaining cost is the HTTP and Python overhead around it. Cache what's expensive, not everything.
- A detour worth knowing about: the first run of this lab showed a constant ~44 ms per request on reused connections, even for
/health, at only ~360 requests per second. That app instance had been started before the tables existed and had been failing to fill its connection pool; a clean restart removed the delay, and the exact cause wasn't pinned down. A well-known cause of exactly this symptom is real, though: on kept-alive connections, Nagle's algorithm combined with delayed ACKs can add ~40 ms per response when a server writes a response in several small pieces. The Java lab in chapter 211C hit that one, andTCP_NODELAYfixed it. When every request takes the same suspicious number of milliseconds, suspect the environment and the network stack before your code, and restart from a clean state before measuring.
Try it yourself
- Add 0.5 ms of latency between the app and PostgreSQL (with
tc netemon a machine that allows it) and rerun: how much worse does N+1 get compared with the join? - Turn on
log_min_duration_statement = 0in PostgreSQL for the N+1 endpoint and count the statements per request. - Add OpenTelemetry tracing to the app and find the N+1 pattern in a trace view.
Revision sheet: the system and its build order
Key ideas
- One serious system teaches integration: contracts, ownership, deployments, cascading failures.
- Requirements as journeys (never fail / fast / can be late) and numbers (availability, latency, RPO/RTO, cost).
- Estimate first: most of TiffinBox fits one database; tracking and AI shape the design.
- Modular monolith with enforced module boundaries; extract only with a reason (the tracking gateway).
- Call when the caller needs the answer; publish (via an outbox) when others just react.
- Walking skeleton first; every milestone ends deployed and observed; ADRs for every contestable decision.
Numbers to remember
- 99.9% ≈ 43 minutes of outage a month.
- Lab: N+1 (21 round trips) 732/s vs join 2,715/s vs cache 4,173/s; proxy hop ~0.3 ms.
- Cross-zone round trip 0.5–1 ms; 20 extra round trips ≈ 10–20 ms.
Pitfalls
- Over-engineering for scale; integration at the end.
- Shared tables across modules; unenforced boundaries.
- Requirements without numbers; undocumented decisions.
Glossary
- Walking skeleton: thinnest deployed, observed end-to-end slice.
- Modular monolith: one deployable with enforced internal module boundaries.
- Derived data: data rebuildable from a source of truth (search and vector indexes).
- Outbox: events written in the same transaction as the change, published later.
- ADR: architecture decision record.