915 B
915 B
005 Early FastAPI OTel Instrumentation
Context
- HTTP spans and HTTP metrics are provided by FastAPI/ASGI OpenTelemetry middleware.
- Starlette caches
middleware_stackon first ASGI entry, including lifespan startup. - Instrumenting FastAPI inside lifespan is too late for the initial middleware stack.
Decision
- Build the application container before returning the FastAPI app from
create_app. - Configure FastAPI OpenTelemetry instrumentation in the app factory, not in lifespan.
- Pass the configured tracer and meter providers directly to
FastAPIInstrumentor.instrument_app(...). - Keep lifespan focused on shutdown and resource cleanup.
Consequences
OpenTelemetryMiddlewareis present in the runtime stack without manual stack rebuilds.- HTTP traces and HTTP metrics use the same startup wiring as other singleton adapters.
- Observability bootstrap stays explicit in the outer adapter layer.