FastAPI Metrics
NotesSo, we have a Prometheus instance running in a container, and a node_exporter running on the host. It’s time to publish some metrics from the application too.
There are a few options, but here we’ll use prometheus-fastapi-instrumentator:
pip install prometheus-fastapi-instrumentatorAdd it to the non_ver_reqs.txt file:
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillow
captcha
pwdlib[argon2]
pyjwt
stripe
prometheus-fastapi-instrumentatorpip freeze > requirements.txtBack in main.py, import the Instrumentator:
from prometheus_fastapi_instrumentator import Instrumentator # NEWdef configure():
prometheus_metrics() # NEW
configure_routing()
def prometheus_metrics():
# Request counts and durations for every route, published at /metrics
Instrumentator(excluded_handlers=["/metrics"]).instrument(main_app).expose(
main_app, include_in_schema=False, should_gzip=True)There are two parts: .instrument() adds middleware that measures every request, and .expose() adds the /metrics page that Prometheus scrapes. excluded_handlers leaves out requests to /metrics itself, which would otherwise be counted every 15 seconds.
An earlier version of this guide only called .expose(), which publishes Python’s own process metrics but no request metrics at all.
Running the application now, there’s a /metrics page at http://localhost:8000/metrics, with metrics such as:
# HELP http_requests_total Total number of requests by method, status and handler.
# TYPE http_requests_total counter
http_requests_total{handler="/",method="GET",status="2xx"} 12.0
http_requests_total{handler="/contact",method="GET",status="2xx"} 2.0
# HELP http_request_duration_seconds Latency with only few buckets by handler. Made to be only used if aggregation by handler is important.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{handler="/",le="0.1",method="GET"} 12.0
...
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 9.99424e+07Requests are grouped by route (handler="/blog/{id}" rather than every individual post) and by status class (2xx, 4xx, 5xx), which keeps the number of different metrics manageable.
Now add the application as a scrape target. With fastapi dev or python main.py on port 8000, Prometheus reaches it at host.containers.internal:8000:
- job_name: 'fastapi'
static_configs:
- targets: ['host.containers.internal:8000']fastapi dev only listens on 127.0.0.1, which containers can’t reach, so start it with fastapi dev main.py --host 0.0.0.0. If you’re running the application with TLS, as in the Getting Started section, add scheme: https to the job, and tls_config: {insecure_skip_verify: true} for a self-signed certificate.
podman restart prometheus/metrics is public: anyone can see how busy your site is. That’s usually harmless, but in production you might want to block it at the reverse proxy, or in OpenShift, only expose it inside the cluster.
That’s cool, but how about something custom?