Data and monitoring · Intermediate · 24 min
Instrument a Python app with Prometheus metrics
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Python 3.14 · FastAPI 0.165.0 · prometheus-client 0.26.0 · Prometheus 3.16.0
You will add a request counter, a latency histogram, an in-progress gauge and a version metric to a FastAPI app with prometheus-client 0.26, serve them on a private port, and have Prometheus 3.16 scrape and query them.
On this page
Server monitoring tells you a machine is busy. It cannot tell you that checkout is slow, or that one route has started returning 404s. For that the application has to report on itself: how many requests it handled, how long they took and how many failed. Adding those measurements to code is called instrumentation.
In this tutorial you take a small FastAPI shop API and instrument it with prometheus-client, the official Python library for Prometheus. You add four metrics, each a different type: a counter of requests, a histogram of how long they take, a gauge of requests in progress and an info metric with the app's version. The library publishes them as a plain text page on a second port, kept away from the public one. Then Prometheus scrapes that page every few seconds and you query the results over its HTTP API.
Along the way you learn the rule that matters most when you choose labels: every distinct combination of label values is a separate time series that Prometheus stores. Choose them carelessly and one metric can grow into millions of series.
If you have not met Prometheus before, monitoring a server with Prometheus and Node Exporter explains scraping and PromQL from the start.
Step 1 · Create the project
Install the Python virtual environment module, curl and jq, then make a folder for the demo and a virtual environment inside it. The exact versions keep the output you see in line with this page:
sudo apt update
sudo apt install -y python3-venv curl jq
mkdir -p ~/metrics-demo
cd ~/metrics-demo
python3 -m venv .venv
.venv/bin/pip install "fastapi==0.165.0" "uvicorn==0.54.0" "prometheus-client==0.26.0"Ubuntu 26.04's python3 is Python 3.14, which all three packages support. Uvicorn is the server that runs the FastAPI app.
Check it worked
.venv/bin/python -c "import fastapi; from importlib.metadata import version; print(fastapi.__version__, version('prometheus-client'))"The command prints 0.165.0 0.26.0.
Step 2 · Write the app you will measure
Create app.py. It has three routes: a product list, one product by ID (with a 404 for unknown IDs) and a checkout that waits 200 milliseconds, standing in for a call to a payment provider. That wait gives the latency metric something to show later:
cat > app.py <<'PY'
import asyncio
from fastapi import FastAPI, HTTPException
app = FastAPI(title="Shop API")
PRODUCTS = {
1: {"id": 1, "name": "Solar lantern", "price": 18.5},
2: {"id": 2, "name": "Phone charger", "price": 7.0},
3: {"id": 3, "name": "Water filter", "price": 32.0},
}
@app.get("/api/products")
async def list_products():
return list(PRODUCTS.values())
@app.get("/api/products/{product_id}")
async def get_product(product_id: int):
if product_id not in PRODUCTS:
raise HTTPException(status_code=404, detail="No such product")
return PRODUCTS[product_id]
@app.post("/api/checkout")
async def checkout():
await asyncio.sleep(0.2) # stands in for a call to a payment provider
return {"status": "paid"}
PYStart it in your first terminal, from ~/metrics-demo, and leave it running. APP_VERSION is read later by the info metric:
cd ~/metrics-demo
APP_VERSION=1.4.0 .venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000Uvicorn prints Uvicorn running on http://127.0.0.1:8000. Run the remaining commands in your third terminal.
Check it worked
curl -s http://127.0.0.1:8000/api/products/2 | jq -r .name
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/products/99The first line is Phone charger and the second is 404.
Step 3 · Serve metrics on their own port
Keep the metrics code in its own file, metrics.py, so the routes stay readable. For now it only starts the metrics server: start_http_server runs a small web server in a background thread that answers with every metric the process has registered.
cat > metrics.py <<'PY'
import os
from fastapi import FastAPI
from prometheus_client import start_http_server
def setup_metrics(app: FastAPI) -> None:
port = int(os.environ.get("METRICS_PORT", "8001"))
addr = os.environ.get("METRICS_ADDR", "127.0.0.1")
start_http_server(port, addr=addr)
PY
cat >> app.py <<'PY'
from metrics import setup_metrics
setup_metrics(app)
PYThe second command adds three lines to the end of app.py, after the routes, so the app sets up its metrics when Uvicorn loads it.
Why a separate port rather than a /metrics route on the app? Your public port usually sits behind a proxy that the internet can reach. Metrics reveal traffic volumes, route names and versions, so they should only be readable by Prometheus. A second port means the proxy never forwards them, and you can firewall that port on its own. The address matters too: it comes from METRICS_ADDR and falls back to 127.0.0.1, because the library's own default is 0.0.0.0, every network interface.
One limit to know now: this works with a single Uvicorn process. If you run several workers (--workers 4), each process keeps its own numbers and would try to open the same port. prometheus-client has a multiprocess mode for that case, with its own setup.
Stop Uvicorn with Ctrl+C in the first terminal and start it again with the same command, so it loads the new code:
APP_VERSION=1.4.0 .venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000Check it worked
curl -s http://127.0.0.1:8001/metrics | grep -E '^(python_info\{|process_resident_memory_bytes )'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/metricsYou see python_info with your Python version as labels and process_resident_memory_bytes with the app's memory use. The library collects these for free. The last line prints 404: the public port has no metrics page.
Step 4 · Count requests with route and status labels
A counter only goes up. Prometheus works out rates from it, such as requests per second, by comparing values over time. You want one counter for all requests, split by three labels: the HTTP method, the route and the status code.
The route label is where most instrumentation goes wrong. Use the route template, /api/products/{product_id}, never the raw path, /api/products/2. Prometheus stores a separate time series for each distinct combination of label values, and each one costs memory and disk for as long as it receives data. With templates, this app has a handful of routes, two methods and a few status codes: a few dozen series at most. With raw paths, every product ID becomes a new series, and so does every made-up URL a bot tries, which is unbounded.
The same reasoning rules out user IDs, email addresses, order numbers, IP addresses and full URLs as labels. They have no fixed upper limit. If you need to find one user's requests, that belongs in logs or traces, which are built for individual events.
FastAPI records the route that matched in the request scope, so the middleware can read the template after the request has been handled. Requests that match no route get the fixed value unmatched. Replace metrics.py:
cat > metrics.py <<'PY'
import os
from fastapi import FastAPI, Request
from prometheus_client import Counter, start_http_server
REQUESTS = Counter(
"shop_http_requests",
"HTTP requests handled, by method, route template and status code.",
["method", "route", "status"],
)
def route_template(request: Request) -> str:
route = request.scope.get("route")
return getattr(route, "path", "unmatched")
def setup_metrics(app: FastAPI) -> None:
@app.middleware("http")
async def track_requests(request: Request, call_next):
status = "500"
try:
response = await call_next(request)
status = str(response.status_code)
return response
finally:
REQUESTS.labels(request.method, route_template(request), status).inc()
port = int(os.environ.get("METRICS_PORT", "8001"))
addr = os.environ.get("METRICS_ADDR", "127.0.0.1")
start_http_server(port, addr=addr)
PYThe finally block runs even when a route raises an error, so a crash is still counted, as a 500.
Restart Uvicorn as before, with Ctrl+C and the same command.
Check it worked
Send a few requests, including two that fail in different ways, then read the counter:
for i in 1 2 3; do curl -s -o /dev/null http://127.0.0.1:8000/api/products; done
curl -s -o /dev/null http://127.0.0.1:8000/api/products/2
curl -s -o /dev/null http://127.0.0.1:8000/api/products/99
curl -s -o /dev/null http://127.0.0.1:8000/api/products/abc
curl -s -o /dev/null http://127.0.0.1:8000/wp-login.php
curl -s http://127.0.0.1:8001/metrics | grep '^shop_http_requests_total'You get these lines, in this order:
shop_http_requests_total{method="GET",route="/api/products",status="200"} 3.0
shop_http_requests_total{method="GET",route="/api/products/{product_id}",status="200"} 1.0
shop_http_requests_total{method="GET",route="/api/products/{product_id}",status="404"} 1.0
shop_http_requests_total{method="GET",route="/api/products/{product_id}",status="422"} 1.0
shop_http_requests_total{method="GET",route="unmatched",status="404"} 1.0Three requests for different products share one series, abc fails FastAPI's integer check with a 422, and the scan for /wp-login.php lands under unmatched instead of creating a series of its own. The library added _total to the name, as Prometheus expects of counters. You will also see shop_http_requests_created lines: the time each series started, which Prometheus can use to spot restarts.
Step 5 · Add latency, in-progress and version metrics
Three more metrics complete the picture.
A histogram records how long each request took by counting it into buckets: "at most 10 ms", "at most 25 ms" and so on. Choose bucket boundaries for your app, not the library's defaults. This shop has fast product reads and a checkout that should finish within 300 ms, so the buckets are dense below half a second, include 0.3 exactly, and stop at 2.5 seconds. A boundary at your target means "what share of checkouts met 300 ms?" has an exact answer. Each bucket is one more series per method and route, so ten or so is plenty.
A gauge can go up and down. shop_http_requests_in_progress goes up when a request starts and down when it ends, which shows a build-up of slow requests before they turn into timeouts.
An info metric carries text as labels with a constant value of 1. Putting the version there lets you line up a change in errors with a deploy, without adding a version label to every other metric.
Replace metrics.py with the full version:
cat > metrics.py <<'PY'
import os
import time
from fastapi import FastAPI, Request
from prometheus_client import Counter, Gauge, Histogram, Info, start_http_server
REQUESTS = Counter(
"shop_http_requests",
"HTTP requests handled, by method, route template and status code.",
["method", "route", "status"],
)
LATENCY = Histogram(
"shop_http_request_duration_seconds",
"Time spent handling HTTP requests, in seconds.",
["method", "route"],
buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.3, 0.5, 1.0, 2.5),
)
IN_PROGRESS = Gauge(
"shop_http_requests_in_progress",
"HTTP requests being handled right now.",
)
BUILD = Info("shop_build", "Version of the running app.")
def route_template(request: Request) -> str:
route = request.scope.get("route")
return getattr(route, "path", "unmatched")
def setup_metrics(app: FastAPI) -> None:
BUILD.info({"version": os.environ.get("APP_VERSION", "dev")})
@app.middleware("http")
async def track_requests(request: Request, call_next):
start = time.perf_counter()
status = "500"
IN_PROGRESS.inc()
try:
response = await call_next(request)
status = str(response.status_code)
return response
finally:
IN_PROGRESS.dec()
route = route_template(request)
REQUESTS.labels(request.method, route, status).inc()
LATENCY.labels(request.method, route).observe(time.perf_counter() - start)
port = int(os.environ.get("METRICS_PORT", "8001"))
addr = os.environ.get("METRICS_ADDR", "127.0.0.1")
start_http_server(port, addr=addr)
PYDurations are in seconds, the unit Prometheus uses everywhere, and the name says so. time.perf_counter() is the right clock for measuring intervals because it never jumps when the system clock is corrected.
The histogram has no status label. Method and route are enough to find a slow endpoint, and leaving status out keeps the series count down: every label you add multiplies it.
These timings stop at your server. A user on a slow mobile connection, common for people on prepaid data in many African markets, waits for the network on top of this. Server latency is the part you control. Measure what users feel in the browser or app separately.
Restart Uvicorn once more, with the same command.
Check it worked
Make two checkouts and read the new metrics:
curl -s -X POST http://127.0.0.1:8000/api/checkout
echo
curl -s -X POST http://127.0.0.1:8000/api/checkout
echo
curl -s http://127.0.0.1:8001/metrics | grep -E '^shop_http_request_duration_seconds_(bucket|count).*checkout'
curl -s http://127.0.0.1:8001/metrics | grep -E '^shop_(http_requests_in_progress|build_info)'Each checkout prints {"status":"paid"}. In the histogram lines, the buckets up to le="0.1" read 0.0 and those from le="0.25" up read 2.0: both checkouts took a little over 200 ms. _count is 2.0. The last two lines are shop_http_requests_in_progress 0.0, since nothing is running while you read it, and shop_build_info{version="1.4.0"} 1.0.
Step 6 · Have Prometheus scrape the app
If Prometheus already runs as a service from the Node Exporter tutorial, add the job below under scrape_configs in /etc/prometheus/prometheus.yml, then check and reload:
promtool check config /etc/prometheus/prometheus.yml
sudo systemctl reload prometheusOtherwise, run Prometheus 3.16.0 from the demo folder to try it. Download the release for your CPU and check it against the published checksums:
cd ~/metrics-demo
PROM_VERSION=3.16.0
ARCH="$(dpkg --print-architecture)"
BASE="https://github.com/prometheus/prometheus/releases/download/v${PROM_VERSION}"
curl -fsSLO "${BASE}/prometheus-${PROM_VERSION}.linux-${ARCH}.tar.gz"
curl -fsSL -o prometheus-sha256sums.txt "${BASE}/sha256sums.txt"
sha256sum --ignore-missing -c prometheus-sha256sums.txt
tar -xzf "prometheus-${PROM_VERSION}.linux-${ARCH}.tar.gz"
mv "prometheus-${PROM_VERSION}.linux-${ARCH}" prometheussha256sum prints the file name followed by OK. Now write the configuration with one scrape job for the app's metrics port:
cat > prometheus.yml <<'YAML'
global:
scrape_interval: 15s
scrape_configs:
- job_name: shop-api
scrape_interval: 5s
static_configs:
- targets: ["127.0.0.1:8001"]
labels:
service: shop-api
YAML
prometheus/promtool check config prometheus.ymlpromtool reports SUCCESS: prometheus.yml is valid prometheus config file syntax. The five-second interval is only so that data arrives quickly while you follow along. Remove that line to fall back to the 15-second default.
Start Prometheus in your second terminal, from ~/metrics-demo, and leave it running:
cd ~/metrics-demo
prometheus/prometheus --config.file=prometheus.yml --storage.tsdb.path=data --web.listen-address=127.0.0.1:9090Its log includes a line with msg="Server is ready to receive web requests.".
Check it worked
Ask Prometheus whether the scrape succeeds:
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=up{job="shop-api"}' | jq -r '.data.result[0].value[1]'The answer is 1. A 0 means Prometheus reached nothing at 127.0.0.1:8001: check that Uvicorn is still running in the first terminal.
Step 7 · Query the metrics over the HTTP API
Everything in the Prometheus web page is also available at /api/v1/query, which is what dashboards and scripts use. Send some traffic first, then wait for a few scrapes:
for i in 1 2 3 4 5; do curl -s -o /dev/null -X POST http://127.0.0.1:8000/api/checkout; done
for i in 1 2 3 4 5; do curl -s -o /dev/null http://127.0.0.1:8000/api/products; done
sleep 15Requests per route and status, summed over everything the app has handled:
curl -s http://127.0.0.1:9090/api/v1/query \
--data-urlencode 'query=sum by (route, status) (shop_http_requests_total)' \
| jq -r '.data.result[] | "\(.metric.route) \(.metric.status) \(.value[1])"' | sortThe 95th percentile checkout time over the last minute, worked out from the histogram buckets:
curl -s http://127.0.0.1:9090/api/v1/query \
--data-urlencode 'query=histogram_quantile(0.95, sum by (le) (rate(shop_http_request_duration_seconds_bucket{route="/api/checkout"}[1m])))' \
| jq -r '.data.result[0].value[1]'The version that is running, and how many series the app produces in total:
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=shop_build_info' | jq -r '.data.result[0].metric.version'
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=count({__name__=~"shop_.*"})' | jq -r '.data.result[0].value[1]'Check it worked
The first query lists lines such as /api/checkout 200 7 and /api/products 200 5: the two checkouts from the previous step plus the five just now. Requests from before the last restart are gone, because the counters live in the process and start again at zero.
The percentile is a number between 0.1 and 0.25, something like 0.2425. The real checkouts took just over 0.2 seconds, but histogram_quantile only knows that they fell between the 0.1 and 0.25 boundaries, and it interpolates inside that bucket. That is why buckets should sit close to the values you care about: a boundary just above the typical checkout time, such as 0.22, makes the bucket holding the true value narrower, so the worst-case error shrinks.
The version query prints 1.4.0. The series count is a few dozen. Watch that number as you add metrics: if it climbs with traffic rather than with code changes, a label is taking values it should not. For more queries on this data, such as error ratios and request rates, go on to the PromQL tutorial.
Step 8 · Lock down the metrics port and remove the demo
When you run this for real, Prometheus scrapes the metrics port across your private network. Start the app with METRICS_ADDR set to the server's private address (for example METRICS_ADDR=10.0.0.5, using your own), so start_http_server listens there instead of on 127.0.0.1, and allow only the Prometheus server to reach the port. With UFW, replacing the address with your Prometheus server's own:
sudo ufw allow from 10.0.0.2 to any port 8001 proto tcpThe UFW tutorial covers the rest of the firewall.
To remove what you built here, stop Prometheus and Uvicorn with Ctrl+C in their terminals. Then delete the demo folder, which holds the app, the virtual environment, the Prometheus download and its data:
cd ~
rm -rf ~/metrics-demoCheck it worked
ls ~/metrics-demo 2>/dev/null || echo "removed"
curl -s -o /dev/null --connect-timeout 2 http://127.0.0.1:9090/-/ready || echo "Prometheus stopped"The commands print removed and Prometheus stopped.
Next steps
- Turn these counters and buckets into request rates, error ratios and latency percentiles: write PromQL for request rates, errors and latency.
- Save the queries you run often so dashboards stay fast: record and reuse queries with Prometheus recording rules.
- Put the graphs on a screen: build a Grafana dashboard.
- Run Prometheus as a hardened service with server metrics alongside: monitor a server with Prometheus and Node Exporter.
Related tutorials
- How to Monitor a Linux Server with Prometheus and Node ExporterYou will install Node Exporter 1.12 and Prometheus 3.16 from the official release files on Ubuntu 26.04, run both as locked-down systemd services that listen on localhost only, and query your server's CPU, memory and uptime with PromQL.
- Write PromQL for request rates, errors and latencyYou will write the PromQL queries for a service's request rate, error ratio and p95 latency, plus week-on-week and missing-data checks, and prove every one with promtool unit tests over synthetic data.
- How to Build a REST API with FastAPIYou will build a small items API with FastAPI 0.163 on Python 3.15 that validates its input, returns the right HTTP status codes, never shows a stack trace to callers, documents itself, and has automated tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials