Chapter 87: Prometheus and Grafana Monitoring
87.3 PromQL you use every day
Story. Meera in Pune had to answer three questions in standup: is CPU high, how many requests per second hit shop-api, and what is error ratio? She learned four PromQL ideas: instant selectors, rate(), sum by (), and a simple ratio. Dollar amounts in the runbook stayed in INR for the India team; the US mirror used USD thresholds in a separate rule file.
Why
Raw counters only go up. You almost always want a rate, an aggregate or a ratio before you alert.
What
- Instant vector — Values right now for a selector.
- Range vector — Values over a window, written
[5m]. - rate() — Per-second average increase of a counter over a window.
- sum / avg / max — Aggregations; often with
by (label). - Counter vs gauge — Counters only increase (use rate); gauges go up and down (use raw or avg).
How
- Find the metric name on the target
/metricspage. - Start with a selector in the Prometheus UI.
- Wrap counters in
rate(...[5m]). - Aggregate with
sum by (label) (...). - Build ratios carefully so the denominator stays healthy.
Example 1: Request rate
sum by (job) (rate(http_requests_total[5m]))
Output
{job="shop-api"} 42.3
What it shows: About 42 requests per second across shop-api over five minutes.
Example 2: Error ratio
sum(rate(http_requests_total{code=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
Output
{} 0.021
What it shows: About 2.1% of requests are 5xx. That is a clear alert candidate if it stays high.
Ravindra Bagale's Tip
Counters need rate() or increase(). Gauges like memory used do not.
Counters साठी rate() किंवा increase(). memory used सारख्या gauges साठी नाही.
Counters के लिए rate() या increase(). memory used जैसी gauges के लिए नहीं.
Quick quiz
Q1. Why use rate() on http_requests_total?
It is a counter; rate() turns it into requests per second.
Q2. What does sum by (job) do?
It adds series together while keeping the job label.
Q3. Counter or gauge for CPU idle ratio math?
node_cpu_seconds_total is a counter; you rate it then compute idle ratio.
Did you understand? Let us try it once more.