Chapter 34 — Observability & Debugging in Production
Part VI · Security, Reliability & Observability | Prerequisites: Ch 33 | Builds: Pulsely instrumented with logs/metrics/traces; an injected clinical incident debugged
Earlier you built a system that survives failure — timeouts, breakers, bulkheads, SLOs, error budgets. This chapter teaches you to see the system while it's failing. They're the same coin: you cannot defend what you cannot observe, and an error budget you can't measure is a wish. Reliability engineering is the immune system; observability is the nervous system. This is the last chapter of Part VI, and it closes a loop the book has been drawing from the start. The promise was this: in production you follow a single request as a trace — one ID stamped on the request at the edge and carried to every service it touches. That trail is what lets you ask which service ate the latency? This is where that promise is paid in full.
By the end you'll be able to instrument Pulsely so that a single production request leaves a coherent, queryable trail; build the three or four dashboards that actually matter at 2 a.m.; alert on the pain your users feel rather than the symptoms your machines emit; and walk a disciplined path from "signing a note is slow" to "this one downstream span is the cause" in minutes, without redeploying and without guessing. This is a concept-dense chapter with real instrumentation code, because the gap between "I read about tracing" and "I can find a needle in a million spans at 2 a.m." is exactly the gap this chapter exists to close. And because Pulsely handles protected health information, this chapter carries one obligation an ordinary app never faces — a second, non-optional trail that records who looked at whose chart — which we develop as the sharpest lesson in the whole chapter.
1. The problem: the night the dashboard lied
It's 02:00. Your phone buzzes. The alert says nothing useful — just HIGH CPU on api-7. You open the on-call chat before you open Grafana, because that's where the truth is: three clinics are messaging "anyone else getting spinning wheels on Pulsely when you sign a note?" You pull up the API dashboard. It is green. Request rate normal. Error rate flat at 0.1%. No 5xxs. No stack traces in the logs. The p50 latency line is a calm, flat 180 ms.
And yet signing an encounter is taking four seconds. Providers are stuck mid-visit; notes aren't saving, claims aren't going out the door, and in one clinic a critical-value alert is sitting undelivered — while every chart you own tells you everything is fine.
Here is what's actually happening, though you don't know it yet. The eligibility service — which the sign-encounter flow calls to verify the patient's coverage before a claim can be queued — slowed from 40 ms to 900 ms an hour ago. It didn't fail; it got slow. Your API's p50 looks fine because most requests don't hit the slow path; the damage is in the p99, which your dashboard isn't showing prominently. And even if it were, the dashboard would only tell you signing is slow, not where — because the slowness lives on the far side of a service boundary, inside a call your API dashboard cannot see into.
Sit with the three distinct failures of this un-observed system, because naming them is half the cure:
- You can't tell if it's broken. Your signals are aggregated and averaged into a flat green line. The pain is real and your instruments don't register it.
- You can't tell where it's broken. "Signing is slow" — slow in your code? In the chart database? In
eligibility? In the network between them? The boundary swallows the answer. - You can't tell why. Even if you knew it was
eligibility, you don't know which requests, which clinic, which code path, what input triggered it.
Logs alone give you the third poorly and the first not at all — you'd be grepping blind across forty stateless instances with no thread tying one request's lines together. Metrics alone give you the first cheaply and the second never. Neither, alone, localizes. You need all three, correlated, or you're debugging by séance.
Now watch the anti-pattern that makes it worse. The instinct — every junior's instinct, and plenty of seniors' — is "I'll add some logging and redeploy." Stop. That instinct is wrong three times over. First, you've now changed the system you're debugging: the bug may not reproduce, or the new code shifts timing and hides it. Second, a deploy is a cycle of minutes to hours, and the incident is now — a patient is in the room. Third, even after the deploy you're still grepping across N instances with no request thread to follow. Adding print statements to find a production bug is like turning on a flashlight by rebuilding the flashlight.
🧭 A useful distinction: monitoring vs observability. Monitoring answers questions you knew to ask in advance — predefined dashboards and alerts for the failures you anticipated. Observability is the property of a system that lets you ask new questions about unanticipated failures, after the fact, without shipping new code. Monitoring is the smoke detector you installed last year; observability is being able to walk into the smoke and find which wire shorted. The 02:00 incidents — the ones that page you — live almost entirely in the gap between the two, because by definition you didn't anticipate them. If you had, you'd have prevented them.
One more framing before we build anything, because it governs every decision in this chapter. Telemetry is not free. Every log line is CPU to serialize and network egress to ship and dollars to ingest and store. Every metric label multiplies cardinality. Every trace is bytes. A naïve "log everything, trace everything, label everything" approach will hand you a bill larger than your compute and a metrics backend that OOMs under the very load you most need to observe. So the goal of this chapter is not maximum data. It's maximum debuggability per dollar — knowing exactly which signal to spend on which question. (With one hard exception we'll come to: the HIPAA audit trail, where "cheaper" is not on the table.)
2. The mental model: one request, one story, three resolutions
Hold two pictures at once — the book has been training this habit all along.
One request is one story
Every user action — sign this encounter — produces a single causal narrative. It crosses process boundaries: the API receives it, writes to the chart database, calls eligibility to verify the patient's coverage, publishes an event to a queue, and a consumer picks that up half a second later in a different process to submit the claim and fan out any critical-value alert. That's one story told across five characters. Observability is the discipline of keeping that story stitched together and queryable — so that, given any symptom, you can pull up the one request that exhibited it and read its narrative end to end, including the async chapter that happened in another process a moment later.
The thread that stitches the story is a single ID — a trace ID (or correlation ID) — minted once at the edge and carried, unbroken, to every downstream call and every log line the request touches. Lose the thread on one hop and the story tears there; everything past the tear is an orphaned fragment you can't connect to the provider — or the patient — who suffered.
Three pillars are three resolutions of the same events
The "three pillars of observability" — metrics, traces, logs — are usually taught as three separate systems. That framing is a trap. They are better understood as three zoom levels on the same stream of events, and you move between them:
METRICS TRACES LOGS
(zoomed out) (one request) (zoomed in)
┌──────────┐ ┌──────────────────┐ ┌────────────────────┐
│ p99 ▁▂█▇▃ │ click │ API ▓▓▓░░░░░░░░░ │ open │ {"msg":"eligibility│
│ over time │ exemplar │ └DB ░▓░ │ span │ call failed", │
│ │ ───────▶ │ └elig ░░▓▓▓▓▓▓ │ ───▶ │ "trace_id":"abc", │
└──────────┘ │ └queue ░░░░░▓ │ │ "status":503,...} │
"is it broken?" └──────────────────┘ └────────────────────┘
cheap, lossy "WHERE is it broken?" "EXACTLY what happened?"
mid-cost expensive at volume
- Metrics are aggregate counts over time. Cheap, lossy, and the right tool for "is it broken, and how badly?" They have no per-request detail — a counter at 4,000 errors tells you nothing about which requests.
- Traces follow one request across services. Mid-cost. The right tool for "where is the time going?" — they localize pain to a hop.
- Logs are full-fidelity events at a single point in code. Expensive at volume, and the right tool for "exactly what happened here?" — the values, the error, the input.
The workflow is the zoom: a metric anomaly (p99 spiked) leads you to an exemplar trace (here's one slow request) leads you to the span logs (here's the exact error on the slow span). You don't pick one pillar; you traverse them.
🧭 Mental model. Metrics tell you that it hurts. Traces tell you where it hurts. Logs tell you why it hurts. The skill is moving between these resolutions fast — and the thing that makes the movement possible is the shared
trace_idthreaded through all three. Instrumentation that produces metrics, traces, and logs but doesn't correlate them gives you three disconnected haystacks instead of one searchable narrative.
Wide events: debugging as query, not grep
There's a fourth idea that quietly unifies the picture: prefer a few high-dimensional structured events per request over many thin log lines. Instead of emitting "got request", then "validated coverage", then "wrote chart", then "sent response" — four lines, each thin — emit one wide event at the end of the request carrying every dimension you might want to slice by: trace_id, route, status, duration_ms, role, clinic_id, chart_ms, eligibility_ms, cache_hit, region, build_sha. Now debugging is a query — "group by route, where status=500, p99 of duration, broken down by clinic" — not a grep. This is the single biggest leap in debuggability you can make, and we'll return to it. Hold the slogan: debugging should be a query, not a grep. (Note what is not in that list: no patient_id, no MRN, no name. High-cardinality identifiers stay off metric labels for cost reasons — and PHI stays out of operational telemetry entirely for legal ones. More on both below.)
Symptoms live at the edge; causes live in the depths
The next piece of the model governs alerting. The pain a user feels is at the edge — the SLI, the user-visible success rate and latency. The cause is somewhere in the depths — a saturated connection pool, a slow downstream, a GC pause, a poison message. You alert where the user feels pain, and you debug toward the cause. Alert on the edge symptom; let the depth signals be diagnostic, not paging. This is the seed of this chapter's ADR, and we'll make it sharp in §5.
The cardinality budget
Next, the constraint that shapes every design decision: cardinality. A metric's cost scales multiplicatively with the number of distinct label values — a counter labeled by route (20 values) × status (5 values) × region (3) is 300 time series, fine; add patient_id (millions) and you've created millions of time series and detonated your metrics backend. Traces and logs, by contrast, scale additively with volume — a million traces is a million traces, expensive but linear. So the core design skill is knowing which pillar absorbs which dimension: high-cardinality identifiers (patient_id, encounter_id, raw path) belong on traces and logs, never on metric labels. Get this one rule wrong and you will, eventually, take down your own observability stack.
The second stream: telemetry you are forbidden to lose
Everything above is operational telemetry: its job is to help you debug, so you sample it, drop it under load, and age it out in days. A clinical system carries a second, entirely separate stream with the opposite rules — the HIPAA audit log, which records every access to protected health information (PHI), including every read. Hold it apart in your mind from the three pillars from the very start:
- Operational telemetry answers "is the system healthy, and why is it slow?" — sampled, lossy, short-lived.
- The audit log answers "who touched this patient's data, and when?" — complete, append-only, retained for years.
They are not two views of one system; they are two systems with opposite failure modes. §8 develops the audit log in full — for now, just don't confuse "monitoring" with "compliance." One you tune for cost; the other you are not allowed to.
3. Theory & invariants
A model tells you how to picture observability. Invariants tell you what must stay true or the whole edifice quietly lies to you. These are the load-bearing rules.
🔑 The correlation-ID invariant. A single ID is minted at the system edge (or accepted from a trusted caller), attached to the request context, and propagated to every downstream call and every log line for that request — including async hops through queues and background jobs. Lose it on one hop and the story breaks exactly there, and everything past the break is unattributable. This is the single most important invariant in the chapter: an observability stack with no correlation ID is three disconnected piles of data. The ID is what turns piles into a narrative.
Now the standard for carrying it across HTTP — but let's separate the idea from the wire format, because they usually arrive in one confusing breath. A trace is the whole request; a span is one step inside it — one chart-DB query, one call to eligibility. The spans nest the way a call stack does, or the way a React component tree does: the incoming HTTP handler is the root span, and every DB query or downstream call it makes is a child span underneath it. That nesting is the story's structure. To carry the story between services, the trace_id and the current span_id ride along in an HTTP header. That header is called traceparent, and the standard that defines it is W3C Trace Context (traceparent, plus an optional tracestate); it also carries a sampling flag. And — critically — the consumer span in the other process links back to the publish span, so the async chapter of the story rejoins the same tree instead of floating off as an orphan.
🔑 The structured-logging invariant. Every log line is a machine-parseable object (JSON), not a sentence. It carries stable, required fields —
timestamp(RFC 3339, UTC),level,service,env,trace_id,span_id,message— plus event-specific fields. Themessageis a low-cardinality constant ("eligibility call failed"), and all variable data goes in fields ({"dependency":"eligibility","status":503,"latency_ms":912}), never interpolated into the message string. The instant you writelog.info(\eligibility failed for ${mrn} in ${ms}ms`)you've created a unique string per request — ungroupable, unqueryable, and (because thatmrn` is PHI) a reportable leak sitting in your log store. Constant message, variable fields: that's the whole discipline.
Why the constant-message rule matters so much: it's what makes logs aggregatable. "eligibility call failed" as a constant lets you count occurrences, group by dependency, and chart the rate. Interpolated, it's a million unique strings you can only grep.
🔑 The percentile invariant. You cannot average percentiles, and you cannot re-aggregate a p99 from per-host p99s. Here's the intuition first, before the rule. A p99 isn't a quantity like a sum or a count — it's a rank: the latency that 99% of requests came in under. You can no more average two hosts' p99s than you can average two classrooms' median scores to get the combined median; the rank has to be recomputed over the pooled data. So each host keeps a histogram: a row of counters, one per latency range (0–5 ms, 5–10 ms, 10–25 ms, …), each counting how many requests landed in that range. Because those are just counts, they add up cleanly: to get a fleet-wide p99 you sum host A's and host B's bucket counts into one merged histogram, then walk up the merged counts until you pass 99% of the total — that value is the true fleet p99. This is why every latency SLI lives in a histogram, never in a pre-computed average or a naked "p99" gauge per pod.
Earlier you saw the percentile math made rigorous — why tail latency is what users feel, why averages hide it, why a service fanning out to many dependencies sees the max of their tails. Here we operationalize it: latency goes into histograms with carefully chosen bucket boundaries, and p99 is derived from the merged buckets at query time. Choose the buckets badly — too coarse around your actual latencies — and your p99 is a useless quantized lie no matter how correct the math.
Now the two vocabularies that organize what you measure.
RED — for request-driven services (the Pulsely API, the chart service, eligibility): Rate (requests per second), Errors (failed requests per second, or error ratio), Duration (latency distribution — as histograms, per the invariant above). RED is the user's-eye view: it tells you the user is hurting.
USE — for resources (the chart database, the queue, the host, the connection pool): Utilization (how busy — % of capacity in use), Saturation (how much queued/overflowing — the wait), Errors (resource-level failures). USE is the bottleneck's-eye view: it tells you which resource is the constraint.
🔑 You need both RED and USE. RED tells you the user is in pain; USE tells you which resource is causing it. They answer different questions and neither substitutes for the other. RED on the API says "sign-encounter p99 is 4s"; USE on the chart database connection pool says "saturation is 100%, requests are queuing for a connection" — together they say "signing is slow because the pool is exhausted." One without the other leaves you guessing.
The SLI/SLO/error-budget vocabulary you've already met plugs straight in here. An SLI is a measured ratio of good events / valid events (e.g., encounters signed under 500 ms with a 2xx ÷ all valid sign requests). An SLO is a target on that ratio over a window (99.9% over 28 days). The error budget is 1 − SLO (0.1% of requests may fail). The burn rate is how fast you're consuming that budget relative to the window — burn rate 1 means you'll exactly exhaust the budget at the window's end; burn rate 14 means you'll exhaust a month's budget in roughly two days. Reliability engineering defined these and set Pulsely's targets. This chapter owns the instrumentation that measures the SLI and the alerting that fires on the burn rate. That division of labor is deliberate; respect it.
Finally, sampling — the lever that makes traces affordable at scale.
🔑 The sampling invariant: whatever you sample, keep all the errors. Head sampling decides at request start whether to record the trace (cheap — flip a coin on the first span — but you may discard the rare slow or failing request precisely because you decided before you knew it was interesting). Tail sampling decides after the trace completes, so you can keep every error and every slow trace plus a small baseline of healthy ones (better signal, but it needs a buffer that holds the whole trace until it finishes). Whichever you choose, the non-negotiable rule is: keep 100% of error traces and slow traces. The traces you most need at 2 a.m. are, by definition, the rare bad ones; a sampler that throws them away has optimized you into blindness. (And note the sharp exception coming in §8: the compliance audit log is never sampled at all — sampling is a cost tool for operational telemetry, and it has no business anywhere near a record of who read a chart.)
📎 Borrowed on credit: cloud-managed observability services. You can run this entire stack yourself — Prometheus for metrics, Tempo or Jaeger for traces, Loki or ELK for logs, Grafana to view them — and we'll instrument against exactly that open shape. But every cloud provider also sells a managed version (CloudWatch, X-Ray, Managed Prometheus/Grafana, and the third-party SaaS like Datadog and Honeycomb). The instrumentation you write here is identical either way — that's the entire point of OpenTelemetry, which we'll meet in §4. The build-vs-buy decision, the provider-specific wiring, the IAM and ingestion economics — and, in a clinical system, whether the vendor will sign a BAA and keep PHI-adjacent telemetry inside HIPAA-eligible services — those belong to Chapter 37 (Cloud & AWS). Here we instrument vendor-neutrally and route to whatever backend you've got. Absorb the assertion now: you instrument once, against OpenTelemetry, and decide where the data lands later.
4. Under the hood: how the trail actually gets made
Let's kill the magic. How does a trace_id minted in your HTTP middleware end up, automatically, on a database span three function calls deep and on a log line you wrote with no trace_id argument? The answer is a small number of mechanisms, and once you see them you'll also see exactly how they break.
Context propagation in Node: AsyncLocalStorage
The linchpin of Node observability is AsyncLocalStorage. The problem it solves will be familiar from the frontend: it's the same job React Context does for a component tree — make a value available deep in the tree without threading it through every function's props. Here the "tree" is the async call chain of one request, and the value is the request context (the trace_id, the current span). In a single-threaded, callback-and-promise runtime you need per-request state that follows the logical request through awaits and callbacks — without threading a context argument through every function signature in your codebase. AsyncLocalStorage gives you exactly that: a store that's transparently carried across async boundaries by the runtime, the way a React Query request context is carried without you passing it by hand.
import { AsyncLocalStorage } from 'node:async_hooks';
type RequestContext = { traceId: string; spanId: string };
export const requestContext = new AsyncLocalStorage<RequestContext>();
// At the edge: mint or accept the trace ID, then run the rest of the request inside the store.
export function contextMiddleware(req, res, next) {
const traceId = req.headers['traceparent']
? parseTraceparent(req.headers['traceparent']).traceId // accept from trusted upstream
: crypto.randomUUID().replace(/-/g, ''); // or mint at the edge
const spanId = crypto.randomBytes(8).toString('hex');
res.setHeader('x-request-id', traceId); // hand it back so support can map a complaint to a trace
requestContext.run({ traceId, spanId }, () => next()); // everything downstream sees this store
}
// Anywhere, arbitrarily deep, with no plumbing:
export function currentTraceId(): string | undefined {
return requestContext.getStore()?.traceId;
}
The magic is that requestContext.getStore() returns the right request's context even when ten requests are interleaved on the event loop, because the runtime associates the store with the async execution chain, not with wall-clock time. This is also why OpenTelemetry's active context can make your database span automatically a child of your HTTP span: OTel stashes the active span in an AsyncLocalStorage, and when the auto-instrumented pg driver starts a query span, it reads the active span as its parent. No plumbing.
🛑 What we deliberately did not explain. The internals of
async_hooks— theinit/before/after/destroylifecycle that lets the runtime track async resource chains — is real and occasionally load-bearing for diagnosing context loss, but it's a rabbit hole we won't descend here. We're usingAsyncLocalStorageas the tool, not reimplementing it. (And note: it has a small but nonzero overhead, which is one reason the runtime team spent years optimizing it.)
And here is the pitfall the mechanism creates, which you will hit:
🏭 If you break out of the async chain — a bare
setTimeout, an un-awaited promise that detaches, an EventEmitter callback registered outside the request, a manual thread/worker hop — the store is gone on the other side.getStore()returnsundefined, your log line has notrace_id, and the trace tears exactly there. This is the number-one cause of "my trace ends halfway through the request." The fix is to capture the context explicitly and re-enter it on the far side (or, for queues, serialize thetraceparentinto the message payload and restore it in the consumer — §6 has the recipe).
Structured logging: pino, child loggers, and why console.log is malpractice
In Node, use pino — it serializes JSON asynchronously with very low overhead. (winston is the common alternative; more featureful, heavier.) The trick that makes correlation automatic is the child logger: bind the request context once, and every line from that child carries it.
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
// Redact at serialization time — allowlist your way out, never log raw bodies on PHI paths.
redact: {
paths: ['req.headers.authorization', '*.password', '*.ssn', '*.dob', '*.mrn', '*.diagnosis', 'req.body'],
censor: '[redacted]',
},
formatters: { level: (label) => ({ level: label }) }, // emit level as a string, not a number
timestamp: pino.stdTimeFunctions.isoTime, // RFC 3339 UTC
});
// Bind the trace context once; every child line carries it automatically.
export function requestLogger() {
const ctx = requestContext.getStore();
return logger.child({ trace_id: ctx?.traceId, span_id: ctx?.spanId, service: 'pulsely-api', env: process.env.ENV });
}
// Usage — constant message, variable fields (the structured-logging invariant in practice):
requestLogger().error({ dependency: 'eligibility', status: 503, latency_ms: 912 }, 'downstream call failed');
Why is console.log unacceptable in production? Three reasons, each disqualifying. It's synchronous — it blocks the event loop on the write, so under load your logging starves your request handling (the worst possible coupling). It's unstructured — a string you can only grep, never query or aggregate. And it's unredacted — whatever you pass goes straight to stdout, tokens and PHI included, which in a clinical system is a reportable breach rather than merely untidy. pino's async serialization, schema-bound fields, and serialization-time redaction fix all three.
OpenTelemetry: the vendor-neutral pipeline
OpenTelemetry (OTel) is the standard that lets you instrument once and route anywhere. Its architecture, concretely:
┌─────────────────────────────────────────┐
│ Pulsely service (Node or JVM) │
│ ┌─────────┐ ┌──────────────────────┐ │
│ │ OTel SDK│ + │ auto-instrumentation │ │ patches http/express/nest,
│ └────┬────┘ │ (pg, ioredis, queue) │ │ pg/prisma, redis, queue clients
└───────┼────────┴──────────────────────┘ │ → spans appear automatically
│ OTLP (gRPC/HTTP)
▼
┌────────── ─────────────────────────────────────────┐
│ OTel Collector │
│ receiver → processor (batch, tail-sample, redact) │ ← the vendor decoupling point
│ → exporter │
└───┬───────────────┬───────────────┬─────────────────┘
▼ ▼ ▼
Tempo/Jaeger Prometheus/Mimir Loki/ELK
(traces) (metrics) (logs)
│
▼
Grafana ◀── one pane, exemplars link metric → trace → log
The SDK runs in-process. Auto-instrumentation monkey-patches the popular libraries — the HTTP server and client, Express/Nest middleware, the pg/Prisma driver, ioredis, queue clients — so that spans for "HTTP request handled," "SQL query executed," "Redis GET," "message published" appear without you writing span code. You add manual spans only for your own meaningful operations. The SDK exports over OTLP (the OpenTelemetry wire protocol) to the Collector, a separate process that receives, processes (batches, tail-samples, scrubs PHI), and exports to your chosen backends.
🏭 The Collector is the single most valuable box in this diagram, and it's the one beginners skip. It decouples your application from your vendor: your app speaks OTLP and knows nothing about Tempo vs Jaeger vs Datadog. Switch backends? Reconfigure the Collector; redeploy nothing. Need tail-sampling, PHI redaction, or to fan out the same telemetry to two backends during a migration? The Collector does it centrally, so a thousand services don't each carry the logic — and centralizing the redaction is exactly what lets you enforce "no PHI in telemetry" in one place instead of praying every service got it right. It's also where you put the bounded queue and circuit breaker that stop a dead telemetry backend from backing up and taking down Pulsely (§8). Run the Collector. Always.
How a span gets linked to its parent: OTel keeps an active context in AsyncLocalStorage. When the auto-instrumented pg driver starts a query, it reads the currently-active span (your HTTP span) and sets it as the parent. Span start/end records the duration; attributes carry dimensions (db.statement, http.route); events mark moments; status records ok/error. The tree assembles itself from the active-context chain — which is also why losing the async context (the pitfall above) detaches a span into a new, orphaned trace.
Trace–log correlation is the final stitch: because your pino child logger injects trace_id/span_id into every record (from the same AsyncLocalStorage OTel uses), a trace in Grafana links to its logs and a log line links back to its trace. Exemplars go one step further — they pin a representative trace_id onto a specific histogram bucket, so when you see a spike in the p99 latency chart you can click the spike and jump straight to an example slow trace. That click is the metric→trace→log zoom from §2, made literal.
The JVM contrast, where it teaches
🏭 (Skip this if you never touch Java — the payoff is just that the same problem reappears in a different runtime.) The JVM does the same job through different mechanics, and the contrast sharpens the concepts. Micrometer is the metrics facade (counter / timer / distribution-summary) — the Java analog of an OTel metrics SDK. The OTel Java agent does bytecode auto-instrumentation. "Bytecode rewriting" just means Java can edit the compiled program as it loads, so it adds tracing to third-party libraries without you changing a line — a
-javaagentflag switches it on, and it's strictly more powerful than Node's monkey-patching of module exports, which only catches libraries that go through the patchedrequire. The Java analog ofAsyncLocalStorageis MDC (Mapped Diagnostic Context): a thread-local map — read that as "a value attached to one worker thread," the Java equivalent of the per-request store — that you stuff thetrace_idinto so the logging framework picks it up. And the failure mode is the same shape: because MDC is thread-local, the moment work hops to another thread — a thread pool, a reactive/CompletableFutureboundary — the MDC is gone, exactly asAsyncLocalStorageis lost across a detached promise. Different runtime, identical lesson: context propagation breaks at concurrency boundaries, and that's where your traces tear.
Metrics transport: pull vs push, and the histogram bucket trap
Two ways metrics reach the backend. Pull (Prometheus): each service exposes a /metrics endpoint, and Prometheus scrapes it on an interval. You get target liveness for free — if the scrape fails, the target is down — and simple ops. Push (OTLP / StatsD): the service pushes metrics out. Better for short-lived jobs and serverless that may not live long enough to be scraped. (We'll weigh this in §7.)
And the trap, which follows directly from the percentile invariant: histogram bucket boundaries are chosen at instrumentation time, and if they're wrong your p99 is garbage. If your latencies cluster around 200 ms but your buckets are [1ms, 10ms, 100ms, 1s, 10s], then everything from 100 ms to 1 s falls in one bucket and your "p99" can only report "somewhere between 100 ms and 1 s" — useless. Pick buckets that bracket your actual latency distribution with resolution where it matters ([5, 10, 25, 50, 100, 200, 400, 800, 1600, 3200] ms for a 200 ms-ish endpoint). Bad buckets make the most important number you own a lie.
5. In production: dashboards that matter, alerts that don't lie, and a debugging method
Instrumentation is the raw material. Production observability is what you do with it: a log policy, a correlation-ID flow, a small set of dashboards, symptom-based alerting, sane sampling, and — above all — a repeatable debugging method so you don't reinvent the wheel under stress.
A log-level policy with teeth
Levels are a contract, not vibes. Make them mean something operational:
- ERROR — an actionable failure that a human should see (paged or ticketed). If nobody needs to act, it's not an error.
- WARN — degraded but handled: a retry fired, a circuit breaker opened, a fallback served. Worth watching, not worth waking anyone.
- INFO — business milestones: encounter signed, lab order placed, claim submitted. The audit-ish narrative of what the system did. (Careful: this is the operational narrative, not the HIPAA audit trail — it may name the action but never the PHI. The compliance log in §8 is a separate, harder-guaranteed stream.)
- DEBUG — off in production by default; enabled per-request or per-service via dynamic config, never by redeploy. The whole point of observability is to not need a deploy to see more.
That last clause is the tell of a mature system: you can turn up verbosity for one clinic, or one route, or one trace, at runtime, with a flag — because redeploying to debug is the anti-pattern §1 condemned.
Correlation-ID flow, end to end
Mint the ID at the edge — the load balancer, gateway, or first service — accept-and-trust it on internal hops (never trust a client-supplied trace header from the public internet without scrutiny; it's an injection vector, §8), and surface it in the API response as x-request-id. That last move is worth its weight in gold during an incident: a front-desk user pastes "signing this visit failed, request ID a1b2c3" into support, and support maps that single string to the exact trace in one hop — no guessing which of ten thousand failed requests was theirs, and no need to search by patient (which would itself be a PHI access).
The dashboards that matter (and the one that doesn't)
You need exactly three kinds of dashboard, and a discipline about it:
- One RED dashboard per service — rate, errors, and duration (with p50/p90/p99 from histograms) for the API, the chart service,
eligibility, the alerts consumer. This is the user's-eye view of each service. - One USE dashboard per critical resource — the chart database connection-pool saturation, queue lag, event-loop lag, CPU/memory. This is the bottleneck's-eye view.
- One top-level "Is Pulsely healthy?" SLO dashboard — the two-to-four user-centric SLIs (encounter-sign success rate, chart-load latency) and their error-budget burn-down. The single screen you open first.
🏭 The anti-pattern is the 60-panel vanity dashboard. Someone, lovingly, builds a wall of every metric the system emits. It is beautiful in a demo and useless at 2 a.m., because under stress nobody can scan sixty panels to find the one that's red. A dashboard that shows everything shows nothing. Build few, opinionated dashboards that answer specific questions, and delete the rest. The measure of a dashboard is whether a tired on-call engineer can read the system's health off it in ten seconds.
And note event-loop lag specifically: in Node it's often the metric that explains "everything is slow but there are no errors and CPU looks fine." A synchronous CPU spin or a flood of pending promises starves the loop; perf_hooks.monitorEventLoopDelay() measures it, and it belongs on every Node USE dashboard. (The JVM analog is GC pause time — same role, different runtime.)
SLO burn-rate alerting: alert on symptoms, not causes
This is the heart of the chapter and the subject of its ADR. The principle, stated flatly: page on the symptom the user feels (SLO burn), route the cause-signals (CPU, restarts, queue depth) to dashboards.
Why? Because cause-based alerts are a fatigue machine. High CPU fires when a nightly claim-batch job runs harmlessly. Pod restarted fires on a routine deploy. Queue depth > 1000 fires during a planned RPM backfill. Each is a 2 a.m. page for a non-problem, and after the tenth false page the on-call engineer mutes the channel — and that's the night the real one fires into the void. Meanwhile, "high CPU" with providers perfectly happy is not an incident, and "providers failing to sign encounters" with CPU at 20% absolutely is. The cause signals are for diagnosis, not notification.
The mechanism is multi-window, multi-burn-rate alerting (the Google SRE pattern). You define an SLI (encounter-sign success rate), then alert on how fast you're burning the error budget, across two time windows:
- Fast burn — e.g., consuming 2% of the 30-day budget in 1 hour (a burn rate ~14×). This is an acute outage. Page someone now.
- Slow burn — e.g., consuming 10% of the budget over 3 days (a burn rate ~1×). This is a chronic, low-grade leak that will exhaust the budget if ignored, but doesn't warrant a 2 a.m. page. File a ticket.
The two windows together solve the false-dichotomy of single-threshold alerting: a single error-rate threshold either pages on every 30-second blip (too sensitive) or sleeps through a slow steady bleed (too dull). Burn rate, across a fast and a slow window, catches both the acute spike and the chronic drip — and pages only for the former.
error-budget burn-down over the 30-day window
budget │██████████████████░░░░░░░░ ← slow burn: budget draining, FILE A TICKET
100% → │ ╲
│ ╲___ fast-burn threshold (2% in 1h) ─┐
│ ╲▼ ← acute drop: PAGE NOW ◀─┘
0 └──────────────────────────────────── time → window end
📎 The SLO targets — what counts as a good event, what the window is, what burn thresholds page — were defined in Chapter 33's reliability ADR and error-budget policy, including the tighter targets a clinical path like critical-value alerting warrants. This chapter owns the instrumentation that measures the SLI from request metrics and the alerting rules that fire on the burn rate. You're wiring the controller Chapter 33 designed.
Alert hygiene
Three rules that separate a sane on-call rotation from a burned-out one. Every alert links to a runbook — a page with no "what do I do" is cruelty. Every page must be actionable and urgent — if it can wait until morning, it's a ticket, not a page; if there's nothing to do, it's not an alert at all. And track the alert→action ratio: an alert that fires fifty times and leads to action zero times is noise that's actively hiding the real signal — kill it.
Sampling and cost in practice
100% trace sampling in dev (cheap, and you want everything). In prod, tail-sampling at the Collector that keeps all errors, all slow traces, and a small baseline of successful ones — the sampling invariant from §3, operationalized. Production config is also where the §3 cardinality budget becomes a hard guardrail: normalize route templates (/encounters/:id, not /encounters/1042) server-side before any high-cardinality path can leak into a metric label. (And to say it once more because it's the trap that bites clinical teams: the audit log is out of scope for all of this — you never sample a record of who read a chart.)
The production-debugging methodology
Here is the disciplined loop. Memorize it; run it the same way every time, so that under stress you're executing a procedure rather than improvising.
1. CONFIRM the symptom → is the SLI actually breached? (not just one angry message)
2. SCOPE the blast radius → which service / endpoint / region / clinic / cohort? (dashboards)
3. FIND an exemplar → pull ONE trace for a bad request (via exemplar or trace search)
4. WALK the trace → which span is slow or errored? (localize to a hop)
5. DROP into span logs → read the exact error / values on that span
6. FORM one hypothesis → "eligibility is slow because its DB pool is saturated"
7. TEST it cheaply → rollback? flag-off? isolate? (don't redeploy to guess)
8. MITIGATE, then root-cause → stop the bleeding FIRST; full RCA can wait
🏭 Step 8 is the one engineers get backwards under pressure. Stopping the bleeding is not the same as finding the cause, and it comes first. If rolling back the last deploy makes signing healthy again, do that now and investigate why afterward, with providers no longer stuck mid-visit. The instinct to "fully understand before acting" is admirable in a code review and dangerous in an incident — especially one where a critical-value alert is sitting undelivered. Mitigate, then diagnose.
🚫 A framing this book rejects. "We have logs, so we're observable." No. Logs alone answer "exactly what happened here" but cannot tell you if the system is broken (no aggregate view) or where across a service boundary (no per-request thread). Observability is the correlated triad — metrics to detect, traces to localize, logs to explain, stitched by one
trace_id— plus the ability to ask new questions of it. A pile ofconsole.logoutput shipped to a grep box is not observability; it's the thing observability replaced.
6. Common pitfalls
Each as signature → fix: the symptom you'll observe, then the principle that resolves it.
Trace ID dropped across an async hop.
Signature: a trace ends mid-request; the queue-publish span is the last thing you see and the consumer's work is an orphaned trace (or invisible). Caused by a detached promise, a setTimeout, a manual worker hop, or — the classic — a queue boundary, where the message leaves your process entirely.
Fix: propagate context explicitly across the break. For queues, inject the traceparent into the message payload/headers on publish and restore it (requestContext.run(...)) in the consumer before doing work. Then verify the link shows up as a connected trace.
// publish: carry the context into the message
const ctx = requestContext.getStore();
await queue.publish('encounter.signed', { encounterId, _traceparent: buildTraceparent(ctx) });
// consume: restore it before doing anything, so logs/spans rejoin the story
queue.on('encounter.signed', (msg) => {
const ctx = parseTraceparent(msg._traceparent);
requestContext.run(ctx, () => submitClaimAndFanOutAlerts(msg));
});
High-cardinality metric label.
Signature: Prometheus memory climbs without bound, scrapes slow, the metrics backend OOMs, or your SaaS bill triples overnight. The cause is a label with unbounded values — patient_id, encounter_id, or a raw path containing IDs.
Fix: move the high-cardinality dimension to trace/log attributes (linear cost). On metrics, use the normalized route template /encounters/:id. Metrics are for low-cardinality aggregates; identifiers belong on traces.
Averaged percentiles. Signature: dashboards look fine but real users complain; a latency regression slips through; "avg of p99 across pods" is a number that means nothing. Fix: never average or re-aggregate percentiles. Merge histogram buckets across instances, then compute p99 from the merged histogram. Alert on the histogram-derived percentile.
Logging in a hot loop / per-row. Signature: log volume and ingestion cost explode; under load the event loop blocks on synchronous writes and the whole service slows. Fix: don't log per-row or per-iteration. Sample the logs, aggregate, or replace the log with a counter metric (you wanted the count, not a thousand lines).
Alerting on causes. Signature: the on-call channel is a firehose of "high CPU," "pod restarted," "queue depth high" — most harmless — and the engineer has muted it, so the real page lands in a muted channel. Fix: page on the SLO symptom (burn rate); demote cause-signals to dashboards used for diagnosis. (This is the chapter's ADR.)
PHI or secrets in an unbounded log field. Signature: a token, a diagnosis, a full request body, an MRN, or a date of birth turns up grep-able in your log store — a reportable HIPAA breach and a storage blowup. Fix: schema-bound fields with an allowlist (log only known-safe fields), redaction at the logger before serialization, and never log raw request bodies on chart, eligibility, or claim endpoints. Treat "PHI reached the log store" with the same gravity as "PHI reached the wrong patient's chart."
Sampling that drops the errors you needed. Signature: you have a confirmed failure but the trace for it is gone — head sampling discarded it before knowing it was interesting. Fix: tail-sample, and always keep error and slow traces. The rare bad trace is the entire reason you're sampling at all; never let the sampler throw it away.
Clock skew / wrong timezone. Signature: spans appear out of order in the waterfall, child finishing "before" parent starts; cross-service correlation is impossible. Fix: UTC everywhere, RFC 3339 timestamps, NTP on every host; rely on monotonic timing for durations within a span rather than subtracting wall-clock timestamps across machines.
Wrong denominator in the SLI. Signature: the availability dashboard reads 99.99% while providers are visibly suffering — because health-check pings and bot traffic are diluting the "total" the ratio divides by. Fix: define "valid events" precisely and exclude synthetic traffic (health checks, uptime probes, your own load tests) from both numerator and denominator. An SLI measured against the wrong population is a confident lie.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
Sampling rate ↔ fidelity ↔ cost. 100% traces give perfect debuggability and an unaffordable bill at scale. Head sampling is cheap but blind to the rare slow request (it decided before it knew). Tail sampling gives the best signal — keep all errors and slow traces — but needs the Collector to buffer whole traces and spend compute deciding. You move toward keeping more when error rates are tiny (the bad traces are precious and cheap to keep) and toward sampling harder when volume explodes. The default that almost always wins: tail-sample, keep 100% of errors and slow traces, keep a few percent of the happy path. (This whole axis is operational; the compliance audit log sits outside it entirely — see §8.)
Logs-heavy ↔ metrics-heavy culture. Logs can answer any question after the fact but cost the most and don't aggregate. Metrics are cheap and alert-able but only answer questions you decided to ask in advance (you can't slice by a dimension you didn't make a label, and you mustn't make high-cardinality labels). Wide structured events blur the line — query-able like metrics, detailed like logs — at higher ingest cost. Pick based on your query patterns and budget; most teams land on metrics for alerting and SLOs, wide events/traces for debugging, thin logs sparingly.
Pull (Prometheus) ↔ push (OTLP). Pull gives you target liveness for free (a failed scrape is the down signal) and simple operations, but struggles with short-lived processes that die between scrapes. Push handles ephemeral and serverless workloads naturally but loses the free liveness signal. You move toward push for Pulsely's short-lived background workers — the nightly claim batch, the RPM ingest jobs, Lambda-style eligibility checks — while pull stays fine for long-running services.
Build ↔ buy. Self-hosting Prometheus/Tempo/Loki gives cost control and data ownership at the price of real operational burden — you now own cardinality limits, retention, scaling, and the 3 a.m. "the metrics backend is down" page. SaaS (Datadog, Honeycomb) is turnkey and excellent but bills per host and per GB in ways that surprise finance the month you scale — and, for a clinical system, the vendor must sign a BAA and keep any PHI-adjacent data inside HIPAA-eligible services, which narrows the field. The decision hinges on team size, data volume, and compliance posture, not feature checklists: a five-person team should almost always buy; a hundred-engineer org with petabytes should probably self-host the high-volume tiers. (The cloud-managed middle ground — and its economics and BAA story — is Chapter 37.)
Vendor-neutral OTel ↔ vendor SDK. OTel avoids lock-in and unifies the three pillars under one instrumentation, but it's younger and heavier to configure correctly. A vendor's own agent is turnkey but sticky — re-instrumenting to leave is real work. The Collector is the hedge: instrument with OTel, point the Collector at whatever backend you've chosen, and you keep the freedom to switch by reconfiguring one process.
More alerts ↔ fewer alerts. Symptom-only alerting risks slower detection of a genuinely novel cause that hasn't yet breached the SLI. Cause alerting catches more, sooner, at the cost of fatigue that eventually makes all alerts ignored. Multi-window burn-rate alerting is the negotiated middle: page on symptoms, but with a fast and slow window so you catch both the acute spike and the slow leak without drowning. The rejected extreme — "alert on everything so we never miss anything" — reliably produces an on-call that misses everything.
8. Security & scale notes
Observability is data, and data is a liability as much as an asset. In a clinical system the liability has teeth: the same trail that saves you at 2 a.m. can leak a patient's chart, and it costs the most exactly when you can least afford it.
Telemetry is a PHI and secrets exfiltration channel. Logs and traces routinely leak tokens, MRNs, diagnoses, medication lists, and full request bodies — because someone logged a whole object "just in case." The discipline: redaction policy, field allowlists, and treating telemetry as data subject to the same retention and access controls as the chart database itself. Your Grafana, Jaeger, and log store need authentication, RBAC, and encrypted transport to the Collector — they hold the same PHI your chart tables do, in a place people forget to lock. A subtler version of this bug is the one from earlier chapters wearing new clothes: a caching or context-loss bug that stitches one patient's chart data into a different clinician's trace view is not a rendering glitch — it's an impermissible disclosure of PHI and a reportable breach, the observability-stack equivalent of serving the wrong chart. (The security chapters own the encryption and PHI-handling primitives; here the point is that they apply to your telemetry, not just your tables.)
🔑 The HIPAA audit log is telemetry you are never allowed to sample — and it logs reads, not just writes. Everything above is operational telemetry: you sample it, drop it under load, and age it out in days, because its job is to help you debug. A clinical system carries a second, separate stream with the opposite rules — the HIPAA audit log — and it inverts every cost tradeoff in this chapter. Six properties, none optional:
- Every chart VIEW is an event, not just every edit. In an ordinary app, reads are free and invisible; you log writes. In a clinical system a clinician opening a patient's chart is itself a recordable disclosure of PHI. Miss it and you cannot answer "did anyone snoop on this record?" — the exact question the audit log exists to answer.
- Append-only and tamper-evident. The audit log is write-once: no update, no delete, not even by an admin. Tamper-evidence — a hash chain where each entry embeds the hash of the prior one, or a WORM (write-once-read-many) store — makes any edit or deletion detectable. An audit log an insider can quietly edit is not an audit log.
- Never sampled, never dropped. "Keep all errors and a few percent of the happy path" is correct for traces and forbidden here. A dropped audit event is a compliance gap, so this stream gets a durable, backpressured, at-least-once path — the outbox pattern, not fire-and-forget — surviving a backend outage instead of being shed under load like operational telemetry.
- Retention in years, not weeks. Operational traces age out in days; HIPAA audit records are retained for six years (longer in some states). Storage tier, access controls, and cost all follow from that number.
- "Who viewed this record" is a first-class query. The schema is designed so that, given a patient, you can list every actor who touched their PHI — when, from where, and under what justification.
- Break-glass is logged, loudly. When a clinician overrides a permission boundary in an emergency (accessing a chart outside their normal panel), the system forces a typed justification and writes a high-visibility audit entry. Break-glass without an audit record is just a broken access control.
Keep the two streams sharply apart: operational telemetry answers "is the system healthy and why is it slow"; the audit log answers "who touched this patient's data." Opposite sampling rules, opposite retention, opposite failure modes (drop-telemetry-to-stay-up vs never-drop-an-access) — and they must not share a pipeline. You don't want a Grafana query reaching into PHI, and you don't want a sampler anywhere near the compliance log.
Telemetry is an attack surface. An open, unauthenticated /metrics endpoint or a public trace UI hands an attacker a map of your internals: every route name, the full dependency graph, version and build info, internal hostnames — and in a health system, the shape of the clinical data model. That's reconnaissance gift-wrapped. Lock down telemetry endpoints; never expose them externally.
Log and trace injection. Attacker-controlled input placed into log fields can forge log lines (inject a fake "level":"error" and a newline to spoof an entry) or break a downstream JSON parser. Structured logging — where fields are set as data, not concatenated into a string — neutralizes this by construction. It's another reason the structured-logging invariant isn't just hygiene; it's a security control.
Cardinality as denial-of-wallet (and self-DoS). A malicious or merely buggy client hammering unique paths (/encounters/<random> over and over) can explode your metric label cardinality and either OOM your metrics backend or run your SaaS bill into the stratosphere. This is a real attack — denial of wallet — and a real footgun. Bound your labels, normalize routes server-side, and rate-limit so one client can't mint infinite label values.
Observability cost scales with load — exactly when you can least afford it. Traffic doubles, telemetry doubles, during the incident. Synchronous logging blocks the event loop under the very load you're trying to observe; exporters back-pressure; the Collector becomes a bottleneck. The mitigations are non-negotiable at scale: async, batched export; sampling that degrades gracefully under pressure; bounded queues that drop operational telemetry before they drop user requests; and a circuit breaker on the export path so a dead telemetry backend can never take Pulsely down with it. Re-read that last clause: your monitoring stack failing must not fail your product — or delay a critical-value alert. Apply the resilience patterns you've already met to your own telemetry pipeline — the Collector's export edge is just another downstream dependency, and it gets a timeout, a breaker, and a bounded buffer like any other. (The one buffer you shed last, and back with durable storage, is the audit log's: dropping a debug span is fine; dropping a record of who read a chart is not.)
Sampling vs incident completeness. Under a flood, head sampling may discard the very traces of the failure you're now trying to postmortem — it sampled them away before they got interesting. Tail sampling plus "keep all errors and slow traces" is what protects the postmortem from your own cost controls. The traces you'll wish you had are the ones a naïve sampler is most likely to drop.
🔑 Your observability is a dependency, and it obeys every reliability rule you've already met. It has its own utilization and saturation, its own failure modes, its own blast radius. Treat it as a first-class production system — secured like the chart database, bounded like any queue, isolated so it fails open (drops telemetry, keeps serving providers) rather than closed (blocks the event loop, takes the product with it). The nervous system must not be able to stop the heart — and the one stream that fails closed by design, refusing to silently drop, is the compliance audit log.
9. Interview lens & exercises
Interview questions
Backend interviews probe whether you operate systems or merely describe them. Observability questions separate the levels sharply, because the senior answer is a procedure and the junior answer is a vibe.
"Signing an encounter is slow but the dashboard is green and there are no errors. Walk me through your next 10 minutes."
- Junior answer: "I'd add some logging and redeploy" or "I'd grep the logs." Changes the system, costs a deploy, searches blind.
- Senior answer: runs the methodology out loud — confirm the symptom against the SLI (don't trust one message), scope the blast radius on the RED dashboard (which route, which region, which clinic), pull an exemplar trace for a slow request, walk it to the slow span (probably a downstream call the API dashboard can't see), drop into that span's logs — and explicitly names event-loop lag and downstream attribution as the usual culprits behind "slow with no errors." The procedure is the signal.
"Why can't you just average p99 latency across your servers?"
- Junior: treats p99 like a number you can average.
- Senior: "Percentiles aren't linear — a p99 is a rank, not a sum, and the average of two p99s isn't the fleet p99. You merge the histogram buckets across hosts into one distribution and compute the percentile from that. Which is why latency lives in histograms, not pre-computed averages, and why bucket choice at instrumentation time matters."
"Design alerting for Pulsely encounter-signing — what pages someone, and what doesn't?"
- Junior: alerts on CPU, memory, pod restarts — cause signals.
- Senior: "Page on the SLO burn rate — encounter-sign success rate against the error budget — using multi-window, multi-burn-rate thresholds: fast burn pages, slow burn tickets. Route CPU/restarts/queue-depth to dashboards for diagnosis, not to the pager. Every alert links a runbook, and I'd track the alert→action ratio and delete alerts that never lead to action." Names the symptoms-over-causes principle as reasoning, ties it to the error budget.
"How is a HIPAA audit log different from your normal application logs?"
- Junior: "It's just logs with more detail."
- Senior: "It's a different stream with opposite rules. It records reads — every chart view is a disclosure — not just writes; it's append-only and tamper-evident (hash-chained or WORM); it's never sampled and never dropped, so it rides a durable at-least-once path like an outbox, not fire-and-forget; it's retained for six years; and it's queryable by patient — who touched this record, when, and under what break-glass justification. Operational telemetry you tune for cost; the audit log you're legally required not to."
"What's the difference between monitoring and observability, and where does each fail?"
- Junior: recites "the three pillars are logs, metrics, traces."
- Senior: "Monitoring answers questions you knew to ask — predefined dashboards for anticipated failures. Observability lets you ask new questions about unanticipated failures without shipping code, which depends on high-dimensional, correlated data and therefore on a cardinality/cost tradeoff. Monitoring fails on the novel 2 a.m. incident you didn't predict; observability fails if you let cost or cardinality limits strip the dimensions you'd need to slice by."
"Your trace ends halfway through a request. Why, and how do you fix it?"
- Junior: "the tracing library is buggy."
- Senior: immediately suspects lost async context — a queue hop, an un-awaited promise, a
setTimeout, or (on the JVM) a thread-pool/MDC boundary — and fixes it by propagating context explicitly across the break: injecttraceparentinto the message and restore the store in the consumer. NamesAsyncLocalStorageand its loss conditions.
Exercises & the Pulsely increment
Do these in order; each builds the instrumentation the next one debugs through.
-
Instrument encounter-signing end to end. Wire
pinostructured logging + anAsyncLocalStoragerequest context + OTel auto-instrumentation on the sign-encounter endpoint. Prove the win: fire one request and confirm a singletrace_idappears in the HTTP-server span, the chart-DB (pg) query span, the outboundeligibilityspan, and every log line for that request. If the ID is missing anywhere, you've found a context-loss boundary — fix it before moving on. -
Build the dashboards. A RED dashboard for the API (rate/errors/duration with p50/p90/p99 from histograms) and a USE dashboard for the chart-database connection pool plus queue lag and event-loop lag. Deliberately choose your histogram buckets to bracket Pulsely's real latency distribution, write down why you chose them, then derive p99 correctly from the merged buckets. Confirm your p99 changes meaningfully when you inject latency (proof the buckets have resolution where it counts).
-
Write the burn-rate alert and the ADR. Define the encounter-sign-success-rate SLI from your existing metrics; write a multi-window, multi-burn-rate alert (fast-burn → page, slow-burn → ticket) against the SLO Chapter 33 set; attach a runbook stub to each. Then write ADR-034 — Alerting strategy: alert on user-facing symptoms (SLO burn), not on causes (CPU, restarts, queue depth) — recording explicitly what becomes a page, what becomes a ticket, and what stays a dashboard-only signal, with the reasoning (alert fatigue, the muted-channel failure, "high CPU with happy providers is not an incident").
-
Build the audit-log stream — and prove it's not your telemetry. Add the HIPAA audit trail as a separate stream: on every chart view (not just edit), write an append-only, hash-chained audit entry — actor, patient, action, timestamp, source, and any break-glass justification. Route it through a durable at-least-once path (an outbox), not the OTel pipeline. Then prove the two properties that make it a compliance log: (a) run "list every actor who viewed patient X" and get a complete answer; (b) kill the audit backend under load and show that operational telemetry is shed (spans dropped) while audit events queue durably and replay — never silently lost. Write down, in one paragraph, why sampling and 14-day retention are correct for traces and forbidden here.
-
The injected-incident lab. The chapter ships a fault: a slow
eligibilitydownstream (it returns correct answers, just at 900 ms) and a poison message that wedges the alerts/claims consumer. Don't read the fault first — let it run. Then: detect it via the burn-rate alert; debug it by the methodology — confirm the SLI breach → scope on the dashboard → pull an exemplar slow trace → walk it to the sloweligibilityspan → drop into that span's logs → form one hypothesis → test cheaply; apply a mitigation (degradeeligibility, isolate the consumer) before you fully root-cause; and verify the trace for the wedged consumer actually links back to the request that enqueued the poison message (if it doesn't, you dropped context across the queue hop — fix it, that's the lesson). Note which patient's critical-value alert was delayed and how you'd confirm it was eventually delivered. -
Write the blameless postmortem. One page, for the lab incident: a timeline (with timestamps off your own telemetry), the contributing factors (note that there's never one cause — the slow downstream and the missing isolation and the un-attributed async hop), an explicit "what made this hard to see" section (the green dashboard, the averaged latency, the lost trace context), a "was any PHI or clinical safety impacted" note (the delayed alert), and concrete action items. No names, no blame — the question is always "what about the system let this happen and stay invisible," never "who messed up." A postmortem that blames a person teaches the team to hide incidents; a blameless one teaches them to surface and fix the conditions. That cultural choice is the last and most durable observability tool in the chapter.
Key takeaways
- One request is one story. Observability is keeping that story stitched across process and async boundaries with a single
trace_id, and making it queryable. Lose the ID on one hop and the story tears there. - Three pillars are three resolutions, not three systems. Metrics ("is it broken?", cheap, lossy) → traces ("where?", per-request) → logs ("exactly what?", expensive). You zoom: metric anomaly → exemplar trace → span logs.
- RED for services, USE for resources — you need both: RED says the user hurts, USE says which resource is the bottleneck.
- You cannot average percentiles. A p99 is a rank, not a sum; latency lives in histograms — merge buckets, then compute p99. Bad buckets make your most important number a lie.
- Alert on symptoms (SLO burn rate), not causes (CPU, restarts, queue depth). Multi-window, multi-burn-rate: fast burn pages, slow burn tickets. Cause signals are for diagnosis; every alert links a runbook (ADR-034).
- Context propagation breaks at concurrency boundaries — a detached promise, a queue hop, a thread-pool/MDC edge. That's where traces tear; fix it by propagating context explicitly.
- Cardinality is the budget. High-cardinality identifiers go on traces/logs (linear cost), never on metric labels (multiplicative — and a denial-of-wallet vector).
- The HIPAA audit log is a second stream with opposite rules. It records every chart view, is append-only and tamper-evident, is never sampled or dropped (durable, at-least-once), is retained for years, and answers "who touched this patient's data" — including break-glass. Never confuse compliance with monitoring.
- Debug by method, not by guesswork: confirm → scope → exemplar trace → slow span → span logs → one hypothesis → test cheaply → mitigate before you root-cause. Never redeploy to add print statements.
- Your observability is itself a production dependency — secure it like the chart database, bound it, and make operational telemetry fail open so a dead backend never takes the product down, while the audit stream fails closed and never silently drops. Postmortems are blameless or they teach people to hide.
← Previous: Ch 33 — Reliability Engineering · Up: Part VI overview · Master TOC · Next: Ch 35 — Testing & Quality Strategy →