master/docs/005-fastapi-otel-early-instrumentation.md

17 lines
915 B
Markdown

# 005 Early FastAPI OTel Instrumentation
Context
- HTTP spans and HTTP metrics are provided by FastAPI/ASGI OpenTelemetry middleware.
- Starlette caches `middleware_stack` on 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
- `OpenTelemetryMiddleware` is 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.