Skip to content

    System Design

    Observability with Micrometer, Prometheus and OpenTelemetry

    Instrument a Spring service once with Micrometer, then read its metrics as Prometheus text, its spans and its trace-linked logs, in a runnable in-memory lab.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Observability and SLOs

    What you'll learn: By the end of this lesson you will be able to pick the right Micrometer meter type, name meters and tags so that Prometheus can use them and cardinality stays bounded, read the Prometheus text format a registry produces, use the Observation API so one instrumented call yields a timer and a span, link log lines to traces, and say exactly what a real Prometheus server and OpenTelemetry Collector add to what a test can show.

    A patient on a ward has three records. The vitals chart is a row of numbers taken at intervals: it tells the nurse something is drifting. The nurses' notes are free-text entries: they say what happened and why. The patient's route chart shows which departments they passed through and how long each took. None replaces the others, and all three are useful only if the same patient number is on every page.

    Metrics, logs and traces are those three records for a service. Observability and SLOs explains what each signal is for and how SLOs sit on top; Alerting and On-Call turns metrics into pages. This lesson is the Java side: how a Spring service produces the signals with Micrometer and OpenTelemetry, what the Prometheus format looks like on the wire, and what goes wrong with labels. Correlation IDs and trace context, and health checks, have lessons of their own.

    Verified with the Micrometer, Micrometer Tracing, Prometheus, OpenTelemetry and Spring Boot documentation, and a lab run on Spring Boot 4.1.2 and Java 25, on 2026-12-01.

    The core idea

    Instrument the code once, against an API; decide where the data goes by wiring. Micrometer's Observation documentation puts it as "Instrument code once, and get multiple benefits out of it." The service records an observation; one handler turns it into a timer for a metrics backend, another into a span for a tracing backend, and the log line carries the same trace id.

    Three illustrations run through it: a minimal example (the lab), a realistic example (ShopStream's checkout SLO) and a failure example (an unbounded tag).

    Four names, four jobs. Micrometer is a metrics facade for the JVM that, since version 1.10, also has the Observation API. Prometheus is both a text format and a server that "scrapes metrics from instrumented jobs" and "stores all scraped samples locally". OpenTelemetry defines the signals: traces, metrics, logs and baggage. The OpenTelemetry Collector is a "Vendor-agnostic way to receive, process and export telemetry data".

    One instrumentation point, several backendsCheckout service to Meter registry (timer); Checkout service to OpenTelemetry SDK (span); Prometheus to Meter registry (scrape); OpenTelemetry SDK to Collector (export)Checkout service: Observation APICheckoutserviceObservation APIMeter registry: timers, countersMeter registrytimers, countersOpenTelemetry SDK: spansOpenTelemetrySDKspansPrometheus: scrapes, storesPrometheusscrapes, storesCollector: receive, exportCollectorreceive, exporttimerspanscrapeexport

    Figure 1. Instrument once, route by wiring. How to read this: the service talks only to the Observation API. The grey boxes are real servers the lab does not run; it replaces both with in-memory objects.

    Choosing a meter type

    Micrometer's documentation describes each type briefly. Counters "report a single metric: a count", with the guidance "Never count something you can time with a Timer or summarize with a DistributionSummary", since those already publish a count. A gauge "is a handle to get the current value" and gauges "maintain only a weak reference to the object being observed", so your code must keep a strong one. A timer is "intended for measuring short-duration latencies and the frequency of such events". A long task timer "lets you measure time while an event being measured is still running". A distribution summary "records values that do not represent a unit of time", such as payload sizes.

    flowchart TD accTitle: Choosing a Micrometer meter type accDescr: A decision flow. A value that can go up and down and is read on demand is a gauge. A duration of a short operation is a timer, and of an operation still running is a long task timer. A size or amount per event is a distribution summary. A plain event count is a counter. A["What do you want to record?"] --> B{"A current value that goes
    up and down?"} B -->|"yes"| G["Gauge"] B -->|"no"| C{"How long something takes?"} C -->|"short, recorded when it ends"| T["Timer"] C -->|"long, watch it while it runs"| L["Long task timer"] C -->|"no"| D{"A size or amount per event?"} D -->|"yes"| S["Distribution summary"] D -->|"no"| K["Counter"]

    Figure 2. Which meter. How to read this: ask the questions in order. The counter is the fallback, not the default, because a timer or summary already counts.

    Names, tags and cardinality

    Micrometer names meters in lowercase dotted words and converts them per backend (http.server.requests becomes http_server_requests_duration_seconds in Prometheus). Prometheus's own practice is base units and a total suffix on counters.

    Tags are where metrics go wrong. Prometheus warns that "every unique combination of key-value label pairs represents a new time series, which can dramatically increase the amount of data stored", and not to use labels for "user IDs, email addresses, or other unbounded sets of values". Micrometer says the same: "Beware of the potential for tag values coming from user-supplied sources to blow up the cardinality of a metric." Its Observation API builds the rule into the call: a low-cardinality key value has "a bounded number of possible values" and becomes a metric tag, while a high-cardinality one has "an unbounded number of possible values" and belongs on the span, not the metric.

    Build it: four orders through an instrumented checkout

    This is the minimal example. CheckoutService is ShopStream's checkout with a payment step, instrumented with one Observation per operation plus a counter, a gauge and a distribution summary. The tests wire it to in-memory backends, and the report prints what each received. There is no Prometheus server and no OpenTelemetry Collector. A SimpleMeterRegistry holds the meters; a PrometheusMeterRegistry is used only as a library to render the scrape text; an InMemorySpanExporter holds the spans. A fake clock makes every duration exact (scripted, so they say nothing about real performance) and a counting id generator makes trace ids repeatable.

    Goal. See one instrumented call become a timer, a Prometheus histogram, a span and a log line, and see what an unbounded tag does.

    Setup. From examples/spring-labs:

    cd examples/spring-labs && ./gradlew :labs:observability-micrometer:test

    Eight tests assert the claims below and one compares the report with examples/spring-labs/golden/observability-micrometer.txt. Four orders run: ord-1 (45 ms), ord-2 (105 ms), ord-3 (card declined, 35 ms) and ord-4 (65 ms). The instrumented call is:

    Observation.createNotStarted(CHECKOUT, observations)
            .lowCardinalityKeyValue("payment.method", "card")      // bounded: becomes a metric tag and a span tag
            .highCardinalityKeyValue("order.id", orderId)          // unbounded: a span tag only
            .observe(() -> {
                // ... the checkout, with a nested payment.authorize observation
            });

    The meters in memory

    The SimpleMeterRegistry, which "holds the latest value of each meter in memory" and "does not export the data anywhere", is the easiest thing to assert against.

    Expected output, captured from a real run (Java 25.0.3, Spring Boot 4.1.2, 2026-12-01), the meters (the first line is the report's heading):

    TIMER checkout.place{error=PaymentDeclinedException,payment.method=card}  count=1.0, total=0.035, max=0.035
    TIMER checkout.place{error=none,payment.method=card}  count=3.0, total=0.215, max=0.105
    LONG_TASK_TIMER checkout.place.active{payment.method=card}  active=0.0, duration=0.0, max=0.0
    TIMER payment.authorize{error=PaymentDeclinedException,provider=mockpay}  count=1.0, total=0.03, max=0.03
    TIMER payment.authorize{error=none,provider=mockpay}  count=3.0, total=0.06, max=0.02
    LONG_TASK_TIMER payment.authorize.active{provider=mockpay}  active=0.0, duration=0.0, max=0.0
    GAUGE shop.carts.open  value=5.0
    DISTRIBUTION_SUMMARY shop.order.items  count=3.0, total=14.0, max=8.0
    COUNTER shop.orders{outcome=declined}  count=1.0
    COUNTER shop.orders{outcome=placed}  count=3.0

    Each observation made timers split by the error tag (none or the exception's class name) and a long task timer (.active), zero because nothing is running. The three successful checkouts total 0.215 seconds and the longest took 0.105. order.id is not a tag on any meter, which a test checks.

    The same meters as Prometheus text

    The Prometheus registry renders the exposition format with scrape(). In a real service that string is the body of the scrape endpoint; Spring Boot publishes it at /actuator/prometheus and says "By default, the endpoint is not available and must be exposed."

    Expected output, captured from a real run (same run), the checkout timer, which has bucket boundaries at 50 ms and 100 ms configured with a MeterFilter:

    # HELP checkout_place_seconds  
    # TYPE checkout_place_seconds histogram
    checkout_place_seconds_bucket{error="PaymentDeclinedException",payment_method="card",le="0.05"} 1
    checkout_place_seconds_bucket{error="PaymentDeclinedException",payment_method="card",le="0.1"} 1
    checkout_place_seconds_bucket{error="PaymentDeclinedException",payment_method="card",le="+Inf"} 1
    checkout_place_seconds_count{error="PaymentDeclinedException",payment_method="card"} 1
    checkout_place_seconds_sum{error="PaymentDeclinedException",payment_method="card"} 0.035
    checkout_place_seconds_bucket{error="none",payment_method="card",le="0.05"} 1
    checkout_place_seconds_bucket{error="none",payment_method="card",le="0.1"} 2
    checkout_place_seconds_bucket{error="none",payment_method="card",le="+Inf"} 3
    checkout_place_seconds_count{error="none",payment_method="card"} 3
    checkout_place_seconds_sum{error="none",payment_method="card"} 0.215

    The dots became underscores and the base unit seconds was added. The type is histogram and the buckets are cumulative: for error="none" one checkout was at or under 0.05 s, two at or under 0.1 s, and +Inf holds all three, equal to _count. The format requires that: a histogram "must have a bucket with {le="+Inf"}" whose value "must be identical to the value of x_count". The 50 ms and 100 ms boundaries stand for SLO thresholds: Prometheus's guidance is that with classic buckets you must have buckets at the exact boundaries you care about.

    A timer with no bucket configuration looks different.

    Expected output, captured from a real run (same run), the payment timer:

    # HELP payment_authorize_seconds  
    # TYPE payment_authorize_seconds summary
    payment_authorize_seconds_count{error="PaymentDeclinedException",provider="mockpay"} 1
    payment_authorize_seconds_sum{error="PaymentDeclinedException",provider="mockpay"} 0.03
    payment_authorize_seconds_count{error="none",provider="mockpay"} 3
    payment_authorize_seconds_sum{error="none",provider="mockpay"} 0.06

    It is a summary with only a count and a sum per label set. You can compute an average, but "you cannot use a summary if you need to aggregate the observations from a number of instances", and there is no quantile to ask for. If latency matters to an SLO, give the timer buckets (Micrometer's serviceLevelObjectives).

    Expected output, captured from a real run (same run), the counter:

    # HELP shop_orders_total  
    # TYPE shop_orders_total counter
    shop_orders_total{outcome="declined"} 1.0
    shop_orders_total{outcome="placed"} 3.0

    The counter gained a _total suffix, as Prometheus's naming practice says.

    What a Prometheus server adds

    scrape() returns a string. A running Prometheus server turns it into data you can use: it pulls the endpoint on a schedule ("time series collection happens via a pull model over HTTP"), stores the samples, answers PromQL queries and evaluates alerting rules for Alertmanager. The lab shows the text one scrape would carry; it cannot show rates over time, retention, queries or alerts.

    sequenceDiagram accTitle: A real Prometheus scrape compared with the lab accDescr: In production a Prometheus server requests the metrics endpoint every interval, the application registry renders the text format, and the server stores the samples. In the lab a test calls scrape directly and prints the string. participant P as Prometheus server participant E as Metrics endpoint participant R as PrometheusMeterRegistry P->>E: GET /actuator/prometheus (every interval) E->>R: scrape() R-->>E: text format E-->>P: 200 + samples Note over P: stores, queries with PromQL, evaluates alert rules Note over R: the lab calls scrape() and prints the string

    Figure 3. Where the lab stops. How to read this: everything from the endpoint rightward is real in production; the lab keeps only the registry and its text.

    One observation, one span

    The same observation also produced spans, because a second handler was registered. Micrometer Tracing's documentation says: "Whenever an Observation is used, a corresponding span is created, started, stopped and reported."

    Expected output, captured from a real run (same run), the spans in the order they ended:

    == Part 3: the spans (InMemorySpanExporter), in the order they ended
    span payment.authorize  trace=1 span=2 parent=1 status=OK
          attributes: {provider=mockpay}
    span checkout.place  trace=1 span=1 parent=none status=OK
          attributes: {order.id=ord-1, payment.method=card}
    span payment.authorize  trace=2 span=4 parent=3 status=OK
          attributes: {provider=mockpay}
    span checkout.place  trace=2 span=3 parent=none status=OK
          attributes: {order.id=ord-2, payment.method=card}
    span payment.authorize  trace=3 span=6 parent=5 status=ERROR
          attributes: {provider=mockpay}
          event: exception
    span checkout.place  trace=3 span=5 parent=none status=ERROR
          attributes: {order.id=ord-3, payment.method=card}
          event: exception
    span payment.authorize  trace=4 span=8 parent=7 status=OK
          attributes: {provider=mockpay}
    span checkout.place  trace=4 span=7 parent=none status=OK
          attributes: {order.id=ord-4, payment.method=card}

    Each checkout is one trace and the payment span's parent is the checkout span's id. The attributes are the key values, with order.id (high cardinality) a span attribute only. The declined order shows status=ERROR and an exception event on both spans, because the error propagated through both observations. OpenTelemetry defines a span as "a unit of work or operation" with a name, parent id, times, span context, attributes, events, links, status and kind; the status is Unset, Ok or Error. The ids here come from a counting test generator; real ids are random.

    The in-memory exporter is InMemorySpanExporter from opentelemetry-sdk-testing, which "Captures exported spans in memory". In production the SDK would hold an exporter such as OTLP and a batching span processor, usually sending to a Collector. That adds what the lab cannot show: retries, batching, sensitive-data filtering, delivery to backends and sampling; Spring Boot "samples only 10% of requests" by default, while the lab kept every span.

    sequenceDiagram accTitle: One observation producing a timer and a span accDescr: The service starts an observation. The metrics handler and the tracing handler both receive the start event; the tracing handler creates a span. The service runs the work, possibly with a nested observation and an error. When the observation stops, the metrics handler records the timer with the error tag and the tracing handler ends the span with its status. participant S as CheckoutService participant O as Observation participant M as Meter handler participant T as Tracing handler S->>O: start (name, key values) O->>M: started (timer sample) O->>T: started (span begins) S->>S: work, nested payment observation S->>O: error (if any) S->>O: stop O->>M: record timer, error tag O->>T: end span, status

    Figure 4. The life of one observation. How to read this: the service makes three calls. The two handlers do the rest, which is why changing the backend does not change the service.

    Logs that name their trace

    The service logs inside the observation and puts the current traceId and spanId into the SLF4J MDC around each line. Spring Boot does this for you: with Micrometer Tracing "Spring Boot will include correlation IDs in your logs by default", built from the traceId and spanId MDC values. The lab sets them by hand to keep the wiring visible.

    Expected output, captured from a real run (same run), the log lines:

    == Part 4: the log lines, with the ids from the MDC
    INFO placing order ord-1  [traceId=1 spanId=1]
    INFO order ord-1 placed  [traceId=1 spanId=1]
    INFO placing order ord-2  [traceId=2 spanId=3]
    INFO order ord-2 placed  [traceId=2 spanId=3]
    INFO placing order ord-3  [traceId=3 spanId=5]
    INFO card declined for ord-3  [traceId=3 spanId=6]
    INFO placing order ord-4  [traceId=4 spanId=7]
    INFO order ord-4 placed  [traceId=4 spanId=7]

    Every line carries the ids of its span: the decline was logged inside the payment span (spanId=6), the others in the checkout span. From a trace you find its logs by traceId, and from a log line you open the trace. What stays out of logs is in Audit Logging.

    What an unbounded tag does

    Expected output, captured from a real run (same run), two counters fed by three orders:

    == Part 5: what an unbounded tag does
    series named shop.orders.by_outcome (tag outcome, two possible values): 2
    series named shop.orders.by_id (tag order_id, one per order): 3

    A counter tagged outcome made two series; one tagged order_id made a series per order. At 500,000 orders a day (the shared ShopStream figure, illustrative) that is up to 500,000 new series a day from one line of code.

    Trade-offs

    Choice Gain Cost Wrong when
    Observation API for operations One call gives a timer and a span Needs both handlers registered You only ever want a single counter
    Direct meters (counter, gauge) Simple, explicit No span, no trace link The operation also needs tracing
    Histogram buckets at the SLO Quantiles that aggregate across instances More series per timer You never alert on latency
    Summary (no buckets) Fewest series Cannot aggregate or ask for a quantile More than one instance serves the endpoint

    In practice: ShopStream's checkout SLO

    This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared ShopStream figures are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    At the shared peak of about 58 checkouts per second, ShopStream wants a latency SLO for checkout: say 99% of checkouts under 100 ms (illustrative). The existing dashboards show an average, which hides the slow tail.

    Starting architecture

    The checkout timer has no buckets, so its Prometheus series are a summary, and several instances serve checkout.

    Options considered

    Option Behaviour Problem
    A. Keep the summary, graph the average Cheap Cannot show the tail or aggregate instances
    B. Percentile histogram on every timer Quantiles from buckets Many series for every timer
    C. Buckets at the SLO boundaries on the checkout timer only Exact "under 100 ms" ratio A boundary change needs a deploy

    The decision

    Option C, plus the Observation API for the checkout and payment steps so the same call also produces the span, with order.id as a high-cardinality key value only.

    Rollout and verification

    Reproduce the lab's buckets, confirm in staging that the scrape shows _bucket lines and that +Inf equals _count, then build the SLO rule on the bucket counters as in Alerting and On-Call.

    The 2 a.m. failure

    A release adds order.id as a low-cardinality key value "to make the dashboard filterable". Series for the checkout timer grow with every order, Prometheus slows and runs out of memory, and the burn-rate alerts stop evaluating. First checks: series count per metric, scrape size, the last deploy. Mitigate by rolling back or dropping the tag with a meter filter; fix lastingly with a test that rejects forbidden tag keys, keeping per-order detail on spans and in logs.

    Architect's notes

    • Decide the tag allowlist per metric and enforce it in a test or meter filter.
    • Put identifiers on spans and logs, never on metric tags.
    • Give latency timers buckets at the SLO boundaries.
    • Test the instrumentation with in-memory backends, and say what that cannot show: scraping, storage, queries, alerts, batching, sampling.

    Common mistakes

    • Tagging with unbounded values.
    • A counter where a timer would count and time.
    • A gauge on an object nothing else holds, so it is garbage collected and goes missing.
    • A latency summary on a multi-instance service.
    • Logs without trace ids, so the three signals cannot be joined.

    Key takeaways

    • Instrument once against an API and choose backends by wiring.
    • Pick the meter by the question: gauge, timer, long task timer, summary, or counter as the fallback.
    • Low-cardinality key values become metric tags; high-cardinality ones belong on spans.
    • An observation gives a timer and a span; the log line joins them through traceId and spanId.
    • The lab shows the formats and the wiring; a real Prometheus and Collector add the pipeline.

    Practice exercises

    Exercise 1 (20 min). Classify these as gauge, counter, timer, long task timer or summary: cart items in memory, payments declined, time to authorise a card, a nightly export that runs for an hour, and request body size.

    Exercise 2 (45 min). Run the lab, then add a bucket at 200 ms to the checkout timer and predict the new le lines before you look.

    Exercise 3 (1 hour). Follow the "Break it" step in the lab README: make order.id a low-cardinality key value and say which tests fail and why.

    The other side of this topic

    The browser has its own signals, such as page timings and errors seen by real users: see Real User Monitoring; a lesson on OpenTelemetry in the browser is planned. The join between the two sides is a trace id in a request header, the subject of the planned lesson on correlation IDs and trace context.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments