Skip to content

OpenTelemetry guide

OpenTelemetry for FastAPI

FastAPI services are async, so context must follow awaits correctly. The OpenTelemetry instrumentations handle that for you, including async database and HTTP clients.

3 min read10 sectionsUpdated

On this page

Key points

  • FastAPIInstrumentor traces each path operation by its route template.
  • Async drivers (asyncpg, SQLAlchemy async, httpx) have their own instrumentations.
  • Avoid --reload with instrumentation; it starts extra processes.
  • Export straight to VitalRix over OTLP/HTTP, or through a Collector.

Install

bash
pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http \
  opentelemetry-instrumentation-fastapi opentelemetry-instrumentation-httpx opentelemetry-instrumentation-asyncpg

Instrument the app

main.pypython
from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

provider = TracerProvider(resource=Resource.create({"service.name": "pricing-api", "service.version": "3.1.0"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")))
trace.set_tracer_provider(provider)

app = FastAPI()
FastAPIInstrumentor.instrument_app(app, excluded_urls="healthz")
HTTPXClientInstrumentor().instrument()
AsyncPGInstrumentor().instrument()

@app.get("/prices/{sku}")
async def get_price(sku: str):
    ...

Running it

bash
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
# or with gunicorn managing uvicorn workers
gunicorn main:app -k uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8000

Because the SDK is set up at import time in each worker process, every worker exports on its own. Avoid --reload in production; with gunicorn, avoid --preload unless you set up the SDK in post_fork.

Async pitfalls

  • Fire-and-forget tasks created with asyncio.create_task inherit the context at creation, which is usually what you want. Make sure they end their spans.
  • Thread pools used for blocking code (run_in_executor) do not carry context automatically; wrap the function to attach the current context.
  • Streaming responses: the server span ends when the response finishes streaming, so long streams look like slow requests. Exclude or name them clearly.

Send it to VitalRix

Shortcut. The VitalRix package does all of the above for you: pip install vitalrix, then vitalrix.init() before the app serves: it turns on every installed instrumentation and sends traces, metrics and logging records. It reads VITALRIX_URL, VITALRIX_API_KEY, OTEL_SERVICE_NAME and DEPLOYMENT_ENVIRONMENT.

Directly. VitalRix accepts OTLP over HTTP with protobuf or JSON, which is what the Python exporter sends. Instead of a Collector at localhost:4318, point the exporter at VitalRix with the per-signal endpoints and your API key. Create the key in VitalRix under Settings, API keys, with trace, metric and log ingestion.

bash
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.vitalrix.com/api/v1/traces/otlp/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.vitalrix.com/api/v1/metrics/otlp/v1/metrics
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.vitalrix.com/api/v1/logs/otlp/v1/logs
export OTEL_EXPORTER_OTLP_HEADERS=x-api-key=your_api_key

Through a Collector. Run an OpenTelemetry Collector next to your app, or as a shared service, when the SDK exports over gRPC or you want one place for batching, sampling and retries. It receives from the SDK and forwards to VitalRix with your key.

otel-collector.yamlyaml
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  memory_limiter: { check_interval: 1s, limit_mib: 512 }
  batch: {}
exporters:
  otlphttp/vitalrix:
    traces_endpoint: ${env:VITALRIX_API}/api/v1/traces/otlp/v1/traces
    metrics_endpoint: ${env:VITALRIX_API}/api/v1/metrics/otlp/v1/metrics
    headers:
      x-api-key: ${env:VITALRIX_KEY}
service:
  pipelines:
    traces:  { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
    metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
bash
docker run -d --name otel-collector -p 4317:4317 -p 4318:4318 \
  -e VITALRIX_API=https://api.vitalrix.com -e VITALRIX_KEY=your_api_key \
  -v "$PWD/otel-collector.yaml:/etc/otelcol-contrib/config.yaml" \
  otel/opentelemetry-collector-contrib:latest

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: pricing-api appears in the service catalog within a minute, with request rate, error rate and p95.
  3. Open an endpoint and then one request to see its trace waterfall, including database spans.
  4. If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a check command that sends one test log.

Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.

Frequently asked questions

Does FastAPI instrumentation include Starlette middleware?

Yes, FastAPI is built on Starlette and the instrumentation wraps the ASGI app, so middleware time is inside the server span.

Can I use zero-code instrumentation with FastAPI?

Yes: opentelemetry-instrument uvicorn main:app. Do not combine it with instrument_app in code.

  • OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
  • OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
  • OpenTelemetry for NestJS: Trace a NestJS service with OpenTelemetry: load the SDK before Nest boots, instrument HTTP, Express and NestJS core, and export JSON to VitalRix.
  • OpenTelemetry for Next.js: Trace a Next.js app with OpenTelemetry using instrumentation.ts: Node.js runtime setup, JSON export straight to VitalRix, fetch spans and Edge caveats.
  • OpenTelemetry for Ruby on Rails: Trace a Ruby on Rails app with OpenTelemetry: gems, an initializer with use_all, ActiveRecord and Sidekiq spans, Puma workers and exporting to VitalRix.
  • OpenTelemetry for Django: Trace a Django app with OpenTelemetry: auto-instrument views and the ORM, run under gunicorn safely, trace Celery tasks and export to VitalRix.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.