Prometheus Rules

Alerts are defined as Prometheus rules. (Not to be confused with Alertmanager, in the next section, which only decides what to do once an alert fires.)

What is a Prometheus rule? It’s a query with a condition. For example, this query returns a result only when the home page has had more than 10 views in the last five minutes:

increase(home_page_hits_total[5m]) > 10

When a rule’s query returns a result, the alert fires.

Create a directory for rules, next to prometheus.yml:

mkdir ~/volumes/prometheus/rules

And add a rules file, with two alerts:

~/volumes/prometheus/rules/fastapi.ymlyaml
groups:
  - name: fastapi
    rules:
      - alert: HomePageBusy
        expr: increase(home_page_hits_total[5m]) > 10
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: The home page has been viewed more than 10 times in 5 minutes
      - alert: FastAPIDown
        expr: up{job="fastapi"} == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: Prometheus can't scrape the FastAPI application
  • HomePageBusy is a simple example, using the custom counter.
  • FastAPIDown is the most useful alert of all: Prometheus sets up to 0 for any target it can’t scrape, so this fires if the application stops responding.
  • for: 1m means the condition must hold for a minute before the alert fires, which avoids alerts for brief blips.
  • labels are used by Alertmanager to decide where alerts go, and annotations describe the alert.

Update prometheus.yml to load every file in the rules directory. The directory is mounted at /etc/prometheus in the container:

~/volumes/prometheus/prometheus.ymlyaml
rule_files:
  - /etc/prometheus/rules/*.yml

Check the configuration, including the rules, and restart Prometheus:

podman exec prometheus promtool check config /etc/prometheus/prometheus.yml
podman restart prometheus

Under Alerts in Prometheus, you’ll see both rules. Refresh the home page more than ten times, and HomePageBusy becomes Pending, and after a minute, Firing: