Chapter 87: Prometheus and Grafana Monitoring
87.6 Recording rules and alerting rules
Story. Every dashboard at a Capgemini-style account in Chennai computed the same heavy rate() of fifteen metrics. Graphs were slow. They moved the common expressions into recording rules. Alerts then used the recorded series. CPU page nights got quieter and Grafana panels loaded faster.
Why
Repeating huge queries burns CPU. Alerts need a stable expression and a for: duration so blips do not wake you.
What
- Recording rule — Periodically evaluates PromQL and writes a new time series (faster dashboards).
- Alerting rule — Evaluates PromQL; when true longer than
for:, it fires an alert. - for: — How long the condition must stay true before firing.
- labels / annotations — Extra fields on the alert (severity, summary, runbook URL).
How
- Put rules in a PrometheusRule CR (operator) or a rule file mounted in Prometheus.
- Record expensive aggregations under clear names like
job:http_requests:rate5m. - Write alerts that use those names when possible.
- Always set
for:(often 5m for saturation).
Example 1: Recording rule
groups:
- name: shop.rules
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
What it shows: Every evaluation interval Prometheus stores job:http_requests:rate5m so Grafana can query a cheap series.
Example 2: Alerting rule
- alert: ShopApiHighErrorRate
expr: |
sum(rate(http_requests_total{job="shop-api",code=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="shop-api"}[5m])) > 0.05
for: 10m
labels:
severity: page
annotations:
summary: "shop-api 5xx ratio above 5 percent"
What it shows: Fires only if error ratio stays over 5% for ten minutes. That avoids paging on a one-minute blip.
Ravindra Bagale's Tip
Name recorded metrics with a team convention (many use level:metric:operations). Consistency beats cleverness.
Recorded metrics ला team convention ने नाव द्या. Consistency cleverness पेक्षा मोठी.
Recorded metrics को team convention से नाम दें. Consistency cleverness से बड़ी है.
Quick quiz
Q1. What is a recording rule for?
Precomputing a PromQL result into a new series for speed and reuse.
Q2. What does for: 10m mean?
The alert condition must stay true for ten minutes before it fires.
Q3. Where do fired alerts go next?
Usually to Alertmanager for grouping, silencing and routing.
Did you understand? Let us try it once more.