Containers

OpenTelemetry Grafana Alloy Pipeline to Tempo, Mimir and Loki

You have a Python service and three Grafana backends: Tempo for traces, Mimir for metrics and Loki for logs. After this guide, the service speaks OTLP to one Grafana Alloy endpoint, and a slow point on a latency graph opens the exact trace behind it, whose spans open the log lines they wrote. That loop is the whole reason to run all three, and it’s the part of an OpenTelemetry Grafana Alloy setup that’s easiest to get almost right.

Original content from computingforgeeks.com - post 189333

We start with zero-code auto-instrumentation on a FastAPI app, then add manual spans and a latency histogram by hand, while Alloy fans the signals out to self-hosted backends in Docker Compose. A default Mimir limit and a Grafana provisioning quirk each break the join silently, so both get the captures that prove it. We confirmed the whole loop working on Ubuntu 26.04 in November 2026, with Alloy v1.21.3, Tempo 3.1.1, Mimir 3.2.4, Loki 3.7.9, Grafana 13.3.1 and the OpenTelemetry Python SDK 1.45.2.

Follow the OTLP path to Grafana

The diagram shows who talks to whom. The app knows one address, the OTLP port on Alloy, and nothing about the backends behind it. Grafana reads all three stores and follows the trace ID from one to the next.

Architecture diagram: shop-api sends OTLP to Grafana Alloy, which fans out to Mimir, Tempo and Loki, all read by Grafana

Keeping the app ignorant of the backends is what makes this layout worth the extra container. Swap Tempo for a hosted tracing service later and you change one exporter block in Alloy, not the environment of every service. It also gives you one place to batch, filter or sample, because every signal passes through the same process before it reaches storage.

Set up the host for the stack

Everything runs on one Linux host with Docker Engine and the Compose plugin. Our lab box was a 4 vCPU, 16 GB VM with a 40 GB disk, called obs01, and the app ran on the same machine so the OTLP endpoint is localhost. Treat that size as a floor for a lab, not a production figure. Three things need to be in place before the first file.

  1. Install Docker Engine and the Compose plugin from Docker’s own apt repository, since the distro’s docker.io package lags behind.
  2. Install Python 3 with the venv module for the app side (sudo apt install python3-venv jq on Ubuntu; jq is for one check near the end).
  3. Limit TCP 3000 (Grafana) to your own address and 4317/4318 (OTLP) to the hosts that run instrumented services, in a cloud security group or Docker’s DOCKER-USER chain.

That last point catches people who rely on ufw. Docker publishes container ports through its own NAT rules, which route that traffic past ufw’s INPUT rules entirely, so a ufw deny on a published port does nothing. The compose file below handles the debug ports itself: it binds 3100, 3200, 9009 and 12345 to 127.0.0.1, so you can curl each backend from the host while nobody else can reach Loki’s or Mimir’s unauthenticated push endpoints. On a real deployment, sizing is driven by span volume per second, active metric series and log bytes per day, and each backend splits into separate components long before one host runs out. The standalone guides for installing Grafana Tempo, Grafana Mimir and Grafana Loki cover them as system services if you’d rather not run containers.

Run Tempo, Mimir and Loki

This is the storage side. Each backend gets a small single-binary config with local filesystem storage, so the whole stack lives in one directory. Create it now, with the two subdirectories that Alloy and Grafana will read from once the containers start.

mkdir -p ~/lgtm/alloy ~/lgtm/grafana/provisioning/datasources
cd ~/lgtm

Tempo comes first, since it is the one most likely to bite you if you copy an older config from a blog post or an old Helm values file.

vim ~/lgtm/tempo.yaml

Tempo receives OTLP over gRPC on 4317 inside the Compose network and serves queries on 3200. Nothing outside the Compose network talks to that 4317, because Alloy owns the published one.

server:
  http_listen_port: 3200
distributor:
  receivers:
    otlp:
      protocols:
        grpc:
          endpoint: 0.0.0.0:4317
storage:
  trace:
    backend: local
    wal:
      path: /var/tempo/wal
    local:
      path: /var/tempo/blocks

Notice what’s missing. Most Tempo examples you’ll find carry ingester and compactor blocks, and the Tempo 3.x line refuses to start with them (the exact error is in the troubleshooting section at the end). Mimir is next.

vim ~/lgtm/mimir.yaml

This runs Mimir as one process with in-memory rings and filesystem blocks. The last two lines matter more than the rest of the file put together, so do not trim them when you adapt it.

multitenancy_enabled: false
server:
  http_listen_port: 9009
  grpc_listen_port: 9095
common:
  storage:
    backend: filesystem
    filesystem:
      dir: /data/common
blocks_storage:
  storage_prefix: blocks
  tsdb:
    dir: /data/tsdb
  bucket_store:
    sync_dir: /data/tsdb-sync
ingester:
  ring:
    replication_factor: 1
    kvstore:
      store: inmemory
store_gateway:
  sharding_ring:
    replication_factor: 1
compactor:
  data_dir: /data/compactor
  sharding_ring:
    kvstore:
      store: inmemory
distributor:
  ring:
    kvstore:
      store: inmemory
ruler_storage:
  storage_prefix: ruler
alertmanager_storage:
  storage_prefix: alertmanager
usage_stats:
  enabled: false
limits:
  max_global_exemplars_per_user: 100000

Mimir ships with max_global_exemplars_per_user set to 0, which means it accepts exemplars on the wire and throws every one away. There is no error and no log line, only an empty Exemplars panel in Grafana later. We proved that with the Mimir counters before setting the limit, and the numbers are in the troubleshooting section. Loki is the last backend.

vim ~/lgtm/loki.yaml

Loki needs structured metadata allowed, because that is where its OTLP endpoint stores trace_id and span_id for each log record.

auth_enabled: false
server:
  http_listen_port: 3100
common:
  instance_addr: 127.0.0.1
  path_prefix: /loki
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory
  storage:
    filesystem:
      chunks_directory: /loki/chunks
      rules_directory: /loki/rules
schema_config:
  configs:
    - from: "2024-04-01"
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h
limits_config:
  allow_structured_metadata: true
analytics:
  reporting_enabled: false

With the TSDB index and schema v13, structured metadata is on by default in current Loki, but writing it down means nobody turns it off by accident when they tune limits later. That’s all three stores configured. None of them is running yet, because Compose starts them together with Alloy and Grafana in the next step.

Build the Alloy pipeline

Alloy is the piece that ties this together. It takes OTLP in on 4317 and 4318, batches it, and hands each signal to the exporter for its backend, so this one file decides where every span, sample and log line ends up.

vim ~/lgtm/alloy/config.alloy

Traces go to Tempo over OTLP gRPC and logs to the native Loki /otlp endpoint. Metrics take a detour through the Prometheus exporter so they land in Mimir with their exemplars attached.

otelcol.receiver.otlp "default" {
	grpc {
		endpoint = "0.0.0.0:4317"
	}

	http {
		endpoint = "0.0.0.0:4318"
	}

	output {
		metrics = [otelcol.processor.batch.default.input]
		logs    = [otelcol.processor.batch.default.input]
		traces  = [otelcol.processor.batch.default.input]
	}
}

otelcol.processor.batch "default" {
	output {
		metrics = [otelcol.exporter.prometheus.mimir.input]
		logs    = [otelcol.exporter.otlphttp.loki.input]
		traces  = [otelcol.exporter.otlp.tempo.input]
	}
}

otelcol.exporter.otlp "tempo" {
	client {
		endpoint = "tempo:4317"

		tls {
			insecure = true
		}
	}
}

otelcol.exporter.otlphttp "loki" {
	client {
		endpoint = "http://loki:3100/otlp"
	}
}

otelcol.exporter.prometheus "mimir" {
	forward_to = [prometheus.remote_write.mimir.receiver]
}

prometheus.remote_write "mimir" {
	endpoint {
		url            = "http://mimir:9009/api/v1/push"
		send_exemplars = true
	}
}

We tested both metric routes into Mimir. The other one swaps the last two blocks for an otelcol.exporter.otlphttp pointed at http://mimir:9009/otlp, and it delivered exemplars too once the Mimir limit was raised. We kept the remote_write route for one practical reason: it adds unit suffixes, so the auto-instrumented metric arrives as http_server_duration_milliseconds_bucket, and the otelcol.exporter.prometheus reference documents that as add_metric_suffixes, default true. Mimir’s OTLP route stored the same metric as http_server_duration_bucket, so dashboards built against one route break on the other.

Grafana reads its admin password from a file instead of the compose environment, which keeps it out of docker inspect output. Create the file and type a password of your own on a single line.

vim ~/lgtm/grafana-pw

Now the compose file that starts all five services and mounts the configs you just wrote.

vim ~/lgtm/compose.yaml

Every image is pinned to the tag we tested, because a floating latest tag on four Grafana projects means four config formats that can change under you on the next pull. Only Grafana’s 3000 and Alloy’s two OTLP ports listen on every interface; Alloy’s UI on 12345 stays on loopback with the backends.

services:
  tempo:
    image: grafana/tempo:3.1.1
    command: ["-config.file=/etc/tempo/tempo.yaml"]
    volumes:
      - ./tempo.yaml:/etc/tempo/tempo.yaml:ro
      - tempo-data:/var/tempo
    ports:
      - "127.0.0.1:3200:3200"
  mimir:
    image: grafana/mimir:3.2.4
    command: ["-config.file=/etc/mimir/mimir.yaml", "-target=all"]
    volumes:
      - ./mimir.yaml:/etc/mimir/mimir.yaml:ro
      - mimir-data:/data
    ports:
      - "127.0.0.1:9009:9009"
  loki:
    image: grafana/loki:3.7.9
    command: ["-config.file=/etc/loki/loki.yaml"]
    volumes:
      - ./loki.yaml:/etc/loki/loki.yaml:ro
      - loki-data:/loki
    ports:
      - "127.0.0.1:3100:3100"
  grafana:
    image: grafana/grafana:13.3.1
    environment:
      GF_SECURITY_ADMIN_USER: admin
      GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_pw
      GF_AUTH_ANONYMOUS_ENABLED: "false"
      GF_USERS_DEFAULT_THEME: system
    secrets:
      - grafana_pw
    volumes:
      - ./grafana/provisioning:/etc/grafana/provisioning:ro
      - grafana-data:/var/lib/grafana
    ports:
      - "3000:3000"
    depends_on: [tempo, mimir, loki]
  alloy:
    image: grafana/alloy:v1.21.3
    command:
      - run
      - --server.http.listen-addr=0.0.0.0:12345
      - --storage.path=/var/lib/alloy/data
      - /etc/alloy/config.alloy
    volumes:
      - ./alloy/config.alloy:/etc/alloy/config.alloy:ro
    ports:
      - "127.0.0.1:12345:12345"
      - "4317:4317"
      - "4318:4318"
    depends_on: [tempo, mimir, loki]
secrets:
  grafana_pw:
    file: ./grafana-pw
volumes:
  tempo-data:
  mimir-data:
  loki-data:
  grafana-data:

The Grafana data source file comes later, once there’s data to point at, so start the stack now and check that every service answers on its readiness endpoint:

docker compose up -d
for p in 3200/ready 3100/ready 9009/ready 12345/-/ready; do echo -n "$p: "; curl -s localhost:$p; echo; done

Do not panic at the first answer from Loki and Mimir. This is what ours said about 40 seconds after start.

3200/ready: ready

3100/ready: Ingester not ready: waiting for 15s after being ready

9009/ready: Ingester not ready: waiting for 15s after being ready

12345/-/ready: Alloy is ready.

Both ingesters hold back for 15 seconds after they consider themselves ready, so a second run a little later shows ready on every line. Alloy also reports the health of each component it built from the config, which is the fastest way to catch a typo in an exporter address:

curl -s localhost:12345/api/v0/web/components | python3 -c "import sys,json;[print(c['localID'],c['health']['state']) for c in json.load(sys.stdin)]"

All six components should read healthy. An exporter shows unhealthy when its backend refuses the connection, so this list also proves that the Compose service names resolve.

prometheus.remote_write.mimir healthy
otelcol.exporter.prometheus.mimir healthy
otelcol.exporter.otlp.tempo healthy
otelcol.exporter.otlphttp.loki healthy
otelcol.processor.batch.default healthy
otelcol.receiver.otlp.default healthy

The same pipeline is drawn as a graph in the Alloy UI. Because 12345 is bound to loopback, reach it through an SSH tunnel from your workstation (ssh -L 12345:localhost:12345 [email protected]) and open http://localhost:12345/graph. Follow the wires from the OTLP receiver through the batch processor to the Tempo exporter, the Loki exporter and the Prometheus exporter that feeds remote_write.

Grafana Alloy UI graph of the OTLP receiver, batch processor and the Tempo, Loki and Prometheus exporters
  1. 1OTLP receiver
  2. 2Tempo exporter
  3. 3Prometheus exporter

A component with a red badge here means it cannot reach its backend, and clicking it shows the last error. Our Grafana Alloy install guide covers running the same config as a system package instead of a container.

Instrument the app with zero code

Now the app side. The service is a small FastAPI shop with a checkout endpoint that sometimes calls an inventory endpoint over HTTP and fails about 8% of the time. It has no OpenTelemetry imports at all, only standard logging. Create a virtual environment and install the app packages together with the OpenTelemetry distro and the OTLP exporter.

mkdir -p ~/shop-api && cd ~/shop-api
python3 -m venv .venv
. .venv/bin/activate
pip install -q fastapi uvicorn httpx opentelemetry-distro opentelemetry-exporter-otlp

The OpenTelemetry packages come in two version lines, which confuses people reading pip list for the first time. Filter the list to see them side by side:

pip list | grep -iE "opentelemetry|fastapi|uvicorn|httpx"

Trimmed to the core OpenTelemetry packages, ours read:

opentelemetry-api                        1.45.2
opentelemetry-distro                     0.66b2
opentelemetry-exporter-otlp              1.45.2
opentelemetry-instrumentation            0.66b2
opentelemetry-sdk                        1.45.2
opentelemetry-semantic-conventions       0.66b2

The API, SDK and exporters are stable and move together, while the distro and instrumentation packages are still beta and carry a matching 0.xxbN number. Keep each line on one version; mixing instrumentation releases is the usual cause of import errors at startup. Next, the app itself.

vim ~/shop-api/app.py

Paste the plain version. It logs with the standard logging module and calls itself with httpx so the trace gets a client span:

import asyncio
import logging
import random

import httpx
from fastapi import FastAPI, HTTPException

app = FastAPI(title="shop-api")
logger = logging.getLogger("shop-api")
logging.basicConfig(level=logging.INFO)


@app.get("/inventory/{item_id}")
async def inventory(item_id: int):
    await asyncio.sleep(random.uniform(0.02, 0.08))
    return {"item": item_id, "in_stock": random.random() > 0.1}


@app.get("/checkout/{order_id}")
async def checkout(order_id: int):
    logger.info("checkout started order_id=%s", order_id)
    await asyncio.sleep(random.uniform(0.02, 0.4))
    if random.random() < 0.5:
        async with httpx.AsyncClient() as client:
            await client.get(f"http://localhost:8000/inventory/{order_id}")
    if random.random() < 0.08:
        logger.error("payment declined order_id=%s", order_id)
        raise HTTPException(status_code=500, detail="payment declined")
    logger.info("checkout finished order_id=%s", order_id)
    return {"order": order_id, "status": "paid"}

opentelemetry-bootstrap scans the packages in the virtual environment and works out the matching instrumentation libraries. Run it after the app’s dependencies are in, never before, or it has nothing to match. The requirements action only prints the list, so look first:

opentelemetry-bootstrap -a requirements

In our venv it matched FastAPI, Starlette, httpx and logging, the four that matter here, plus a handful of standard-library ones. The ASGI instrumentation is not listed because the FastAPI one pulls it in as a dependency:

opentelemetry-instrumentation-asyncio==0.66b2
opentelemetry-instrumentation-dbapi==0.66b2
opentelemetry-instrumentation-exceptions==0.66b2
opentelemetry-instrumentation-logging==0.66b2
opentelemetry-instrumentation-sqlite3==0.66b2
opentelemetry-instrumentation-threading==0.66b2
opentelemetry-instrumentation-urllib==0.66b2
opentelemetry-instrumentation-wsgi==0.66b2
opentelemetry-instrumentation-click==0.66b2
opentelemetry-instrumentation-fastapi==0.66b2
opentelemetry-instrumentation-grpc==0.66b2
opentelemetry-instrumentation-httpx==0.66b2
opentelemetry-instrumentation-requests==0.66b2
opentelemetry-instrumentation-starlette==0.66b2
opentelemetry-instrumentation-tortoiseorm==0.66b2
opentelemetry-instrumentation-urllib3==0.66b2

Nothing on that list is harmful to have, so install the lot. The same command with the install action runs pip for each entry:

opentelemetry-bootstrap -a install

The connection to Alloy is all environment variables, so put them in a launcher script rather than retyping them every time you restart the app.

vim ~/shop-api/run-app.sh

Change the cd path to your own home directory. Logs need no extra switch, because the logging instrumentation that bootstrap installed attaches an OTLP handler to the root logger by default. Older guides set OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true; the SDK now marks that variable deprecated, and setting it makes the logging instrumentation skip its own handler in favour of the SDK’s old one. The one logging variable we do set, OTEL_PYTHON_LOG_CODE_ATTRIBUTES, adds the file, function and line number to each record, which the handler leaves out unless asked:

cd /home/eugene/shop-api
. .venv/bin/activate
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_PYTHON_LOG_CODE_ATTRIBUTES=true
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab
export OTEL_METRIC_EXPORT_INTERVAL=5000
exec opentelemetry-instrument --service_name shop-api uvicorn app:app --port 8000

We use OTLP over HTTP on 4318 because it passes through proxies and load balancers without the HTTP/2 requirements of gRPC. The 5 second metric interval is for the lab only; the SDK default of 60 seconds is fine in production and costs far less. Start the app in one terminal.

bash ~/shop-api/run-app.sh

In a second terminal, send it steady traffic. This loop hits the checkout endpoint a little over twice a second with random order IDs:

while true; do curl -s -o /dev/null localhost:8000/checkout/$((RANDOM%9000+1)); sleep 0.4; done

Ask Tempo for recent traces from the service before you open Grafana at all. If this comes back empty, the problem is between the app and Tempo, and no Grafana setting will fix it.

curl -s "localhost:3200/api/search?tags=service.name%3Dshop-api&limit=3" | python3 -m json.tool | head -30

Each trace root is named after the FastAPI route template, not the concrete URL, which keeps span names low in cardinality. The block below is trimmed to the first two traces; the metrics object at the end of the full response said Tempo inspected 61 traces to answer, so data had been flowing for a while.

{
    "traces": [
        {
            "traceID": "10e87b961d6b7c7e81369c9332466393",
            "rootServiceName": "shop-api",
            "rootTraceName": "GET /checkout/{order_id}",
            "startTimeUnixNano": "1794488952322045208",
            "durationMs": 182
        },
        {
            "traceID": "45462d8c1ab8080a1b2b86196fe2bbcf",
            "rootServiceName": "shop-api",
            "rootTraceName": "GET /checkout/{order_id}",
            "startTimeUnixNano": "1794488951213792633",
            "durationMs": 268
        },

Loki should have the log lines with the trace context attached. Query the stream for the service directly, again skipping Grafana so a data source setting cannot hide the result.

curl -s -G localhost:3100/loki/api/v1/query_range --data-urlencode 'query={service_name="shop-api"}' --data-urlencode limit=2 | python3 -m json.tool | head -30

Trimmed to selected metadata keys of one record, this is the proof that logs and traces now share an ID:

                "stream": {
                    "code_file_path": "/home/eugene/shop-api/app.py",
                    "code_function_name": "checkout",
                    "code_line_number": "21",
                    "deployment_environment": "lab",
                    "detected_level": "info",
                    "service_instance_id": "87b16849-8e3c-401d-a878-1ee6715000e1",
                    "service_name": "shop-api",
                    "severity_text": "INFO",
                    "span_id": "b0dbca4186ef4f83",
                    "telemetry_auto_version": "0.66b2",
                    "telemetry_sdk_language": "python",
                    "trace_id": "6db336e6a63a27434c3d5369d2a5d54b"
                },

We first captured that record with the deprecated SDK variable still set, then re-ran the app with the launcher above: 52 lines landed within about 15 seconds of the restart, with the same fields, code_* included. Not every key in that block is a stream label. Ask Loki for its labels:

curl -s localhost:3100/loki/api/v1/labels

Only three resource attributes are indexed, which Loki’s OTLP endpoint does by default for a short list that includes these:

{"status":"success","data":["deployment_environment","service_instance_id","service_name"]}

Everything else, trace_id, span_id and the code location among them, is structured metadata. That distinction decides how you query them, and getting it wrong is one of the broken links covered at the end. The metrics side gives you the older HTTP semantic convention names from the auto-instrumentation, in milliseconds.

        "http_client_duration_milliseconds_bucket",
        "http_client_duration_milliseconds_count",
        "http_client_duration_milliseconds_sum",
        "http_server_active_requests",
        "http_server_duration_milliseconds_bucket",
        "http_server_duration_milliseconds_count",
        "http_server_duration_milliseconds_sum",
        "http_server_response_size_bytes_bucket",
        "http_server_response_size_bytes_count",
        "http_server_response_size_bytes_sum",
        "target_info"

That list came from localhost:9009/prometheus/api/v1/label/__name__/values. Without a single line of tracing code, you already have request traces with client spans, request rate and latency metrics, and logs carrying trace IDs. What you don’t have is any business meaning: Tempo can tell you checkout took 400 ms, not which step inside it was slow.

Add manual spans and a latency histogram

Manual instrumentation runs alongside the auto-instrumentation, not instead of it. Your spans become children of the FastAPI request span, and your histogram goes out through the same OTLP exporter. Replace the app with the instrumented version.

vim ~/shop-api/app.py

Checkout now has a reserve-stock span and a charge-card span, each with order.id as an attribute. A declined payment records the exception and sets the span’s status to error, and the histogram records how long the whole handler took, labelled by outcome:

import asyncio
import logging
import random
import time

import httpx
from fastapi import FastAPI, HTTPException
from opentelemetry import metrics, trace
from opentelemetry.trace import Status, StatusCode

app = FastAPI(title="shop-api")
logger = logging.getLogger("shop-api")
logging.basicConfig(level=logging.INFO)

tracer = trace.get_tracer("shop-api")
meter = metrics.get_meter("shop-api")
checkout_duration = meter.create_histogram(
    "shop.checkout.duration",
    unit="s",
    description="Checkout handler duration",
    explicit_bucket_boundaries_advisory=[0.025, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 1.0],
)


@app.get("/inventory/{item_id}")
async def inventory(item_id: int):
    await asyncio.sleep(random.uniform(0.02, 0.08))
    return {"item": item_id, "in_stock": random.random() > 0.1}


@app.get("/checkout/{order_id}")
async def checkout(order_id: int):
    start = time.perf_counter()
    outcome = "ok"
    logger.info("checkout started order_id=%s", order_id)
    try:
        with tracer.start_as_current_span("reserve-stock") as span:
            span.set_attribute("order.id", order_id)
            await asyncio.sleep(random.uniform(0.01, 0.15))
            if random.random() < 0.5:
                async with httpx.AsyncClient() as client:
                    await client.get(f"http://localhost:8000/inventory/{order_id}")
            span.add_event("stock reserved", {"order.id": order_id})
            logger.info("stock reserved order_id=%s", order_id)

        with tracer.start_as_current_span("charge-card") as span:
            span.set_attribute("order.id", order_id)
            span.set_attribute("payment.provider", "examplepay")
            await asyncio.sleep(random.uniform(0.01, 0.25))
            if random.random() < 0.08:
                err = RuntimeError("payment declined")
                span.record_exception(err)
                span.set_status(Status(StatusCode.ERROR, "payment declined"))
                logger.error("payment declined order_id=%s", order_id)
                outcome = "declined"
                raise HTTPException(status_code=500, detail="payment declined")
            span.add_event("charge authorised", {"payment.provider": "examplepay"})
            logger.info("card charged order_id=%s", order_id)
        return {"order": order_id, "status": "paid"}
    finally:
        checkout_duration.record(time.perf_counter() - start, {"outcome": outcome})

Two details carry the correlation. The histogram is recorded inside the request span, so the SDK can attach that span’s trace ID to the measurement as an exemplar. The SDK’s exemplar filter defaults to trace_based (we read it in sdk/metrics/_internal/__init__.py of the installed package), which keeps measurements taken inside a sampled span. The bucket boundaries are an advisory hint, so the histogram has useful resolution around the 100 to 500 ms range checkout actually lives in, instead of the SDK’s default buckets.

Restart the launcher with Ctrl+C and bash ~/shop-api/run-app.sh, leave the traffic loop running, and check that the custom histogram reached Mimir under the name you expect:

curl -s localhost:9009/prometheus/api/v1/label/__name__/values | python3 -m json.tool | grep -E "shop|target_info"

The dotted OTel name became Prometheus style, with the unit appended as _seconds. Query this name, not the dotted one from the code, in every panel and alert.

        "shop_checkout_duration_seconds_bucket",
        "shop_checkout_duration_seconds_count",
        "shop_checkout_duration_seconds_sum",
        "target_info"

Now the check most guides skip: ask Mimir for the exemplars on that histogram directly. If this returns an empty data array, Grafana’s Exemplars switch will show nothing either:

S=$(date -d "-3 min" +%s); E=$(date +%s)
curl -s -G localhost:9009/prometheus/api/v1/query_exemplars --data-urlencode "query=shop_checkout_duration_seconds_bucket" --data-urlencode start=$S --data-urlencode end=$E | head -c 600

Each exemplar carries a trace_id and span_id next to the measured value, and the series labels include the outcome attribute from the code:

{"status":"success","data":[{"seriesLabels":{"__name__":"shop_checkout_duration_seconds_bucket","instance":"397ff6c8-a2ef-438b-af1f-2f23bfd9a140","job":"shop-api","le":"0.05","otel_scope_name":"shop-api","outcome":"ok"},"exemplars":[{"labels":{"span_id":"3114f83f81e548f4","trace_id":"9e09ba07ce1b1cf67279b0fcdf52c6a6"},"value":"0.038940397000033045","timestamp":1794489450.894},{"labels":{"span_id":"0473c5706c8df9ce","trace_id":"e711a697e59df33982a0a2aaeb486275"},"value":"0.04884532500000205","timestamp":1794489461.933}

The label is trace_id, which is the name Grafana’s Mimir data source needs in the next step. Our p95 for checkout over that window was 0.422 s, which lines up with the random sleeps in the handler, so the numbers are real and not an artefact of the buckets.

Point Grafana at all three

This is where the three backends become one tool. Each Grafana data source holds one half of a link. Mimir knows which label holds a trace ID, Tempo knows how to build a Loki query from a span, and Loki knows which field to turn into a Tempo link. Provision all three from a file so the links survive a rebuild.

vim ~/lgtm/grafana/provisioning/datasources/datasources.yaml

Look closely at the double dollar signs before you paste. They are not a typo, and the next paragraph explains why the file breaks without them.

apiVersion: 1
datasources:
  - name: Mimir
    type: prometheus
    uid: mimir
    access: proxy
    url: http://mimir:9009/prometheus
    isDefault: true
    jsonData:
      httpMethod: POST
      exemplarTraceIdDestinations:
        - name: trace_id
          datasourceUid: tempo
  - name: Tempo
    type: tempo
    uid: tempo
    access: proxy
    url: http://tempo:3200
    jsonData:
      tracesToLogsV2:
        datasourceUid: loki
        tags:
          - key: service.name
            value: service_name
        spanStartTimeShift: "-5m"
        spanEndTimeShift: "5m"
        filterByTraceID: false
        filterBySpanID: false
        customQuery: true
        query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__span.traceId}"'
  - name: Loki
    type: loki
    uid: loki
    access: proxy
    url: http://loki:3100
    jsonData:
      derivedFields:
        - name: TraceID
          matcherType: label
          matcherRegex: trace_id
          datasourceUid: tempo
          url: "$${__value.raw}"

Grafana expands ${...} in provisioning file values as environment variables. Written with a single dollar sign, ${__span.traceId} is looked up as an environment variable, found empty, and stored as nothing; our first attempt saved the Tempo query as {service_name=""} | trace_id="" and threw no error. Escaping it as $${...} passes the macro through to the data source intact. Restart Grafana to load the file:

docker compose -f ~/lgtm/compose.yaml restart grafana

Log in at http://10.0.1.50:3000 as admin with the password from grafana-pw, then open Connections, Data sources. With editable left unset, the provisioned sources can’t be saved from the UI, which is what you want, but the pages are still the best place to confirm the values landed. Start with Mimir and scroll to the Exemplars section:

Grafana Mimir data source Exemplars settings linking the trace_id label to the Tempo data source
  1. 1Data source: Tempo
  2. 2Label name: trace_id

Two values must match the other side of the link. Data source: Tempo sends exemplar clicks to the Tempo data source, and Label name: trace_id must be the exact label Mimir returned in the query_exemplars output above. A different spelling there, such as traceID, gives you exemplar dots that don’t open anything, because Grafana looks the label up by exact name and silently skips the link when it is missing. The Tempo data source holds the trace-to-logs half:

Grafana Tempo data source Trace to logs settings with the Loki data source and a custom query on trace_id
  1. 1Data source: Loki
  2. 2Use custom query
  3. 3Query on trace_id

Under Trace to logs, check three things in order:

  1. Data source: Loki is the target for span log lookups.
  2. Use custom query is switched on.
  3. Query on trace_id shows the full LogQL with ${__span.traceId}, not an empty trace_id="".

Is the custom query necessary? Honestly, not on this Grafana. We expected the default trace ID filter to miss logs that keep trace_id in structured metadata, tested it against Loki directly, and it returned the same 3 lines as the explicit filter. We kept the custom query because it scopes the lookup to the span’s own service stream, which matters once ten services share one Loki. Loki holds the last link, the derived field:

Grafana Loki data source derived field named TraceID matching the trace_id label with an internal link to Tempo
  1. 1Name: TraceID
  2. 2Type Label, trace_id
  3. 3Internal link: Tempo

The derived field is Name: TraceID, matched as Type Label, trace_id so Grafana reads the structured metadata field directly instead of running a regex over the log line, with an Internal link: Tempo. A regex matcher would find nothing here, because the OTLP log body is just the message text and the ID never appears in it. Grafana itself is covered in more depth in our guide to installing Grafana with Nginx and SSL, which is how you’d front this port on a real network.

Verify one trace end to end

With the traffic loop still running, walk the loop the way you would during an incident: start at a latency spike, land on the trace, finish on the logs. The exemplar and trace screenshots below follow trace 5c00746510c3bece8eebcf88b08ad130; the logs leg was captured on a second run of the same lab, so its ID differs. Open Explore, choose the Mimir data source, and run the p95 query for the checkout histogram:

histogram_quantile(0.95, sum by (le) (rate(shop_checkout_duration_seconds_bucket[1m])))

Turn on the Exemplars switch under the query editor. Exemplar dots appear over the line, each one a real request whose trace you can open. If the switch is on and no dots appear, jump to the first troubleshooting entry before touching Grafana, because the cause is almost always in Mimir.

Grafana Explore p95 checkout latency from Mimir with the Exemplars switch on and exemplar dots over the line

The dots sit at their bucket’s measured value, so the high ones are the slow checkouts worth opening. If you need a refresher on why the query wraps rate() inside histogram_quantile, the PromQL cheat sheet has the pattern. Hover a dot near the top of the graph:

Grafana exemplar tooltip showing trace_id and the Query with Tempo link

The tooltip shows the exemplar value, 0.432 s in the 0.5 bucket, and its trace_id. That request was slower than the p95, so it is exactly the kind you would open during an incident. Click Query with Tempo and Explore splits, with the full trace on the right.

Grafana Tempo trace view with the manual reserve-stock and charge-card spans and the charge-card span attributes
  1. 1reserve-stock span
  2. 2charge-card span
  3. 3Span attributes
  4. 4Related logs

This is where the manual spans pay for themselves, because the auto-instrumented trace alone had no span that named a checkout step. Read the trace from the top.

  1. The reserve-stock span sits under the FastAPI request span, with the httpx client call to inventory nested inside it when that branch ran.
  2. The charge-card span follows it, so you can see at a glance which of the two steps ate the 432 ms.
  3. Expand charge-card and the Span attributes show order.id and payment.provider from the code.
  4. Click Related logs on the span to run the Tempo data source’s Loki query for this trace.

In Grafana 13 the span button reads Related logs; older guides call it Logs for this span, and it is the same feature. The Loki pane opens with the custom query filled in from the service and trace ID of the span. The time range is the span widened by five minutes each side, so logs written slightly before or after the span still match.

Grafana Loki pane opened by Related logs, with the card charged line expanded and its TraceID link to Tempo
  1. 1Query filled in from the span
  2. 2card charged log line
  3. 3TraceID link to Tempo

That is the pane Related logs opened from the charge-card span of trace d23a343fb05ea0ea209b53627fb4bddc on our second run. The Query filled in from the span is the custom trace-to-logs query with the service name and trace ID substituted, so nobody typed it. Four log lines came back for this checkout, ending with the card charged log line for order_id=6543, which ties the order number in the logs to a business transaction. Expand that line and the TraceID link to Tempo sits under Links. Click it:

Grafana Explore split view with the Tempo trace opened from the Loki TraceID link beside the log lines
  1. 1Same trace ID as the log line
  2. 2charge-card span in the opened trace

Explore splits and Tempo opens the trace beside the logs. The header carries the Same trace ID as the log line, d23a343fb05ea0ea209b53627fb4bddc, with 9 spans over 333 ms, and the charge-card span in the opened trace is the step that wrote the log. That closes the loop from logs back to traces. When a user reports a failed order and all you have is the order number, you can search Loki for it and land on the trace in one click.

If the Tempo backend later moves into a cluster, the same data source settings apply; the Tempo on Kubernetes guide covers that deployment, and only the URL changes. To turn these three signals into service level objectives with burn-rate alerts, the guide to an open source observability stack with SLOs and error budgets builds on this pipeline. For background reading on how these signals fit together beyond the wiring, there’s a list of observability and OpenTelemetry books we’d start with.

Each failure below breaks one link without breaking the signals themselves, which is why they’re hard to spot: traces, metrics and logs all arrive, and only the jump between them dies. All of them happened in our lab while building this.

Exemplars panel is empty and query_exemplars returns “data”:[]

Metrics arrive and the latency graph draws, but the Exemplars switch adds no dots, and Mimir answers {"status":"success","data":[]}. The Mimir counters show where the exemplars go.

curl -s localhost:9009/metrics | grep -i exemplar | grep -v "^#" | grep -v bucket

The remote_write route this guide uses gave us only that empty data:[] at the default limit. For the counters we switched to Mimir’s OTLP route, still at the default limit, and trimmed the output to the three that tell the story: the distributor counted 122 exemplars in and accepted none:

cortex_distributor_exemplars_in_total{user="anonymous"} 122
cortex_distributor_received_exemplars_total{user="anonymous"} 0
cortex_ingester_tsdb_exemplar_exemplars_appended_total{user="anonymous"} 0

That’s max_global_exemplars_per_user: 0, the default, confirmed in localhost:9009/config on our instance. Set it under limits as in the Mimir config above and restart Mimir. After the change, in our OTLP route test, cortex_distributor_received_exemplars_total read 114 against 114 in, and query_exemplars returned data on both routes. Exemplars sent before the change are gone, so generate fresh traffic before you check again.

Related logs opens an empty Loki query with trace_id=””

The button exists, but the query it runs has empty values and returns nothing. Read back what Grafana actually stored, since the UI form is easy to misread.

curl -s -u admin:"$(cat ~/lgtm/grafana-pw)" localhost:3000/api/datasources/uid/tempo | jq .jsonData.tracesToLogsV2.query

Our unescaped provisioning file produced a query with both values blank, and Grafana raised no warning when it loaded it.

"{service_name=\"\"} | trace_id=\"\""

The Loki derived field URL was stored as "" by the same mistake, which makes the TraceID link vanish from log lines. Change every ${__span...} and ${__value.raw} in the provisioning file to $${...} and restart Grafana. Data sources created by hand in the UI don’t have this problem, only file provisioning does.

A Loki line filter on the trace ID returns 0 lines

Searching logs with |= "<trace id>" is the habit from Promtail days, when the ID was printed in the log line. With OTLP logs, the ID lives in structured metadata, so the line filter has nothing to match. On the same trace in our lab, the two forms gave different answers.

naive line filter |=trace id:
0 lines
structured metadata filter | trace_id=:
3 lines

Use a label filter after the stream selector, {service_name="shop-api"} | trace_id="...", in ad hoc queries, alerts and any custom trace-to-logs query you write. The line filter does not fail loudly, so a saved search built on it keeps returning nothing and looks like a quiet service rather than a wrong query.

Tempo exits with “field ingester not found in type app.Config”

A Tempo config copied from a 2.x example, with ingester.max_block_duration and compactor.compaction.block_retention, stops the container immediately with a YAML parse error.

failed parsing config: failed to parse configFile /t.yaml: yaml: unmarshal errors:
  line 9: field ingester not found in type app.Config
  line 11: field compactor not found in type app.Config

Remove both blocks; the minimal config in this guide starts cleanly on the 3.x line. If you need retention or block tuning, take the key names from the Tempo configuration reference for your exact release rather than an old blog post, since the 3.x architecture moved those jobs to different components.

Dashboards show no data after switching metric routes

Moving from the remote_write route to Mimir’s OTLP endpoint, or back, renames every metric with a unit. http_server_duration_milliseconds_bucket became http_server_duration_bucket in our test, so every panel built on the old name went blank while the data kept flowing. Pick one route per environment and list the names with /prometheus/api/v1/label/__name__/values before you build dashboards on them.

Keep reading

Install DeepSeek Harness (dsh) on Linux: Ubuntu, Debian, Rocky AI Install DeepSeek Harness (dsh) on Linux: Ubuntu, Debian, Rocky Best UI Applications for Managing Docker Containers Containers Best UI Applications for Managing Docker Containers DeepSeek Harness With Ollama: Local Model Setup, vLLM, llama.cpp AI DeepSeek Harness With Ollama: Local Model Setup, vLLM, llama.cpp OpenShift 5 New Features Tested on a Single Node Cluster Containers OpenShift 5 New Features Tested on a Single Node Cluster Install LocalAI on Linux: Docker, Binary and GPU Setup AI Install LocalAI on Linux: Docker, Binary and GPU Setup Manage OpenShift / OKD Users with  HTPasswd Identity Provider Openshift Manage OpenShift / OKD Users with HTPasswd Identity Provider

Leave a Comment

Press ESC to close