Chapter 33 — Reliability Engineering: Resilience Patterns, SLOs, and DR
Part VI · Security, Reliability & Observability | Prerequisites: Ch 25, Ch 29–Ch 30 | Builds: Pulsely with timeouts, retries, circuit breakers, bulkheads, and SLOs
Earlier you met an invariant that has been waiting in the wings for the whole book: failure is independent per hop, and the chain is only as reliable as the product of its parts. We located that truth on the spine and walked on. We have been building toward this chapter ever since — you learned to make a single write safe to repeat, to spread load across interchangeable, finite-capacity stages, and that the tail, not the average, is what users feel, and that a chain saturates from its slowest link. This chapter cashes the debt. It is the long-deferred owner of resilience: the discipline of building a system that stays useful while its parts misbehave, and of deciding — on purpose, with a budget — how reliable "reliable enough" actually is.
The reframe to carry through every beat: reliability is not the absence of failure; it is the bounding of its blast radius and the predictability of recovery. You will never prevent a clearinghouse from slowing down or a region from going dark. What you can engineer is whether that fault stays a fault — contained to one feature, recovered automatically — or metastasizes into a full outage that outlives the original problem. In healthcare, "outage" is not a lost sale; it is a clinician who cannot open a chart during a visit, a critical lab that never fans out, a claim silently dropped. This is a dense, pattern-heavy chapter, and most of it is plumbing you install once and reuse on every remote call you ever write.
1. The problem: a slow dependency takes down things that don't depend on it
It is 08:00 on a Monday and Pulsely is down. Not gracefully degraded — down. The on-call pulls up the dashboard and the story makes no sense at first: chart reads are timing out, and opening a patient's chart doesn't call the clearinghouse, doesn't call anything slow, it just reads from a cache and the database. Yet here it is, returning 503s while providers stare at spinners with patients in the room.
Rewind ninety seconds. The eligibility partner — the clearinghouse that answers real-time 270/271 coverage checks at check-in — didn't crash. It got slow: its p99 crept from 40 ms to 900 ms. Nothing alarmed, because nothing was down; the partner was answering, just twenty times slower. Pulsely's check-in handler called it the way it always does, synchronously, with no real timeout. Each check-in request now parked for nearly a second waiting on that call. Off-peak that's a handful of in-flight checks; at Monday-morning clinic open it's hundreds. Each parked request holds a connection from the shared connection pool (a fixed, shared set of reusable database connections the whole server borrows from) that it grabbed before the slow call. The pool — shared by check-in and chart-read alike — drained. Now chart reads, which need a connection to load the timeline, queue behind an empty pool. Charts slow. Clinicians see spinners and do the most natural, most destructive thing in the world: they hit refresh. Every retry is a new request piling onto a system already past saturation, so offered load triples just as capacity collapses.
Here's the part that turns an incident into a war story. The eligibility partner recovers at 08:08 — back to 40 ms. Pulsely does not recover. The retry backlog and the queued work form a self-sustaining loop: the system is now generating enough internal load, from retries and timeouts-of-timeouts, to keep itself saturated with no external cause at all. It stays down for twenty more minutes, long after the trigger is gone, until someone sheds load by hand. That shape — a system that, once pushed past a threshold, stays broken under its own power even after the original cause is removed — is metastable failure, and it is the single most important failure mode in this chapter.
Pull the lessons out of the wreckage:
- Failure is contagious through shared resources. Check-in and chart-read share a connection pool, share the event loop, share the host's CPU. A fault on one edge of the system flooded a node that other edges depended on. Nothing about the chart-read code was wrong.
- Naïve retries are an accelerant, not a remedy. They convert a slow dependency into a load multiplier exactly when the system can least absorb it.
- "Just add servers" or "just restart it" can make it worse. More capacity gives the feedback loop more fuel; a restart drops the backlog but also drops every in-flight order and half-charted encounter. Capacity is not the lever here; isolation and shedding are.
- Every remote call is a partial-failure surface, not a binary. It can be slow, wrong, partial, or duplicated — four distinct bad outcomes — long before it is cleanly "down."
🚫 A framing this book rejects. "We'll make it reliable by writing careful code and adding redundancy." Careful code prevents your bugs; it does nothing about a healthy-but-slow partner, a saturated pool, or a retry storm — those are systemic, emergent, and indifferent to how clean your handler is. Reliability is not a property you write into a function; it is a property you engineer into the topology with valves, fuses, and compartments. A flawless handler behind no timeout is a liability waiting for a slow Monday.
Why is this a backend problem specifically, and not something your years of application code already taught you? Because in-process calls lied to you. A function call either returns or throws, fast, deterministically — there is no "the call is taking 900 ms and is also still consuming a resource the rest of the program needs." The network adds three things with no analog in single-process code: latency tails (a call that is slow rather than failed), partial failure (the call succeeded on the server but the response was lost, so you don't know its fate), and shared-resource coupling (your wait for one dependency starves an unrelated one). Reliability engineering is the body of technique for the world where calls don't return cleanly.
2. The mental model: valves, fuses, and watertight compartments
Picture Pulsely not as a stack of layers but as a graph: nodes are services (API edge, chart-read, patient search, claim submission, alerts) and the database/cache/clearinghouse behind them; edges are the calls between them. Now overlay a second meaning on that graph — it is also a failure-propagation graph. A fault is a fluid; it enters at one node and flows along edges into everything that calls or is called by the afflicted part, pooling wherever resources are shared. Reliability work is, almost literally, plumbing: you install fittings on the edges and bulkheads around the nodes so that when fluid escapes, it is contained to one compartment instead of flooding the hull.
Hold three fittings in your head, because every tool in this chapter is one of them, and each does exactly one job. Conflating them — reaching for the wrong fitting for the leak you have — is the most common conceptual error in this whole subject.
a request crossing an edge:
┌───────────┐ timeout (valve): ┌───────────┐
│ caller │ ── bound how long ──▶ │ downstream│
│(chart-read)│ I'll wait │ (search) │
└────┬──────┘ └───────────┘
│ breaker (fuse): if this edge keeps failing,
│ stop calling entirely for a while
│
╔═════════╧═════════╗ bulkhead (compartment): claim submission's
║ separate pools ║ resources are walled off from chart-read's,
║ per critical path║ so one flooding doesn't sink the other
╚═══════════════════╝
- Bound latency with timeouts (and their composable form, deadlines). A timeout is a valve: it decides how long you are willing to wait before you give up and reclaim your resources. Its job is purely temporal — it has nothing to say about whether to try again.
- Survive transient faults with retries and circuit breakers. A retry is a second attempt at a fault you believe is fleeting; a breaker is a fuse that, after enough failures on an edge, stops calling that edge at all for a cooldown — failing fast to give the dependency room to recover and to stop spending your resources on calls that won't succeed.
- Isolate the blast radius with bulkheads and load shedding. A bulkhead is a watertight compartment: separate resource pools so a flood in one (slow search draining its pool) cannot reach another (claim submission's pool, untouched). Load shedding is throwing cargo overboard: when the whole ship is past its waterline, you reject low-priority requests at the edge to stay afloat for the high-priority ones.
🧭 Mental model. Every tool maps to exactly one job. Timeouts bound time. Retries and breakers survive transient faults. Bulkheads and shedding isolate blast radius. When something goes wrong in production, name which of the three jobs is failing before you reach for a tool — "chart reads are slow because eligibility is slow" is a blast-radius problem (you needed a bulkhead), not a retry problem. Using a retry to solve a blast-radius problem is exactly how §1 happened.
Above all of these sits a different kind of thing — not an actuator but a controller. SLOs (Service Level Objectives) are the control system that decides how much of this machinery you need and whether, today, you are allowed to ship a feature or must stop and stabilize. The SLIs (Service Level Indicators — the actual measurements, e.g. the percentage of chart reads that succeeded) measure reality, the SLO sets the target for that number, and the error budget is the currency that turns "is it reliable enough?" from a vibe into arithmetic. Resilience patterns are the actuators; SLOs are the thermostat reading the room.
And when the compartment metaphor fails entirely — a whole region is lost, the data itself is corrupted, isolation is moot because there is nothing left to isolate — you fall back to disaster recovery: RTO and RPO, the two numbers that define how far back in time and how long in wall-clock you fall when the ship goes down and you must raise a new one.
3. Theory & invariants
A mental model tells you how to picture failure; invariants tell you what must hold no matter how clever your code is. These are the load-bearing rules of resilience.
Failure is not binary — and most of it is grey
🔑 The partial-failure invariant. A remote call has more than two outcomes. It can crash (fail-stop, clean error — the easy case), it can be slow/grey (answering, but far slower than healthy), it can be wrong/Byzantine (a confident bad answer), and it can be partial (succeeded on the server, but the response never reached you — so you cannot tell success from failure). Most production pain is grey: the slow, intermittent, "it's up but it's awful" state that binary health checks score as healthy. Design for grey, not just for down.
This is why a naïve health check — "did the port respond?" — is dangerous: it reports green through the exact failure that hurts you most.
Deadlines compose; timeouts don't
🔑 The deadline invariant. A timeout is a relative duration ("wait 2 seconds"); a deadline is an absolute instant ("respond by 08:00:03.250"). The difference is everything in a multi-hop call. Deadlines compose: each hop subtracts the time already elapsed and passes the remaining budget downstream, so the leaf knows how long the whole chain still has. Timeouts don't compose: if every hop independently waits its full 2 seconds, a four-hop chain can burn 8 seconds while the clinician — who left at 3 — is long gone. A hop whose remaining budget is ≤ 0 must fail fast without making the call at all: there is no point starting work the caller has already abandoned.
This single invariant kills the §1 trap where "caller times out at 2 s and retries, while the original request is still running downstream for 5 s," silently doubling real load. With deadline propagation, the downstream knows the request is dead and stops. If you have used AbortController in the browser to cancel a fetch that no one is waiting for anymore, this is the same instinct pushed across every hop of a distributed call.
Retry only what is safe to repeat
🔑 The retry-safety invariant. You may retry an operation only if it is idempotent or carries an idempotency key (you've already met these), and only if the error is retryable. Retrying a non-idempotent write — a submitted claim, an e-prescription — after a timeout where the write actually succeeded is how you submit a duplicate claim or send a duplicate prescription. And you must classify errors: retry timeouts, connection resets, and 503s; never retry 4xx validation errors (the input is wrong; trying again won't fix it) or non-idempotent 500s of unknown effect (you don't know whether the side effect happened).
Earlier you made the single write safe to repeat. This chapter is what consumes that safety: idempotency is the precondition that makes retrying a write legal at all. Without it, retry is a correctness bug wearing a reliability costume — and in healthcare that bug is a duplicate claim or a double-dosed order, not a rounding error.
Retries multiply — so budget them
Here is the arithmetic that turns retries from medicine into poison. If a request fans out through N layers, and each layer retries up to 3×, then a single user request can become 3^N calls at the leaf. Three layers of "just retry three times with backoff" is a 27× load multiplier the instant things start failing — precisely when the leaf can least take it. Two defenses, both mandatory at scale:
- Retry budgets. Cap retries as a fraction of request volume — say, "retries may not exceed 10% of base traffic" — enforced with a token bucket. When the budget is exhausted, you stop retrying and fail, accepting a few more errors to avoid a self-inflicted flood.
- Retry at one layer only. Ideally only the outermost layer (closest to the user) retries; inner layers fail fast and let the edge decide. This collapses 3^N back toward 3.
🔑 Jitter is not optional. Synchronized clients retrying on the same fixed schedule produce a thundering herd — they all hammer the recovering dependency at the same instant and knock it back down. Full-jitter exponential backoff decorrelates them:
sleep = random(0, base · 2^attempt). The randomization is the whole point; fixed backoff and even "equal-jitter" backoff leave clients partially synchronized, while full jitter spreads them across the whole interval. Always jitter; always cap the maximum backoff; always respect the remaining deadline (don't sleep past the moment the caller gave up).
The circuit breaker is a state machine
A breaker has three states, and the discipline is in the transitions:
failures exceed threshold
┌────────┐ over a min-volume window ┌────────┐
│ CLOSED │ ──────────────────────────▶ │ OPEN │
│ (call │ │ (fail │
│ through│ ◀──────────┐ │ fast, │
└────────┘ probe │ │ no call│
▲ succeeds │ └───┬────┘
│ │ │ cooldown
│ ┌───┴──────┐ │ elapses
└──────────────│ HALF-OPEN│◀─────────────┘
probe fails │ (one │
→ OPEN again │ probe) │
└──────────┘
🔑 The breaker invariant. In the Open state the breaker fails fast without calling downstream at all. This is counterintuitive — you're refusing to even try — but it serves two purposes: it stops spending the caller's finite resources (threads, connections, event-loop time) on calls that are overwhelmingly likely to fail, and it gives the downstream breathing room to recover instead of being pinned under load. After a cooldown it goes Half-Open and allows a small number of probe requests; success closes it, failure re-opens it. Crucially, the trip threshold must be a percentage over a minimum-volume window, not a raw count — "2 errors out of 3 requests" must not trip a breaker that protects an endpoint doing 10,000 rps.
Queues are governed by Little's Law
📎 Borrowed on credit: Little's Law. Here it is the foundation of backpressure. The intuition first: if requests arrive faster than you can finish them, the backlog grows forever — there is no queue size that saves you. Think of a request queue with no debounce or throttle; every extra click just deepens a backlog you will never drain. Now the formula that names it: L = λ · W — the average number of in-flight requests (L) equals the arrival rate (λ) times the average wait (W). The consequence that matters: when λ exceeds your service capacity, L grows without bound and W explodes with it. You cannot buffer your way out of sustained overload; an "unbounded queue to absorb spikes" is a latency bomb that serves requests long after the client gave up. The only stable answers are to bound the queue and shed what won't fit. (Chapter 30 owns the math of saturation and tail latency; this chapter owns what you do about it.)
Error-budget arithmetic
An SLO of 99.9% availability over a 30-day window is not a slogan; it is a quantity you can spend. The error budget is (1 − SLO) × total events. For 99.9% over 30 days that's roughly 43 minutes of full downtime, or 0.1% of all requests, that you are allowed to fail before you've broken your promise. The key derived quantity is burn rate: the fraction of budget consumed per unit time, normalized so that a burn rate of 1 exactly exhausts the budget over the window. You alert on burn rate, not raw error rate — because a 30-second blip and a slow steady bleed need different responses, and only burn rate distinguishes them.
RTO and RPO are independent and cost-driven
🔑 RPO vs RTO. RPO (Recovery Point Objective) is the maximum tolerable data loss, measured in time — "we can lose at most 5 minutes of writes." It maps to your backup cadence and replication lag. RTO (Recovery Time Objective) is the maximum tolerable time to restore service — "we must be back within 1 hour." It maps to failover and restore speed. They are independent axes (you can have near-zero RPO with a multi-hour RTO, or vice versa) and both are driven by cost: RPO≈0 demands synchronous replication that taxes every write; low RTO demands warm standby or active-active that taxes your budget. You set them per data tier, not once for the whole system — a signed encounter is not the same tier as a cached timeline.
4. Under the hood: building the machinery in Node/TS
Theory is clean; the implementation is where the gotchas live. Pulsely's lab is Node/TS, and Node has a specific, sharp-edged relationship with every one of these patterns. Let's wire them by hand.
Timeouts: there is no timeout unless you add one
The first shock for a pivoting dev: most Node clients do not time out by default. A fetch, a pg query, a redis call — left alone, many will wait effectively forever for a hung socket. And the timeouts that do exist are plural and independent. undici (the engine behind fetch) distinguishes three, and a request can hang forever if you set only one of them:
- connect timeout — how long to wait for the TCP connection to open in the first place.
- headers timeout — how long to wait for the server to start replying (the first byte of the response).
- body-idle timeout — how long a stall mid-download is allowed, once bytes are already flowing.
A hang can happen at any of the three stages, so setting just one leaves the other two doors open. The modern, uniform mechanism that lets you enforce a single wall-clock bound over all of them is AbortController / AbortSignal:
// AbortSignal.timeout fires the signal after `ms`; pass it into any abortable client.
async function callWithTimeout<T>(ms: number, fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
const signal = AbortSignal.timeout(ms); // Node 18.17+/20+: self-firing timeout signal
return fn(signal);
}
// Every outbound call takes the signal — fetch, undici, pg (via a query cancel), etc.
const res = await callWithTimeout(800, (signal) =>
fetch('https://eligibility.internal/coverage', { signal }),
);
A timeout that isn't wired into the client does nothing. The most common production bug in this whole chapter is "we set a timeout" where the timeout was a setTimeout racing the call but never cancelling it — the slow call kept running and kept holding its connection.
Deadline propagation: build what gRPC gives you for free
HTTP/REST has no native notion of a request deadline, so you build one. Carry an absolute deadline (epoch ms) on the request context — the AsyncLocalStorage you've already met for request-scoped state — and at every hop compute the remaining budget:
import { AsyncLocalStorage } from 'node:async_hooks';
const ctx = new AsyncLocalStorage<{ deadline: number }>(); // absolute epoch ms
function remainingMs(): number {
const store = ctx.getStore();
if (!store) return Infinity;
return store.deadline - Date.now();
}
// Each hop bounds its call by min(its own policy, what's left of the whole-request budget).
async function callDownstream(localTimeout: number, url: string): Promise<Response> {
const budget = remainingMs();
if (budget <= 0) {
throw new DeadlineExceededError(); // fail fast — don't start work nobody is waiting for
}
const timeout = Math.min(localTimeout, budget);
const res = await fetch(url, {
signal: AbortSignal.timeout(timeout),
headers: { 'X-Request-Deadline': String(ctx.getStore()!.deadline) }, // propagate downstream
});
return res;
}
The receiving service reads X-Request-Deadline, seeds its context with it, and the budget composes across the whole chain. Contrast this with gRPC, where a deadline is a first-class part of every call (grpc-timeout), and Go, where context.Context carries the deadline through every function by convention. In REST you hand-roll it — but the invariant is identical: each hop subtracts elapsed time and passes the remainder.
🏭 The header-based deadline is also your defense against the §1 "caller retries while original still runs" trap. When the caller gives up and retries, the original downstream sees its deadline has passed and aborts itself, rather than completing wasted work that doubles the effective load.
The event-loop coupling trap — and why "bulkhead" means something different in Node
Skippable JVM aside — take only the payoff. Java taught a generation of engineers that a bulkhead is a thread pool: thread-per-request means a slow dependency parks a pooled thread, and libraries partition thread pools so claim-submission's threads can't all be consumed by slow search. The failure mode there is thread-pool exhaustion. The transferable payoff: a bulkhead is any mechanism that gives a dependency its own finite resource so it cannot drain a shared one. In Node that resource is not threads — read on.
Node is different, and you must internalize the difference. Node runs your JavaScript on a single thread (the event loop). There are no per-request threads to partition. A slow I/O call doesn't block the loop — that's the good news — but two things bite you instead:
- A flood of pending async operations (thousands of in-flight promises waiting on a slow dependency) piles up unbounded, consuming memory and, worse, every one of them holding a connection from a shared pool.
- Any synchronous CPU work — a tight loop, synchronous crypto, a giant
JSON.parseon a fat chart payload — blocks the loop entirely, and now every request stalls, not just the slow-dependency one. This is event-loop lag, and it is Node's signature saturation signal.
So in Node, "bulkhead" rarely means threads. It means bounded concurrency and separate pools: a semaphore capping how many concurrent calls a given dependency may have in flight, and dedicated connection pools per critical path so claim submission and chart reads don't share one drain.
// A dependency-scoped concurrency bulkhead: only N calls to `search` in flight at once.
class Semaphore {
private active = 0;
private queue: Array<() => void> = [];
constructor(private max: number, private maxQueue: number) {}
async run<T>(fn: () => Promise<T>): Promise<T> {
if (this.active >= this.max) {
if (this.queue.length >= this.maxQueue) throw new BulkheadFullError(); // shed, don't buffer ∞
await new Promise<void>((resolve) => this.queue.push(resolve));
}
this.active++;
try {
return await fn();
} finally {
this.active--;
this.queue.shift()?.();
}
}
}
// Separate pools per critical path — claim submission's DB access is walled off from chart-read's.
const claimsPool = new Pool({ max: 10 /* dedicated */ });
const chartReadPool = new Pool({ max: 20 /* dedicated */ });
For hard isolation — where you cannot afford even shared CPU or memory — you go further: separate Node processes, worker threads, or separate Kubernetes deployments for chart-read vs claim submission, so a chart-read brownout literally cannot touch the claim-submission process.
Retry mechanics: classify, budget, jitter, respect the deadline
A correct retry wrapper does four things in order, and skipping any one of them is a §1 in miniature:
const retryBudget = new TokenBucket({ ratePerSec: 50, burst: 100 }); // cap retries vs base load
async function withRetry<T>(
op: () => Promise<T>,
opts: { maxAttempts: number; baseMs: number; idempotent: boolean },
): Promise<T> {
let attempt = 0;
for (;;) {
try {
return await op();
} catch (err) {
attempt++;
const retryable = isRetryable(err) && opts.idempotent; // never retry non-idempotent/4xx
if (!retryable || attempt >= opts.maxAttempts) throw err;
if (!retryBudget.tryTake()) throw err; // budget exhausted → stop retrying
const backoff = Math.random() * opts.baseMs * 2 ** attempt; // FULL jitter
if (backoff >= remainingMs()) throw err; // don't sleep past the deadline
await sleep(backoff);
}
}
}
Note isRetryable(err) && opts.idempotent: the retry is gated on both a retryable error and the operation being safe to repeat. Libraries like got and undici have built-in retry, and you'll still wrap them — because the built-ins don't know about your retry budget or your breaker, and integrating those is the point.
Circuit breaker internals
A real breaker counts failures over a rolling window — time-based (failures in the last 10 s) or count-based (failures in the last 100 calls) — and trips on a percentage over a minimum volume. In Node, opossum implements this with event emitters and a half-open probe; in the JVM, Resilience4j uses a bucketed ring-buffer sliding window. The mechanics differ; the invariant is the same: don't trip on noise, and fail fast once tripped.
import CircuitBreaker from 'opossum';
const breaker = new CircuitBreaker(submitClaim, {
timeout: 1000, // a call slower than this counts as a failure
errorThresholdPercentage: 50, // trip when ≥50% of a window fails…
volumeThreshold: 20, // …but only after ≥20 calls (no tripping on 1-of-2)
resetTimeout: 5000, // cooldown before a half-open probe
});
breaker.fallback(() => ({ status: 'degraded' })); // what to return while open
Load shedding mechanics
Shedding happens at the edge, before you commit resources. The signal is system health, not request count: a concurrency or queue-depth limit, or — the Node-native one — event-loop lag measured with perf_hooks.monitorEventLoopDelay(). When the signal crosses a threshold, reject early with 503 (or 429) and a Retry-After, and prioritize by request class — drop a background analytics refresh before you ever drop a live chart read or a claim submission.
import { monitorEventLoopDelay } from 'node:perf_hooks';
const lag = monitorEventLoopDelay({ resolution: 20 });
lag.enable();
function shouldShed(requestClass: 'chart-read' | 'claim'): boolean {
const p99LagMs = lag.percentile(99) / 1e6;
if (requestClass === 'claim') return p99LagMs > 250; // protect money: shed only when severe
return p99LagMs > 80; // shed background reads earlier to save the system
}
SLI instrumentation — define here, wire it next chapter
An SLI is a ratio of good events over valid events. Availability counts non-5xx responses (and excludes client 4xx — a clinician's malformed request is not your outage). Latency SLIs are computed from histogram percentiles, never from averages, because averaging hides the tail that users actually feel (a lesson you've already met, now operationalized).
📎 Borrowed on credit: the instrumentation that measures all this. You define SLIs and SLOs here — the ratios, the windows, the targets — and you wire the raw counters and histograms. But the machinery that collects metrics, stores traces, renders the burn-down, and fires the multi-window burn-rate alert is observability tooling, and that is the next chapter's job. Chapter 34 owns logs, metrics, traces, and burn-rate alerting end to end — including the immutable HIPAA audit log that records every chart view, not just every write. Here, just hold the shape: an SLI is a good/valid ratio from request metrics, and a latency SLI must come from histogram buckets. We name the alert; Ch 34 builds it.
5. In production: one resilience client, and the order that matters
The amateur scatters try/catch and ad-hoc timeouts across two hundred call sites; each is subtly different, none is tested under failure, and the policy lives in nobody's head. The professional routes every outbound dependency call through one wrapper — a resilience client — that composes all the patterns in the correct nesting order. Get the order wrong and the patterns fight each other.
request
│
▼
[ deadline check ] ── remaining ≤ 0? fail fast, never call
│
▼
[ bulkhead / semaphore ] ── too many in flight for this dep? shed
│
▼
[ circuit breaker ] ── open? fail fast with fallback
│
▼
[ retry-with-budget ] ── outermost loop; each attempt is fresh
│ ▲
▼ │ (one attempt)
[ timeout ] ── inner: each attempt gets its OWN timeout
│
▼
the actual call → fallback on final failure
The order is not arbitrary, and two relationships are worth burning in:
- Retry is outside timeout. Each retry attempt must get its own fresh timeout, not share one budget across attempts; otherwise the first slow attempt eats the entire window and there's nothing left to retry into.
- Retry is inside the breaker's accounting. The breaker must see the post-retry outcome — if a call only succeeds after three tries, that's still a degraded dependency, and a breaker that only counts the final success will never trip. The breaker watches the whole retried operation, not each individual attempt.
Policy as data, not code
The thresholds — timeout, max attempts, breaker percentage, bulkhead size, fallback — belong in a per-dependency policy table you can tune without a redeploy, not buried in code:
const policies: Record<string, ResiliencePolicy> = {
clearinghouse: { timeoutMs: 1000, retries: 2, breakerPct: 50, bulkhead: 20, fallback: 'fail-loud' },
patientSearch: { timeoutMs: 300, retries: 1, breakerPct: 50, bulkhead: 40, fallback: 'recent-patients' },
messaging: { timeoutMs: 500, retries: 3, breakerPct: 60, bulkhead: 30, fallback: 'enqueue-later' },
};
Note the defaults are conservative — short timeouts — because the default is what hurts you at 3 a.m., on the dependency someone forgot to tune. A "30 second default timeout" is almost always wrong: it's longer than any clinician will wait and longer than your connection pool can sustain under load. Derive timeouts from observed p99/p99.9 latency plus headroom, not from round numbers, and always keep the timeout below the caller's remaining deadline.
Graceful degradation: decide per feature, in advance
When a dependency is down or shed, what do you serve? The answer is per-feature and must be decided before the incident:
| Feature | Degraded behavior | Acceptable? |
|---|---|---|
| Chart timeline | Serve stale cached timeline + "updated a moment ago" banner | Yes — visible staleness beats a blank chart |
| Patient/provider search | Disable the search box with a banner; fall back to the recent-patients list | Yes |
| Care-gap suggestions | Drop the module entirely | Yes — it's enrichment |
| Care-team messaging | Enqueue for later delivery | Yes — routine messages are async by nature |
| Claim submission | Never silently degrade — fail loud | No — it's money |
| Critical-value alert | Never silently drop — escalate on an alternate path | No — it's patient safety |
🛑 What we deliberately did not explain. How you collect the metrics behind these SLIs, store the traces that localize a slow span, render a burn-down chart, wire the multi-window burn-rate alert, or keep the immutable audit log that records every chart view — that is all Chapter 34, and we have only defined the SLIs and named the alert here. We also did not re-derive idempotency (its own chapter owns the mechanism; we only consume it), nor re-derive saturation and tail-latency math (Chapter 30 owns those; we apply them). The boundary is deliberate: this chapter decides what to defend and which objective to hold; the neighbors own the math going in and the instruments coming out.
Idempotency keys, recapped
Every degradable write path that you intend to retry must carry a client-generated idempotency key. The server dedupes on it via a unique constraint or a key store, so a retried claim submission — the same key arriving twice because the client's first response was lost — results in one claim and one charge, not a duplicate that a payer will reject or an auditor will flag. Without this, none of the retry machinery above is safe on writes; with it, the §4 wrapper's idempotent: true becomes true in fact, not just in the type.
SLO operations
Pick 2–4 user-centric SLIs — not CPU%, which is a cause, not a symptom the clinician feels. For Pulsely: chart-read availability and p99 latency (the clinician-in-the-room path), and claim-submission success rate (the money path). A clinical system also earns a safety SLI — e.g. critical-value alert delivery within N seconds — because a missed alert is not a latency regression, it is a patient-harm event. Set a rolling window (28 or 30 days). Then the part that gives SLOs teeth: an error-budget policy. When the budget is exhausted, the team freezes feature work and spends on reliability until the budget refills, signed off by both engineering and product. That policy is what converts a number into a decision, and it is exactly what the ADR below encodes.
Disaster recovery in practice
Classify data by RPO tier: signed encounters, clinical orders, and submitted claims demand RPO≈0 (synchronous replication or point-in-time recovery — you cannot lose a signed note or a claim), while the cached chart timeline is lossy and rebuildable (no backup needed — you regenerate it from the source-of-truth tables). Then the rule that saves careers: a backup is worthless until a restore has been rehearsed. Schedule game-day restores, restore to a fresh instance, and measure the actual RTO against your target — most teams discover their real RTO is multiples of what they assumed, or that the backup was silently incomplete. The runbook must contain concrete steps ("restore snapshot X to instance Y, repoint the connection string in secret Z, verify with query Q"), not the aspiration "restore the DB."
Chaos engineering as practice
Chaos is not random destruction; it is a hypothesis-driven experiment. State a hypothesis ("if patient search dies, the breaker opens, the chart timeline degrades to the cached recent view, and claim-submission p99 is unaffected"), run it in staging first and then in a blast-radius-limited slice of prod, with an abort switch, inject one fault (latency, errors, or a kill) on one dependency, and verify the resilience you built actually fires. The point is validation, not chaos for its own sake — you are proving the compartments hold before a real storm tests them. In a PHI system, keep chaos experiments off real patient data paths where a fault could corrupt or leak a chart; inject at the dependency boundary, never into the clinical record itself.
🏭 The Pulsely increment. By the end of this chapter Pulsely has: every outbound call (DB, patient search, clearinghouse/eligibility, lab, messaging) behind the one resilience client with deadline-propagated timeouts, jittered retries under a token-bucket budget, an
opossumbreaker per dependency, and dedicated pools isolating claim submission / chart reads / search; load shedding at the edge keyed on event-loop lag and prioritized by request class (background reads before live chart reads, claim submission last); graceful-degradation fallbacks (stale timeline, recent-patients search) with claim submission explicitly fail-loud and critical alerts explicitly non-droppable; defined SLOs (chart-read availability + p99, claim-submission success, alert-delivery safety) with an error-budget policy; and a tested restore runbook with per-tier RTO/RPO targets. Two ADRs capture the decisions (below).
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
No timeout, or the library default.
Signature: requests hang for minutes; the connection pool exhausts; an unrelated endpoint starts failing (the §1 cascade).
Fix: an explicit, short, deadline-bounded timeout on every call, wired into the client via AbortSignal — and set connect and headers and body-idle timeouts, not just one.
Retries without idempotency.
Signature: duplicate claims and duplicate e-prescriptions after a transient timeout where the write actually succeeded.
Fix: idempotency keys on every retried write; gate retries on idempotent && retryable. Retrying a bare non-idempotent write is a correctness bug.
Retry storms / metastable failure. Signature: the system stays down after the dependency recovers; load spikes 3–9× during the incident with no external cause. Fix: full jitter, a retry budget capping retries as a % of traffic, retry only at the edge, and a breaker to stop calling a failing dependency entirely. Remove the feedback loop's fuel.
Caller timeout shorter than downstream processing. Signature: the caller times out and retries while the original request is still running downstream, doubling the real load on an already-slow dependency. Fix: deadline propagation so the downstream aborts when the budget is gone; don't let independent timeouts at each hop run past the request's actual deadline.
Breaker on raw counts, or no minimum volume. Signature: the breaker trips on 1 error during low traffic, or never trips because the window is too long. Fix: a percentage threshold over a minimum-volume sliding window; tune the half-open probe count.
Bulkhead omitted; one shared pool. Signature: slow eligibility drains the connection pool that chart reads share, and clinical paths die for a billing reason. Fix: dedicated pools or semaphores per critical path; isolate the clinical and money paths from everything else.
Unbounded queue "to absorb spikes." Signature: latency climbs without bound, the process OOMs, and requests are served long after the client gave up. Fix: bounded queues plus load shedding (Little's Law); reject fast with 429/503 rather than buffering to infinity.
Averaged-latency SLI. Signature: dashboards are green while clinicians complain; the average looks fine because the tail is drowned out. Fix: percentile SLIs computed from histogram buckets; track p99/p99.9, never the mean.
Alerting on raw error rate, not burn rate. Signature: you get paged for a 30-second blip, and you miss a slow steady bleed that quietly drains the whole budget. Fix: multi-window, multi-burn-rate alerting tied to the error budget (defined here, wired next chapter).
Backups never restore-tested. Signature: during a real outage you discover the backups are corrupt, incomplete, or your RTO is simply "unknown." Fix: scheduled game-day restores that measure actual RTO/RPO against the stated targets.
Fallback that silently hides failure. Signature: a stale chart served as if it were live; a claim "succeeds" without reaching the clearinghouse; a critical alert quietly swallowed. Fix: degrade loudly — surface the degraded state in the UI and metrics — and never silently degrade money or patient-safety paths.
7. Tradeoffs
Every pattern in this chapter is a dial, not an absolute. Senior judgment is naming the dial and saying why you set it where you did.
Retries: reliability vs amplification. Retries hide transient faults beautifully — and multiply load catastrophically when the fault isn't transient. Reverse toward fewer or no retries when the operation is expensive or non-idempotent, or when the dependency is already overloaded (let the breaker dominate; another attempt just deepens the hole).
Aggressive vs lenient timeouts. Short timeouts protect the caller and reclaim resources fast, but they cut off slow-but-valid responses, producing false failures against a dependency that is merely loaded, not broken. Tune from the latency distribution (p99 + headroom), never from gut feel or round numbers.
Circuit breaker vs always-try. A breaker prevents resource waste and grants recovery room — but it produces correlated fast failures during the open window and can flap if mistuned. In the rare case where a fast failure is worse than a slow success (an idempotent read with an excellent cache fallback, say), you might let it always try. Rare, but name it.
Bulkhead isolation vs utilization. Partitioned pools waste idle capacity — claim submission's pool sits unused while chart reads are slammed — but they contain the blast radius absolutely. Reverse toward shared pools only for non-critical, fungible workloads where a flood is survivable.
Tighter SLO vs cost and velocity. Every additional nine multiplies infrastructure and on-call cost and slows shipping (more change control, more caution). The right SLO is the lowest one users won't notice, not the highest you can brag about.
🚫 A framing this book rejects. "Five nines for everything." It is uneconomic, it stalls feature work under a permanent change-freeze, and — the part people miss — it's usually unmeasurable: 99.999% is 5 minutes a year, which you cannot even distinguish from noise without enormous traffic. Pick the objective the user actually feels, and spend your reliability budget where the pain is, not uniformly.
RPO≈0 vs latency and cost. Synchronous cross-region replication gives near-zero data loss and crushes write latency (every write waits for a remote ack). Choose async replication with a small RPO for most data, and reserve synchronous for the records you cannot lose — signed encounters, orders, claims. The companion dial is RTO: multi-region active-active gives a near-zero RTO at high cost; a warm standby gives a minutes-scale RTO far cheaper.
Chaos in prod vs safety. Real signal requires prod — staging never reproduces prod's scale, data, and traffic mix. But the blast radius is real patients and real PHI. Reverse to staging-only when you lack the abort switches and observability to bound the damage; earn prod chaos by building those first.
8. Security & scale notes
Reliability and security are the same coin viewed from two sides: both are about behavior under adversarial, abnormal conditions, and the mechanisms overlap more than beginners expect.
Load shedding is your DoS valve. The exact mechanism that protects you from an organic traffic spike is your first line against abusive traffic. Shed by request class and enforce per-tenant fairness — per-clinic concurrency caps — so one noisy or misconfigured clinic's integration cannot starve every other tenant. This overlaps rate limiting but differs in trigger: a rate limiter reacts to request counts against a quota; a load shedder reacts to system health (event-loop lag, queue depth) regardless of who's sending the traffic. You want both: the quota for fairness, the shedder for survival.
Retry amplification is an attacker's lever. An attacker — or merely a buggy device integration — who can reliably trigger errors can weaponize your own retry logic to multiply load against you, turning your resilience machinery into a self-DoS. Retry budgets and breakers are the cap that denies them the multiplier.
Breakers and fallbacks can leak — and here that leak is a reportable breach. Error responses and degraded states can disclose your dependency topology and timing to an attacker probing for structure. Worse, a stale fallback is a correctness and authz hazard: if a cache key isn't scoped to both the patient and the requesting clinician, a degraded "serve the cached version" path can serve one patient's chart to the wrong clinician. That is not a cosmetic bug — under HIPAA it is a reportable breach. Verify that authorization still holds on every fallback path: minimum-necessary access, tenant isolation per clinic, and role scope (patient vs provider vs biller) must all survive degradation. Degradation must never bypass the trust boundary, and it must never widen access beyond what the audit log will later have to justify.
DR is a security surface. Backups contain the crown jewels — encrypt them at rest, restrict restore access tightly (a restore is a full PHI exfiltration vector), and authenticate/encrypt the replication channel. One subtle trap: a restore can resurrect PHI you purged for a HIPAA-mandated deletion, a patient amendment, or a records-retention expiry — test that your erasure guarantees survive a restore, or your deletion promise is a lie the moment you recover from backup. And remember the audit log: a restore rolls back the immutable "who viewed what" record too, so the audit store needs its own append-only, tamper-evident durability, separate from the operational database.
Now the scale behavior, which is where the tail comes back to bite.
Goodput collapses past saturation — unless you shed. Without load shedding, a system pushed past its capacity doesn't just plateau; goodput falls as offered load rises, because the system spends its capacity on work that will time out before it completes. With shedding, goodput plateaus — you serve what you can and cleanly reject the rest:
goodput
│ ┌──── with shedding (plateaus) ────────
│ /
│ / ╲
│ / ╲ without shedding: collapses
│ / ╲ (capacity spent on doomed work)
│ / ╲___________
└──┴───────────────────────────▶ offered load
saturation point
🔑 Tail-latency amplification. A service that fans out to 100 dependencies and needs all of them sees the max of 100 p99 latencies — and the max of 100 p99 draws behaves closer to p99.99 than p99. Here is the intuition, because the leap is not obvious: p99 means 1 call in 100 is slow. If you make 100 calls and must wait for the slowest, the odds that at least one of them landed on that 1-in-100 slow case are now roughly even — so the call you actually wait on behaves like a much rarer, much slower event (near p99.99), not the typical p99. It is exactly
Promise.allover 100 requests: the whole batch is only as fast as its single slowest member, so the rare slow tails you'd normally never notice now dominate every page load. The consequence: each individual dependency's p99 must be far tighter than your aggregate SLO, or the fan-out blows the budget on its own. (You've already met this math; here it dictates that per-dependency timeouts must be aggressive precisely because of the fan-out.) Hedged requests — send a duplicate to a second replica after a short delay and take the first to answer — are a mitigation worth knowing, though not required for Pulsely.
Health-check honesty. Distinguish liveness ("is the process alive?") from readiness ("can it serve traffic right now?"). A node failing readiness should remove itself from the load balancer before it brownouts, shedding gracefully. But keep liveness shallow — a deep health check that calls downstream dependencies is a cascade waiting to happen: one slow dependency marks the entire fleet unhealthy at once, and the load balancer has nowhere to route. The health check that calls everything is how you turn one slow clearinghouse into a total outage.
9. Interview lens & exercises
Interview questions
Reliability questions separate engineers who recite patterns from those who reason about failure propagation. The tell is always whether they get the order and the interactions right.
"A downstream service slows down and your whole system goes down — walk me through why, and how you'd prevent it."
- Junior answer: "Add retries, or add more servers." (Both deepen the hole — retries amplify load, capacity feeds the loop.)
- Senior answer: names metastable failure and the shared-resource coupling that let a fault on one edge flood an unrelated node; prescribes timeouts + deadline propagation + bulkheads + breakers + load shedding, and crucially explains the order — bulkhead to contain, breaker to fail fast, shed at the edge — and why retries must be budgeted and jittered or they become the accelerant.
"How do you set a timeout value?"
- Junior: "30 seconds," or some round number.
- Senior: "From the observed p99/p99.9 of that dependency plus headroom, bounded by the caller's remaining deadline, and propagated downstream so a hop with no budget left fails fast. A round number is almost always wrong — it's longer than the user waits and longer than the pool sustains."
"What SLO would you set for the chart timeline, and what does it let you decide?"
- Junior: "99.999%, and monitor CPU."
- Senior: a user-centric SLI (availability + p99 latency), a deliberately modest target (the lowest clinicians won't notice), an error budget that drives a ship-vs-freeze policy, and burn-rate alerts rather than raw error-rate alerts. CPU is a cause, not a symptom the clinician feels.
"Retry safely — what has to be true?"
- Junior: "Retry three times with backoff."
- Senior: the operation must be idempotent or carry an idempotency key; only retryable errors are retried (timeouts/503, never 4xx or unknown-effect 500s); backoff is full-jittered; retries are budgeted as a fraction of traffic; and ideally only the edge retries to avoid 3^N amplification.
"RTO vs RPO — define them and give Pulsely numbers per data type."
- Junior: conflates the two, or answers "we back up nightly."
- Senior: RPO = tolerable data loss (maps to replication/backup cadence); RTO = tolerable time to restore (maps to failover/restore speed); they're independent. Signed encounters / orders / claims → RPO≈0 (sync/PITR), cached chart timeline → lossy and rebuildable; both validated by rehearsed restores that measure actual numbers.
Exercises & the Pulsely increment
Do these in code where you can, on paper where you can't. Fluency, not perfection.
-
Build the shared resilience client. Wrap Pulsely's
clearinghouseandpatientSearchcalls in one wrapper composing — in the right order — deadline check → bulkhead/semaphore → breaker → retry-with-budget → per-attempt timeout → fallback. Give claim submission and chart reads separatepgpools. Add a stale-timeline fallback. Then prove the nesting order: write a test showing each retry attempt gets its own timeout, and that the breaker counts the post-retry outcome. -
Break it on purpose (chaos drill). Inject 800 ms latency + 50% errors into the
patientSearchdependency in staging. Assert four things: the breaker opens, the chart timeline degrades to the cached recent view with a banner, claim-submission p99 is unaffected (proving the bulkhead held), and the system recovers within the cooldown with no retry backlog. If claim-submission p99 moved, your bulkhead is a lie — find the shared resource. -
SLO + error budget. Define chart-read-availability and claim-submission-success SLIs from the request metrics you have. Compute the 30-day error budget in minutes and in failed-request count. Specify a multi-window, multi-burn-rate alert (fast burn → page, slow burn → ticket) — you'll wire it next chapter, but design it now. Write the one-paragraph error-budget policy. Capture both ADRs (below).
-
Restore game-day. Take a backup, simulate data loss, restore to a fresh instance, and measure the actual RTO and RPO against your stated targets. Confirm that PHI purged for a HIPAA deletion did not come back, and that the audit log survived. Write the gap — and the concrete fix — into the DR runbook. (Almost everyone's first measured RTO is several times their assumed one. That discovery is the entire point.)
The ADRs
ADR-033a — Pulsely SLOs & error-budget policy. Decision: Adopt user-centric SLIs (chart-read availability ≥ 99.9% and p99 ≤ 300 ms; claim-submission success ≥ 99.95%; critical-value alert delivered within 60 s ≥ 99.95%) over a rolling 30-day window. Alert on multi-window burn rate (fast: 2% of budget in 1 h → page; slow: 10% in 3 days → ticket). Policy: when a budget is exhausted, feature work on that surface freezes and the team spends on reliability until it refills, with joint eng+product sign-off. Rejected: uniform "five nines" (uneconomic, stalls velocity, unmeasurable at Pulsely's traffic); alerting on raw error rate (pages on blips, misses slow burns).
ADR-033b — Timeout/retry/circuit-breaker policy. Decision: All outbound calls go through one resilience client; per-dependency policy lives in a tunable config table (timeout from observed p99 + headroom, never a round number); retries are full-jittered, gated on idempotency, and capped by a token-bucket budget (≤10% of base traffic), with retry at the edge only; an opossum breaker per dependency trips on a percentage over a minimum-volume window; claim submission / chart reads / patient search get dedicated pools; deadlines propagate via X-Request-Deadline. Constraint: a write is retried only if it carries an idempotency key. Rejected: scattered per-call try/catch (untestable, policy lives nowhere); shared connection pool (couples clinical, money, and non-critical paths).
Key takeaways
- Reliability is bounding the blast radius and recovering predictably, not preventing failure — which is impossible. Every remote call is a partial-failure surface: slow, wrong, partial, or duplicated, not a binary up/down.
- Metastable failure is the enemy: a slow dependency plus naïve retries plus shared resources creates a feedback loop that keeps the system down after the cause is gone. Adding capacity or restarting can deepen it.
- Three jobs, three tools, never conflated: bound latency with timeouts/deadlines, survive transient faults with retries + breakers, isolate blast radius with bulkheads + load shedding.
- Deadlines compose; timeouts don't — each hop subtracts elapsed time and passes the remainder, failing fast when the budget is gone. Retry only idempotent/keyed operations on retryable errors, with full jitter and a budget, because retries multiply load as 3^N.
- The circuit breaker fails fast when open to stop spending resources and let the dependency recover; trip on a percentage over minimum volume, never a raw count. Bound queues and shed load — Little's Law says unbounded queues are latency bombs.
- Route every outbound call through one resilience client with the patterns nested in the right order: deadline → bulkhead → breaker → retry → per-attempt timeout → fallback. Keep policy as tunable data; default to conservative timeouts.
- SLOs are the controller above the actuators: user-centric SLIs, modest targets, an error budget that drives ship-vs-freeze, and burn-rate (not error-rate) alerting. RTO and RPO are independent, cost-driven DR targets — and a backup is worthless until a restore is rehearsed and measured. In a PHI system, a degraded fallback that leaks a chart or a restore that resurrects deleted PHI is a reportable breach, not a bug.
← Previous: Ch 32 — Authentication & Authorization · Up: Part VI overview · Master TOC · Next: Ch 34 — Observability & Debugging →