Frameworks 13 min read

OpenTelemetry for FastAPI: tracing setup and fixes

Native FastAPI telemetry, the zero-code agent and FastAPIInstrumentor: which one to use, how to run it under uvicorn and gunicorn, and how to fix missing, duplicate and badly named spans. Tested with FastAPI 0.165 and OpenTelemetry 1.45 (November 2026).

David Granzin By David Granzin

Short answer: run your app under the OpenTelemetry agent. It needs no code changes, works on every FastAPI version, and traces incoming requests, httpx calls and database queries in one step.

Quick start

pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install

export OTEL_SERVICE_NAME=orders
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

opentelemetry-instrument uvicorn main:app

Send a request and a trace named after the route, such as GET /orders/{order_id}, reaches the endpoint within five seconds. Keep the protocol line: the Python agent exports over gRPC unless told otherwise.

Most tutorials start with FastAPIInstrumentor.instrument_app(app). That still works, but since FastAPI 0.142.0 the framework creates request spans itself, and the older instrumentation has to coexist with it.

Key takeaways

  • Use the agent by default, native FastAPI telemetry when you only want framework spans, and SDK setup in code for custom samplers or processors.
  • Set OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf when your endpoint is port 4318 or an HTTPS URL.
  • uvicorn skips atexit hooks on SIGTERM. Shut the provider down in the lifespan or lose the last batch on every deploy.
  • Group and alert on http.route, never on the raw path.

Three ways to instrument FastAPI

All three feed the same pipeline. They differ in who creates the spans and who configures the provider.

Native FastAPIZero-code agentFastAPIInstrumentor
NeedsFastAPI 0.142+opentelemetry-distroopentelemetry-instrumentation-fastapi
Code changesNoneNoneOne call per app
Server spansYes, plus dependency, endpoint and serialization spansYesYes
httpx, SQLAlchemy, RedisNoYesSeparate instrumentors
HTTP attribute namesStable (http.request.method)Old (http.method) unless OTEL_SEMCONV_STABILITY_OPT_IN=http
Skip health checksexclude functionOTEL_PYTHON_FASTAPI_EXCLUDED_URLSexcluded_urls

They combine. When the contrib FastAPI instrumentation is active on an app, FastAPI detects its middleware and switches its own tracing, metrics and logs off for that app, so you never get two server spans.

Native tracing in FastAPI 0.142+

FastAPI records telemetry through opentelemetry-api on every request, which is a no-op until an SDK exists. The standard extra adds the SDK and the OTLP HTTP exporter, and FASTAPI_OTEL_AUTO_CONFIGURE wires them up from the usual OTEL_* settings:

pip install "fastapi[standard]"

export FASTAPI_OTEL_AUTO_CONFIGURE=true
export OTEL_SERVICE_NAME=orders
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

fastapi run main.py

After one call to an endpoint that raised, a local sink received all three signals:

POST /v1/traces   application/x-protobuf
POST /v1/metrics  application/x-protobuf
POST /v1/logs     application/x-protobuf
  • Spans. A GET /orders/{order_id} server span with fastapi.dependencies, fastapi.endpoint and fastapi.serialization children. telemetry={"operation_spans": False} keeps only the server span.
  • Logs. Unhandled exceptions are exported as log records with the stack trace. Check them for sensitive data or pass "logs": False.
  • Export is opt-in. Since 0.143.0 FastAPI adds exporters only with FASTAPI_OTEL_AUTO_CONFIGURE=true or telemetry={"auto_configure": True}.
  • HTTP only. With OTEL_EXPORTER_OTLP_PROTOCOL=grpc, automatic setup logs a warning at startup and exports nothing.
  • Existing providers win. If your code or the agent already set a global provider, FastAPI writes to it. Leave auto-configure off.

Outgoing HTTP calls, database queries and log correlation are not covered. The next two sections add them.

Zero-code with opentelemetry-instrument

The agent instruments every supported library in your environment without touching your code. opentelemetry-bootstrap installs an instrumentation for each package it finds, and opentelemetry-instrument starts your program with the SDK configured and those instrumentations on.

pip install opentelemetry-distro opentelemetry-exporter-otlp

# Installs an instrumentation package for every library already in the venv.
opentelemetry-bootstrap -a install

# uv venvs have no pip, so pipe the list instead.
opentelemetry-bootstrap -a requirements | uv pip install -r -

Run bootstrap after your own dependencies are installed, and again in your Docker build when they change.

export OTEL_SERVICE_NAME=orders
export OTEL_RESOURCE_ATTRIBUTES=service.version=1.4.2,deployment.environment.name=production
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_PYTHON_FASTAPI_EXCLUDED_URLS="health,ready"
export OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=sqlite3

opentelemetry-instrument uvicorn main:app
  • The protocol default is gRPC. Without OTEL_EXPORTER_OTLP_PROTOCOL the distro expects port 4317. See gRPC vs HTTP.
  • Bootstrap installs overlapping packages. With SQLite it adds both the sqlalchemy and the sqlite3 instrumentation, and every query shows up twice. OTEL_PYTHON_DISABLED_INSTRUMENTATIONS turns one off.
  • The server span comes from the contrib instrumentation. Add fastapi to OTEL_PYTHON_DISABLED_INSTRUMENTATIONS to use FastAPI's native spans instead. The excluded-URLs variable then no longer applies.

Set up the SDK in code

Choose this when the configuration should live in version control, you need a custom sampler or processor, or you cannot change the start command. Install opentelemetry-sdk, opentelemetry-exporter-otlp-proto-http and the instrumentations you use, then build the provider once:

telemetry.py

import logging

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.instrumentation.logging import LoggingInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor


def setup_telemetry(engine) -> TracerProvider:
    resource = Resource.create(
        {
            "service.name": "orders",
            "service.version": "1.4.2",
            "deployment.environment.name": "production",
        }
    )
    provider = TracerProvider(resource=resource)
    # Endpoint and headers come from OTEL_EXPORTER_OTLP_* variables.
    provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    trace.set_tracer_provider(provider)

    HTTPXClientInstrumentor().instrument()
    SQLAlchemyInstrumentor().instrument(engine=engine)
    LoggingInstrumentor().instrument(set_logging_format=True)
    logging.getLogger().setLevel(logging.INFO)
    return provider

Call it before the app is created. FastAPI picks up the global provider and adds the server spans:

main.py

from fastapi import FastAPI
from sqlalchemy import create_engine

from telemetry import setup_telemetry

engine = create_engine("sqlite:///orders.db")
provider = setup_telemetry(engine)

app = FastAPI(
    telemetry={"exclude": lambda scope: scope["path"] in ("/health", "/ready")},
)

On FastAPI older than 0.142, or when you want request hooks and header capture, the contrib instrumentation creates the server span:

from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

app = FastAPI()

FastAPIInstrumentor.instrument_app(
    app,
    excluded_urls="health,ready",
    # Drop the "http send" and "http receive" child spans.
    exclude_spans=["send", "receive"],
)

A second instrument_app call logs a warning and changes nothing. The same goes for an app the agent already instrumented, so your excluded_urls argument is ignored there.

Exclude health checks

A load balancer probing /health every few seconds can produce more traces than your users do. Each approach has its own switch:

  • Contrib and agent: OTEL_PYTHON_FASTAPI_EXCLUDED_URLS="health,ready", OTEL_PYTHON_EXCLUDED_URLS for every HTTP instrumentation, or the excluded_urls argument. Values are comma-separated regexes searched in the full URL, so health also matches /healthcare/42. Write /health$ to be exact.
  • Native: FastAPI(telemetry={"exclude": lambda scope: scope["path"] == "/health"}). The function gets the ASGI scope and returns True to skip the request.

Excluded requests create no span at all. To keep failed probes, leave them in and drop the successful ones in a Collector or with tail sampling.

httpx and SQLAlchemy spans

Outgoing calls are where most request time goes, and each library has its own instrumentor.

  • httpx. HTTPXClientInstrumentor().instrument() patches every Client and AsyncClient, including ones created earlier. Each request becomes a client span and carries a traceparent header, which joins your service to the next one. If the downstream trace does not connect, read context propagation.
  • SQLAlchemy. SQLAlchemyInstrumentor().instrument(engine=engine) instruments one engine. For an async engine pass engine.sync_engine. With no arguments it patches create_engine, so it must run before your engines are built. Spans are named like SELECT orders.db, with the statement in db.statement.

Check the supported range

Instrumentations declare which library versions they patch. As of November 2026 the SQLAlchemy one supports versions below 2.1. With 2.1.9 installed, the agent printed one line at startup and created no database spans:

sqlalchemy only instruments "sqlalchemy<2.1.0,>=1.0.0; extra == "instruments"", but currently installed version ("sqlalchemy 2.1.9") falls outside of that range, so nothing can be instrumented.

Custom spans in route handlers

Automatic spans show where a request went. Custom spans show what your code did in between. Get a tracer once per module and use it as a context manager or a decorator. Both work on async functions:

main.py

import asyncio
import logging

import httpx
from opentelemetry import trace
from sqlalchemy import text

logger = logging.getLogger("orders")
tracer = trace.get_tracer("orders")


@tracer.start_as_current_span("load recommendations")
async def load_recommendations(order_id: int) -> list[str]:
    await asyncio.sleep(0.01)
    return ["sku-1"]


async def price_order(order_id: int) -> float:
    with tracer.start_as_current_span("price order") as span:
        span.set_attribute("order.id", order_id)
        await asyncio.sleep(0.01)
        if order_id == 13:
            raise ValueError("no price for order 13")
        return 42.0


@app.get("/orders/{order_id}")
async def get_order(order_id: int):
    with engine.connect() as conn:
        conn.execute(text("SELECT 1"))
    async with httpx.AsyncClient() as client:
        await client.get("https://example.com/")

    # Both coroutines run concurrently and stay children of the request.
    total, recs = await asyncio.gather(price_order(order_id), load_recommendations(order_id))

    trace.get_current_span().set_attribute("order.total", total)
    logger.info("order %s loaded", order_id)
    return {"id": order_id, "total": total, "recs": recs}

One measured request to this handler, colored by the instrumentation scope that produced each span:

  • Async is handled for you. The current span lives in a contextvars variable that asyncio copies into every task, so spans started inside asyncio.gather or create_task get the right parent.
  • Threads need help. A plain def endpoint runs in FastAPI's threadpool with the context intact. Work handed to your own ThreadPoolExecutor loses it unless the threading instrumentation is on.
  • Exceptions are recorded. An exception leaving a start_as_current_span block adds an exception event and ERROR status. With order 13 above, price order, fastapi.endpoint and the server span were all marked as errors.
  • get_current_span() returns the innermost span. Under native telemetry that is fastapi.endpoint. With the contrib instrumentation it is the server span.
  • 4xx is not an error. A handler that raises HTTPException(422) leaves the server span UNSET. Only unhandled exceptions and 5xx responses set ERROR.

Logs with trace_id

opentelemetry-instrumentation-logging puts the active trace and span IDs on every stdlib logging record, so a log line leads straight to its trace. Under the agent, two variables control it:

# Add trace_id and span_id to the stdlib logging format
export OTEL_PYTHON_LOG_CORRELATION=true

# Export log records over OTLP. The handler is already attached; pick the exporter.
export OTEL_LOGS_EXPORTER=otlp

In code, LoggingInstrumentor().instrument(set_logging_format=True) adds the IDs to the format. A log call inside a request then prints:

2026-11-29 01:36:05,466 INFO [orders] [main.py:63] [trace_id=18069dea60d9b7b06fd8883c208caa90 span_id=59bf422e3b67ef39 resource.service.name=orders trace_sampled=True] - order 42 loaded
  • OTLP export is on by default. The instrumentation attaches a handler that turns each record into an OpenTelemetry log with the trace context. It only needs an exporter. OTEL_PYTHON_LOG_AUTO_INSTRUMENTATION=false turns it off.
  • Unset the old variable. OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true is deprecated. It activates the SDK's old handler, and the instrumentation logs a warning and skips its own.
  • Custom formats. OTEL_PYTHON_LOG_FORMAT overrides the format. With your own formatter, such as JSON, call instrument(inject_trace_context=True) and read otelTraceID and otelSpanID from the record. A bare instrument() adds neither. The Django logging guide shows the same pattern with a dictConfig, and Python logging levels covers which level to log at.
  • No IDs outside a request. Both fields are 0 there. uvicorn's access log has its own format and does not show them.

uvicorn --reload, workers and gunicorn

How the server starts processes decides whether instrumentation reaches them.

  • uvicorn --reload and --workers start new Python processes. The agent loads through a sitecustomize module on PYTHONPATH, so those processes are instrumented only while that path is set. Older releases removed it after startup, which is where the advice that --reload loses instrumentation comes from. Current releases keep it: under both flags, every request produced the same spans as a single process. Django's runserver autoreloader behaves the same way on current releases.
  • Spans vanish under --reload on your version? Upgrade the distro or set up the SDK in code, which runs wherever your module is imported.
  • gunicorn forks instead. For the agent, upstream recommends gunicorn with uvicorn workers:
pip install gunicorn uvicorn-worker

opentelemetry-instrument gunicorn main:app \
  --workers 4 \
  --worker-class uvicorn_worker.UvicornWorker \
  --bind 0.0.0.0:8000

Threads do not survive a fork, and the batch processor exports from a background thread. The SDK restarts it in the child through an os.register_at_fork hook, and in our runs spans arrived from every worker, with and without --preload.

Metrics are the weaker spot. The periodic reader's thread and locks are inherited too, and upstream recommends initializing the SDK after the fork. With code-based setup, build both providers in post_fork:

gunicorn.conf.py

from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

bind = "0.0.0.0:8000"
workers = 4
worker_class = "uvicorn_worker.UvicornWorker"
preload_app = True


def post_fork(server, worker):
    # Runs in each worker after the fork: its own providers and export threads.
    resource = Resource.create({"service.name": "orders"})

    tracer_provider = TracerProvider(resource=resource)
    tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    trace.set_tracer_provider(tracer_provider)

    reader = PeriodicExportingMetricReader(OTLPMetricExporter())
    metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))

With this config, two workers each exported their own spans and their own http.server.request.duration metric stream.

Production settings

These settings control volume, identity and what survives a deploy. The SDK reads them however it was configured:

# Keep 10% of new traces; follow the caller's decision when there is one
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.1

# Batch span processor (defaults shown)
export OTEL_BSP_SCHEDULE_DELAY=5000
export OTEL_BSP_MAX_QUEUE_SIZE=2048
export OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512

export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
# Use the stable HTTP and database attribute names in the contrib packages
export OTEL_SEMCONV_STABILITY_OPT_IN=http,database
  • Resource attributes. Set service.name, service.version and deployment.environment.name through OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES, or in Resource.create. Without a service name everything is reported as unknown_service. The SDK adds a unique service.instance.id per process.
  • Sampling. parentbased_traceidratio decides once at the edge and every downstream service follows, so traces stay complete. Keeping only slow or failed requests needs tail sampling in a Collector. See the sampling guide.
  • Batching. Use BatchSpanProcessor. SimpleSpanProcessor exports inside the request and adds the exporter's latency to every response. A full queue drops new spans, so raise OTEL_BSP_MAX_QUEUE_SIZE for bursty services.
  • Attribute names. The contrib HTTP and database instrumentations emit the old names by default. Opting in gives them the same attributes as FastAPI's native spans: http.request.method, http.response.status_code, url.path, db.query.text.

The last batch is not flushed on SIGTERM by default. uvicorn runs the lifespan shutdown, then re-raises the signal, and the process dies without running atexit hooks, which is where the SDK's flush lives.

That is what a test showed: a request followed by SIGTERM one second later exported nothing, while Ctrl+C flushed normally. Every rolling deploy loses up to five seconds of spans this way. Shut the provider down in the lifespan, however it was configured:

from contextlib import asynccontextmanager

from fastapi import FastAPI
from opentelemetry import trace


@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    provider = trace.get_tracer_provider()
    if hasattr(provider, "shutdown"):
        provider.shutdown()


app = FastAPI(lifespan=lifespan)

Common problems

Three symptoms cover most searches. Each has a short list of causes, checked in this order.

No spans appear

First find out whether spans are created or only fail to arrive. The console exporter prints each finished span as JSON:

OTEL_TRACES_EXPORTER=console OTEL_METRICS_EXPORTER=none OTEL_LOGS_EXPORTER=none \
  opentelemetry-instrument uvicorn main:app

If spans print, the problem is the export. If nothing prints, it is the instrumentation.

  • gRPC exporter, HTTP port. The agent defaults to gRPC. Pointed at port 4318 it retries with this warning and delivers nothing. Set OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf or use port 4317.
    WARNING:opentelemetry.exporter.otlp.proto.grpc.exporter:Transient error StatusCode.UNAVAILABLE encountered while exporting traces to localhost:4318, retrying in 1.08s. Error details: failed to connect to all addresses; last error: UNAVAILABLE: ipv4:127.0.0.1:4318: Failed parsing HTTP/2 (Expected SETTINGS frame as the first frame, got frame type 79)
  • No provider. Native telemetry and instrument_app record nothing until an SDK provider exists. Set FASTAPI_OTEL_AUTO_CONFIGURE=true, run under the agent, or call trace.set_tracer_provider.
  • Instrumentation not installed. The agent only activates installed packages. Compare opentelemetry-bootstrap -a requirements with pip list. In a uv venv, -a install fails on every package because there is no pip.
  • Killed before the flush. Spans wait up to five seconds in the batch queue. See the lifespan flush in production settings.
  • Sampled out or excluded. Check OTEL_TRACES_SAMPLER, an upstream traceparent with the sampled flag off, and exclude patterns that match too much.
  • Rejected by the backend. The exporter logs a 401 or 404. The OTLP guide lists each status code and its fix.

Duplicate spans

Each of these produced doubled spans in a test, and each has a different fix:

What you seeCauseFix
Every span arrives twice, same IDsYour own exporter plus FASTAPI_OTEL_AUTO_CONFIGURE=true sending to the same endpointLeave auto-configure off when you build the provider
Two spans per query, SELECT and SELECT orders.dbDriver and ORM instrumentation both active (sqlite3, psycopg or asyncpg next to sqlalchemy)OTEL_PYTHON_DISABLED_INSTRUMENTATIONS for the driver
http send and http receive children on every requestThe contrib ASGI middleware traces each ASGI messageexclude_spans=["send", "receive"]
Two root server spans for one request to a mounted appContrib instrumentation on the parent app, native telemetry in the sub-applicationUse one approach for both, or instrument the sub-app too
A second span named after the raw pathapp.add_middleware(OpenTelemetryMiddleware) on top of instrument_appRemove the manual middleware

Running under the agent and also calling instrument_app duplicated nothing. The second call is skipped.

Route names showing as raw paths

A correctly instrumented app names server spans by route template: GET /orders/{order_id}, with the same value in http.route. If you see GET /orders/42, check these:

  • Plain ASGI middleware. OpenTelemetryMiddleware from opentelemetry-instrumentation-asgi knows nothing about FastAPI routes and names spans after the path. Use FastAPIInstrumentor or native telemetry.
  • You are looking at an attribute. url.path (or http.target) always holds the raw path. Group, chart and alert by http.route. Grouping by path creates a series per ID, which is a cardinality problem.
  • Unmatched requests. A 404 for a path with no route gets the span name GET and no http.route. That is intentional: scanners would otherwise create unlimited names.
  • Mounted sub-applications. With the contrib instrumentation, a request to an app mounted at /v1 was named GET /v1. Native telemetry reported the full template, GET /v1/items/{item_id}.

Send it to Maple

Maple accepts OTLP directly, so any setup above works unchanged. Point the exporter at the ingest endpoint and put your ingest key in the Authorization header. The Python instrumentation docs cover metrics and logs as well.

export OTEL_SERVICE_NAME=orders
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
A trace in Maple: a POST /api/checkout request shown as a timeline waterfall of 15 spans across 6 services, with one span marked as an error.
A checkout trace in Maple. Your FastAPI server, client and custom spans show up the same way, nested by parent.

Sources and further reading

FAQ

Common questions

Does FastAPI support OpenTelemetry natively?
Yes, since FastAPI 0.142.0. FastAPI records request spans, HTTP metrics and error logs through the OpenTelemetry API on its own. It exports them when a provider is configured, or when you set FASTAPI_OTEL_AUTO_CONFIGURE=true with an OTLP endpoint. Older versions need opentelemetry-instrumentation-fastapi.
How do I add tracing to a FastAPI app without changing code?
Install opentelemetry-distro and opentelemetry-exporter-otlp, run opentelemetry-bootstrap -a install, then start the app with opentelemetry-instrument uvicorn main:app. Service name, endpoint and headers come from OTEL_* environment variables.
Do I still need FastAPIInstrumentor.instrument_app?
Only on FastAPI older than 0.142, or when you want its options such as header capture and request hooks. On newer versions FastAPI creates the server span itself. If both are present on the same app, FastAPI detects the contrib middleware and turns its own spans off.
How do I exclude health checks from FastAPI traces?
With the contrib instrumentation, set OTEL_PYTHON_FASTAPI_EXCLUDED_URLS="health,ready" or pass excluded_urls to instrument_app. The values are regexes searched in the full URL. With native FastAPI telemetry, pass an exclude function in FastAPI(telemetry={...}).
Why are no spans showing up from my FastAPI app?
The usual causes are an exporter protocol that does not match the port (the Python distro defaults to gRPC, port 4317), no SDK provider configured, a process killed before the 5 second batch was sent, or a sampler that drops the trace. Switch OTEL_TRACES_EXPORTER to console to see whether spans are created at all.
Does opentelemetry-instrument work with uvicorn --reload and --workers?
Yes on current releases. uvicorn starts the reloader's child and each worker as a new Python process that inherits PYTHONPATH, so the agent loads again in each one. Older releases removed the agent from PYTHONPATH after startup, so those processes started uninstrumented. On those versions, upgrade or set up the SDK in code.

See your first trace today.

Add the SDK, point your OTLP exporter at Maple, and traces arrive.

maple.dev: observability on OpenTelemetry