Grafana: Bookshelf End to End

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Grafana 13.3.x. Tested with Grafana Enterprise 13.3.0 in the hands-on lab (Alloy 1.10, Prometheus 3.5, Loki 3.5, Tempo 2.8).

The earlier pages of this subsection each explain one part: data sources, panels, rules, policies, contact points, templates and provisioning. This page puts them together for the lab service Bookshelf and then breaks the service on purpose. When it is done you have the "Bookshelf service health" dashboard and five alerts that were all loaded from files, and you have seen each alert go from pending to firing to a message at the webhook receiver. The same dashboard and the same five alerts are built in Kibana on Kibana: Bookshelf End to End, which ends with the side-by-side comparison.

Everything below runs in the grafana profile of the hands-on lab; the files named here are the ones listed on that page and are loaded by the Grafana container at start, so there is nothing to click.

flowchart LR B["bookshelf"] -->|"/actuator/prometheus"| P["Prometheus"] B -->|"JSON log file"| A["Alloy"] B -->|"OTLP traces"| A A --> L["Loki"] A --> T["Tempo"] P --> G["Grafana: dashboard and five rules"] L --> G T --> G G -->|"policy tree, contact point bookshelf-webhook"| W["webhook-receiver /grafana"] LG["loadgen modes"] --> B

What gets built

Alert (rule uid) Condition Pending period Severity How the lab breaks it

Bookshelf high 5xx ratio (bookshelf-5xx-ratio)

5xx share of requests over 5 minutes above 0.05

2 minutes

critical

curl -X POST localhost:8090/mode/failing

Bookshelf p95 latency above SLO (bookshelf-p95-latency)

95th percentile of request duration over 5 minutes above 0.5 s

5 minutes

warning

curl -X POST localhost:8090/mode/slow

Bookshelf no data (bookshelf-no-data)

max(up{job="bookshelf"}) below 1, and No Data handled as Alerting

2 minutes

critical

docker compose stop bookshelf loadgen

Bookshelf error-log spike (bookshelf-error-log-spike)

More than 20 ERROR lines in 5 minutes, counted in Loki

1 minute

warning

curl -X POST localhost:8090/mode/log-errors

Bookshelf SLO burn rate (bookshelf-slo-burn-rate)

5xx ratio above 0.072 in both the 1 hour and the 5 minute window (14.4 times the budget of a 99.5 percent SLO)

2 minutes, kept firing 5 minutes

critical

curl -X POST localhost:8090/mode/failing

The thresholds are the lab values used across this section: 0.05 for the 5xx ratio and 0.5 s for the latency objective. They are deliberately low so that a breach is visible within minutes. The reasoning for each number is on Provisioning Alerting Resources and Designing Actionable Alerts.

Start the lab

cd lab
docker compose --profile grafana up -d
curl -s -u admin:admin http://localhost:3000/api/v1/provisioning/alert-rules | jq -r '.[].title'

Five titles mean the alerting file was loaded. A rule group with no folder yet creates the folder bookshelf, and the dashboard provider reuses it, so the dashboard and the rules sit in one folder.

Data sources

Three data sources are provisioned with fixed uids, so that dashboards and rules can refer to them: prometheus (the default), loki and tempo. The Loki data source has a derived field that turns the trace_id in a JSON log line into a link to Tempo, and the Tempo data source links back to the logs of a trace. The $$ in the derived field URL is how a literal $ is written in a provisioning file, because Grafana interpolates environment variables in these files (see Data Sources).

grafana/provisioning/datasources/datasources.yaml
apiVersion: 1
datasources:
  - name: Prometheus
    uid: prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    jsonData:
      timeInterval: 15s
      prometheusType: Prometheus
      prometheusVersion: 3.5.0
  - name: Loki
    uid: loki
    type: loki
    access: proxy
    url: http://loki:3100
    jsonData:
      derivedFields:
        - name: trace_id
          matcherRegex: '"trace_id":\s*"(\w+)"'
          urlDisplayLabel: Trace
          url: "$${__value.raw}"
          datasourceUid: tempo
  - name: Tempo
    uid: tempo
    type: tempo
    access: proxy
    url: http://tempo:3200
    jsonData:
      tracesToLogsV2:
        datasourceUid: loki
        filterByTraceID: true
      serviceMap:
        datasourceUid: prometheus
  - name: TestData
    uid: testdata
    type: grafana-testdata-datasource
    access: proxy
    isDefault: false

Check them with curl -s -u admin:admin http://localhost:3000/api/datasources/uid/prometheus/health; the other two work the same way and answer Data source successfully connected. and Data source is working.

The dashboard

The dashboard is a classic JSON file loaded by a file provider. The provider has allowUiUpdates: false, so the file is the source of truth, and the dashboard has the uid bookshelf-service-health, which the alert rules link to.

grafana/provisioning/dashboards/dashboards.yaml
apiVersion: 1
providers:
  - name: bookshelf
    orgId: 1
    folder: bookshelf
    type: file
    disableDeletion: false
    allowUiUpdates: false
    options:
      path: /var/lib/grafana/dashboards/bookshelf

The layout follows the overview level of Dashboard Design Principles:

Row and panel Query Reading it

Variables job, application and route

Query variables chained on http_server_requests_seconds_count (job, then application for that job, then the uri values for both; route is multi-value with All as .+)

Filter the time series (ids 5 and 6) and the table (id 8). The stat panels keep application="bookshelf" so that they show the same numbers as the alert rules.

Annotations "Annotations & Alerts" and "Deployments"

The built-in Grafana annotations, and Grafana annotations tagged bookshelf and deploy

Alert state changes and a marker for each deploy posted to the annotations API (see Annotations and Links).

Golden signals, stat "Requests per second" (id 1)

sum(rate(http_server_requests_seconds_count{application="bookshelf"}[$__rate_interval]))

Traffic. A flat zero means no data or no clients.

Golden signals, stat "5xx ratio" (id 2)

The 5xx rate divided by the total rate; unit Percent (0.0-1.0), red from 0.05

Errors. This is the panel the alert links to (panelId 2).

Golden signals, stat "p95 latency" (id 3)

histogram_quantile(0.95, ...) over the _bucket series; unit seconds, red from 0.5

Latency against the objective.

Golden signals, stat "Instances up" (id 4)

count(up{job="bookshelf"} == 1) or vector(0), with the value 0 mapped to DOWN

Saturation of the simplest kind: is anything scraped.

Golden signals, time series (ids 5 and 6)

Request rate by status; p95 per uri with a dashed 0.5 s threshold line

The shared crosshair in a six hour window shows which route breaks first.

Logs and traces, logs (id 7) and table (id 8)

{application="bookshelf"} | json | level="ERROR"; p95 per route as a sorted table

Error lines with a link from trace_id to Tempo; slowest routes.

Dependencies (collapsed, ids 9 and 10)

jvm_memory_used_bytes{area="heap"}; hikaricp_connections_active / hikaricp_connections_max

Heap and connection pool utilisation, one scroll away.

The file is long because every panel spells out its query, unit, thresholds and options. The structure is the one explained on Library Panels, JSON Model and Versions and built by hand on Building Dashboards.

grafana/dashboards/bookshelf-service-health.json
{
  "uid": "bookshelf-service-health",
  "title": "Bookshelf service health",
  "tags": [
    "bookshelf",
    "golden-signals"
  ],
  "timezone": "utc",
  "schemaVersion": 41,
  "version": 1,
  "refresh": "30s",
  "time": {
    "from": "now-6h",
    "to": "now"
  },
  "graphTooltip": 1,
  "editable": true,
  "panels": [
    {
      "id": 20,
      "type": "row",
      "title": "Golden signals",
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "panels": []
    },
    {
      "id": 1,
      "type": "stat",
      "title": "Requests per second",
      "description": "Request rate of the whole service.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 0,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[$__rate_interval]))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "reqps",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 2,
      "type": "stat",
      "title": "5xx ratio",
      "description": "Share of requests answered with a 5xx status. The alert threshold is 0.05.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 6,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[$__rate_interval])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[$__rate_interval]))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "percentunit",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.05
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 3,
      "type": "stat",
      "title": "p95 latency",
      "description": "95th percentile of the request duration. The latency objective is 0.5 s.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 12,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application=\"bookshelf\"}[$__rate_interval])))",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.5
              }
            ]
          },
          "mappings": [],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 4,
      "type": "stat",
      "title": "Instances up",
      "description": "Scrape targets of job bookshelf that answer.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 4,
        "w": 6,
        "x": 18,
        "y": 1
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "count(up{job=\"bookshelf\"} == 1) or vector(0)",
          "legendFormat": "",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "none",
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "red",
                "value": null
              },
              {
                "color": "green",
                "value": 1
              }
            ]
          },
          "mappings": [
            {
              "type": "value",
              "options": {
                "0": {
                  "text": "DOWN",
                  "color": "red"
                }
              }
            }
          ],
          "color": {
            "mode": "thresholds"
          }
        },
        "overrides": []
      },
      "options": {
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": false
        },
        "colorMode": "background",
        "graphMode": "area"
      }
    },
    {
      "id": 5,
      "type": "timeseries",
      "title": "Requests per second by status",
      "description": "Request rate split by HTTP status.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 5
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "sum by (status) (rate(http_server_requests_seconds_count{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval]))",
          "legendFormat": "{{status}}",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "reqps",
          "custom": {
            "lineWidth": 1,
            "fillOpacity": 10,
            "thresholdsStyle": {
              "mode": "off"
            }
          }
        },
        "overrides": []
      },
      "options": {
        "tooltip": {
          "mode": "multi"
        }
      }
    },
    {
      "id": 6,
      "type": "timeseries",
      "title": "p95 latency per route",
      "description": "95th percentile per route; the dashed line is the 0.5 s objective.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 5
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le, uri) (rate(http_server_requests_seconds_bucket{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval])))",
          "legendFormat": "{{uri}}",
          "refId": "A",
          "range": true
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s",
          "custom": {
            "lineWidth": 1,
            "fillOpacity": 10,
            "thresholdsStyle": {
              "mode": "dashed"
            }
          },
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "green",
                "value": null
              },
              {
                "color": "red",
                "value": 0.5
              }
            ]
          }
        },
        "overrides": []
      },
      "options": {
        "tooltip": {
          "mode": "multi"
        }
      }
    },
    {
      "id": 21,
      "type": "row",
      "title": "Logs and traces",
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 13
      },
      "panels": []
    },
    {
      "id": 7,
      "type": "logs",
      "title": "Error logs",
      "description": "ERROR lines of the service; open a line to follow its trace_id into Tempo.",
      "datasource": {
        "type": "loki",
        "uid": "loki"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 14
      },
      "targets": [
        {
          "datasource": {
            "type": "loki",
            "uid": "loki"
          },
          "editorMode": "code",
          "expr": "{application=\"bookshelf\"} | json | level=\"ERROR\"",
          "queryType": "range",
          "refId": "A"
        }
      ],
      "options": {
        "showTime": true,
        "wrapLogMessage": true,
        "sortOrder": "Descending",
        "enableLogDetails": true
      }
    },
    {
      "id": 8,
      "type": "table",
      "title": "Slowest routes",
      "description": "p95 per route, over the dashboard range.",
      "datasource": {
        "type": "prometheus",
        "uid": "prometheus"
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 14
      },
      "targets": [
        {
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "editorMode": "code",
          "expr": "histogram_quantile(0.95, sum by (le, uri) (rate(http_server_requests_seconds_bucket{job=\"$job\",application=\"$application\",uri=~\"$route\"}[$__rate_interval])))",
          "legendFormat": "{{uri}}",
          "refId": "A",
          "range": false,
          "instant": true,
          "format": "table"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "Time": true
            },
            "renameByName": {
              "Value": "p95 (s)"
            }
          }
        },
        {
          "id": "sortBy",
          "options": {
            "fields": {},
            "sort": [
              {
                "field": "p95 (s)",
                "desc": true
              }
            ]
          }
        }
      ],
      "fieldConfig": {
        "defaults": {
          "unit": "s"
        },
        "overrides": []
      }
    },
    {
      "id": 22,
      "type": "row",
      "title": "Dependencies",
      "collapsed": true,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 22
      },
      "panels": [
        {
          "id": 9,
          "type": "timeseries",
          "title": "JVM heap used",
          "description": "Heap used by the service.",
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "gridPos": {
            "h": 8,
            "w": 12,
            "x": 0,
            "y": 23
          },
          "targets": [
            {
              "datasource": {
                "type": "prometheus",
                "uid": "prometheus"
              },
              "editorMode": "code",
              "expr": "jvm_memory_used_bytes{application=\"bookshelf\",area=\"heap\"}",
              "legendFormat": "heap",
              "refId": "A",
              "range": true
            }
          ],
          "fieldConfig": {
            "defaults": {
              "unit": "bytes",
              "custom": {
                "lineWidth": 1,
                "fillOpacity": 10,
                "thresholdsStyle": {
                  "mode": "off"
                }
              }
            },
            "overrides": []
          },
          "options": {
            "tooltip": {
              "mode": "multi"
            }
          }
        },
        {
          "id": 10,
          "type": "timeseries",
          "title": "Connection pool utilisation",
          "description": "Active over maximum pool connections.",
          "datasource": {
            "type": "prometheus",
            "uid": "prometheus"
          },
          "gridPos": {
            "h": 8,
            "w": 12,
            "x": 12,
            "y": 23
          },
          "targets": [
            {
              "datasource": {
                "type": "prometheus",
                "uid": "prometheus"
              },
              "editorMode": "code",
              "expr": "hikaricp_connections_active{application=\"bookshelf\"} / hikaricp_connections_max{application=\"bookshelf\"}",
              "legendFormat": "pool",
              "refId": "A",
              "range": true
            }
          ],
          "fieldConfig": {
            "defaults": {
              "unit": "percentunit",
              "custom": {
                "lineWidth": 1,
                "fillOpacity": 10,
                "thresholdsStyle": {
                  "mode": "off"
                }
              }
            },
            "overrides": []
          },
          "options": {
            "tooltip": {
              "mode": "multi"
            }
          }
        }
      ]
    }
  ],
  "templating": {
    "list": [
      {
        "name": "job",
        "label": "Job",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count, job)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count, job)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 1,
        "sort": 1,
        "current": {
          "text": "bookshelf",
          "value": "bookshelf"
        }
      },
      {
        "name": "application",
        "label": "Application",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count{job=\"$job\"}, application)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count{job=\"$job\"}, application)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 1,
        "sort": 1,
        "current": {
          "text": "bookshelf",
          "value": "bookshelf"
        }
      },
      {
        "name": "route",
        "label": "Route",
        "type": "query",
        "datasource": {
          "type": "prometheus",
          "uid": "prometheus"
        },
        "definition": "label_values(http_server_requests_seconds_count{job=\"$job\", application=\"$application\"}, uri)",
        "query": {
          "qryType": 1,
          "query": "label_values(http_server_requests_seconds_count{job=\"$job\", application=\"$application\"}, uri)",
          "refId": "PrometheusVariableQueryEditor-VariableQuery"
        },
        "refresh": 2,
        "sort": 1,
        "current": {
          "text": [
            "All"
          ],
          "value": [
            "$__all"
          ]
        },
        "multi": true,
        "includeAll": true,
        "allValue": ".+"
      }
    ]
  },
  "annotations": {
    "list": [
      {
        "builtIn": 1,
        "name": "Annotations & Alerts",
        "datasource": {
          "type": "grafana",
          "uid": "-- Grafana --"
        },
        "enable": true,
        "hide": true,
        "iconColor": "rgba(0, 211, 255, 1)",
        "type": "dashboard",
        "target": {
          "type": "dashboard",
          "limit": 100,
          "matchAny": false,
          "tags": []
        }
      },
      {
        "name": "Deployments",
        "datasource": {
          "type": "grafana",
          "uid": "-- Grafana --"
        },
        "enable": true,
        "hide": false,
        "iconColor": "blue",
        "target": {
          "type": "tags",
          "tags": [
            "bookshelf",
            "deploy"
          ],
          "limit": 100,
          "matchAny": false
        }
      }
    ]
  }
}

Reference: Grafana: Provisioning, dashboards and Grafana: View dashboard JSON model. Open the dashboard at http://localhost:3000/d/bookshelf-service-health. With the load generator running, expect about 10 requests per second, no red stat and a p95 around 0.2 s.

The alert rules, contact point, template and policies

One provisioning file, grafana/provisioning/alerting/bookshelf.yaml, holds all alerting resources: two rule groups (bookshelf-service-level and bookshelf-availability-and-logs, each evaluated every minute), the contact point bookshelf-webhook, the template group bookshelf, the mute timing bookshelf-weekends and the policy tree. Every rule is a query, a Reduce expression (last, dropping non-numeric results) and a Threshold or Math expression as the condition. The three rules on the request metrics use OK for No Data, because no traffic is not an incident by itself; the no-data rule uses Alerting and the error-log rule reads Loki with an instant query. The rules carry the labels team: bookshelf-sre, application: bookshelf and a severity, and the 5xx rule carries the dashboard and panel link that fills dashboardURL and panelURL in the notification. Each rule is explained on the page named below:

grafana/provisioning/alerting/bookshelf.yaml
apiVersion: 1

groups:
  - orgId: 1
    name: bookshelf-service-level
    folder: bookshelf
    interval: 1m
    rules:
      - uid: bookshelf-5xx-ratio
        title: Bookshelf high 5xx ratio
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [0.05] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 2m
        isPaused: false
        annotations:
          summary: 'Bookshelf 5xx ratio is {{ printf "%.1f" $values.B.Value }} (threshold 0.05)'
          description: 'More than 5 percent of Bookshelf requests answered with a 5xx status for 2 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-5xx-ratio
          __dashboardUid__: bookshelf-service-health
          __panelId__: '2'
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

      - uid: bookshelf-p95-latency
        title: Bookshelf p95 latency above SLO
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application="bookshelf"}[5m])))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [0.5] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 5m
        isPaused: false
        annotations:
          summary: 'Bookshelf p95 latency is {{ printf "%.2f" $values.B.Value }} s (SLO 0.5 s)'
          description: 'The 95th percentile of Bookshelf request latency has been above the 0.5 s objective for 5 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-latency
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: warning

      - uid: bookshelf-slo-burn-rate
        title: Bookshelf SLO burn rate
        condition: E
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[1h])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[1h]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: B
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: C
              type: reduce
          - refId: D
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              reducer: last
              settings: { mode: dropNN }
              refId: D
              type: reduce
          - refId: E
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: '$C > 0.072 && $D > 0.072'
              refId: E
              type: math
        noDataState: OK
        execErrState: Error
        for: 2m
        keepFiringFor: 5m
        isPaused: false
        annotations:
          summary: 'Bookshelf burns its error budget 14.4 times too fast (1h {{ printf "%.3f" $values.C.Value }}, 5m {{ printf "%.3f" $values.D.Value }})'
          description: 'The 5xx ratio exceeds 0.072 in both the 1 hour and the 5 minute window, a 14.4x burn of a 99.5 percent availability objective.'
          runbook_url: https://example.com/runbooks/bookshelf-slo-burn
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

  - orgId: 1
    name: bookshelf-availability-and-logs
    folder: bookshelf
    interval: 1m
    rules:
      - uid: bookshelf-no-data
        title: Bookshelf no data
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: prometheus
            model:
              datasource: { type: prometheus, uid: prometheus }
              editorMode: code
              expr: 'max(up{job="bookshelf"})'
              instant: true
              range: false
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: lt, params: [1] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: Alerting
        execErrState: Error
        for: 2m
        isPaused: false
        annotations:
          summary: 'Bookshelf is not reporting metrics or is down'
          description: 'The up series for job bookshelf is missing or 0 for 2 minutes.'
          runbook_url: https://example.com/runbooks/bookshelf-no-data
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: critical

      - uid: bookshelf-error-log-spike
        title: Bookshelf error-log spike
        condition: C
        data:
          - refId: A
            relativeTimeRange: { from: 600, to: 0 }
            datasourceUid: loki
            model:
              datasource: { type: loki, uid: loki }
              editorMode: code
              expr: 'sum(count_over_time({application="bookshelf"} | json | level="ERROR" [5m]))'
              queryType: instant
              intervalMs: 1000
              maxDataPoints: 43200
              refId: A
          - refId: B
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: A
              reducer: last
              settings: { mode: dropNN }
              refId: B
              type: reduce
          - refId: C
            relativeTimeRange: { from: 0, to: 0 }
            datasourceUid: __expr__
            model:
              datasource: { type: __expr__, uid: __expr__ }
              expression: B
              conditions:
                - evaluator: { type: gt, params: [20] }
                  operator: { type: and }
                  query: { params: [C] }
                  reducer: { type: last, params: [] }
                  type: query
              refId: C
              type: threshold
        noDataState: OK
        execErrState: Error
        for: 1m
        isPaused: false
        annotations:
          summary: 'Bookshelf logged {{ printf "%.0f" $values.B.Value }} ERROR lines in 5 minutes'
          description: 'More than 20 ERROR log lines in 5 minutes, counted in Loki from the JSON logs of the service.'
          runbook_url: https://example.com/runbooks/bookshelf-error-logs
        labels:
          application: bookshelf
          team: bookshelf-sre
          severity: warning

contactPoints:
  - orgId: 1
    name: bookshelf-webhook
    receivers:
      - uid: bookshelf-webhook
        type: webhook
        disableResolveMessage: false
        settings:
          url: http://webhook-receiver:8080/grafana
          httpMethod: POST
          title: '{{ template "bookshelf.title" . }}'
          message: '{{ template "bookshelf.message" . }}'

templates:
  - orgId: 1
    name: bookshelf
    template: |
      {{ define "bookshelf.title" -}}
      [{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}
      {{- end }}

      {{ define "bookshelf.message" -}}
      {{ range .Alerts -}}
      * {{ .Labels.alertname }} ({{ .Labels.severity }}): {{ .Annotations.summary }}
        {{ if .Annotations.runbook_url }}Runbook: {{ .Annotations.runbook_url }}{{ end }}
      {{ end -}}
      {{- end }}

muteTimes:
  - orgId: 1
    name: bookshelf-weekends
    time_intervals:
      - weekdays: ['saturday', 'sunday']
        location: 'UTC'

policies:
  - orgId: 1
    receiver: bookshelf-webhook
    group_by: ['alertname', 'grafana_folder']
    group_wait: 30s
    group_interval: 5m
    repeat_interval: 4h
    routes:
      - receiver: bookshelf-webhook
        object_matchers:
          - ['team', '=', 'bookshelf-sre']
        routes:
          - receiver: bookshelf-webhook
            object_matchers:
              - ['severity', '=', 'critical']
            group_wait: 10s
            group_interval: 1m
            repeat_interval: 1h
          - receiver: bookshelf-webhook
            object_matchers:
              - ['severity', '=', 'warning']
            mute_time_intervals:
              - bookshelf-weekends
            repeat_interval: 12h

Reference: Grafana: Provision alerting resources with files. The same resources as Terraform are on Provisioning Alerting Resources.

Check what Grafana loaded, and that the file round-trips through the export (the keys the file uses are the keys Grafana writes back):

curl -s -u admin:admin 'http://localhost:3000/api/prometheus/grafana/api/v1/rules' \
  | jq -r '.data.groups[].rules[] | "\(.name)\t\(.state)\t\(.health)"'
curl -s -u admin:admin 'http://localhost:3000/api/v1/provisioning/alert-rules/export?format=yaml' | head -20

Break the service and watch

Run these in order, with the notification receiver open in a second terminal (docker compose logs -f --no-log-prefix webhook-receiver). The times below were measured on the lab for this page, from the moment the load generator switched mode to the first WEBHOOK line of that alert; treat them as the order of magnitude, not as promises.

Step Command First notification What you see

1. Break with 5xx errors

curl -X POST localhost:8090/mode/failing

Error-log spike after 1 min 42 s; high 5xx ratio after 2 min 32 s; SLO burn rate after 2 min 38 s

Each rule is Pending, then Firing when its pending period has passed. The three arrive as three notifications, one per alertname, because the policy tree groups by alertname and grafana_folder. The critical policy waits 10 seconds (its group wait) after the instance starts firing.

2. Return to normal

curl -X POST localhost:8090/mode/normal

Resolved messages: 5xx ratio after 5 min 29 s; error-log spike after 7 min 39 s; burn rate after 10 min 35 s

The 5 minute rate windows must drain first. The burn rate rule shows Recovering for its 5 minute keep-firing period before it resolves.

3. Slow responses

curl -X POST localhost:8090/mode/slow

p95 latency above SLO after 6 min 51 s

The rule waits for its 5 minute pending period, so it is the slowest to fire. Its resolved message is held until the next group interval (5 minutes, inherited from the default policy) after the rule recovers.

4. Stop the service

docker compose stop bookshelf loadgen

No data after 3 min 20 s

The up series drops to 0 and then disappears; the rule has No Data handled as Alerting and a 2 minute pending period. Start the containers again and the resolved message follows after about 1 min 20 s (the critical group interval is 1 minute).

5. Errors in the log only

curl -X POST localhost:8090/mode/log-errors

Error-log spike after 1 min 52 s

Responses stay 200, so the 5xx, latency and burn rate rules stay quiet and only the log rule fires.

All times are from one run on a laptop with Docker Desktop; the first notification of an alert needs its pending period plus up to one evaluation interval (1 minute) plus the group wait of the policy (10 seconds for critical, 30 seconds for warning).

What the receiver gets

Each delivery is one WEBHOOK line in the receiver log. The title and message come from the template group bookshelf of the lab file:

[FIRING:1] Bookshelf high 5xx ratio
* Bookshelf high 5xx ratio (critical): Bookshelf 5xx ratio is 0.4 (threshold 0.05)
  Runbook: https://example.com/runbooks/bookshelf-5xx-ratio

The body of that delivery, with the labels alertname, application, grafana_folder, severity and team, the annotations, the dashboardURL and panelURL of the dashboard panel with id 2, and the values of the query and expression refIds, is the payload shown on Contact Points and Integrations. A resolved delivery has "status": "resolved" and an endsAt timestamp. Read the deliveries with:

docker compose logs --no-log-prefix webhook-receiver | grep WEBHOOK
curl -s localhost:8081 | jq -r '.[] | "\(.time) \(.path)"'

Read the alert history

State changes are also stored in Loki, because the lab enables the Loki state history backend (GF_UNIFIED_ALERTING_STATE_HISTORY_BACKEND=loki). Every transition of the 5xx rule, with the values that caused it, is one log line:

curl -s -G http://localhost:3100/loki/api/v1/query_range \
  --data-urlencode 'query={from="state-history"} | json | ruleTitle="Bookshelf high 5xx ratio"' \
  --data-urlencode limit=5 | jq -r '.data.result[].values[][1]'

Each line shows previous, current (Pending, Alerting, Normal), the values of the query and expression refIds and the labels. The Alerting, History views of the UI read the same data (see Monitoring Alerts and State History).

Clean up

docker compose --profile grafana down -v
docker ps -a

What can go wrong

  • The folder uid is generated. The rule file creates the folder bookshelf when it does not exist, because Grafana provisions alerting before dashboards, so the folder gets a random uid. Look it up (curl -s -u admin:admin http://localhost:3000/api/folders | jq) where an API call needs a folderUID.

  • The dashboardUid and panelId keys do nothing in a rule file. The export shows them, but a rule loaded from a file with those keys had no dashboard link on Grafana 13.3.0. The annotations __dashboardUid__ and __panelId__ set the link, and dashboardURL and panelURL appear in the notification.

  • A $ in a value disappears. Provisioning files interpolate environment variables, so the derived field URL in the data source file writes $$ for a literal $. Rule annotations, the query model and the template group are not interpolated.

  • The burn rate alert fires much sooner than the arithmetic says. In a lab that has run for a few minutes the 1 hour rate is computed over the minutes that exist. Start the alert test after an hour of healthy traffic to see the textbook behaviour.

  • Resolved messages arrive late. A grouped notification is sent again only after the group interval of its policy: 1 minute for critical and 5 minutes for warning in the lab tree.

  • The no-data rule never fires. The query is max(up{job="bookshelf"}); if you removed the scrape job instead of stopping the service the series is missing, which is exactly the No Data case the rule handles with noDataState: Alerting.

  • Changing the file has no effect. Rules from files are read at start; call curl -s -u admin:admin -X POST http://localhost:3000/api/admin/provisioning/alerting/reload after editing.

In the books

The three-part pattern here (a dashboard that answers "is it healthy", alert rules that page on the same numbers, and a routed notification) is the one Salituro’s Learn Grafana 10.x builds in its dashboard and alerting chapters, and the one McCollam’s Getting Started with Grafana (Apress) sketches for alert notification channels. Both predate unified alerting’s current form: the notification channels they configure per alert are replaced by contact points and a policy tree, rules are written as query, Reduce and Threshold expressions, and the whole setup can be provisioned from files as above.

Where to go next

For the same exercise in Kibana see Kibana: Bookshelf End to End. To keep this setup in Git, read Dashboards as Code and Provisioning Alerting Resources; for the practices behind the numbers, Grafana: Best Practices.