Skip to main content

OpenTelemetry · Python · Tutorial

OpenTelemetry Python in Production: Django, FastAPI and Flask

Bootstrap, framework quirks, Gunicorn and Uvicorn workers, resource attributes, custom spans, log correlation and shutdown: OpenTelemetry Python done properly.

aiAxonIQ Team, Engineering at aiAxonIQ

Nov 12, 20268 min read

Most Python services get a first trace out of OpenTelemetry Python in a few minutes: install the distro, run opentelemetry-bootstrap, prefix the start command with opentelemetry-instrument. The trouble arrives later, and it is specific to how Python applications are deployed. Gunicorn forks workers after the SDK has started its background threads. Development reloaders run your code in a process that was never patched. A FastAPI app initialized in the wrong order emits nothing. And a worker killed with SIGTERM takes its last batch of spans with it.

This guide covers the production setup for Django, FastAPI and Flask in roughly the order those problems show up: installation, framework quirks, pre-fork servers, noise control, resource attributes, custom spans, log correlation and shutdown. Everything uses the upstream OpenTelemetry packages.

Install the distro and let bootstrap pick instrumentations

The opentelemetry-distro package brings the API, the SDK and two command-line tools. opentelemetry-bootstrap scans the packages installed in the active environment and installs the matching instrumentation libraries, so it has to run after your application dependencies are installed, not before:

pip install -r requirements.txt
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install

export OTEL_EXPORTER_OTLP_ENDPOINT="https://app.aiaxoniq.com/otlp"
export OTEL_EXPORTER_OTLP_HEADERS="x-license-key=YOUR_LICENSE_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
export OTEL_SERVICE_NAME="orders-api"

opentelemetry-instrument python app.py
  • Set the protocol explicitly. The Python distro defaults OTEL_EXPORTER_OTLP_PROTOCOL to grpc, unlike the Java agent, which defaults to HTTP. Pointed at an HTTP endpoint without http/protobuf, the service starts normally and the failure only appears as export errors in its logs.
  • Pin what bootstrap installs. Instrumentation packages are versioned in lockstep with the SDK: for example, the 0.66b0 instrumentations pair with SDK 1.45.0. For reproducible images, run opentelemetry-bootstrap -a requirements once, commit the output, and install from that file in your build instead of running bootstrap every time.
  • On uv, opentelemetry-bootstrap -a install can produce a broken environment. The documented alternative is uv run opentelemetry-bootstrap -a requirements | uv add --requirement -, repeated whenever dependencies change.

Framework notes: Django, Flask and FastAPI

Django

The Django instrumentation has to load your settings, so DJANGO_SETTINGS_MODULE must be set in the environment of the instrumented process, not only inside manage.py. For local runs use opentelemetry-instrument python manage.py runserver --noreload: the autoreloader would otherwise run main twice. ORM queries appear as child spans through the database driver instrumentation (psycopg, mysqlclient and so on), which bootstrap installs when it finds the driver. To copy request fields onto server spans, list them in OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS, for example path_info,content_type.

Flask

Flask in debug mode starts a reloader that breaks instrumentation. If you need debug mode locally, keep it and turn the reloader off with app.run(debug=True, use_reloader=False). In production Flask runs under Gunicorn or another WSGI server, which brings its own concern, covered in the next section.

FastAPI

The FastAPI instrumentation patches the FastAPI class itself, so the patch has to be in place before your module executes from fastapi import FastAPI. Under opentelemetry-instrument that happens automatically. If you initialize programmatically, which multi-worker deployments often require, call initialize() at the very top of the entry module:

# main.py
from opentelemetry.instrumentation.auto_instrumentation import initialize

initialize()  # must run before FastAPI is imported

from fastapi import FastAPI

app = FastAPI()

Gunicorn, Uvicorn and the fork problem

This is the issue that causes the most confusion in Python deployments. opentelemetry-instrument gunicorn --workers 4 app:app initializes the SDK in the Gunicorn master, which then forks the workers. A fork copies memory but not threads, so each worker inherits SDK objects whose background threads are not running and whose locks may be held. The OpenTelemetry docs call out PeriodicExportingMetricReader specifically: its export thread does not exist in the children, so metrics break. Per the upstream troubleshooting guide, traces and logs survive multiple workers under both Gunicorn and Uvicorn, while metrics only work out of the box with Gunicorn running Uvicorn workers.

The preferred fix is to initialize OpenTelemetry after the fork, so each worker owns its SDK components. There are three ways to do it.

Gunicorn with Uvicorn workers (ASGI)

For FastAPI, Starlette and other ASGI apps, run Gunicorn with the Uvicorn worker class, which the OpenTelemetry docs recommend for multi-worker auto-instrumentation:

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

Recent Uvicorn releases deprecate the uvicorn.workers module in favor of the separate uvicorn-worker package, which provides the same class as uvicorn_worker.UvicornWorker.

Gunicorn post_fork (WSGI: Django, Flask)

For WSGI apps, drop opentelemetry-instrument from the command and initialize in Gunicorn's post_fork hook instead. The same OTEL_* environment variables still configure everything:

# gunicorn.conf.py, run with: gunicorn -c gunicorn.conf.py --workers 4 orders.wsgi:application
from opentelemetry import metrics, trace
from opentelemetry.instrumentation.auto_instrumentation import initialize


def post_fork(server, worker):
    initialize()


def worker_exit(server, worker):
    # Flush buffered spans and metrics before this worker process ends
    for provider in (trace.get_tracer_provider(), metrics.get_meter_provider()):
        if hasattr(provider, "force_flush"):
            provider.force_flush()

Two rules keep this working. Do not also wrap the command in opentelemetry-instrument, or the master initializes an SDK the workers then inherit. And avoid --preload: it imports your application in the master before the fork, so frameworks are already imported by the time initialize() runs in the worker and the patches arrive too late.

Uvicorn with --workers

Plain uvicorn main:app --workers 2 works with the programmatic pattern from the FastAPI section: initialize() at the top of the module runs inside each worker when it imports the app.

One related change helps metrics in all three setups. Since SDK 1.44.0, every Python process gets its own generated service.instance.id, regenerated in forked children, so per-worker metric streams no longer collide. It does not repair inherited threads, so initialize after the fork regardless. Never set a single service.instance.id for all workers through OTEL_RESOURCE_ATTRIBUTES; metric streams are meant to have one writer each.

Cut the noise before it is exported

Auto-instrumentation records everything it can see, including probes and libraries you do not care about. Two variables handle most of it:

export OTEL_PYTHON_EXCLUDED_URLS="healthz,readyz,metrics"
export OTEL_PYTHON_DISABLED_INSTRUMENTATIONS="redis"
  • `OTEL_PYTHON_EXCLUDED_URLS` takes comma-separated regular expressions and applies to every instrumentation that supports it. To scope an exclusion to one library, use OTEL_PYTHON_<LIBRARY>_EXCLUDED_URLS, such as OTEL_PYTHON_DJANGO_EXCLUDED_URLS, OTEL_PYTHON_FASTAPI_EXCLUDED_URLS or OTEL_PYTHON_REQUESTS_EXCLUDED_URLS.
  • `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS` takes instrumentation entry point names, usually the library name. The gRPC client, for instance, is grpc_client.
  • Kubernetes probes hitting every pod every few seconds are the usual first exclusion. They add trace volume with no diagnostic value.

Resource attributes

Every span, metric and log record carries the resource it came from. Set these from your deployment tooling:

export OTEL_SERVICE_NAME="orders-api"
export OTEL_RESOURCE_ATTRIBUTES="service.version=2.8.1,deployment.environment.name=production,service.namespace=shop"

service.name is the key nearly every backend view groups by; without it the SDK reports a placeholder starting with unknown_service. service.version should come from the release tag or git SHA so you can compare before and after a deploy. deployment.environment.name separates staging from production; older conventions used deployment.environment, so match whatever your dashboards expect.

Custom spans for your own code

Instrumentation covers requests, database calls and outbound HTTP. The business logic in between needs spans you add yourself, using only the opentelemetry-api package:

from opentelemetry import trace

tracer = trace.get_tracer(__name__)


@tracer.start_as_current_span("reserve_inventory")
def reserve_inventory(order):
    trace.get_current_span().set_attribute("order.line_items", len(order.lines))
    return inventory.reserve(order.lines)


def price_order(order):
    with tracer.start_as_current_span("price_order") as span:
        total = apply_promotions(order)
        span.set_attribute("order.total_cents", total)
        return total
  • Exceptions are handled for you. By default, start_as_current_span records an exception that escapes the block and sets the span status to error. Catch and swallow an exception yourself and you have to record it explicitly with span.record_exception().
  • Context follows `await` because it lives in contextvars. It does not follow work handed to a ThreadPoolExecutor or loop.run_in_executor, so spans created there lose their parent. asyncio.to_thread copies the context; for plain executors, add opentelemetry-instrumentation-threading or run the function through contextvars.copy_context().run.
  • Libraries should import only `opentelemetry-api`. Without an SDK configured, the API is a no-op, so shared packages can carry spans without forcing setup on whoever installs them.

Logs that carry the trace ID

There are two separate features here, and it helps to pick one deliberately.

  • OTLP log export. The logging instrumentation attaches a handler to the root logger and turns standard logging records into OpenTelemetry log records, with the active trace and span IDs attached. Since Python SDK 1.40.0 it is on by default under opentelemetry-instrument and controlled by OTEL_PYTHON_LOG_AUTO_INSTRUMENTATION. Earlier releases required OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true.
  • Correlation in text logs. If logs go to stdout and a separate agent ships them, set OTEL_PYTHON_LOG_CORRELATION=true. Every record gains otelTraceID, otelSpanID, otelTraceSampled and otelServiceName attributes, so a formatter can include %(otelTraceID)s in plain text or as a field in JSON logs.

Running both paths at once stores every log line twice. If a log shipper already collects stdout, either keep correlation and set OTEL_LOGS_EXPORTER=none, or keep OTLP export and stop shipping the duplicates.

Sampling

The default sampler is parentbased_always_on, which records every trace and respects upstream decisions. Start there. If volume forces a change, OTEL_TRACES_SAMPLER=parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.25 keeps about a quarter of new traces, decided at the start of each request. Keeping errors and slow requests reliably needs tail sampling, compared in OpenTelemetry sampling: head vs tail.

Shutdown: flush before the process ends

The SDK buffers spans and exports them in batches. Its providers register an atexit handler that flushes and shuts down on normal interpreter exit, so a script that returns from main loses nothing. Three situations bypass it:

  • SIGTERM on a bare process. Python installs no SIGTERM handler, so a queue consumer or scheduler started as python worker.py dies without running atexit. Gunicorn and Uvicorn handle SIGTERM themselves; your own long-running processes need the handler below.
  • Gunicorn workers. The worker_exit hook in the configuration above flushes each worker on its way out.
  • `os._exit`. It skips atexit entirely, and forked multiprocessing children end that way. Call force_flush() on the tracer provider at the end of child work.
import signal
import sys


def _handle_sigterm(signum, frame):
    # Raises SystemExit, so atexit handlers run and the SDK flushes
    sys.exit(0)


signal.signal(signal.SIGTERM, _handle_sigterm)

On Kubernetes, the drain and the flush both have to finish inside terminationGracePeriodSeconds, 30 seconds by default.

Checklist

  • opentelemetry-bootstrap runs after application dependencies, and its output is pinned.
  • OTEL_EXPORTER_OTLP_PROTOCOL matches the endpoint.
  • Multi-worker servers initialize after the fork: Uvicorn workers under Gunicorn, post_fork, or initialize() at the top of the module. No --preload.
  • Reloaders are off wherever instrumentation is expected.
  • Health checks are excluded and unused instrumentations are disabled.
  • service.name, service.version and the environment attribute are set on every deployment.
  • Logs carry trace IDs through exactly one path.
  • SIGTERM leads to a flush in every process type you run.

Sending it to aiAxonIQ

Nothing in this setup is specific to one backend. To send it to aiAxonIQ, the endpoint, license key header and protocol from the first code block are the only settings involved. The APM & Distributed Tracing module receives spans over OTLP, builds the service map from them, and joins them with logs that carry the same trace ID in Log Management.

The Python monitoring page lists the frameworks and libraries the upstream instrumentation covers, with the same setup steps in short form.

Put this into practice with aiAxonIQ APM & Tracing.

More articles