Skip to main content

Chapter 43 — Capstone: Designing, Building & Operating Pulsely End-to-End

Part VIII · Synthesis | Prerequisites: all prior chapters | Builds: the full capstone — harden, operate, break, scale, and recover Pulsely

For forty-two chapters you have been building Pulsely one box of the spine at a time. You parsed HTTP by hand, then handed it to Express and Nest; you modeled the encounter aggregate, indexed it from EXPLAIN, and made the claim pipeline idempotent over a broker. You fronted it with OIDC SSO and RBAC, instrumented it with OpenTelemetry, and shipped it to Fargate behind a blue-green pipeline. Every piece passed its own tests. None of that proves the system works. A backend is not the sum of its chapters; it is what happens in the seams between them at 3 a.m. under load you didn't rehearse. This chapter is where we stop building components and start operating a system — designing it as one artifact, hardening it against a checklist, then deliberately breaking it, scaling it, and recovering it, watching the whole time through the instrumentation Part VI gave us.

This is a low-new-concept, high-integration chapter on purpose. We re-teach nothing; we cite relentlessly and assemble. If a beat feels thin on mechanism, that is because the mechanism already has a home chapter — go re-read it. The work here is judgment, not vocabulary.


1. The problem: the system nobody has seen whole​

It's 2 a.m. and the page reads Pulsely worklist p99 = 8.2s, error budget burning at 40×. The on-call engineer — competent, six weeks in — opens the dashboards and freezes. Worklist latency is up, but so are claims-service connection-pool waits, and the critical-value alert consumer's queue is climbing, and one Postgres replica is lagging twelve seconds. Which of those is the cause and which are symptoms? They have never seen Pulsely on a single diagram. They know the charting code. They know the claims code. They have never been forced to reason about the two of them sharing one connection pool, one event loop, one database, under real concurrency. The incident's first hour is archaeology — reconstructing the system's shape from grep and Slack scrollback — and archaeology is the most expensive thing you can do while a clinic's revenue and, worse, its patient-safety alerts are on fire.

This is the integration gap, and it is the reason capstones exist. A system can pass every unit test and every per-chapter exercise and still fall over, because the dangerous failure modes don't live inside the boxes — they live in the edges no single chapter owned. Auth ↔ chart: does a revoked token still hydrate a cached patient timeline? Claims ↔ clearinghouse ↔ remit: if the 837 goes out but the outbox write loses its transaction, is there a claim on the wire with no claim record behind it? Search index ↔ write path: does a patient who revoked consent keep showing up in results? Each of those is a question about a seam, and seams are exactly what you never tested, because testing a seam requires the whole system standing up at once.

So there are three things "done" can mean, and most engineers stop at the first. It runs on my machine — the demo worked. It's deployed — CI is green and the canary went out. I can operate it — I can reason about it under load, predict how it fails, and restore it after data loss. Only the third is what a senior engineer is paid for, and it is invisible until something goes wrong. This chapter forces the difference into the open by refusing to call Pulsely finished until we have proven, with evidence from the dashboards, that we can break it on purpose and survive.

🧭 Mental model. A component is correct when it does what its tests say. A system is operable when you can answer three questions cold: How do I know it's healthy right now? What happens when its slowest dependency gets slow? How do I get it back after it loses data? Everything up to here earned the first kind of confidence. This chapter is the only place you earn the second — and the second is the one that pages you.


2. The mental model: four verbs and a layered derivation​

Hold two pictures. The first is the shape of Pulsely as one system; the second is the lifecycle of operating it.

Pulsely as a layered derivation​

Pulsely is not a pile of services; it is a stack where each layer is derived from the one beneath it. From the top:

edge / API gateway ── TLS, OIDC SSO, rate-limit, routing (Ch 6, 14, 32)
│
identity & authz ── tokens, RBAC, minimum-necessary, (Ch 32)
│ RLS tenancy, break-glass
domain services ── scheduling · encounters/charting · (Ch 14–17)
│ orders(lab/eRx) · CLAIMS
async backbone ── outbox → broker → idempotent (Ch 25–27)
│ consumers (837/835, alerts)
read models ── worklist/chart timeline · RPM vitals (Ch 20, 22)
│ · patient-search idx (denormalized)
storage ── Postgres (primary+replica) · Redis (Ch 17–21)
│
────────────────────────────── observability + IMMUTABLE AUDIT LOG (Ch 34)
cut through ALL

The design doc walks this top-down — start at the contract a client sees and derive what must exist beneath it. The build walks it bottom-up — you can't serve a worklist before the storage and the outbox exist. Holding both directions is the skill: the doc is a promise made downward, the build is the payment made upward, and they must meet in the middle without a gap. Every box here is a chapter you already finished; the novelty is the arrows between them.

The four lifecycle verbs​

The chapter's spine is four verbs, and "done" means all four:

  1. Design — write the consolidated design doc and the ADR library (§5). This is the falsifiable artifact: every capacity number and latency budget in it is a prediction.
  2. Build / Harden — assemble the running system and drive it against a production-readiness checklist (§4, §5). Hardening is what turns "it runs" into "it survives."
  3. Operate — run three drills (§5): break it, scale it, recover it. Each drill tries to violate a stated invariant.
  4. Reflect — the structured retrospective (§7): what you'd do differently, with the conditions under which you'd reverse it.

Most teams do verb 1 badly, verb 2 partially, and verbs 3 and 4 never — until an incident does verb 3 for them, unscheduled, in production, with patients affected.

🧭 Drills are controlled experiments, not vandalism. Chaos engineering is the scientific method aimed at your SLOs: hypothesis → bound the blast radius → inject one fault → observe through existing instrumentation → compare to predicted steady state → fix → re-run. "Kick it and see what breaks" is not a drill; it's an outage you scheduled for yourself. The discipline is that you write down what you expect before you inject, so the drill can tell you that you were wrong.


3. Theory & invariants​

A system you can operate is a system whose invariants you have written down, because operating it is defending those invariants. Drills are organized attempts to violate them; if you can't name them, you can't tell a successful drill from a disaster.

🔑 The Pulsely invariant catalogue. These are the load-bearing truths every drill must leave standing. (1) Exactly-once effect on claim submission — a claim is transmitted to the clearinghouse once and a claim row exists once, even if the request is retried or a message is redelivered. This is idempotency (Ch 25), not exactly-once delivery, which doesn't exist. A double-submitted 837 is a duplicate claim — a denial at best, fraud at worst. (2) 837 transmitted ⇒ claim row exists — there is never a claim on the wire with no record behind it, and never a recorded claim silently never transmitted; this is what the outbox buys us. (3) No double-booked slot — a finite appointment slot is claimed by at most one patient, even when two front-desk staff grab the same 9:00 at the same instant. (4) Read-your-writes for the charting provider's own signed note — if you sign a note, your next chart read shows it, even while other read models are still eventually consistent. (5) Bounded worklist/RPM staleness — a new result or vital appears in the provider's monitoring view within a stated bound (say 10s p99), never "eventually, maybe"; for a critical value that bound is a patient-safety SLA, not a nicety. (6) Critical-value alerts at-least-once, deduplicated at the edge — a critical-potassium alert may be generated twice but is paged once.

Each invariant declares a consistency model, and the models differ per surface — this is the heart of the design. Claims and appointment slots are strong / linearizable on the write path — meaning every reader sees the write the instant it commits, as if there were a single copy of the data and a single queue of operations — because money and patient safety demand it, and we will trade availability under partition (staying correct even if it means briefly refusing a write when the network splits) to keep it (Ch 17, Ch 23). If you own optimistic UI updates in React Query — where the client shows a value before the server has confirmed it — this is the exact opposite: a claim write or a slot booking can never show as done until it truly is. Worklist, RPM view, and patient search are eventual with a stated staleness bound — they are read models rebuilt asynchronously from the event log. Counts (a provider's panel size, unread-message tallies) are eventually consistent and explicitly allowed to be approximate — nobody is harmed if a panel count is briefly off by three. Declaring this per-surface is what lets you scale: you only pay for strong consistency where a patient or a dollar would be hurt by its absence.

To measure whether you're keeping the promises, restate the reliability vocabulary you've already met concretely. An SLI is the measured thing: p99 worklist-read latency, read straight off the gateway's histogram. An SLO is the target over a window: p99 worklist-read < 300 ms over 28 days. The error budget is the difference — the amount of badness you're allowed to spend, and crucially, the budget is what the drills are permitted to consume. A drill that would blow a quarter's budget is not a drill; it's a decision for the business, not the on-call.

Two failure classes the drills hunt, each worth saying slowly.

Metastable failure is the system that will not recover even after the trigger is removed. The database comes back, but the retry storm and the cold cache now feed each other, and the system sits there pinned — healthy components locked in a sick loop.

Gray failure is the component that is partially up and lying about it. Its health check returns 200 while it serves errors to half its callers, so the load balancer keeps routing to it. If you've ever had a health-check endpoint return 200 while the app was actually white-screening for half your users — green light, broken product — that's gray failure: the monitor says fine, the users say broken, and nothing takes the box out of rotation.

And for recovery, two numbers you will declare and then test: RPO (recovery point objective — the maximum data loss you'll accept, e.g. 5 minutes) and RTO (recovery time objective — the maximum downtime, e.g. 30 minutes). Asserting these is junior; the senior move is the drill in §5 that measures the real numbers, which are almost always worse.

📎 Borrowed on credit: the falsifiable design doc. We treat the consolidated design doc not as documentation but as a bundle of predictions. "The worklist read path sustains 5k QPS." "DB failover completes in under 60s." "Restore RTO is 30 minutes." Each is a claim the drills either confirm or refute. A design doc nobody tests is a wish list; a design doc whose claims are drilled is an engineering instrument. We cash this in §5 — every drill maps to a sentence in the doc.


4. Under the hood: assembling and tracing the whole system​

Up to now Pulsely's pieces ran in their own chapters' compose files. The capstone's first physical act is one stack that brings the whole thing up reproducibly — because a system you can't stand up in one command is a system you can't drill.

make up → gateway · claims-svc · encounter-svc · worklist-svc ·
claim-submitter · alert-consumer ·
postgres(primary) · postgres(replica) · redis ·
broker · patient-search · otel-collector + dashboards

One docker compose / Makefile target, one network, one set of seeded synthetic patients, the metrics-traces-logs pipeline from Chapter 34 wired in from the start. The reproducibility is the point: the 12-factor discipline of config, not code means the same artifacts that run here run on Fargate (Ch 37), so a drill outcome locally is evidence about production, not a toy.

The end-to-end trace for POST /claims​

The unit of reasoning is not a box; it is a request's whole journey. Follow one claim submission and watch where the trace context lives — and where it dies:

client ─[trace=T1]→ gateway ──authn──→ claims-svc
│ (span: db.tx)
├──► BEGIN
│ INSERT claims ... ← strong, linearizable
│ INSERT outbox (event, T1) ← SAME transaction
└──► COMMIT ✅ atomic: claim + intent to transmit
│
outbox relay ─[trace=T1]→ broker ─→ claim-submitter
│ (NEW span, must
│ re-attach T1 from
│ the message envelope)
└──► transmit 837 → clearinghouse

The two truths to extract. First, the claim row and the outbox row are written in the same database transaction (Ch 25) — that single COMMIT is what makes invariant (2) hold. A dual-write (insert the claim, then separately publish to the broker) has a window where the claim exists but the event was lost — a recorded claim that never reaches the clearinghouse, i.e. unbilled revenue nobody notices — or the event fired but the transaction rolled back — an 837 on the wire with no claim behind it. The outbox collapses that window to zero. Second — and this is where incidents go blind — the trace ID T1 does not propagate across the broker for free. Synchronous HTTP carries trace headers automatically; a message queue is an async boundary, and unless you explicitly stuff T1 into the message envelope and re-attach it in the consumer, the trace ends at the broker. Then the on-call sees the claim span tree stop at "published" and the clearinghouse transmission appear in a separate, unlinked trace, and the 2 a.m. archaeology begins. The fix is one line in the envelope and one line in the consumer; the cost of forgetting it is every future incident.

Node-specific integration hazards​

Three things only bite once the pieces share a process and a database:

  • The event loop is a shared failure domain. You've already met this hazard: one slow synchronous operation — a giant JSON.parse of an RPM batch, a synchronous bcrypt, a tight loop over a 50k-row vitals result — stalls every in-flight request on that instance, not just the one that triggered it. In isolation you never noticed; at integration, a worklist endpoint doing synchronous work can spike claim latency on the same instance. Event-loop lag is therefore a first-class signal, not a curiosity.
  • Connection-pool sizing across services sharing one Postgres. If claims-svc and worklist-svc each open a pool of 50 against a Postgres that allows 100 connections, two healthy services exhaust the database between them and a third gets too many clients. Pools must be sized to aggregate concurrency against the shared limit (Ch 19), not per-service in isolation. This is the single most common integration scaling wall, and §5's scale drill finds it on cue.
  • Graceful shutdown. On SIGTERM during a rolling deploy, an instance must drain — stop accepting new requests, finish in-flight ones, flush the outbox relay — before exiting. Skip it and a deploy drops claims mid-flight, which violates invariant (1) for no reason other than carelessness.

🏭 The JVM would fail differently here, and the contrast teaches (skippable if you're Node-only — the payoff is just where the blast radius lands). Under thread-per-request (Ch 9), one slow handler blocks a thread and the system degrades gracefully — throughput drops, but unrelated requests on other threads keep flowing. Under Node's single loop, the same slow synchronous call degrades catastrophically — the whole instance stalls. Different failure shapes demand different defenses: Node leans harder on never blocking the loop and on event-loop-lag alerting; the JVM leans on thread-pool and bulkhead tuning. Same goal — isolate the blast radius — different mechanism.

Where the drills hook in​

Mechanically, faults inject at the proxy/sidecar layer so we don't touch business code: add latency or an error percentage to a dependency, kill a process, promote the replica to simulate primary loss, or drop broker traffic with a network rule to simulate a partition. The instrumentation reads it back through the USE and RED signals (Ch 34) — Utilization/Saturation/Errors for resources, Rate/Errors/Duration for requests. The plain version: which alarm lights up first tells you what kind of failure you have. Read the order, not just the levels:

  • Saturation climbs first → you hit a capacity wall (a pool, a CPU, a disk fills up).
  • Errors jump first → a dependency died outright.
  • Latency climbs but errors stay flat → something is slow-but-up — a gray failure.

The order the signals move in is the diagnosis.

Make this concrete. Inject 2s of latency into the Postgres replica and watch: worklist-read Duration climbs while Errors stay flat and DB Saturation (connection waits) climbs right behind it — latency-first, then saturation, errors last. That ordering says "a downstream got slow and is back-pressuring the pool," not "a downstream died." Now inject a flat 50% error rate on the patient-search dependency instead: search-read Errors jump immediately, Duration on the surviving half stays flat, Saturation never moves — error-first with no saturation says "hard failure, not capacity." Reading the signal order before touching anything is the single habit that separates a five-minute diagnosis from a two-hour one; the dashboards already encode the answer, and the drill is where you practice reading them under no real pressure so you can read them under real pressure.


5. In production: the doc, the checklist, and the three drills​

This is the chapter's center of gravity: the artifacts and the operations that turn a built system into an operated one.

The consolidated design doc​

One document, navigable, links out instead of inlining everything — because a 200-page tome nobody reads is worse than no doc, and a one-pager is the thing on-call actually opens. Standard sections: context & goals, non-goals (what Pulsely deliberately doesn't do — global multi-region, sub-50ms chart loads), the one-page architecture diagram (below), data model, API surface, capacity estimates (Ch 41's worksheet, instantiated), failure modes, SLOs, security & HIPAA model, and runbook links. The skeleton is the one from Chapter 39; the discipline is keeping every claim falsifiable and keeping the doc living — reviewed at each drill, not written once and abandoned.

The capacity estimates are where the doc earns the word falsifiable. Don't write "scales well"; write the numbers and let the scale drill grade them. Instantiate the Chapter 41 worksheet: worklist and RPM monitoring reads dominate at, say, 5k QPS peak (the RPM stream is a genuine firehose — many devices, many readings per minute); the read cache holds the working set of active timelines (a few GB in Redis); claims are write-critical but low-QPS (hundreds/sec) and strongly consistent; the outbox relay must drain faster than claims arrive or the clearinghouse queue backs up. Each of those is a prediction — "the worklist path sustains 5k QPS on N instances with the cache warm," "the relay clears its backlog within 30s of the submitter returning" — and Drill 2 is the experiment that confirms or refutes each one. A capacity section with no numbers is the tell of a doc that has never been tested against reality.

The one-page diagram is the most valuable artifact in the building, because it is what the on-call opens at 2 a.m.:

┌────────── TRUST BOUNDARY (HIPAA) ──────────┐
clients ──TLS──► [ API GATEWAY ] OIDC SSO · authz · rate-limit │
│ │ │ │
┌──────┘ ┌─────┘ ┌────┘ │
[claims-svc] [encounter-svc] [worklist-svc] ── sync edges ──▶
│ (strong) │ (strong, │ (read model)
▼ │ versioned) ▼
[Postgres pri]──►[Postgres rep] [RPM store · search idx]
│ outbox
╠══════►[ BROKER ]═══► [claim-submitter] ─► clearinghouse (837/835)
║ ╚═══► [alert-consumer] ──page care team (║ async)
── observability + IMMUTABLE AUDIT LOG underlie everything ──

Mark the trust boundaries (the gateway, and every cross-service call that must carry verified, minimum-necessary identity — Ch 32) and the sync vs async edges (a slow sync edge cascades; an async edge absorbs). On-call's first question is "which edge is the cause?", and this diagram is the only thing that answers it in seconds.

The ADR library​

Collect the through-line decisions the book made part by part, each in the Context → Decision → Alternatives → Consequences → Status form from Chapter 39, cross-linked so the history of reasoning survives:

ADRDecisionStatus
0002Modular monolith of services over microservices for v1Accepted
0007Outbox over dual-write for the claim→clearinghouse (837) eventAccepted
0009Async claim pipeline over synchronous in-request 837 submissionAccepted
0011Dedicated patient-search index over Postgres full-textAccepted
0014OIDC SSO + short-lived JWT + rotating refresh over server sessionsAccepted
0016Strong consistency on claims & slots; eventual on worklist/RPM/searchAccepted
0021pgvector in Postgres over a dedicated vector DBAccepted

The senior practice is the supersession discipline: you never delete an ADR. When hindsight reverses a call (see §7), you write a new ADR with status Accepted that links back to the old one, now Superseded, so a future engineer can recover not just the current decision but the reasoning that changed. The "superseded in hindsight" appendix (§7) is where the book's honesty lives.

The production-readiness checklist​

This is the operable core — the floor below which Pulsely is not allowed to be called done:

  • Health and readiness are distinct and honest — /healthz (am I alive?) ≠ /readyz (can I serve? — are my pools warm, my deps reachable?). A readiness check that always returns 200 is gray failure waiting to happen.
  • Structured logs with correlation IDs that propagate across the async boundary (the §4 trace fix).
  • Dashboards: one per service + one "is Pulsely up?" overview built on SLIs, not raw CPU.
  • Alerts tied to SLO burn rate, not raw thresholds — worklist error budget burning > 10×, not CPU > 80%.
  • A runbook per alert — the page links to the steps, so on-call doesn't improvise.
  • Backups taken and restore-tested — see the recovery drill; an untested backup is theater.
  • Secrets never in env-dumped logs, sourced from a secrets manager (Ch 31).
  • Timeout + retry budget on every external call — clearinghouse, lab, e-Rx, eligibility — each timeout shorter than its caller's (Ch 33).
  • Immutable audit log verified — every PHI access, including reads (chart views), lands append-only and tamper-evident; access is RBAC + minimum-necessary; the break-glass path is itself audited. A read that isn't logged is a compliance gap, not just a missing metric.
  • Graceful shutdown, resource limits set, rollback path defined (Ch 36, Ch 38).

Now the three drills. Each is a controlled experiment against one invariant, run on synthetic data (see §8 — a chaos drill against real claims or real patients is its own incident and a reportable one).

Drill 1 — Break (chaos)​

Hypothesis, stated before injecting: "Killing the claim-submitter under load will NOT lose claims; it will only delay transmission to the clearinghouse, which drains from the broker when the submitter returns." That is a claim about invariants (1) and (2) holding while a component dies.

Bound the blast radius (one consumer, synthetic traffic, a 10-minute window), then kill -9 the claim-submitter mid-load. Watch the dashboards. The predicted steady state: claims-svc RED metrics flat (claim writes unaffected — they commit independently of the submitter), broker queue depth climbing (the 837 events accumulating, the broker absorbing the async edge), zero data loss. Restart the submitter; the backlog drains, each 837 transmits — and transmits exactly once (invariant 1: the same claim never goes out twice, so no duplicate-claim denial). If instead claim writes also failed when the submitter died, you've discovered a hidden synchronous coupling at a seam that should have been async — a bulkhead is missing — and you file the gap. The drill's value is identical whether it confirms or refutes: a confirmed hypothesis is earned confidence, a refuted one is a bug found before a patient found it. Then escalate — kill the alert-consumer next, same protocol, but with a clinical twist worth naming: a delayed critical-value alert is not a delayed marketing ping. Its staleness bound is a patient-safety SLA (invariant 5), so the drill must confirm not just "no loss" but "drains within the safety bound" — and if it can't, the alert path needs a tighter guarantee than the money path does. Then kill the search indexer.

Drill 2 — Scale (load-test and fix one bottleneck)​

Load-test the worklist / RPM read path with a realistic, read-heavy mix (Ch 30) and ramp until something gives. The first bottleneck is almost always one of three, all foreshadowed: connection-pool exhaustion (the §4 aggregate-sizing wall), an N+1 on chart hydration (loading each note's authoring provider in a separate query — Ch 16), or a cache stampede on a hot patient's chart key — or a hot RPM dashboard key — when its TTL expires under load (Ch 21). Read the dashboards to name it — saturation-first on DB connections points to the pool; flat saturation but exploding query count points to N+1; a latency cliff exactly at TTL boundaries points to stampede.

Then apply exactly one fix — coalesce the N+1 into a batched join, or add request coalescing + jittered TTL for the stampede (Ch 29) — and re-test. The point of one fix is to prove the bottleneck moved: the slowest serial hop sets the floor, so removing it must surface the next one. When it does, you stop — you have now found the next bottleneck, and chasing it is a separate, evidence-driven decision, not reflexive gold-plating.

Drill 3 — Recover (disaster restore)​

Declare the numbers in the design doc first — RPO 5 minutes, RTO 30 minutes — so the drill can falsify them. Then destroy the primary Postgres and restore: promote the replica, or restore from the base backup + WAL replay to a point in time (Ch 19). Lay the timeline against the declared targets so the gap is unmissable:

incident start ──┬── detection ──┬───── restore steps ──────┬── service up
T0 │ T0+90s │ promote · WAL replay · │ T0+?
│ │ warm pools · re-route │
RPO mark: last durable WAL = T0−12s → actual RPO 12s (declared 5m ✅)
RTO mark: T0 → service up → actual RTO 2h10m (declared 30m ❌)

Measure the actual RPO (the gap between the last durable WAL and the crash) and the actual RTO (wall-clock from "primary gone" to "service serving"). The lesson is reliably humbling: RPO usually beats its target (replication is fast) while RTO blows it 3–4×, because nobody timed the WAL replay on a full dataset, or the runbook had a manual step nobody had practiced, or the app came up before its connection pools were warm and the first traffic wave knocked it back down. Document the gap and fix the runbook — pre-stage the base backup, script the promotion, warm the pools before re-routing, and (§8) re-apply consent revocations and re-rotate secrets. That gap, found in a drill on synthetic data, is the difference between a 30-minute incident and the four-hour one where you're learning the restore procedure for the first time while a clinic can't chart.

After the drills, the operating cadence closes the loop: every gap becomes a backlog item with an owner and a severity, the design doc is updated so it stays the source of truth rather than rotting back into Slack archaeology, and the drill itself is scheduled to recur — quarterly, not once. A gap found and filed but never owned is a gap you will rediscover in production; a drill run once and never again is a snapshot of a system that has since drifted. The work product of operating Pulsely is not "the drills passed" — it's a living register of known failure modes, each with an owner, a fix or an accepted-risk note, and a re-test date. That register, more than any green build, is what tells a new on-call engineer the system is actually understood.

🛑 What we deliberately did not re-explain. How the outbox relay actually polls and marks rows (Ch 25); how WAL and PITR mechanically work (Ch 19); how circuit breakers and bulkheads are implemented (Ch 33); how the trace pipeline samples and stores spans (Ch 34); how the load test is wired (Ch 30). This is a synthesis chapter — it composes those mechanisms and reads their output. If a mechanism is unclear, the gap is in its home chapter, not here.


6. Common pitfalls​

Each is the signature you'll observe at integration time, then the principle that resolves it.

The demo passes, first real load tips it over. Signature: flawless in the demo, falls over at 200 concurrent providers. Fix: the demo never exercised the connection pool or the event loop; nothing is "done" until it's load-tested. Size pools to actual aggregate concurrency, not to whatever number looked round.

A chaos drill kills one component and the whole system cascades. Signature: the alert-consumer dies and claim writes start failing too. Fix: a missing timeout/circuit-breaker/bulkhead at the seam turned an async dependency into a synchronous one. Per-dependency timeouts shorter than the caller's, isolated pools, and the async edge actually being async.

The system stays down after the fault is removed (metastable). Signature: you restore the database and the system still won't recover — pinned by a retry storm hammering a cold cache. Fix: jittered backoff + retry budget so retries don't synchronize, load shedding so the system can dig out, and cache warming on recovery so the first wave of reads doesn't all miss at once.

Backups exist but restore fails or takes hours. Signature: "we have backups" — and the first time anyone runs a restore is during the real incident. Fix: an untested backup is theater; schedule periodic restore drills and measure RTO for real (Drill 3).

An 837 is on the wire but no claim row exists. Signature: a claim transmitted to the clearinghouse with no matching claim record — or a recorded claim that was never transmitted. Fix: a dual-write race — the transmit-intent and the insert weren't atomic. Route through the outbox so the DB write and the event are one transaction (the §4 picture).

Trace IDs vanish mid-journey. Signature: the claim trace stops at the broker; the clearinghouse transmission is in a separate, unlinked trace; incident debugging goes blind. Fix: context propagation broke at the async boundary — carry the trace/correlation ID in the message envelope and re-attach it in the consumer.

ADRs describe a system that no longer exists. Signature: a new engineer follows ADR-0011 and finds the patient-search index works nothing like it says. Fix: mark it Superseded, link forward to the ADR that replaced it; review the doc at every drill so it stays alive.

Alert fatigue — the real page gets ignored. Signature: on-call mutes an ops channel that cries CPU > 80% twelve times a night, and misses the one page that mattered. Fix: delete alerts on raw resources; alert on symptom + budget burn (SLO violation), which fires rarely and means something every time.


7. Tradeoffs — and what we'd do differently​

Every decision in Pulsely was a bet, and a capstone is the place to grade the bets with hindsight. For each, the bet, what it cost, and the condition under which you'd reverse it.

Async claim pipeline (outbox + consumers) vs synchronous in-request submission. Chosen for resilience and decoupling — the §5 break drill passed because of it. Paid for in eventual-consistency complexity and harder debugging (the trace-propagation hazard is a direct tax of going async). Reverse it for a genuinely low-volume system where simplicity dominates and a synchronous 837 submit would never be the bottleneck. We'd keep it for Pulsely.

Dedicated search index vs Postgres full-text. Chosen for patient-search scale (Ch 22). Paid for in a second consistency boundary to keep in sync — the index lag is now a thing that can leak a patient who revoked consent (§8). Reverse it for an early-stage product where Postgres full-text is plenty and one fewer moving part wins. Hindsight ADR: for v1's actual traffic, we shipped the dedicated index too early — Postgres FTS would have carried us another year and saved a whole sync pipeline. ADR-0011 is superseded by ADR-0024 "Defer the dedicated index until query volume justifies the second consistency boundary." This is the honest reversal the appendix demands.

Services-in-one-repo (modular monolith) vs true microservices. Chosen to keep the capstone operable by one person (Ch 39). Paid for in shared failure domains — one event loop, one Postgres, the integration hazards of §4. Reverse it when team size or independent deploy cadence forces it (Ch 29), never before.

Strong consistency on claims & slots vs eventual everywhere. Chosen because money and patient safety demand it. Paid for in write-path latency and reduced availability under partition (Ch 23). Never reverse this for claims or slot booking — this is the one bet with no condition that flips it.

How much to harden before shipping vs ship-and-learn. The readiness checklist is the floor, not the ceiling. Gold-plating reliability the business doesn't need is itself a failure — five-nines on a feature with twelve users is waste. Tie hardening spend to the error budget and actual traffic: harden where the budget is burning, not where a checklist online said to.

Single design doc vs distributed READMEs. Chosen for incident speed — one place to look at 2 a.m. Paid for in the maintenance discipline of keeping it current. The first thing that rots when a team is busy, and the most expensive thing to have rotted when an incident hits.

🚫 A framing this book rejects. "We don't need drills — we have good monitoring and we'll handle incidents when they happen." This is the single most expensive belief in operations. Monitoring tells you the system is currently on fire; it tells you nothing about how it fails until it's failing in production with patients affected. The drill is the only way to learn the failure modes on your schedule, on synthetic data, with the blast radius bounded — instead of on the patient's schedule, on real charts, with the blast radius being a missed critical value. You either run the experiment, or the experiment runs you.


8. Security & scale notes​

Security and scale are properties of the assembled whole, and the seams introduce risks no component owned alone. In healthcare the stakes change character: a broken access check is not a lost sale, it's a reportable HIPAA breach.

The threat surface of the system, not the parts. Auth-token replay across services — a token verified at the gateway must still be re-validated (or its identity propagated trustably) at each service, or an internal call becomes an authentication bypass (Ch 32). IDOR at the gateway — GET /encounters/:id (or /patients/:id) must check that the caller is on that patient's care team and has minimum-necessary access, not merely that they're authenticated; changing the ID in the URL is the trust-boundary failure wearing a microservices costume, and here the payload isn't a stranger's shopping cart, it's one patient's chart served to the wrong clinician. Patient search leaking restricted state — because the index is a separate read model with its own consistency lag, a patient who revoked consent, or a restricted VIP/employee record, can keep surfacing in results until the index catches up; the deletion or consent change must propagate to the index, and the query must filter on current access scope, not just match text. The broker as an unauthenticated trust boundary — anything that can publish to the claims topic can forge a claim event, and a fabricated 837 is fraud; the broker needs authn too, or it's an open door behind your gateway. And secrets sprawl — more components means more places a key can leak; one secrets manager, never env-dumped into logs.

The audit log is a security control, not a log file. HIPAA makes Pulsely's immutable audit log first-class, and that reshapes the architecture at the seams. Every PHI access — including every chart view, not just every write — is recorded append-only and tamper-evident, so "who viewed this patient's record, and when" is always answerable. Two consequences: (1) read paths carry an audit obligation the original design never had — the worklist and RPM read models must emit audit events, so a read that isn't logged is a compliance gap, not a missing metric; (2) break-glass — emergency access to a chart outside your normal scope, for a code-blue on a patient who isn't yours — is allowed, but only with a mandatory justification that is itself audited and reviewed, so the system stays usable in an emergency without becoming an open door. And RLS tenancy (row-level security per clinic/org) is the backstop under all of it: even a bug in a service query cannot return another organization's patients, because the database itself refuses the rows.

Drills must run on synthetic data — non-negotiable. A chaos drill that corrupts real claims, or a load test that pages ten thousand real patients' care teams with a fabricated critical-value alert, is itself a Sev-1 — and, because it touches PHI, a reportable incident. Drills run against a synthetic dataset or scrubbed PHI, in an environment isolated from production side effects. This is not bureaucracy; it's the difference between an experiment and an outage.

Behavior under load, introduced by integration. Cache stampede on a hot patient's chart or a hot RPM dashboard key (Drill 2). Thundering herd after a failover — when the primary dies and the replica is promoted, every cache that was keyed to the old primary misses at once and a wall of reads hits a cold database (Ch 30). Connection-pool exhaustion as the true scaling wall (§4). And absent backpressure letting a queue grow unbounded into OOM — the RPM stream is a real firehose, and a break drill that "passes" by accumulating readings forever isn't passing; it's deferring the failure to the broker's memory limit. Bounded queues, load shedding, and a defined drop policy are availability features.

🔑 Rate limiting and load shedding are availability features, not just security ones. A single abusive or buggy client — or one misconfigured device flooding vitals — must not be able to consume the whole system's error budget. Per-user and per-endpoint limits (Ch 11, Ch 41) protect every other clinic from the worst one. Under saturation, shedding the lowest-value load (returning 429s, deferring a bulk chart export) is what keeps claims and critical-value alerts flowing while, say, a background report degrades — graceful degradation is a choice you design in, not a thing that happens to you.

Recovery has its own security surface. A restored backup can reintroduce deleted data — a patient who exercised right-to-erasure reappears, or a revoked consent comes back live, a privacy regression born of a restore (Ch 31). It can also restore stale credentials that were rotated after the backup was taken. The DR runbook (Drill 3) must explicitly account for both: re-apply erasures and consent revocations, and re-rotate secrets post-restore. Recovery that ignores security restores yesterday's vulnerabilities along with yesterday's data.


9. Interview lens & exercises​

Interview questions​

The capstone questions probe whether you can reason about a whole system under stress, which is the senior signal no amount of LeetCode reaches.

"Design Pulsely's provider worklist (or RPM monitoring view) end-to-end."

  • Junior answer: draws boxes — gateway, service, database, cache — and connects them. Ignores consistency and failure entirely.
  • Senior answer: names the read/write split, states the staleness SLO ("eventual within 10s p99, read-your-writes for the provider's own signed note"), picks fan-out-on-write vs read and justifies it by the actual access pattern and panel-size distribution — a provider's patient panel, a device's reading volume, not a social graph (Ch 41) — then names what breaks first under 10× and the metric that warns of it.

"Your service depends on three others and one gets slow. What happens?"

  • Junior: "add retries" — and causes a retry storm that turns a slow dependency into a total outage.
  • Senior: walks the timeout that's shorter than the caller's, the bulkhead that isolates the pool, the circuit breaker that stops hammering a dead dependency, and the difference between graceful degradation and cascade — naming metastable failure as the thing retries-without-jitter cause.

"Walk me through restoring after the primary database is lost."

  • Junior: "we have backups."
  • Senior: states the RPO/RTO targets, the restore steps (promote replica or PITR from base + WAL), and — the tell — that they've tested it and know the real RTO is 4× the assumed one, because they ran the drill. Bonus tell: they mention re-applying erasures and re-rotating secrets post-restore.

"How do you know Pulsely is healthy right now?"

  • Junior: "CPU and memory look fine."
  • Senior: names the SLIs, the error-budget burn rate, and the two or three dashboards that actually matter — and notes that CPU looking fine is exactly what a gray failure looks like from the outside.

"What would you do differently?"

  • Junior: "nothing, it works."
  • Senior: names a specific decision (we shipped the dedicated patient-search index a year early), its cost at scale (a whole second consistency boundary to maintain, and a consent-leak surface), and the condition under which they'd reverse it — i.e., narrates the superseding ADR from §7. The ability to grade your own past decisions is the seniority signal this whole book builds toward.

Exercises & the Pulsely increment​

This is the full capstone. Do all four; the value is in the evidence you produce, not the prose.

  1. Write the consolidated design doc + ADR library. Use the Chapter 39 skeleton: context, non-goals, the one-page diagram, data model, API surface, capacity estimates, failure modes, SLOs, security & HIPAA model, runbook links. Collect the through-line ADRs (the table in §5) and include a "superseded in hindsight" appendix that reverses at least one earlier decision with full reasoning. If your doc has no honest reversal, you haven't reflected — re-read §7.

  2. Run the break drill. Write the hypothesis first. Kill the claim-submitter under synthetic load, predict the blast radius, then confirm via traces and metrics that claim writes are unaffected and the broker absorbs the backlog. Escalate to killing the alert-consumer (check the safety-bound drain) and the search indexer. File every gap. A drill that finds nothing means your instrumentation is too coarse to see the failure — fix that, because in production the failure will be there whether or not you can see it.

  3. Run the scale drill. Load-test the worklist / RPM read path, read the dashboards to name the first bottleneck (pool exhaustion / N+1 / stampede), apply exactly one fix, and re-test to prove the bottleneck moved. Stop there and write down the next one.

  4. Run the recovery drill. Declare RPO/RTO in the doc, then destroy the primary, restore to a point in time, measure the actual numbers, and document the gap. Update the DR runbook with what the drill taught you — including the security steps (re-apply erasures and consent revocations, re-rotate secrets).

Produce, alongside these, the drill-results matrix — for each injected fault: invariant tested, predicted behavior, observed behavior, gap found. That single table is the most senior artifact in your portfolio: it is proof you operated a system, not just built one.


Key takeaways​

  • A backend is not the sum of its chapters; the dangerous failures live in the seams between components, which no single chapter ever tested.
  • "Done" has three meanings — runs on my machine, deployed, operable. Only the third (reason under load, predict failure, restore after loss) is what seniority means, and it's invisible until something breaks.
  • Pulsely is a layered derivation: the design doc walks it top-down, the build walks it bottom-up, and they must meet without a gap. The four lifecycle verbs are Design, Build/Harden, Operate, Reflect — and all four are required.
  • Operating a system is defending its invariants. Write them down (exactly-once claim effect, 837 transmitted ⇒ claim exists, no double-booked slot, bounded staleness), declare a consistency model per surface, and tie SLOs and the error budget to what the drills may consume.
  • The design doc is falsifiable: every capacity and latency claim is a prediction the drills confirm or refute. ADRs are never deleted — they're superseded with a forward link, so the history of reasoning survives.
  • Drills are controlled experiments: hypothesis → bound blast radius → inject → observe via existing instrumentation → confirm/refute → fix. Break it (chaos), scale it (find and move one bottleneck), recover it (measure real RPO/RTO, which is always worse than declared).
  • Integration introduces failures no component owned: shared event loop, aggregate pool sizing, trace context dying at the async boundary, metastable retry storms, patient-search leakage of restricted records, restore-reintroduced erased data. Run drills on synthetic data, always — a chaos drill on real PHI is a reportable incident.
  • You either run the experiment on your schedule with the blast radius bounded — or production runs it for you on the patient's.

← Previous: Ch 42 — Backend for AI Features · Up: Part VIII overview · Master TOC · Next: Ch 44 — Interview Readiness & the Senior Career →