How-To Guide

How to Link Metrics to Traces with Exemplars

Attach trace ids to histogram measurements as exemplars so you can jump from a latency spike on a dashboard straight to the request that caused it.

On this page

  1. Introduction
  2. What an Exemplar Is
  3. Enabling Exemplar Support in Your Metrics Stack
  4. Choosing Where to Attach Exemplars
  5. Retention and Cost Considerations
  6. Using Exemplars During an Incident
  7. Pitfalls and Limitations
  8. Conclusion

Introduction

A latency dashboard tells you that p99 jumped at 14:03. It does not tell you which request was slow, which customer, or which code path. A trace tells you exactly that, but traces are sampled, and the slow request you care about may not have been captured. Exemplars close the gap: a histogram bucket carries a few sample measurements, each annotated with the trace id and timestamp of a real request. On the dashboard the spike becomes a clickable point that opens the trace of an actual slow request, turning a two-hour investigation into a two-minute one.

What an Exemplar Is

An exemplar is a sidecar data point attached to a metric series. For a latency histogram, each bucket can carry a handful of exemplars, and each exemplar holds a value (the observed latency), a timestamp, and a set of labels, most importantly the trace id and span id. The metric remains a cheap aggregate; the exemplars are sparse pointers into the detailed data.

Exemplars are sampled by design to keep cost low. You do not need one per request; a handful per bucket is enough to answer “show me an example of a slow request”. The trace id in the exemplar is the link: given it, the tracing backend can render the full request.

import { trace } from '@opentelemetry/api';
import { hrtime } from 'node:process';

const histogram = getOrCreateHistogram('http.server.duration');

export async function observeRequest<T>(fn: () => Promise<T>): Promise<T> {
  const start = hrtime.bigint();
  try {
    return await fn();
  } finally {
    const seconds = Number(hrtime.bigint() - start) / 1e9;
    const span = trace.getActiveSpan();
    const ctx = span?.spanContext();
    histogram?.record(seconds, {
      'http.method': 'GET',
      // Exemplar labels: point this measurement at its trace.
      trace_id: ctx?.traceId ?? '',
      span_id: ctx?.spanId ?? '',
    });
  }
}

Enabling Exemplar Support in Your Metrics Stack

Exemplars are a first-class concept in OpenMetrics and are supported by Prometheus, the OpenTelemetry SDKs and Grafana. The metric must be a histogram or a counter, and the client library must attach the exemplar labels when it records a value. Enable the feature in the SDK and confirm that the scrape endpoint renders exemplars in the OpenMetrics format, because a silent misconfiguration means the labels never leave the process.

The trace id must come from the active span at record time. If metrics are recorded in a context where no span is active, the exemplar has no link. Ensure the metric observation happens inside the instrumented span, or thread the span context explicitly, rather than reading it from ambient state that may be absent.

# OpenMetrics wire format: a histogram bucket with exemplars
http_server_duration_seconds_bucket{le="0.5"} 1042 # {trace_id="4bf92f3577b34da6a3ce929d0e0e4736",span_id="00f067aa0ba902b7"} 0.48 1698249740.123
http_server_duration_seconds_bucket{le="1"} 1088 # {trace_id="a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",span_id="1234567890abcdef"} 0.91 1698249741.004
http_server_duration_seconds_bucket{le="+Inf"} 1090

Choosing Where to Attach Exemplars

Attach exemplars to the metrics you actually investigate: request latency, queue wait time, query duration and error counters. Do not add them to every series; the value is in the spikes, and high-cardinality series with exemplars multiply storage and scrape size for little benefit. Focus on the histograms whose buckets you look at when something is slow.

For a request-scoped metric, the exemplar belongs to the server span. For a database call, it belongs to the client span for that query, so the exemplar opens a trace that already has the query as a child. Attaching the outer request’s trace id to an inner measurement is still useful, but attaching the inner span id is what lets the trace backend jump straight to the slow operation.

Retention and Cost Considerations

Exemplars are sparse, so their storage cost is far lower than full traces, but they are still time series data: a hundred thousand buckets each carrying a few exemplars is meaningful. Cap the number of exemplars per bucket and let the SDK sample them, and age them out with the rest of the series. Because exemplars only matter during the window you investigate, a short retention aligned with your trace retention is enough.

Align exemplar retention with trace retention. An exemplar that points at a trace which has already been deleted is a dead link. Keep both windows the same, and if traces are retained for seven days, keep exemplars for seven days too, so every pointer still resolves.

Using Exemplars During an Incident

The workflow is simple and fast: the dashboard shows a p99 spike, you click the exemplar dot in the slow bucket, and the trace opens at the slow request. From there you see which span consumed the time, which downstream call was slow, and which user or tenant it affected. This is the difference between a metric that says “something is slow” and a metric that says “this request was slow, here is why”.

Exemplars also help confirm a hypothesis. If you suspect a specific dependency is causing the spike, filter the exemplars by the relevant label and open one; if every slow exemplar points at the same downstream span, the hypothesis is confirmed with evidence rather than correlation.

Pitfalls and Limitations

The most common failure is recording the metric outside the span, which yields exemplars with empty trace ids. The second is forgetting to enable OpenMetrics on the scrape, so the exemplars exist in the SDK but never reach the backend. The third is a metrics backend that stores exemplars but a dashboard that does not render them, so the feature is invisible.

Exemplars are samples, not a full record; they cannot answer “what is the distribution of slow requests” because most slow requests have no exemplar. Use them to find one concrete example, then use traces and logs to understand the class. And remember that an exemplar without a matching retained trace is a dead link, so retention must be coordinated.

Conclusion

Exemplars are the bridge between aggregate metrics and detailed traces. Attach the active trace id to your latency histograms, enable OpenMetrics on the scrape, render them on the dashboard and align their retention with traces. The payoff is a dashboard that not only shows that latency spiked but lets you click through to a real slow request in one step, which is what turns monitoring into diagnosis.

Sources: OpenTelemetry: Exemplars, Prometheus: Exemplars, OpenMetrics specification.

FAQ

Do exemplars replace trace sampling?
No. Traces give you the full picture of sampled requests, and exemplars give you pointers from metrics to a few of those traces. They complement each other: exemplars help you find the interesting request, and tracing lets you inspect it.
Why are my exemplars missing from the scrape output?
Usually the metric is recorded outside an active span, so the trace id is empty, or OpenMetrics is not enabled on the endpoint. Confirm both: record inside the span, and check that the scrape exposes the exemplar in the OpenMetrics format.

Related Examples