Skip to main content

Data and monitoring · Intermediate · 26 min

Trace a Python web app with OpenTelemetry

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · FastAPI 0.165.0 · opentelemetry-sdk 1.45.2 · OpenTelemetry Collector 0.166.0

You will add OpenTelemetry tracing to a FastAPI app that calls a second service with httpx, with named resources, your own spans, events and recorded errors, exported first to the terminal and then to a Collector, with sampling set from environment variables.

On this page

Metrics tell you that the quote endpoint got slow. A trace tells you why: it records one request as a tree of timed steps, called spans, across every service the request touched. You can see that 300 of the 305 milliseconds went on pricing, and that the call to the rates service took 4.

OpenTelemetry is the vendor-neutral standard for producing that data. Its Python SDK creates spans, ready-made instrumentation libraries create them for frameworks such as FastAPI and httpx, and an exporter sends them somewhere. Because the format (OTLP) is open, the same code can feed Jaeger, Grafana Tempo or a paid service by changing configuration, not code.

In this tutorial you trace a small quote API. It calls a separate rates service over HTTP and does some slow pricing work. You name the service with resource attributes, switch on automatic spans for FastAPI and httpx, add your own span with attributes and an event, record a failure, print everything to the terminal, then send it over OTLP to an OpenTelemetry Collector and turn on sampling with environment variables. If spans and traces are new to you, read metrics, logs and traces and when to use each first.

Step 1 · Create the project and the two services

Make a throwaway project folder and add the web stack. The exact versions keep what you see in line with this page:

Bash
mkdir -p ~/otel-demo
cd ~/otel-demo
uv init --no-package --python 3.15
uv add "fastapi==0.165.0" "uvicorn==0.54.0" "httpx==0.29.0"

uv init also creates a main.py that this tutorial does not use.

The first service is a stand-in for an exchange-rate provider. It uses only the standard library, answers GET /rates/<city> on port 8001 with a rate, returns 404 for cities it does not know, and prints the traceparent header of every request it receives. That header is how tracing crosses from one service to the next, and you will look at it in step 3:

Bash
cat > rates.py <<'PY'
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

RATES = {"lagos": 1.075, "nairobi": 1.16, "accra": 1.15, "london": 1.2}


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        city = self.path.rsplit("/", 1)[-1].lower()
        print(f"{self.path} traceparent={self.headers.get('traceparent')}", flush=True)
        if city not in RATES:
            self.send_response(404)
            self.end_headers()
            return
        body = json.dumps({"city": city, "rate": RATES[city]}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", 8001), Handler).serve_forever()
PY

The quote API is split into three small files so you can change one at a time later. rates_client.py holds one shared httpx client and the lookup; pricing.py holds the slow work, a 300 millisecond pause standing in for a database query; app.py holds the routes:

Bash
cat > rates_client.py <<'PY'
import httpx

http = httpx.Client(base_url="http://127.0.0.1:8001", timeout=2.0)


def lookup_rate(city: str) -> float | None:
    try:
        resp = http.get(f"/rates/{city}")
        resp.raise_for_status()
    except httpx.HTTPError:
        return None
    return resp.json()["rate"]
PY
cat > pricing.py <<'PY'
import time


def price_basket(items: int) -> float:
    time.sleep(0.3)  # stands in for a slow database query
    return items * 12.5
PY
cat > app.py <<'PY'
from fastapi import FastAPI, HTTPException

from pricing import price_basket
from rates_client import lookup_rate

app = FastAPI(title="Quote API")


@app.get("/quote")
def quote(city: str, items: int = 3):
    rate = lookup_rate(city)
    if rate is None:
        raise HTTPException(status_code=502, detail="Rates service unavailable")
    return {"city": city, "items": items, "total": round(price_basket(items) * rate, 2)}


@app.get("/healthz")
def healthz():
    return {"ok": True}
PY

Start the rates service in your first terminal and leave it running. tee shows its output and also saves it to rates.log, so you can search it later:

Bash
cd ~/otel-demo
uv run python rates.py | tee rates.log

Start the app in your second terminal and leave it running too:

Bash
cd ~/otel-demo
uv run uvicorn app:app --host 127.0.0.1 --port 8000

Run the remaining commands in your fourth terminal, from ~/otel-demo. The third is for the Collector in step 6.

Check it worked

Bash
curl -s 'http://127.0.0.1:8000/quote?city=Lagos'
echo
curl -s -o /dev/null -w '%{http_code}\n' 'http://127.0.0.1:8000/quote?city=Atlantis'

The first command prints {"city":"Lagos","items":3,"total":40.31} after a short pause. The second prints 502: the rates service does not know Atlantis, so the app reports that its upstream failed.

Step 2 · Name the service and print spans to the terminal

Add the OpenTelemetry API and SDK, the OTLP exporter you will use in step 6, and the instrumentation libraries for FastAPI and httpx:

Bash
uv add "opentelemetry-api==1.45.2" "opentelemetry-sdk==1.45.2" \
  "opentelemetry-exporter-otlp-proto-http==1.45.2" \
  "opentelemetry-instrumentation-fastapi==0.66b2" \
  "opentelemetry-instrumentation-httpx==0.66b2"

The two numbering schemes are deliberate. The API and SDK are stable and versioned 1.x; the instrumentation libraries live in the separate contrib project, are still marked beta, and each 0.x release is built against one SDK release. Upgrade them together: 1.45 goes with 0.66b.

Now create telemetry.py. It does three jobs. It describes the process with a resource, the set of attributes attached to every span it sends. It installs a tracer provider with an exporter. And it switches on the instrumentation:

Bash
cat > telemetry.py <<'PY'
import os

from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
    ConsoleSpanExporter,
    SimpleSpanProcessor,
)


def setup_tracing(app: FastAPI) -> None:
    resource = Resource.create(
        {
            "service.name": "quote-api",
            "service.version": os.environ.get("APP_VERSION", "dev"),
        }
    )
    provider = TracerProvider(resource=resource)
    if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
        provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    else:
        provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
    trace.set_tracer_provider(provider)

    HTTPXClientInstrumentor().instrument()
    FastAPIInstrumentor.instrument_app(
        app, excluded_urls="healthz", exclude_spans=["receive", "send"]
    )
PY
cat >> app.py <<'PY'

from telemetry import setup_tracing

setup_tracing(app)
PY

The second command adds three lines to the end of app.py, so tracing is set up once the routes exist.

What each part does:

  • service.name is the one attribute every tracing back end groups by. Without it your spans arrive as unknown_service. service.version lets you compare a slow release with the one before it.
  • Resource.create also reads the OTEL_RESOURCE_ATTRIBUTES environment variable, so operators can add attributes such as the environment name without a code change. You will set one below.
  • With no OTLP endpoint configured, spans go to ConsoleSpanExporter, which prints each finished span as JSON. SimpleSpanProcessor exports every span the moment it ends, which suits a terminal. Step 6 switches to BatchSpanProcessor, which is what you want in production.
  • excluded_urls="healthz" stops load balancer health checks from filling your traces. exclude_spans drops two tiny internal spans per request that only record the ASGI messages being sent and received.

Stop the app with Ctrl+C in the second terminal and start it again with a version and an environment attribute:

Bash
APP_VERSION=1.0.0 OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=dev \
  uv run uvicorn app:app --host 127.0.0.1 --port 8000

Check it worked

Bash
curl -s 'http://127.0.0.1:8000/quote?city=Lagos'

The second terminal now prints JSON blocks before each access log line. The last one is the server span, something like this (shortened):

JSON
{
    "name": "GET /quote",
    "context": {
        "trace_id": "0x41feafa4fb99829e114ad03843e6b70b",
        "span_id": "0xade80bc1d74274c2",
        "trace_state": "[]"
    },
    "kind": "SpanKind.SERVER",
    "parent_id": null,
    "attributes": {
        "http.method": "GET",
        "http.route": "/quote",
        "http.url": "http://127.0.0.1:8000/quote?city=Lagos",
        "http.status_code": 200
    },
    "resource": {
        "attributes": {
            "deployment.environment.name": "dev",
            "service.name": "quote-api",
            "service.version": "1.0.0"
        }
    }
}

The span is named after the route template, /quote, not the full URL, so all quotes group together. parent_id is null because this span is the root of the trace. Your IDs will differ. There is no span for the /healthz request the app answered earlier.

Note that http.url includes the query string. Never pass tokens, phone numbers or other personal data in URLs: they end up in every trace.

Step 3 · Follow one request into the rates service

Look again at the output from that request. Above the server span is a second span, named GET, with "kind": "SpanKind.CLIENT". The httpx instrumentation created it for the outgoing call to the rates service. It shares the server span's trace_id, and its parent_id is the server span's span_id. That parent link is how a back end draws the tree.

The client span also did something you cannot see in the JSON: it added a traceparent header to the outgoing request. Show the last line the rates service printed:

Bash
tail -n 1 rates.log

Check it worked

The line looks like /rates/Lagos traceparent=00-41feafa4fb99829e114ad03843e6b70b-5a09594607f5f296-03. The header has four parts separated by hyphens, defined by the W3C Trace Context standard:

  • 00 is the format version.
  • The 32 hex characters are the trace ID. They match the trace_id in the app's spans, without the 0x.
  • The next 16 are the span ID of the client span that made the call.
  • The last two are flags. An odd number, here 03, means the trace is sampled and being recorded.

If the rates service were also instrumented, it would read this header and make its spans children of the client span, and the trace would continue across both services. Any OpenTelemetry SDK, in any language, does this.

Step 4 · Wrap the slow work in your own span

Automatic spans cover the edges of the service: requests in and calls out. Everything between them is one block of unexplained time. In this app that time is price_basket, so give it a span of its own.

Replace pricing.py:

Bash
cat > pricing.py <<'PY'
import time

from opentelemetry import trace

tracer = trace.get_tracer(__name__)


def price_basket(items: int) -> float:
    with tracer.start_as_current_span("price_basket") as span:
        span.set_attribute("basket.items", items)
        time.sleep(0.3)  # stands in for a slow database query
        span.add_event("prices loaded", {"price.rows": items})
        total = items * 12.5
        span.set_attribute("basket.subtotal", total)
        return total
PY
  • trace.get_tracer(__name__) returns a tracer named after the module, so spans show which part of your code made them.
  • start_as_current_span starts a span, makes it the current one while the block runs, and ends it when the block exits. Because the FastAPI server span is current when price_basket is called, the new span becomes its child automatically.
  • Attributes describe the whole span and are what you filter and group by later: show me slow price_basket spans where basket.items is over 20. Prefix your own with a namespace, as here, so they never clash with the standard names. Keep personal data, such as email addresses, out of them.
  • An event is a timestamped note inside a span. It shows where in the 300 milliseconds something happened, without the cost of another span.

Restart the app in the second terminal with the same command as before, so it loads the new code:

Bash
APP_VERSION=1.0.0 OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=dev \
  uv run uvicorn app:app --host 127.0.0.1 --port 8000

Check it worked

Bash
curl -s 'http://127.0.0.1:8000/quote?city=Nairobi&items=5'

The response is {"city":"Nairobi","items":5,"total":72.5}. In the second terminal a span named price_basket appears, with "kind": "SpanKind.INTERNAL", "basket.items": 5, "basket.subtotal": 62.5, and an events list holding prices loaded. Its start_time and end_time are about 0.3 seconds apart, and its parent_id is the span_id of the GET /quote span printed after it. Spans print as they end, so children always come before their parent.

Step 5 · Record a failure on a span

When the rates service returns 404, the app answers 502 and the server span is marked as an error. But nothing says why. lookup_rate catches the httpx exception and returns None, so the reason is lost. Give the lookup its own span and record the exception on it before you handle it.

Replace rates_client.py:

Bash
cat > rates_client.py <<'PY'
import httpx
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer(__name__)
http = httpx.Client(base_url="http://127.0.0.1:8001", timeout=2.0)


def lookup_rate(city: str) -> float | None:
    with tracer.start_as_current_span("lookup_rate") as span:
        span.set_attribute("quote.city", city)
        try:
            resp = http.get(f"/rates/{city}")
            resp.raise_for_status()
        except httpx.HTTPError as exc:
            span.record_exception(exc)
            span.set_status(Status(StatusCode.ERROR, "rate lookup failed"))
            return None
        return resp.json()["rate"]
PY

record_exception adds an event named exception with the type, message and stack trace. set_status marks the span as failed, which is what back ends count and colour red. Both calls are needed here because the code handles the error itself. If an exception escapes a start_as_current_span block instead, the SDK records it and sets the status for you.

The client is created when the module loads, before setup_tracing runs. That is fine: the httpx instrumentation patches httpx's transport class, so clients that already exist are traced too.

Restart the app in the second terminal with the same command again:

Bash
APP_VERSION=1.0.0 OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=dev \
  uv run uvicorn app:app --host 127.0.0.1 --port 8000

Check it worked

Bash
curl -s 'http://127.0.0.1:8000/quote?city=Atlantis'

The response is {"detail":"Rates service unavailable"}. In the second terminal the trace now has three spans: the client GET with http.status_code 404, then lookup_rate with "quote.city": "Atlantis", a status of "status_code": "ERROR" with "description": "rate lookup failed", and an exception event whose exception.type is httpx.HTTPStatusError, and last the GET /quote server span with status ERROR and http.status_code 502. Anyone reading the trace now sees which call failed and the exact error.

Step 6 · Send spans over OTLP to a Collector

The terminal is no place to keep traces. In production the SDK sends them over OTLP, OpenTelemetry's own protocol, usually to an OpenTelemetry Collector running next to the app. The Collector receives, filters and forwards data to whichever back end you use, so changing back end never means redeploying the app.

Download the core Collector distribution for Linux, check it against the published SHA-256 sum and unpack it into the project:

Bash
OTELCOL_VERSION=0.166.0
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/aarch64/arm64/')"
FILE="otelcol_${OTELCOL_VERSION}_linux_${ARCH}.tar.gz"
BASE="https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v${OTELCOL_VERSION}"
curl -fsSLO "$BASE/$FILE"
curl -fsSLO "$BASE/$FILE.sha256"
echo "$(cat "$FILE.sha256")  $FILE" | sha256sum -c
mkdir -p collector
tar -xzf "$FILE" -C collector
./collector/otelcol --version

A hand-installed binary gets no security updates from apt. To upgrade, run the same commands with a newer OTELCOL_VERSION from the releases page. Running the Collector as a pipeline covers installing it as a service.

Write a minimal configuration. It receives OTLP over HTTP on port 4318, on the loopback address only, and hands every span to the debug exporter, which prints it in full:

Bash
cat > collector.yaml <<'YAML'
receivers:
  otlp:
    protocols:
      http:
        endpoint: 127.0.0.1:4318

exporters:
  debug:
    verbosity: detailed

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [debug]
YAML
./collector/otelcol validate --config collector.yaml

validate prints nothing and exits cleanly when the file is correct.

Start the Collector in your third terminal, saving its output to collector.log:

Bash
cd ~/otel-demo
./collector/otelcol --config collector.yaml 2>&1 | tee collector.log

Then restart the app in the second terminal with an OTLP endpoint. telemetry.py sees the variable and switches to OTLPSpanExporter, which reads the same variable and posts to its /v1/traces path:

Bash
APP_VERSION=1.0.0 OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=dev \
  OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
  uv run uvicorn app:app --host 127.0.0.1 --port 8000

The app terminal no longer prints spans. BatchSpanProcessor queues them and sends them in batches, by default every 5 seconds or sooner when 512 are waiting, on a background thread so requests never wait on the network.

Check it worked

Bash
curl -s 'http://127.0.0.1:8000/quote?city=Accra'
echo
sleep 6
grep -E '^ +Name +: ' collector.log | sort | uniq -c
grep -m 1 'service.name' collector.log

After the pause the first grep lists the four span names from that request, GET, GET /quote, lookup_rate and price_basket, each with a count of 1. The second prints -> service.name: Str(quote-api): the resource arrived with the spans. Scroll through the third terminal to see each span laid out with its trace ID, parent ID, attributes and events.

If nothing arrives, check the app terminal. The exporter logs a warning when it cannot reach the endpoint and retries, and spans it cannot deliver are dropped, never sent back to the request.

Step 7 · Keep a fraction of traces with sampling

Recording every request is right while you learn. On a busy service it means paying to send, store and search millions of nearly identical traces. Sampling keeps a share of them. It matters even more where bandwidth is metered: if your servers ship telemetry over a link billed by the gigabyte, as many teams on prepaid or mobile backhaul connections do, every unsampled trace is data you do not pay for.

The SDK reads its sampler from two environment variables, so you can change the rate without touching code:

  • OTEL_TRACES_SAMPLER=parentbased_traceidratio keeps a share of new traces, chosen from the trace ID. Because the choice is made from the ID, every service that sees the same trace makes the same decision.
  • OTEL_TRACES_SAMPLER_ARG=0.25 sets that share to 25 per cent.
  • The parentbased_ part means that when a request arrives with a traceparent header, the app follows the caller's decision instead of making its own, so traces are never cut in half.

The default is parentbased_always_on, which is why every request has been traced so far. Restart the app in the second terminal with the sampler set:

Bash
APP_VERSION=1.0.0 OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=dev \
  OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
  OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.25 \
  uv run uvicorn app:app --host 127.0.0.1 --port 8000

Check it worked

Send 40 requests and count how many new traces reach the Collector. The 40 requests take about 15 seconds:

Bash
before="$(grep -cE '^ +Name +: GET /quote$' collector.log)"
for i in $(seq 1 40); do curl -s -o /dev/null 'http://127.0.0.1:8000/quote?city=London&items=1'; done
sleep 7
after="$(grep -cE '^ +Name +: GET /quote$' collector.log)"
echo "$((after - before)) of 40 requests were traced"
grep -c 'London traceparent=00-.*-0[02]$' rates.log

The first line reports a number close to 10, such as 9 of 40 requests were traced; the exact figure changes from run to run. The second number is the requests that were not sampled, about 30. Their traceparent headers still reached the rates service, but with flags 00 or 02, which tell it not to record this trace either.

Sampling is a trade. A ratio sampler drops slow and failed requests as readily as fast ones. To keep every error, sample in the Collector after a trace completes, with tail sampling, which running the Collector as a pipeline introduces.

Step 8 · Stop everything and remove the demo

Stop the Collector, the app and the rates service with Ctrl+C in their terminals.

The next command deletes ~/otel-demo and everything in it: the code, the virtual environment, the Collector download and the log files. Copy out anything you want to keep first.

Bash
cd ~
rm -rf ~/otel-demo

Check it worked

Bash
ls ~/otel-demo 2>/dev/null || echo "removed"
curl -s -o /dev/null --connect-timeout 2 http://127.0.0.1:8000/healthz || echo "app stopped"

The commands print removed and app stopped.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.