Watching a hospital ward
A hospital never waits for a patient to say "something feels wrong". The ward has monitors that turn it into numbers, minute by minute: how many patients came in, how many beds are in use, how long people wait. Nurses write notes about what they did. And every patient has a chart that goes with them from ward to ward, so anyone can see where they've been and how long each stop took.
Each of these answers a different question. The monitor says whether something is wrong, and when it started. The chart says where: which ward the patient got stuck in. The notes say why: exactly what happened at that bed.
An alarm on a monitor only catches problems someone thought of in advance. Good records let a doctor work out a problem nobody expected, without having to examine the patient all over again. Being able to do that is called observability.
Monitoring and observability
Monitoring watches for known failure modes: you decide in advance what to measure and when to alert. Observability is a property of the system: how well you can explain its behaviour from the outside, including failures nobody predicted, using only the telemetry it already emits, without shipping new code to find out.
Three signals do most of the work, and each answers a different question:
| Signal | What it is | Answers |
|---|---|---|
| Metrics | Numeric measurements aggregated over time (http.server.requests count, latency, CPU) | Is something wrong, how much, since when? Cheap to store and to alert on |
| Traces | The path of one request through every service, with timings | Where is it wrong: which hop is slow or failing? |
| Logs | Timestamped records of individual events | Why: the exact error, input and state at that moment |
The signals are most useful when they're joined: an alert on a metric leads to an example trace, and the trace id leads to the log lines written while serving that request. Profiles (continuous CPU and memory profiling) are increasingly treated as a fourth signal.
Notes with a case number
Nurses write a note every time they do something: "gave a dose", "sent for an X-ray". With many patients on the ward, a pile of plain notes is a muddle: which patient was that?
So every patient gets a case number, and it goes on every note written about them. In a computer system it's called a trace id. A nurse caring for patient 42 keeps a stamp with "42" on it at her desk, and stamps each note before she writes it, so she never forgets. When she moves on to another patient, she wipes the stamp clean.
The notes are also written on a form with boxes (time, ward, case number, what happened) rather than as a scribbled sentence. That way, finding "every note for case 42" or "every note that says fell" takes seconds.
Structured logs and correlation ids
A structured log is an event with named fields, usually one JSON object per line, rather than free text. Log
backends can then filter and aggregate by field (level=ERROR AND orderId=42) instead of grepping with regexes.
With concurrent requests, log lines interleave. A correlation id (in a traced system, the trace id) on every line ties together everything written for one request, across threads and services.
In Java, SLF4J's MDC (Mapped Diagnostic Context) holds per-thread key-value pairs that the logging backend adds to every line. Because threads are pooled, always remove what you put:
1MDC.put("orderId", order.id());2try {3log.info("payment taken"); // includes orderId in its fields4} finally {5MDC.remove("orderId"); // the next request on this thread must not inherit it6}
With Micrometer Tracing on the classpath, Spring Boot puts traceId and spanId into the MDC for you. Spring Boot
3.4 added built-in structured logging: logging.structured.format.console=ecs (or logstash, gelf) writes JSON
lines that include the MDC. MDC is thread-local, so it doesn't follow work handed to another thread by itself:
executors and reactive code need context propagation (Micrometer's Context Propagation library does this).
Log levels still matter: INFO for business events, WARN for something odd but handled, ERROR for failures someone
should look at. Never log secrets or personal data, and remember logs are the most expensive signal per event.
The ward monitors
Monitors turn the ward into numbers over time, called metrics, and there are three kinds. A tally counts things that only go up, like patients admitted today. A reading shows how much right now and can go up or down, like beds in use. And a wait-time chart sorts every patient into boxes, "seen within 5 minutes", "within 15", "within 30", so the ward can say "nine in ten patients were seen within 15 minutes".
A screen at the nurses' station collects every monitor's numbers every little while and keeps the history.
One rule keeps the screen readable: label numbers by ward, not by patient name. A separate line for every patient who ever visited would fill the screen and slow it to a crawl.
For each ward, three numbers tell you most of what matters: how many patients arrive, how many have complications, and how long they wait. For each machine, like the X-ray: how busy it is, how long the queue is, and whether it breaks down.
Metrics, their types and cardinality
A metric is a named, numeric time series with tags (labels): http.server.requests{uri="/orders",status="200"}.
Micrometer, the metrics facade Spring Boot uses, has these core types:
- Counter: only increases (requests served, orders placed). Query it as a rate.
- Gauge: a current value that goes up and down (queue size, pool connections in use).
- Timer and DistributionSummary: count, total and max of durations or sizes, optionally with a histogram of buckets so the backend can compute percentiles such as p95 and p99 across instances. Averages hide the slow tail; use percentiles.
1@Service2class CheckoutService {3private final Counter placed;4private final Timer payment;56CheckoutService(MeterRegistry registry) {7placed = Counter.builder("orders.placed").tag("channel", "web").register(registry);8payment = Timer.builder("payment.duration").publishPercentileHistogram().register(registry);9}1011void checkout(Order order) {12payment.record(() -> gateway.charge(order));13placed.increment();14}15}
Spring Boot Actuator records http.server.requests for every endpoint, plus JVM, pool and cache metrics. Add
micrometer-registry-prometheus and expose /actuator/prometheus, and Prometheus scrapes (pulls) it at a regular
interval, typically every 15 to 60 seconds.
Cardinality is the number of distinct tag combinations, and every one is its own time series. Tags must come from a small, bounded set: route templates, status codes, regions. A tag holding a user id, order id or raw URL creates a series per value and can overload the metrics backend. Put such values in logs and traces instead.
Two checklists say what to measure. RED, for every service: Rate (requests per second), Errors (failed requests per second), Duration (latency distribution). USE, for every resource (CPU, memory, disk, connection pool): Utilisation, Saturation (queued work), Errors. Google's SRE book calls latency, traffic, errors and saturation the four golden signals.
The chart that travels
A patient comes in at reception, goes to the emergency room, and from there to X-ray and to the lab. Their chart goes with them the whole way, under the same case number. The chart for one visit is called a trace.
Every ward adds its own entry: when the patient arrived, when they left, and which ward sent them there. Reception's entry comes first; the emergency room's entry says "sent by reception"; X-ray and the lab both say "sent by the emergency room".
Afterwards, a doctor can lay the chart out and see the whole visit at a glance: two hours in total, and ninety minutes of it waiting at the lab. That's where to look.
The chart only works if every ward passes it on. If one ward forgets, the next ward starts a fresh chart, and the visit is split in two.
Distributed tracing
A trace is the tree of work done for one request. Each unit of work, such as handling an HTTP request, a database query or an outgoing call, is a span: a name, start and end time, attributes, a status, its trace id, its own span id, and the id of its parent span. The first span has no parent and is the root. A trace viewer draws the spans as a waterfall, so the slow or failing hop stands out.
Context propagation carries the trace across process boundaries. The W3C Trace Context standard defines the
traceparent HTTP header:
1traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-012version-trace id (16 bytes)-parent span id (8 bytes)-flags (01 = sampled)
Each service reads the header, creates its spans as children of the caller's span, and sends a new traceparent with
its own span id on every outgoing call. Messaging works the same way, with the context in message headers (Kafka record
headers, for example). A companion tracestate header carries vendor-specific data, and baggage carries your own
key-value pairs along the trace.
If one hop doesn't propagate (a hand-built HTTP client, a thread pool that loses the context), the trace breaks into disconnected pieces. Instrumentation libraries handle the common clients and servers; check the gaps.
One form, and a records office
The hospital uses one standard form for monitors, notes and charts, the same form every hospital in the country uses. So any records company can read them, and switching companies doesn't mean rewriting a single note.
Every ward sends its forms to a records office, called the Collector. The office tidies them up and sends them on to the archives.
Writing up a full chart for every single patient takes a lot of paper, so the hospital keeps only some. One way is to decide at reception: "keep a full chart for one patient in ten". That's cheap, but the patient who had a complication might be one of the nine. The better way is for the office to hold every chart until the visit is over, then keep all the ones with complications or long waits, and only a few of the ordinary ones.
The monitors' numbers are never thrown away like this, so the counts stay right.
OpenTelemetry, the Collector and sampling
OpenTelemetry (OTel), a CNCF project formed from OpenTracing and OpenCensus, is the vendor-neutral standard for telemetry: a specification and semantic conventions (standard attribute names), an API that code and libraries instrument against, SDKs that implement it (sampling, batching, exporting), and OTLP, the wire protocol (gRPC on port 4317, HTTP on 4318 by default). Instrument once and send the data to Jaeger, Grafana Tempo, Prometheus, a commercial vendor or CloudWatch, without changing code.
The OpenTelemetry Collector is a separate process that runs pipelines of receivers (OTLP, Prometheus, and many more), processors (batching, filtering, adding attributes, sampling) and exporters. It keeps vendor details and credentials out of your services.
Storing every span is expensive at scale, so traces are sampled:
- Head sampling decides when the root span starts, typically a fixed ratio, and propagates the decision in the
sampledflag so the whole trace is kept or dropped together. Cheap, but blind: at 10% it drops 90% of the rare failing requests along with the boring ones. - Tail sampling decides once the trace's spans have had time to arrive (the processor's
decision_wait), for example in the Collector'stail_samplingprocessor: keep every trace with an error or high latency, plus a small share of the rest. It needs all spans of a trace to reach the same Collector instance, and holds them in memory while it waits.
Metrics are computed from every request, so sampling traces doesn't distort them.
In Spring Boot, Micrometer Tracing (the successor of Spring Cloud Sleuth since Boot 3) records spans through an
OpenTelemetry or Brave bridge, and auto-configured RestClient, RestTemplate and WebClient builders propagate W3C
context. Spring Boot samples 10% of traces by default:
1# keep everything (fine in development)2management.tracing.sampling.probability=1.03management.endpoints.web.exposure.include=health,prometheus
The starter and OTLP export property names differ between Spring Boot 3 and 4 (Boot 4 adds
spring-boot-starter-opentelemetry), so check the reference for your version. The OpenTelemetry Java agent is the
alternative: it instruments a jar with no code changes.
Alarms that matter
The hospital sets itself a goal, called a service level objective: 999 in every 1,000 patients seen within 15 minutes, counted over a month. The other one in a thousand is its allowance for bad days. While there's plenty of allowance left, the ward can try out a new way of working. When it's nearly used up, the ward stops changing things and fixes what's slowing it down.
Alarms wake the doctor on duty for what patients feel, like waiting too long, not for what might cause it. A busy X-ray machine is fine if patients are still seen on time; waking the doctor every time a machine is busy would teach them to ignore the alarm. When patients really do wait, the alarm goes off, and the doctor uses the monitors, the charts and the notes to find out why.
SLOs, error budgets and alerting on symptoms
- An SLI (service level indicator) is a measured ratio of good events: the share of requests that succeed in under 300 ms.
- An SLO (objective) is the target for it over a window: 99.9% over 30 days.
- The error budget is what's left: 0.1% of requests, or about 43 minutes of full downtime in 30 days. While budget remains, ship features; when it's spent, prioritise reliability. An SLA is the contract with penalties, normally looser than the SLO.
Alert on symptoms, not causes. Page a human for what users feel: error rate, latency against the SLO, ideally as a burn rate (how fast the budget is being spent), with a fast window for sharp outages and a slow one for steady leaks. High CPU, a restarted pod or a full queue that users don't notice are causes: put them on dashboards or open tickets, not pages. Every page should be urgent, actionable and rare, or people learn to ignore them.
Resilience mechanisms are worth instrumenting too: a circuit breaker changing state or a spike in retries is a metric worth graphing, and often explains the symptom.