Kubernetes Observability

How Do You Monitor a FastAPI Application With OpenTelemetry?

November 28, 2026
7
min read
Kubernetes Observability

When a FastAPI endpoint starts responding slowly or returns an HTTP 500 error, access logs can show which request failed and how long it took, but not the operations behind the failure. FastAPIInstrumentor addresses this by adding OpenTelemetry request tracing and HTTP server metrics to your application without requiring instrumentation in every endpoint. It records request durations, route information, and exceptions, while additional instrumented operations can provide the context needed to investigate performance problems.

This guide walks you through instrumenting a FastAPI application and exporting telemetry to Jaeger or another OTLP-compatible backend such as Grafana Tempo. You’ll learn how to verify traces and metrics, customize instrumentation, and troubleshoot missing telemetry. It also compares programmatic instrumentation with native FastAPI support and the opentelemetry-instrument wrapper.

What FastAPIInstrumentor Monitors

FastAPIInstrumentor uses OpenTelemetry’s ASGI middleware to capture incoming HTTP requests as server spans and generate HTTP server metrics. Each span represents a timed operation within a trace, while a trace connects related operations through a shared trace ID. The instrumentor captures the following information:

  • Request spans: Each incoming request produces a server span containing HTTP attributes and timing information. For example, a request to /items/42 produces a span named GET /items/{item_id}, with http.route set to /items/{item_id}. Using route templates limits cardinality. The ASGI middleware can also generate internal http receive and http send spans.
  • HTTP metrics: The instrumentor records request-duration histograms and active request counts, along with request and response body sizes when the relevant lengths are available. These metrics help you track latency, traffic, and request behavior across the service.
  • Errors and exceptions: Unhandled exceptions are recorded as span events and mark the server span as ERROR. HTTP 5xx responses generally indicate server errors, while handled 4xx responses leave server span status unset. Application logs are a separate telemetry signal that FastAPIInstrumentor does not automatically collect.

To capture database queries, outgoing API calls, or internal functions as additional spans, you need to instrument those operations separately.

The attribute and metric names depend on OTEL_SEMCONV_STABILITY_OPT_IN. By default, the current instrumentation emits older experimental HTTP conventions. Set the variable to http to use stable names or http/dup to emit both during migration.

Default (Experimental) NameStable Name (OTEL_SEMCONV_STABILITY_OPT_IN=http)
http.methodhttp.request.method
http.status_codehttp.response.status_code
http.schemeurl.scheme
http.targeturl.path and url.query
http.routehttp.route (unchanged)
http.server.duration (milliseconds)http.server.request.duration (seconds)
http.server.request.sizehttp.server.request.body.size
http.server.response.sizehttp.server.response.body.size
http.server.active_requestshttp.server.active_requests (unchanged)

Queries and alerts built on one naming scheme may not match telemetry emitted under the other. Choose your convention before configuring dashboards, or use http/dup while migrating existing queries. The OpenTelemetry SDK providers and exporters determine where these spans and metrics are sent.

How to Instrument FastAPI With FastAPIInstrumentor: Step by Step

FastAPIInstrumentor captures HTTP request spans and metrics through ASGI middleware, but that telemetry needs to be processed and exported before you can inspect it. The OpenTelemetry SDK handles this through tracer and meter providers, span processors, and exporters, allowing you to change monitoring backends without rewriting your FastAPI endpoints.

This setup uses Python 3.12, FastAPI 0.162.6, Uvicorn 0.54.0, OpenTelemetry SDK 1.45.2, and FastAPI instrumentation 0.66b2. Docker runs Jaeger locally so you can inspect the resulting traces.

Keep the FastAPI application and OpenTelemetry configuration in separate Python files. This makes it easier to manage instrumentation independently of your endpoint handlers, especially as the application grows. The project will have the following structure once you’ve created the files:

fastapi-monitoring/
├── main.py
├── telemetry.py
├── .venv/
├── Dockerfile
├── compose.yaml
└── tempo.yaml

main.py contains the FastAPI routes and registers FastAPIInstrumentor, while telemetry.py configures the OpenTelemetry providers and exporters. The .venv directory holds your Python dependencies. The Dockerfile and compose.yaml are only needed for the Docker Compose deployment, while tempo.yaml is used if you choose Grafana Tempo instead of Jaeger.

Step 1: Install FastAPI, Uvicorn, and OpenTelemetry

Create the project directory and a Python virtual environment to keep the application’s monitoring dependencies separate from other projects. The commands below use Bash on Linux, macOS, or Windows Subsystem for Linux (WSL).

mkdir fastapi-monitoring
cd fastapi-monitoring
python3.12 -m venv .venv
source .venv/bin/activate

Install FastAPI, Uvicorn, and the OpenTelemetry packages:

python -m pip install \
  "fastapi==0.162.6" \
  "uvicorn==0.54.0" \
  "opentelemetry-sdk==1.45.2" \
  "opentelemetry-exporter-otlp-proto-http==1.45.2" \
  "opentelemetry-instrumentation-fastapi==0.66b2"

FastAPI defines the application routes, and Uvicorn serves requests through ASGI. The opentelemetry-instrumentation-fastapi package connects that request lifecycle to OpenTelemetry, allowing incoming requests to produce spans and HTTP metrics. The SDK manages those measurements, while opentelemetry-exporter-otlp-proto-http delivers them to an OTLP-compatible backend.

OpenTelemetry’s core packages use 1.x versions, while its instrumentation packages use a separate 0.x version series. Installing compatible versions together helps avoid dependency conflicts and keeps the setup reproducible. If you’re adding instrumentation to an existing FastAPI application, check compatibility with its installed dependencies before changing versions.

Step 2: Configure the OpenTelemetry SDK and Exporters

Installing FastAPIInstrumentor adds the ability to capture request activity, but it doesn’t establish where that telemetry should go. The SDK needs a tracer provider to manage spans and a meter provider to collect metrics, with exporters responsible for delivering each signal to its destination.

Jaeger receives the request traces through OTLP/HTTP, while a console exporter prints HTTP metrics to the terminal. Since Jaeger doesn’t ingest OTLP metrics, separating their destinations allows both signals to be verified without running another monitoring backend.

Create telemetry.py in the project directory:

# telemetry.py
import os

from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
    ConsoleMetricExporter,
    PeriodicExportingMetricReader,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
    ConsoleSpanExporter,
)


def configure_telemetry() -> tuple[TracerProvider, MeterProvider]:
    resource = Resource.create(
        {SERVICE_NAME: os.environ.get("OTEL_SERVICE_NAME", "fastapi-demo")}
    )

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

    if os.environ.get("OTEL_DEBUG_CONSOLE") == "1":
        tracer_provider.add_span_processor(
            BatchSpanProcessor(ConsoleSpanExporter())
        )

    trace.set_tracer_provider(tracer_provider)

    reader = PeriodicExportingMetricReader(
        ConsoleMetricExporter(),
        export_interval_millis=5000,
    )
    meter_provider = MeterProvider(
        resource=resource,
        metric_readers=[reader],
    )
    metrics.set_meter_provider(meter_provider)

    return tracer_provider, meter_provider

The Resource attaches a service.name attribute to the telemetry, which allows tracing backends to distinguish operations belonging to different services. In this setup, Jaeger identifies the application as fastapi-demo. When a request crosses multiple services, their spans can be grouped by service while remaining part of the same distributed trace.

Rather than exporting every span as soon as it finishes, BatchSpanProcessor queues completed spans and sends them in batches. This reduces the network overhead of individual exports, although spans waiting in the queue can be lost if the process terminates unexpectedly. The default maximum queue holds 2,048 spans, with up to 512 spans per export batch. You can adjust these limits using OTEL_BSP_MAX_QUEUE_SIZE and OTEL_BSP_MAX_EXPORT_BATCH_SIZE when tuning the application for production.

Metrics follow a separate pipeline. PeriodicExportingMetricReader collects measurements every five seconds and passes them to ConsoleMetricExporter, which prints the results in the application terminal. This interval makes local verification easier, while a longer interval may be appropriate in production to reduce collection and export overhead.

To export metrics to a backend that accepts OTLP, add this import to telemetry.py:

from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter

Replace the existing reader definition with:

reader = PeriodicExportingMetricReader(
    OTLPMetricExporter(),
    export_interval_millis=5000,
)

With a base OTEL_EXPORTER_OTLP_ENDPOINT configured, the exporter sends metrics to /v1/metrics. This allows an OpenTelemetry Collector or another metrics-capable backend to receive the measurements without changing how FastAPI collects them.

Keep provider initialization in one place because OpenTelemetry’s global tracer provider can only be set once per process. Repeated calls to trace.set_tracer_provider() don’t replace an existing provider, and multiple SDK configurations can result in unexpected telemetry behavior.

Step 3: Add FastAPIInstrumentor to Your Application

FastAPIInstrumentor.instrument_app() connects the configured SDK to FastAPI by wrapping the application’s ASGI middleware stack. Once registered, it observes incoming requests and records their timing and HTTP attributes without requiring instrumentation code inside every endpoint.

FastAPI also has native OpenTelemetry support. Disable that instrumentation when using FastAPIInstrumentor to prevent the two implementations from recording overlapping request spans and metrics.

Create main.py in the same directory as telemetry.py:

# main.py
from fastapi import FastAPI, HTTPException
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

from telemetry import configure_telemetry

tracer_provider, meter_provider = configure_telemetry()

app = FastAPI(
    telemetry={
        "tracing": False,
        "metrics": False,
        "logs": False,
    }
)

FastAPIInstrumentor.instrument_app(
    app,
    tracer_provider=tracer_provider,
    meter_provider=meter_provider,
)


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 0:
        raise HTTPException(status_code=404, detail="not found")
    if item_id < 0:
        raise ValueError("negative item id")
    return {"item_id": item_id}


@app.get("/healthz")
async def healthz():
    return {"status": "ok"}

The /items/{item_id} endpoint provides three request outcomes for examining how OpenTelemetry represents different responses. Requests to /items/42 succeed, /items/0 return a handled HTTP 404, and /items/-1 raise an unhandled ValueError that produces HTTP 500. Comparing their spans helps distinguish successful requests, client errors, and application failures.

Register instrument_app() after creating the FastAPI instance and adding any custom middleware, but before the application starts serving requests. The instrumentor can then capture the HTTP method, matched route, request duration, and available response attributes as traffic passes through the middleware.

The resulting server span represents the HTTP request, but it doesn’t automatically show every operation performed inside an endpoint. If a request spends most of its time waiting for a database query, for example, the database client also needs instrumentation before that query can appear as a separate span.

You can instrument internal operations manually using trace.get_tracer(__name__) and tracer.start_as_current_span("load-item"). When those operations run within the active request context, their spans appear beneath the HTTP server span in the same trace, making it possible to distinguish time spent in application code from delays in downstream services.

instrument_app() also supports route exclusions, request hooks, and HTTP header capture, which control which requests are recorded and how much context their spans contain.

To remove instrumentation during test cleanup, call:

FastAPIInstrumentor.uninstrument_app(app)

For applications where multiple FastAPI instances are created dynamically, FastAPIInstrumentor().instrument() can instrument instances created after it runs. The opentelemetry-instrument wrapper offers another approach when instrumentation needs to be configured without modifying application startup code.

Step 4: Configure the OTLP Endpoint and Service Name

The exporter needs a destination for the spans collected by FastAPIInstrumentor. OpenTelemetry uses environment variables to configure service identity, backend endpoints, and authentication, allowing the same application to send traces to Jaeger, Grafana Tempo, or another OTLP-compatible service.

Environment VariablePurposeExample
OTEL_SERVICE_NAMEIdentifies the application in traces and metricsfastapi-demo
OTEL_RESOURCE_ATTRIBUTESAdds resource metadatadeployment.environment.name=development
OTEL_EXPORTER_OTLP_ENDPOINTBase OTLP endpointhttp://localhost:4318
OTEL_EXPORTER_OTLP_TRACES_ENDPOINTFull traces-only endpointhttp://localhost:4318/v1/traces
OTEL_EXPORTER_OTLP_HEADERSAdds authentication or other exporter headersapi-key=YOUR_KEY

For OTLP/HTTP, base endpoints and signal-specific endpoints are handled differently. When OTEL_EXPORTER_OTLP_ENDPOINT is set to http://localhost:4318, the exporter constructs the path for each signal, such as /v1/traces or /v1/metrics. A signal-specific variable such as OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, however, must contain the complete URL because the exporter uses it without appending another path.

OTLP/gRPC doesn’t use these HTTP signal paths. A gRPC exporter connects to a target such as http://localhost:4317, and the backend must accept that transport. Using the wrong transport or omitting /v1/traces from a traces-specific HTTP endpoint can prevent spans from arriving even when instrumentation is working.

Set the environment variables for the local Jaeger setup:

export OTEL_SERVICE_NAME=fastapi-demo
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_SEMCONV_STABILITY_OPT_IN=http

OTEL_SERVICE_NAME identifies the application in Jaeger, while OTEL_EXPORTER_OTLP_ENDPOINT points to its OTLP/HTTP receiver. The semantic convention setting enables stable HTTP attribute and metric names, including http.request.method, http.response.status_code, and http.server.request.duration.

Queries written against older HTTP conventions may not match these stable attribute and metric names, so the convention setting also matters when configuring dashboards and alerts.

With the current telemetry.py configuration, traces are sent through OTLP while metrics are printed to the terminal. Replacing the console metric exporter with OTLPMetricExporter allows metrics to use the same base endpoint, provided the backend supports OTLP metrics.

For authenticated backends, supply credentials through OTEL_EXPORTER_OTLP_HEADERS or OTEL_EXPORTER_OTLP_TRACES_HEADERS rather than embedding them in application code.

Step 5: Run Jaeger and Verify Traces, Metrics, and Errors

Jaeger allows you to inspect individual requests through their spans, timing information, HTTP attributes, and exception events. While HTTP metrics show service behavior over time, traces provide the request-level context needed to investigate latency and failures.

Start Jaeger in a Docker container:

docker run --rm --name jaeger \
  -p 16686:16686 \
  -p 4317:4317 \
  -p 4318:4318 \
  cr.jaegertracing.io/jaegertracing/jaeger:2.23.0

Port 16686 serves the Jaeger interface, while 4317 and 4318 receive OTLP traffic over gRPC and HTTP, respectively. The container uses in-memory storage, making it suitable for local testing rather than long-term trace retention.

In another terminal, return to the fastapi-monitoring directory, activate the virtual environment, and set the environment variables from Step 4 if they aren’t already available in that shell. Start the application with console span output enabled:

OTEL_DEBUG_CONSOLE=1 uvicorn main:app --host 0.0.0.0 --port 8000

The console exporter prints completed spans alongside the metrics already configured in telemetry.py. This provides another place to inspect telemetry when spans don’t appear in Jaeger, helping distinguish problems with instrumentation from failures in the export pipeline.

Verify a Successful Request

Send a request to the application:

curl http://localhost:8000/items/42

The response should be:

{"item_id":42}

Open http://localhost:16686, select fastapi-demo, and search for the GET /items/{item_id} operation. The server span should contain http.route=/items/{item_id} rather than using the raw path /items/42 as its name. Grouping requests under their route templates prevents individual item IDs from creating separate operations, which is important when analyzing latency across endpoints.

Figure: FastAPI request traces in Jaeger

The trace may also contain http receive and http send child spans. These represent ASGI request and response operations rather than calls to downstream services. When database clients or outbound HTTP requests are instrumented, their operations can appear in the same trace, allowing you to identify where a slow request spent its time.

Verify HTTP Metrics

The ConsoleMetricExporter prints measurements in the Uvicorn terminal every five seconds. Look for the following metrics:

  • http.server.request.duration: A histogram of HTTP request durations, measured in seconds under the stable semantic conventions.
  • http.server.active_requests: The number of HTTP requests being processed.
  • http.server.request.body.size and http.server.response.body.size: Request and response body sizes when the necessary content-length information is available.

A request-duration histogram helps identify latency trends, while active request counts provide information about concurrent load. Neither measurement identifies the application operation responsible for a slow request, which is where traces become useful. By examining traces from the same time window, you can investigate whether the delay came from application code, a database query, or another service.

Body-size measurements depend on the information available to the middleware. A GET request without a body may not produce http.server.request.body.size, so its absence doesn’t necessarily indicate an instrumentation problem.

Verify an Unhandled Exception

Trigger an application failure:

curl -i http://localhost:8000/items/-1

The negative item ID raises a ValueError, causing FastAPI to return HTTP 500. Find the resulting trace in Jaeger and inspect the server span for an ERROR status and an exception event.

The event records the exception type and may include its message and stack trace. Combined with the span’s timing and relationships, this helps establish what failed and where the failure occurred during request processing. Exception events remain part of the tracing signal, complementing application logs rather than replacing them.

Figure: HTTP 500 trace with a ValueError exception

Verify a Handled HTTP Error

Send a request that produces a handled error:

curl -i http://localhost:8000/items/0

FastAPI returns HTTP 404, but the server span generally retains an unset status under the OpenTelemetry HTTP conventions. A client-error response doesn’t necessarily indicate that the server failed to process the request, so handled 4xx responses and unhandled exceptions are represented differently.

This affects alerting because counting only spans marked ERROR can miss increases in HTTP 404 responses. Use http.response.status_code or corresponding HTTP metrics when tracking client-error rates separately from application failures.

If spans appear in the console but not in Jaeger, investigate the export path by checking the container, endpoint, port, and exporter errors. When spans appear in neither location, check whether FastAPIInstrumentor is registered and whether the tracer provider was configured before the application started handling requests.

Step 6: Customize Exclusions, Request Hooks, and Captured Headers

Health checks can generate large volumes of spans without adding much diagnostic value, while application-specific attributes can make traces more useful during investigations. FastAPIInstrumentor supports both requirements through URL exclusions and request hooks, along with options for controlling internal ASGI spans and capturing HTTP headers.

Add a request hook to main.py, above the existing instrument_app() call. Place its imports alongside the other imports at the top of the file:

from typing import Any

from opentelemetry.trace import Span


def server_request_hook(span: Span, scope: dict[str, Any]):
    if span and span.is_recording():
        headers = dict(scope.get("headers") or [])
        tenant = headers.get(b"x-tenant-id")
        if tenant:
            span.set_attribute("app.tenant_id", tenant.decode())

The hook receives the server span and ASGI scope for each request. It extracts the example x-tenant-id header and adds its value as app.tenant_id, making it possible to filter traces by tenant when investigating problems affecting only part of an application.

For production use, derive tenant identifiers from authenticated context rather than trusting arbitrary client-provided headers.

Replace the existing FastAPIInstrumentor.instrument_app() call with:

FastAPIInstrumentor.instrument_app(
    app,
    tracer_provider=tracer_provider,
    meter_provider=meter_provider,
    excluded_urls="/healthz$",
    exclude_spans=["send", "receive"],
    server_request_hook=server_request_hook,
    http_capture_headers_server_request=[
        "x-request-id",
        "authorization",
    ],
    http_capture_headers_sanitize_fields=["authorization"],
)

The excluded_urls option accepts comma-separated regular expressions, with /healthz$ excluding health-check requests without removing unrelated traffic. The same exclusion can be configured through OTEL_PYTHON_FASTAPI_EXCLUDED_URLS when environment-based configuration is preferable.

The exclude_spans setting removes internal ASGI receive and send spans while retaining the server span. This can reduce trace volume for applications where those internal operations add little diagnostic value, although some response-handling attributes may no longer be available. Server span status and exception events remain useful when investigating unhandled failures.

Request hooks add application context without requiring changes to individual endpoints, while the header capture options record selected headers as span attributes. Because authorization headers may contain credentials, http_capture_headers_sanitize_fields replaces their values with [REDACTED] before they appear in exported spans.

Restart Uvicorn to apply the modified configuration:

OTEL_DEBUG_CONSOLE=1 uvicorn main:app --host 0.0.0.0 --port 8000

Check that the health endpoint still responds:

curl http://localhost:8000/healthz

The response should succeed without generating a new FastAPI request trace. To verify the custom attribute and header sanitization, send a request containing test headers:

curl \
  -H "x-tenant-id: acme" \
  -H "authorization: Bearer test" \
  http://localhost:8000/items/7

Inspect the resulting server span in Jaeger. It should contain app.tenant_id=acme and show the authorization header as [REDACTED], without the internal http receive and http send child spans.

Figure: Custom tenant attribute and redacted authorization header

Optional: Export to Grafana Tempo or Deploy With Docker Compose

OTLP separates FastAPI instrumentation from the backend receiving its telemetry. Once the application is instrumented, changing the exporter endpoint is sufficient to send traces to another compatible service. Docker Compose provides another deployment option when you want the application and tracing backend to run together.

Exporting Traces to Grafana Tempo

Grafana Tempo accepts traces through OTLP/HTTP and OTLP/gRPC, so the same exporter can send FastAPI spans to Tempo instead of Jaeger. Tempo stores traces rather than general-purpose application metrics, leaving the console exporter or another metrics-capable destination responsible for HTTP measurements.

Create tempo.yaml in the project directory:

server:
  http_listen_port: 3200

distributor:
  receivers:
    otlp:
      protocols:
        grpc:
          endpoint: "0.0.0.0:4317"
        http:
          endpoint: "0.0.0.0:4318"

storage:
  trace:
    backend: local
    wal:
      path: /data/tempo/wal
    local:
      path: /data/tempo/blocks

The configuration enables OTLP receivers and stores trace data locally. Binding the receivers to 0.0.0.0 allows connections through the container network, so access to those ports should be restricted outside development environments.

Stop the standalone Jaeger container before starting Tempo locally because both use port 4318. Run Tempo from the project directory so the container can mount tempo.yaml:

docker run --rm --name tempo \
  -p 3200:3200 \
  -p 4318:4318 \
  -v "$(pwd)/tempo.yaml:/etc/tempo.yaml:ro" \
  -v tempo-data:/data/tempo \
  grafana/tempo:2.10.10 \
  -config.file=/etc/tempo.yaml

Tempo runs as UID/GID 10001:10001 and needs write access to /data/tempo. If the container fails with a permission-denied error, set ownership of the named volume before restarting Tempo:

docker run --rm --user 0 \
  -v tempo-data:/data/tempo \
  python:3.12-alpine \
  sh -c 'mkdir -p /data/tempo/wal /data/tempo/blocks && chown -R 10001:10001 /data/tempo'

Run the original Tempo command again after correcting the permissions.

Point FastAPI to Tempo’s OTLP/HTTP receiver:

export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

After restarting FastAPI and generating another request, the same exporter sends its spans to Tempo instead of Jaeger. To inspect those traces visually, connect Grafana to Tempo through its query endpoint on port 3200. When Grafana and Tempo share a Docker network, the Tempo data source URL can be http://tempo:3200.

Other OTLP-compatible backends can receive the same telemetry once their supported transport, endpoint, and authentication headers are configured.

Deploying FastAPI and Jaeger With Docker Compose

Docker Compose allows FastAPI and Jaeger to run on the same network, avoiding the need to manage their processes separately. The application can reach the tracing backend through its Docker service name, while Jaeger’s interface remains accessible from the host.

Create a Dockerfile in the project directory alongside main.py and telemetry.py:

FROM python:3.12-slim

WORKDIR /app

RUN pip install --no-cache-dir \
    "fastapi==0.162.6" \
    "uvicorn==0.54.0" \
    "opentelemetry-sdk==1.45.2" \
    "opentelemetry-exporter-otlp-proto-http==1.45.2" \
    "opentelemetry-instrumentation-fastapi==0.66b2"

COPY main.py telemetry.py ./

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Create compose.yaml in the same directory:

services:
  jaeger:
    image: cr.jaegertracing.io/jaegertracing/jaeger:2.23.0
    ports:
      - "16686:16686"
      - "4317:4317"
      - "4318:4318"

  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      OTEL_SERVICE_NAME: fastapi-demo
      OTEL_EXPORTER_OTLP_ENDPOINT: http://jaeger:4318
      OTEL_SEMCONV_STABILITY_OPT_IN: http
      OTEL_DEBUG_CONSOLE: "1"
    depends_on:
      - jaeger

The application uses http://jaeger:4318 because localhost inside its container refers to the FastAPI container rather than Jaeger. Docker’s internal service-name resolution allows the application to connect to the tracing backend directly.

Stop any standalone Jaeger or Tempo containers using the same host ports, then run Compose from the fastapi-monitoring directory:

docker compose up --build

Once FastAPI is running, generate a request:

curl http://localhost:8000/items/42

The resulting trace is available in Jaeger at http://localhost:16686. The application also writes console telemetry to its container logs, which you can inspect with:

docker compose logs -f app

Stop the foreground Compose session with Ctrl+C, then remove the containers and network:

docker compose down

The setup runs a single Uvicorn process, keeping SDK initialization straightforward. With multiple workers or Gunicorn, providers and exporters must be initialized within the appropriate worker lifecycle. Creating them before a worker forks can interfere with asynchronous span export, so production deployments need to account for how their application server starts worker processes.

Native FastAPI Telemetry vs. FastAPIInstrumentor vs. opentelemetry-instrument

FastAPI applications can generate OpenTelemetry data through the framework’s native telemetry, programmatic instrumentation with FastAPIInstrumentor, or the opentelemetry-instrument wrapper. All three approaches can capture incoming HTTP requests, but they differ in how instrumentation is enabled and how much control you have over the collected data.

FastAPI’s native telemetry is built into the framework and can record HTTP request traces, metrics, and exception logs. It also supports WebSocket tracing and spans for operations such as dependency resolution and endpoint execution. FastAPIInstrumentor uses OpenTelemetry’s ASGI middleware instead, giving you control over providers, exclusions, request hooks, and captured headers. The wrapper loads supported instrumentation libraries when the application starts and configures the SDK through environment variables or command-line options.

 Native FastAPI TelemetryFastAPIInstrumentor in Codeopentelemetry-instrument Wrapper
SetupConfigure FastAPI’s built-in telemetry and exportersInitialize the SDK and call instrument_app(app)Install the OpenTelemetry distro and run the app through the wrapper
CoverageHTTP requests, WebSockets, request operations, and supported error logsHTTP request spans, metrics, and exception eventsFastAPI requests and other supported libraries with instrumentation installed
ConfigurationFastAPI’s telemetry settings and OpenTelemetry providersPython code, custom providers, request hooks, and exclusionsEnvironment variables and command-line options
Best suited forApplications using FastAPI’s native telemetryApplications needing custom tracing behavior or control over providersApplications needing automatic instrumentation across supported libraries

For the programmatic approach, keep the FastAPIInstrumentor.instrument_app() configuration from the previous section. It gives you direct access to request hooks and span processors, which is useful when traces need application-specific attributes or custom sampling behavior.

FastAPI’s native telemetry is an alternative when those contrib-specific options aren’t needed. It can use configured OpenTelemetry providers or configure OTLP export through FASTAPI_OTEL_AUTO_CONFIGURE=true. The destination must support the signals being exported; Jaeger alone cannot receive the HTTP metrics and logs.

Instrument FastAPI With the opentelemetry-instrument Wrapper

The wrapper uses automatic instrumentation to capture telemetry without requiring manual TracerProvider initialization or an instrument_app() call. It can also instrument supported HTTP clients, database libraries, and other dependencies when their instrumentation packages are installed.

With the virtual environment from the previous setup activated, install the OpenTelemetry distro and exporter:

python -m pip install \
  "opentelemetry-distro==0.66b2" \
  "opentelemetry-exporter-otlp==1.45.2"

Install the instrumentation packages for the libraries already present in the environment:

opentelemetry-bootstrap -a install

Bootstrap identifies supported libraries and installs their corresponding instrumentation packages. The instrumentation becomes active when the application starts through opentelemetry-instrument, not when bootstrap runs.

Create a separate application named zero_code_app.py in the fastapi-monitoring directory:

# zero_code_app.py
from fastapi import FastAPI

app = FastAPI(
    telemetry={
        "tracing": False,
        "metrics": False,
        "logs": False,
    }
)


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 0:
        raise ValueError("negative item id")
    return {"item_id": item_id}

FastAPI’s native telemetry is disabled here so the wrapper’s FastAPI instrumentation is the only source of incoming HTTP spans. No OpenTelemetry SDK initialization or instrumentation calls are needed inside the application.

Ensure Jaeger is running using the Docker command from Step 5 or the Docker Compose setup. If Tempo is using port 4318, stop it first. Configure OTLP/HTTP export so traces reach Jaeger while metrics appear in the application terminal:

export OTEL_SERVICE_NAME=fastapi-zero-code
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=console
export OTEL_LOGS_EXPORTER=none
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_SEMCONV_STABILITY_OPT_IN=http
export OTEL_METRIC_EXPORT_INTERVAL=5000

Start the application through the wrapper on port 8001:

opentelemetry-instrument uvicorn zero_code_app:app --port 8001

Send a successful request followed by one that raises an exception:

curl http://localhost:8001/items/42
curl -i http://localhost:8001/items/-1

Open Jaeger at http://localhost:16686 and select fastapi-zero-code. The successful request should produce a GET /items/{item_id} server span, while the second request produces an HTTP 500 response and an error trace. HTTP metrics will appear in the Uvicorn terminal through the console exporter.

The wrapper creates request spans automatically, but it cannot identify every operation inside an endpoint. Database calls and outgoing HTTP requests need their corresponding instrumentation libraries, while application-specific operations can still be measured with manually created spans.

Avoid Duplicate FastAPI Instrumentation

Use one approach to instrument incoming FastAPI requests. FastAPIInstrumentor skips repeated instrumentation of the same application instance, but running the programmatically instrumented main.py through opentelemetry-instrument can cause SDK provider conflicts and prevent your custom instrumentation settings from taking effect.

If you use the wrapper to instrument other libraries while retaining FastAPI’s native telemetry, disable the wrapper’s FastAPI instrumentor with OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=fastapi. Keep a single SDK configuration path so traces and metrics aren’t exported twice.

Choose programmatic instrumentation when you need request hooks, exclusions, or custom providers. The wrapper is more convenient when automatic coverage across supported libraries matters more than configuring each instrumentor in Python.

Troubleshooting Missing FastAPI Spans

When FastAPI traces or metrics don’t appear in your monitoring backend, the problem may be in the instrumentation, SDK configuration, or export pipeline. Start by running the programmatic setup with OTEL_DEBUG_CONSOLE=1 uvicorn main:app --port 8000 and generating a request. If spans appear in the terminal but not in Jaeger, focus on the exporter and backend connection. Otherwise, check whether the application is recording spans.

ProblemLikely CauseHow to Fix It
No spans appear in the terminalThe tracer provider isn’t configured, instrumentation runs too late, or sampling disables recording.Initialize configure_telemetry() before instrument_app() and before requests are served. Check OTEL_SDK_DISABLED and OTEL_TRACES_SAMPLER. For the wrapper, use OTEL_TRACES_EXPORTER=console,otlp to enable console output.
Spans appear in the terminal but not in JaegerThe OTLP endpoint, port, or transport is incorrect.Confirm that OTLP/HTTP uses port 4318 and /v1/traces for a signal-specific endpoint. OTLP/gRPC uses port 4317. In Docker Compose, use http://jaeger:4318 instead of localhost.
Some requests or routes are missingAn exclusion regex matches more URLs than intended, or sampling drops requests.Check excluded_urls and OTEL_PYTHON_FASTAPI_EXCLUDED_URLS. Use anchored patterns such as /healthz$ where appropriate. Review OTEL_TRACES_SAMPLER and downstream sampling settings.
Requests aren’t traced after enabling instrumentationFastAPI’s middleware stack was already built before instrumentation was registered.Call instrument_app() after creating the application and adding custom middleware, but before startup. Don’t call it inside a lifespan handler.
Duplicate spans or provider warningsNative FastAPI telemetry, FastAPIInstrumentor, or the wrapper is instrumenting requests more than once.Use one FastAPI request instrumentation approach and initialize the SDK once. If combining the wrapper with native FastAPI telemetry, set OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=fastapi.
Traces disappear with reload or multiple workersThe process serving requests lacks instrumentation, or exporters were initialized before a Gunicorn worker fork.Reproduce the issue with one worker and no reload. Ensure each serving process initializes OpenTelemetry. For Gunicorn, initialize providers and exporters after forking to avoid inherited background-thread and lock problems.
HTTP metrics don’t appear in JaegerJaeger accepts traces but doesn’t store OpenTelemetry metrics.Inspect the metrics printed by ConsoleMetricExporter, or use OTLPMetricExporter to send them to a metrics-capable backend or OpenTelemetry Collector.

Once telemetry appears in the expected destination, generate successful and failing requests again to confirm that HTTP attributes, request-duration metrics, and exception events are being captured.

How to Monitor FastAPI Applications With groundcover

groundcover combines OpenTelemetry instrumentation with eBPF-based monitoring to provide visibility into FastAPI request performance, errors, and service dependencies. FastAPIInstrumentor captures application spans and custom attributes, while groundcover’s eBPF sensor observes supported service and network activity without requiring code changes. You can investigate traces alongside logs, metrics, and Kubernetes events to identify the causes of slow or failing requests.

Combining eBPF and OpenTelemetry connects application-level operations with infrastructure and downstream service activity. A FastAPI span can identify time spent processing a request, while eBPF telemetry adds network interactions, HTTP request and response details, and Kubernetes workload context.

Export FastAPI Telemetry to groundcover

For FastAPI applications running in Kubernetes with the groundcover sensor installed, configure the OpenTelemetry exporter to send telemetry directly to the sensor’s in-cluster OTLP endpoint.

Add these environment variables to your FastAPI container’s Kubernetes Deployment:

env:
  - name: OTEL_EXPORTER_OTLP_ENDPOINT
    value: "http://groundcover-sensor.groundcover.svc.cluster.local:4318"
  - name: OTEL_EXPORTER_OTLP_PROTOCOL
    value: "http/protobuf"

The OTLPSpanExporter in telemetry.py sends request traces through OTLP/HTTP. To export HTTP metrics as well, replace ConsoleMetricExporter with OTLPMetricExporter. Both signals can then reach groundcover without changes to your FastAPI routes.

For applications running outside Kubernetes, use your groundcover BYOC ingestion endpoint and a third-party ingestion key:

export OTEL_EXPORTER_OTLP_ENDPOINT="https://YOUR_BYOC_ENDPOINT"
export OTEL_EXPORTER_OTLP_HEADERS="apikey=YOUR_INGESTION_KEY"

Store the ingestion key in your application’s secret management system. If you already use an OpenTelemetry Collector in Kubernetes, you can configure its export pipeline to forward FastAPI telemetry to groundcover alongside your existing destinations.

Verify FastAPI Traces and Metrics in groundcover

Generate successful and failing requests using the /items/42 and /items/-1 endpoints. Open groundcover’s Traces view and search for your FastAPI workload.

For telemetry ingested through the Kubernetes sensor, groundcover adds pod, namespace, node, and cluster metadata. It also sets service.name to the owning Kubernetes Deployment name, so use that name when filtering traces.

Inspect request spans for HTTP status codes, durations, exception events, and custom attributes such as app.tenant_id. The APM views also provide request rates, error rates, and latency measurements for identifying performance problems.

Configure OpenTelemetry Trace Sampling

The sensor’s direct OpenTelemetry ingestion uses a default sampling ratio of 5%. To retain all traces reaching this sampling stage during initial verification, configure the sensor’s Helm values with:

agent:
  sensor:
    apmIngestor:
      otel:
        direct:
          samplingRatio: 1

Apply the updated sensor configuration, generate fresh requests, and confirm that their traces appear in groundcover. You can then adjust the sampling ratio for production traffic.

Investigate FastAPI Performance With eBPF and Agent Mode

groundcover’s eBPF sensor adds visibility into supported service interactions, including HTTP payloads, headers, query parameters, and Kubernetes context. Combined with OpenTelemetry spans, this helps you identify which downstream operations or infrastructure conditions contributed to a slow FastAPI request.

Agent Mode lets you investigate these issues using natural-language questions, such as “Why are HTTP 500 errors increasing for my FastAPI service?” It queries logs, traces, metrics, and Kubernetes events to identify error patterns, contributing services, and infrastructure changes.

With groundcover’s managed Bring Your Own Cloud (BYOC) architecture, telemetry processing and storage run in your cloud account, while groundcover manages the control plane. Your team can monitor FastAPI applications and their Kubernetes dependencies from one platform while keeping observability data in your environment.

FAQs

opentelemetry-python-contrib is the OpenTelemetry project’s repository for Python framework and library instrumentation. It includes opentelemetry-instrumentation-fastapi, the package that provides FastAPIInstrumentor. The instrumentor captures HTTP request spans and metrics, while the OpenTelemetry SDK processes and exports them to your monitoring backend.

Yes. OpenTelemetry Python auto-instrumentation captures FastAPI requests without adding instrument_app() to your application. Install opentelemetry-distro, run opentelemetry-bootstrap -a install, and start the application with opentelemetry-instrument. The wrapper activates supported instrumentation libraries at startup. Avoid enabling overlapping native, manual, and wrapper-based FastAPI instrumentation.

prometheus-fastapi-instrumentator generates Prometheus metrics such as http_requests_total and http_request_duration_seconds, exposing them through /metrics for scraping. FastAPIInstrumentor captures OpenTelemetry HTTP spans and metrics, which can be sent to an OTLP-compatible backend through configured exporters. Use the former for Prometheus-focused HTTP metrics collection and the latter when you also need distributed tracing and request-level context.

Yes. Enable Prometheus’s OTLP receiver with --web.enable-otlp-receiver and configure OTLPMetricExporter to send metrics over HTTP to /api/v1/otlp/v1/metrics. With default name translation, http.server.request.duration becomes http_server_request_duration_seconds. Prometheus 3.0 and later also support preserving dotted OpenTelemetry metric names through the otlp.translation_strategy: NoTranslation setting.

Yes. groundcover’s eBPF sensor monitors supported FastAPI HTTP traffic, request latency, errors, and service dependencies in Kubernetes without requiring SDK instrumentation or application code changes. You can also send OpenTelemetry traces and metrics to groundcover over OTLP to capture custom spans and application-specific attributes. Combining eBPF and OpenTelemetry lets you investigate request performance alongside logs, metrics, Kubernetes events, and downstream service activity.

Sign up for Updates

Keep up with all things cloud-native observability.

We care about data. Check out our privacy policy.