FastAPI: From Basics to Production · Deployment, Observability and Performance
Logging, Metrics and Tracing
Structured logs, Prometheus metrics and OpenTelemetry traces for FastAPI.
Emit structured JSON logs (structlog or logging with a JSON formatter) including request IDs and user IDs; expose metrics (request rate, latency histograms, errors) with prometheus-fastapi-instrumentator or OpenTelemetry metrics; and add traces with opentelemetry-instrumentation-fastapi plus SQLAlchemy and httpx instrumentation to see where time goes across services. Send errors to Sentry or similar.
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from prometheus_fastapi_instrumentator import Instrumentator
FastAPIInstrumentor.instrument_app(app, excluded_urls="health,metrics")
HTTPXClientInstrumentor().instrument()
SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine)
Instrumentator().instrument(app).expose(app, endpoint="/metrics", include_in_schema=False)
tracer = trace.get_tracer(__name__)
async def checkout(order_id: int):
with tracer.start_as_current_span("checkout", attributes={"order.id": order_id}):
...
# Configure exporters via OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_SERVICE_NAME env vars
Common pitfalls
- High-cardinality metric labels (user IDs, raw paths).
- Exposing /metrics publicly.
- Logging request bodies with secrets.
Key points
- JSON logs with request IDs
- RED metrics per route
- OpenTelemetry traces across services
Further reading: OpenTelemetry Python
Practice questions
Why should metrics use the route template (/orders/{id}) rather than the raw path?
Answer
Raw paths create a time series per ID (high cardinality), exploding storage and making aggregation useless.
What does tracing add beyond logs?
Answer
Traces show the timing and causal structure of a request across services and dependencies (DB queries, HTTP calls), pinpointing where latency comes from.
Open in the app to mark lessons complete, take notes and track your progress.