Prometheus & custom Python metrics
Expose metrics from your app and write alerting rules.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
Prometheus pulls numeric metrics from your services on a schedule and stores them as time series. You query them with PromQL and define alert rules that fire when something goes wrong.
Explained simply
Prometheus is a program that collects numbers about your systems over time. Examples are how many requests your API served, how many failed, and how long they took. Each number with a timestamp is a sample, and a list of samples over time is called a time series.
Prometheus works by asking. Every few seconds it sends an HTTP request to each service it watches and reads a plain text page, usually at /metrics. This is called scraping. Your app does not need to know where Prometheus is; it only has to serve that page.
In Python, the prometheus_client library builds that page for you. You create a metric object once, like a counter for requests, and update it in your code. The library keeps the current values in memory and prints them when Prometheus asks.
To read the data you write queries in PromQL, the Prometheus query language. To be warned about problems, you write alert rules: a query plus a condition. When the condition stays true long enough, Prometheus sends the alert to Alertmanager, which notifies a person.
Press Play on a diagram to walk through it one step at a time.
- Prometheus to FastAPI app: GET /metrics every 15s1GET /metrics every 15s
- FastAPI app to Prometheus: Counters and histograms2Counters and histograms
- Prometheus to Alertmanager: Rule fires: HighErrorRate3Rule fires: HighErrorRate
- Alertmanager to On-call: Grouped notification sent4Grouped notification sent
- On-call to Alertmanager: Silence while fixing5Silence while fixing
- 1Grafana
Dashboards built from PromQL queries
- 2Alertmanager
Groups, routes and silences alerts
- 3Prometheus server
Scrapes, stores, evaluates rules
- 4Exporters
node_exporter, kube-state-metrics, cAdvisor
- 5Your app's /metrics
Custom counters and histograms
In depth
The data model: names, labels and samples
Every time series is identified by a metric name plus a set of labels, which are key and value pairs. http_requests_total{method="GET", route="/orders", status="200"} and the same name with status="500" are two different series. Each scrape adds one sample (a timestamp and a float value) to every series.
This makes labels powerful: you can sum, filter and group by any of them. It also makes them dangerous. Every new label value creates a new series, and Prometheus keeps recent series in memory. A label like user_id or full URL path with IDs inside can create millions of series and run the server out of memory. This is the cardinality problem.
Prometheus also adds two labels itself when it scrapes: job (from the scrape config) and instance (the host and port of the target). It also records a series called up for each target: 1 if the last scrape worked, 0 if it failed.
- Use labels for small, fixed sets: method, route template, status code
- Never put user IDs, emails or raw URLs in labels
- up == 0 is the first query to run when a target looks silent
Running Prometheus and configuring a scrape
Prometheus is a single binary that listens on port 9090 and stores data on local disk (15 days by default, changed with --storage.tsdb.retention.time). Its main file is prometheus.yml. The global section sets scrape_interval; the built-in default is 1 minute, but 15 seconds is the common choice. Each entry in scrape_configs is a job with a list of targets.
In Docker Compose, targets are reached by service name, for example api:8000. In Kubernetes you rarely list targets by hand. Prometheus discovers Pods and Services through the Kubernetes API (kubernetes_sd_configs), or, with the Prometheus Operator, you create a ServiceMonitor object that selects Services by label.
After starting it, open http://localhost:9090 and go to Status, then Targets. Each target shows UP or DOWN plus the last error, such as connection refused or a timeout. promtool check config prometheus.yml validates the file before you restart.
- 1Read prometheus.yml
Jobs, targets and scrape interval
- 2Discover targets
Static list, or Kubernetes API
- 3Scrape /metrics
HTTP GET on each target, every interval
- 4Add job and instance
Labels that say where data came from
- 5Write to TSDB
Compressed blocks on local disk
Choosing the metric type
prometheus_client offers four types. A Counter only goes up (and resets to zero when the process restarts); use it for things you count, like requests, errors or bytes sent. The library adds the _total suffix to the exposed name. A Gauge can go up and down; use it for current values like queue length, open connections or temperature.
A Histogram counts observations into buckets. For a latency histogram you get one _bucket series per bucket (with an le label meaning less than or equal), plus _sum and _count. The default buckets run from 5 ms to 10 s, which fits most web APIs; pass buckets=[...] when your latencies are very different. Because buckets can be added up across Pods, histograms let you compute a p95 for the whole service.
A Summary calculates quantiles inside each process. In client_python it only exposes _count and _sum, and quantiles from several Pods cannot be combined anyway, so histograms are the usual choice.
- Only increases
- Requests, errors, bytes
- Query with rate() or increase()
- Goes up and down
- Queue length, connections in use
- Query the value directly
- Counts values into buckets
- Latency, request size
- Query with histogram_quantile()
How PromQL rate() really works
A selector like http_requests_total returns an instant vector: the latest value of each matching series. Adding a range, like http_requests_total[5m], returns a range vector: all samples from the last five minutes. Functions like rate() take a range vector and return one value per series.
rate() computes the per-second average increase over the window. It also handles counter resets: if the value drops (the Pod restarted), rate() treats the drop as a reset instead of a negative change. increase() is the same idea expressed as a total over the window, so increase(x[1h]) is roughly rate(x[1h]) times 3600.
The window must contain at least two samples, so a common rule is to make it at least four times the scrape interval. With 15 second scrapes, [1m] works and [5m] is smoother. Always apply rate() first and sum() after: sum(rate(x[5m])), never rate(sum(x)), because summing first hides the resets.
- sum by (route) (...) keeps only the route label in the result
- =~ and !~ match labels with regular expressions, like status=~"5.."
- Check queries in the Prometheus web UI Graph tab before using them in alerts
Alert rules that page for the right reasons
An alerting rule lives in a rules file listed under rule_files in prometheus.yml. Each rule has alert (the name), expr (a PromQL expression), for (how long it must stay true), labels (such as severity) and annotations (human text such as summary). Prometheus evaluates rules every evaluation_interval. While expr is true but for has not passed, the alert is pending; after that it is firing and is sent to Alertmanager.
Alertmanager (port 9093) groups related alerts into one notification, removes duplicates, routes by labels (severity critical to the pager, warning to a chat channel) and supports silences during planned work.
Good alerts describe user pain: high error ratio, high p99 latency, or the service being down. Alerting on CPU at 80% usually creates noise, because high CPU without user impact is not an emergency. Use ratios rather than raw counts, so the alert works at both quiet and busy times. Validate files with promtool check rules.
- 1Inactive
Expression returns nothing
- 2Pending
True, waiting for the for duration
- 3Firing
Sent to Alertmanager, someone is notified
- 4Resolved
Expression false again, resolve message sent
- Back to step 1
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Run Prometheus and scrape a target~50m
- 2Expose metrics with prometheus_client~50m
- 3Add counters and histograms~50m
- 4Write PromQL queries~50m
- 5Define an alerting rule~50m
Key points
- Prometheus pulls metrics; your app just exposes them on /metrics.
- Counters only go up; use rate() to turn them into per-second values.
- Histograms record durations in buckets so you can compute percentiles.
- Alert rules need a for: duration so brief blips do not page anyone.
Key terms
Tap a card to flip it. 0/5 known
Examples
from prometheus_client import Counter, Histogram, start_http_server
import random, time
REQUESTS = Counter("http_requests_total", "Requests", ["status"])
LATENCY = Histogram("http_request_duration_seconds", "Latency")
start_http_server(8001) # serves /metrics
while True:
with LATENCY.time():
time.sleep(random.random() / 10)
REQUESTS.labels(status="200").inc()
# PromQL: sum(rate(http_requests_total{status=~"5.."}[5m]))Expose a counter and histogram, then query the error rate.
Instrument a FastAPI app with a middleware
Step 1: create a counter and a histogram at module level, so they exist once per process. Step 2: add an HTTP middleware that times every request. Step 3: label by the route template (like /orders/{id}), not the raw path, to keep cardinality low. Step 4: mount the prometheus_client ASGI app at /metrics. Step 5: run uvicorn, call a few endpoints and open /metrics to see the new series. Note: with several worker processes you must use client_python's multiprocess mode, or each worker reports only its own numbers.
import time
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, make_asgi_app
REQS = Counter("http_requests", "HTTP requests", ["method", "route", "status"])
LAT = Histogram("http_request_duration_seconds", "Request latency", ["route"])
app = FastAPI()
app.mount("/metrics", make_asgi_app())
@app.middleware("http")
async def metrics(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
route = getattr(request.scope.get("route"), "path", "unmatched")
LAT.labels(route).observe(time.perf_counter() - start)
REQS.labels(request.method, route, str(response.status_code)).inc()
return responseScrape the app and add an error-ratio alert
Step 1: in prometheus.yml set a 15 second scrape interval and add a job that targets api:8000. Step 2: list a rules file. Step 3: in the rule, divide the 5xx rate by the total rate, so the alert means more than 5% of requests are failing. Step 4: for: 10m stops short spikes from paging anyone. Step 5: run promtool check config and promtool check rules, reload Prometheus, and look at the Alerts page, where the rule shows as inactive, pending or firing.
# prometheus.yml
global:
scrape_interval: 15s
rule_files: ["alerts.yml"]
scrape_configs:
- job_name: api
static_configs:
- targets: ["api:8000"]
# alerts.yml
groups:
- name: api
rules:
- alert: HighErrorRatio
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.05
for: 10m
labels: { severity: page }Quick reference
- Prometheus listens on 9090, Alertmanager on 9093, node_exporter on 9100
- up == 0 lists every target whose last scrape failed
- sum by (route) (rate(http_requests_total[5m])) gives requests per second per route
- histogram_quantile(0.95, sum by (le) (rate(x_bucket[5m]))) gives the p95 across all Pods
- Make rate() windows at least 4 times the scrape interval
- promtool check config prometheus.yml and promtool check rules alerts.yml catch mistakes
- Label by route template, never by user ID or raw URL
Common mistakes
- Labels with unbounded values like user ID, which explode memory use.
- Graphing a raw counter instead of rate(), which only shows a rising line.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run Prometheus in Docker so that it scrapes itself, and find the up series in the web UI.
- Exercise 2medium
Add a Gauge called jobs_in_queue to a Python worker that rises when a job is added and falls when it finishes, and expose it on port 8001.
- Exercise 3hard
Write an alert that fires when p99 latency of the api job is above 500 ms for 10 minutes, with a summary annotation that shows the current value.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can Prometheus receive pushed metrics?
- Prometheus is pull-based. For short batch jobs that end before they can be scraped, push to a Pushgateway, which Prometheus then scrapes; do not use it for normal services.
- How long does Prometheus keep data?
- By default 15 days on local disk. For long-term or highly available storage, teams add a remote backend such as Thanos, Grafana Mimir or a managed Prometheus service.
- What is the difference between rate() and irate()?
- rate() averages the increase over the whole window, which is smooth and right for alerts. irate() uses only the last two samples, so it reacts fast but is jumpy and best for zoomed-in graphs.
- Do I need an exporter for my Python app?
- No. Exporters are for software you cannot change, like Linux hosts or databases. For your own code, prometheus_client exposes metrics directly.