TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท infrastructure ยท observability ยท monitoring ยท opentelemetry ยท spring

Observability: logs, metrics and traces

Understanding a running system from the signals it emits. Metrics show trends and trigger alerts, structured logs record individual events, and distributed traces follow one request across services, all tied together by a shared trace id.

15 min6 animations

๐Ÿ–จ๏ธ Cheat sheet

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:

SignalWhat it isAnswers
MetricsNumeric measurements aggregated over time (http.server.requests count, latency, CPU)Is something wrong, how much, since when? Cheap to store and to alert on
TracesThe path of one request through every service, with timingsWhere is it wrong: which hop is slow or failing?
LogsTimestamped records of individual eventsWhy: 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.

Three signals, three questions5 steps
Nurses' notes01234๐Ÿค’Patients๐Ÿ‘ฉโ€โš•๏ธWard๐Ÿ“ˆWard monitor๐Ÿ“‹ Patient chart๐Ÿง‘โ€โš•๏ธDoctor
Press play and watch it happen!

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 {3    log.info("payment taken");      // includes orderId in its fields4} finally {5    MDC.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.

Correlation ids in the MDC4 steps
Nurses' notes012345๐Ÿค’Ana๐Ÿค•Ben๐Ÿ‘ฉโ€โš•๏ธWard nurse๐Ÿง‘โ€โš•๏ธDoctor
Press play and watch it happen!

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 {3    private final Counter placed;4    private final Timer payment;5 6    CheckoutService(MeterRegistry registry) {7        placed = Counter.builder("orders.placed").tag("channel", "web").register(registry);8        payment = Timer.builder("payment.duration").publishPercentileHistogram().register(registry);9    }10 11    void checkout(Order order) {12        payment.record(() -> gateway.charge(order));13        placed.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.

Counters, gauges and histograms5 steps
๐Ÿ‘ฉโ€โš•๏ธWard๐Ÿ”ขAdmissions tally๐Ÿ›๏ธBeds in useโฑ๏ธWait-time chart๐Ÿ–ฅ๏ธNurses' station screen
Press play and watch it happen!

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-012             version-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.

Spans and context propagation5 steps
Chart for case 420123๐Ÿค’Patient๐Ÿ›Ž๏ธReception๐Ÿš‘Emergency room๐ŸฉปX-ray๐ŸงชLab
Press play and watch it happen!

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 sampled flag 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's tail_sampling processor: 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.

The Collector and tail sampling5 steps
๐Ÿš‘Emergency room๐ŸงชLab๐Ÿ—‚๏ธRecords office๐Ÿ—„๏ธ Chart archive๐Ÿ“ˆ Monitor history
Press play and watch it happen!

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.

SLOs and alerting on symptoms5 steps
๐Ÿค’Patients๐Ÿ‘ฉโ€โš•๏ธWard๐ŸฉปX-ray machine๐Ÿชฃ Allowance๐Ÿง‘โ€โš•๏ธDoctor on duty
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Observability: logs, metrics and traces, told the same way as the story.
  1. The monitor shows that patients are suddenly waiting far too long. What should the doctor look at next to find which ward they're stuck in?
  2. Someone wants the admissions tally split by patient name, so they can see each person. Why is that a bad idea?
  3. The hospital decides at reception to keep a full chart for one patient in ten. What's the catch?
  4. The X-ray machine is very busy, but every patient is still seen on time. Should the alarm wake the doctor?
Answer every question to check.Passing marks Observability: logs, metrics and traces as done.
Got the hang of Observability: logs, metrics and traces? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿš€ Shipping to productionStep 10 of 10

โ† Previous on the path๐Ÿฌ Rate limitingLast step ๐ŸŽ‰Back to the path