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/protobufwhen your endpoint is port 4318 or an HTTPS URL. - uvicorn skips
atexithooks onSIGTERM. 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 FastAPI | Zero-code agent | FastAPIInstrumentor | |
|---|---|---|---|
| Needs | FastAPI 0.142+ | opentelemetry-distro | opentelemetry-instrumentation-fastapi |
| Code changes | None | None | One call per app |
| Server spans | Yes, plus dependency, endpoint and serialization spans | Yes | Yes |
| httpx, SQLAlchemy, Redis | No | Yes | Separate instrumentors |
| HTTP attribute names | Stable (http.request.method) | Old (http.method) unless OTEL_SEMCONV_STABILITY_OPT_IN=http | |
| Skip health checks | exclude function | OTEL_PYTHON_FASTAPI_EXCLUDED_URLS | excluded_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 withfastapi.dependencies,fastapi.endpointandfastapi.serializationchildren.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=trueortelemetry={"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_PROTOCOLthe distro expects port 4317. See gRPC vs HTTP. - Bootstrap installs overlapping packages. With SQLite it adds both the
sqlalchemyand thesqlite3instrumentation, and every query shows up twice.OTEL_PYTHON_DISABLED_INSTRUMENTATIONSturns one off. - The server span comes from the contrib instrumentation. Add
fastapitoOTEL_PYTHON_DISABLED_INSTRUMENTATIONSto 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_URLSfor every HTTP instrumentation, or theexcluded_urlsargument. Values are comma-separated regexes searched in the full URL, sohealthalso matches/healthcare/42. Write/health$to be exact. - Native:
FastAPI(telemetry={"exclude": lambda scope: scope["path"] == "/health"}). The function gets the ASGI scope and returnsTrueto 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 everyClientandAsyncClient, including ones created earlier. Each request becomes a client span and carries atraceparentheader, 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 passengine.sync_engine. With no arguments it patchescreate_engine, so it must run before your engines are built. Spans are named likeSELECT orders.db, with the statement indb.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
contextvarsvariable that asyncio copies into every task, so spans started insideasyncio.gatherorcreate_taskget the right parent. - Threads need help. A plain
defendpoint runs in FastAPI's threadpool with the context intact. Work handed to your ownThreadPoolExecutorloses it unless thethreadinginstrumentation is on. - Exceptions are recorded. An exception leaving a
start_as_current_spanblock adds anexceptionevent andERRORstatus. With order 13 above,price order,fastapi.endpointand the server span were all marked as errors. get_current_span()returns the innermost span. Under native telemetry that isfastapi.endpoint. With the contrib instrumentation it is the server span.- 4xx is not an error. A handler that raises
HTTPException(422)leaves the server spanUNSET. Only unhandled exceptions and 5xx responses setERROR.
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=falseturns it off. - Unset the old variable.
OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=trueis deprecated. It activates the SDK's old handler, and the instrumentation logs a warning and skips its own. - Custom formats.
OTEL_PYTHON_LOG_FORMAToverrides the format. With your own formatter, such as JSON, callinstrument(inject_trace_context=True)and readotelTraceIDandotelSpanIDfrom the record. A bareinstrument()adds neither. The Django logging guide shows the same pattern with adictConfig, and Python logging levels covers which level to log at. - No IDs outside a request. Both fields are
0there. 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
--reloadand--workersstart new Python processes. The agent loads through asitecustomizemodule onPYTHONPATH, so those processes are instrumented only while that path is set. Older releases removed it after startup, which is where the advice that--reloadloses instrumentation comes from. Current releases keep it: under both flags, every request produced the same spans as a single process. Django'srunserverautoreloader behaves the same way on current releases. - Spans vanish under
--reloadon 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.versionanddeployment.environment.namethroughOTEL_SERVICE_NAMEandOTEL_RESOURCE_ATTRIBUTES, or inResource.create. Without a service name everything is reported asunknown_service. The SDK adds a uniqueservice.instance.idper process. - Sampling.
parentbased_traceidratiodecides 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.SimpleSpanProcessorexports inside the request and adds the exporter's latency to every response. A full queue drops new spans, so raiseOTEL_BSP_MAX_QUEUE_SIZEfor 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/protobufor 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_apprecord nothing until an SDK provider exists. SetFASTAPI_OTEL_AUTO_CONFIGURE=true, run under the agent, or calltrace.set_tracer_provider. - Instrumentation not installed. The agent only activates installed packages. Compare
opentelemetry-bootstrap -a requirementswithpip list. In a uv venv,-a installfails 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 upstreamtraceparentwith 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 see | Cause | Fix |
|---|---|---|
| Every span arrives twice, same IDs | Your own exporter plus FASTAPI_OTEL_AUTO_CONFIGURE=true sending to the same endpoint | Leave auto-configure off when you build the provider |
Two spans per query, SELECT and SELECT orders.db | Driver 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 request | The contrib ASGI middleware traces each ASGI message | exclude_spans=["send", "receive"] |
| Two root server spans for one request to a mounted app | Contrib instrumentation on the parent app, native telemetry in the sub-application | Use one approach for both, or instrument the sub-app too |
| A second span named after the raw path | app.add_middleware(OpenTelemetryMiddleware) on top of instrument_app | Remove 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.
OpenTelemetryMiddlewarefromopentelemetry-instrumentation-asgiknows nothing about FastAPI routes and names spans after the path. UseFastAPIInstrumentoror native telemetry. - You are looking at an attribute.
url.path(orhttp.target) always holds the raw path. Group, chart and alert byhttp.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
GETand nohttp.route. That is intentional: scanners would otherwise create unlimited names. - Mounted sub-applications. With the contrib instrumentation, a request to an app mounted at
/v1was namedGET /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"
Sources and further reading
- FastAPI docs: OpenTelemetry
- FastAPI 0.142.0 release notes: native OpenTelemetry support
- FastAPI 0.143.0 release notes: opt-in exporter setup
- OpenTelemetry: Python zero-code instrumentation
- OpenTelemetry: Python agent troubleshooting and pre-fork servers
- opentelemetry-instrumentation-fastapi reference
- opentelemetry-instrumentation-logging reference