- Creating a histogram metric
- Recording per-request timings using Flask’s
before_requestandafter_requesthooks - Inspecting the generated Prometheus metrics (including default buckets)
- Customizing histogram buckets
- Using a summary metric and the Python-client limitation for quantiles
Tip: Use per-path and per-method labels to slice latency metrics in Prometheus and visualize percentiles in Grafana or another dashboard.
Basic histogram example
Create a histogram metric and observe latency for each request. Place the timing logic in Flask’sbefore_request and after_request hooks so every request is measured automatically.
before_request()records the timestamp when the request arrives (time.time()).after_request()computes the latency by subtracting the start time from the current time, then callsobserve()on the histogram with the appropriate labels.start_http_server(8000)exposes metrics on port 8000 for Prometheus to scrape.
Note: You can store the
start_time on the request object because Flask exposes a request-local proxy for each incoming request.Example metric output
When you scrape or query the histogram metric in Prometheus, the client creates buckets and count metrics. A scraped output may look like:Customizing histogram buckets
To change bucket boundaries, pass thebuckets parameter when you instantiate the Histogram. For low-latency, high-resolution needs, provide a list of bucket upper bounds:
Using a Summary metric
ASummary records observed values and can calculate configurable quantiles (in some client libraries). The usage pattern is almost identical to a Histogram: create the metric and call .observe() with the measured latency.
Warning: The Python Prometheus client does not implement configurable quantiles for Summary metrics the same way some other language clients do. If you need server-side quantiles, prefer Histograms and compute quantiles in Prometheus (e.g.,
histogram_quantile()), or check the client library updates for support in your language.Histogram vs Summary — quick comparison
Links and references
- Prometheus Python client
- PromQL histogram_quantile()
- Flask request lifecycle (before_request/after_request)