Grafana: Labels, Annotations and Rule Templates
|
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.
To do this by hand, follow Create an Alert Rule.
An alert rule is more than a query and a condition. Every alert instance it produces carries two sets of key and value pairs, and they have opposite jobs. Labels say which alert this is and decide where it goes: they are the only input the notification policy tree matches on, they decide which instances are the same instance from one evaluation to the next, and silences match on them. Annotations say what a human should know: a summary, a longer description, a runbook link, a link to the dashboard panel. Mixing the two up is the most common cause of alerts that are routed wrongly, that flap into new instances, or that arrive without any context.
This page covers both sets, the template language used inside them, and two techniques that build on templates (dynamic labels and dynamic thresholds). The routing side is on Notification Policies, the message layout on Notification Templates, and the rule’s queries and conditions on Alert Rules: Queries and Conditions. The design principles behind the metadata contract (owner, severity, runbook) are in Designing Actionable Alerts, and the general model of instances in Alerting Fundamentals. The running example is the Bookshelf service (see Metrics and Observability) and the rules of the Hands-on Lab.
Labels and annotations side by side
| Labels | Annotations | |
|---|---|---|
Purpose |
Identify the alert instance, support searching, silencing and routing. |
Give responders the context to understand and fix the problem. |
Identity |
The full label set is the identity of an instance. A different value is a different instance. |
Not part of the identity. Changing an annotation does not create a new instance. |
Typical keys |
|
|
Used for matching |
Notification policies, silences, the alert rule list filters. |
Not used for routing. Shown in the UI and available to notification templates. |
Template input |
Query labels ( |
The same. |
Source: Grafana: Labels and annotations.
Labels
Labels uniquely identify an alert instance. Two instances of one rule that share the alert name but differ in one label value are two separate instances:
{alertname="Bookshelf high 5xx ratio", uri="/api/books"}
{alertname="Bookshelf high 5xx ratio", uri="/api/loans"}
A label set is built from three kinds of labels:
-
User-configured labels that you add to the rule, such as
severity,teamorservice. Their values can be generated by a template (see below). -
Query labels returned by the data source. A rule whose query returns one series per
uriproduces one instance per route automatically, which is why multi-dimensional rules need no copy-and-paste. -
Reserved labels that Grafana adds:
alertname(the rule name) andgrafana_folder(the title of the folder that holds the rule). Any label that begins withgrafana_is reserved for Grafana’s internal use, and administrators can turn reserved labels off with theunified_alerting.reserved_labelsoption.
Three rules about conflicts matter in practice. Two rules cannot produce instances with identical label sets, and when they
do Grafana discards one of the instances. A label name can appear only once in a set. And if a configured label has the
same name as a query label, the configured label overrides the query label, while a configured label that matches a reserved
label name is dropped. The practical consequence: do not give a label the name of a query label unless you want to replace
it, and do not try to set grafana_folder yourself.
Grafana’s built-in Alertmanager accepts Unicode label keys and values. An external Prometheus Alertmanager is stricter: keys
must match [a-zA-Z_][a-zA-Z0-9_]*. Before sending alerts to an external Alertmanager, Grafana removes whitespace from keys,
replaces other disallowed ASCII characters with _, replaces other characters with their lowercase hexadecimal form, and
appends a short hash when several keys would collapse to the same name. If you send alerts to an external Alertmanager, keep
keys to letters, digits and underscores from the start so that routing rules there match what you wrote here.
Source: Grafana: Labels and annotations (sections "Label types", "Conflicts", "Reserved labels" and "Label key format and naming rules").
Annotations
Annotations are shown in the alert UI and, by default, in notifications. The documentation suggests writing them so a first responder can act on them directly, and names these optional keys:
-
summary: a short statement of what was detected and why it matters. -
description: a longer explanation with the likely impact and suggested responses. -
runbook_url: a link to the runbook that guides the operator through the incident. -
__dashboardUid__and__panelId__: together they link the alert to a dashboard panel.
Custom keys are allowed too. Both __dashboardUid__ and __panelId__ must be set together, otherwise the link does not
work. Set from the UI, the link is created in the rule form under Configure notification message with Link dashboard and
panel; starting from a panel (panel menu, More…, New alert rule) pre-fills both annotations and copies the panel’s
query into the rule. The alert state is then visible on the linked panel, and notifications carry a link to it. The query in
the panel and the query in the rule are not synchronised afterwards, so an edit to one must be repeated in the other. Viewing
linked rules from the panel’s Alert tab works only for time series panels.
Source: Grafana: Labels and annotations (section "Annotations") and Grafana: Link alert rules to panels.
The Bookshelf metadata contract
The lab rules use the contract described in Designing Actionable Alerts: three labels and three annotations, plus the dashboard link.
| Item | Value on the Bookshelf rules | Consumer |
|---|---|---|
Label |
|
A child policy under the Default policy. |
Label |
|
Identifies the service in notifications and dashboards. |
Label |
|
Child policies below the team policy: critical pages, warning opens a ticket, info goes to chat. |
Annotation |
One sentence with the impact |
First line of the notification. |
Annotation |
Link to the response procedure |
The responder’s next step. |
Annotations |
|
Panel link and state on the dashboard. |
As rule-group file provisioning, the metadata part of a rule looks like this. It replaces the labels and annotations keys
of the complete rule shown in
Designing Actionable Alerts; the 2 is the id of the
panel in the dashboard’s JSON model.
labels:
application: bookshelf
team: bookshelf-sre
severity: critical
annotations:
summary: More than 5% of Bookshelf requests are failing with 5xx.
description: The 5xx ratio has stayed above 5% for 2 minutes.
runbook_url: https://wiki.example.com/runbooks/bookshelf-5xx
__dashboardUid__: bookshelf-service-health
__panelId__: "2"
Reference: Grafana: Provision alert rules with files.
The same two maps are the labels and annotations arguments of a grafana_rule_group rule in the Terraform provider
(grafana_rule_group), as in the
Terraform example on Observability as Code.
In the UI the labels are entered under Configure labels and notifications with + Add labels (a key, then a value or a template), and the annotations under Configure notification message.
Templating labels and annotations
Both labels and annotations can contain Go templates that are evaluated for each alert instance when it fires. This is a different feature from notification templates, which format the message for a whole group of alerts (see Notification Templates). Inside a rule you have two main variables, and a third that the documentation recommends against.
| Variable | What it holds |
|---|---|
|
The query labels of the instance only. It does not contain the labels you configured on the rule, nor the reserved labels, and with a classic condition it contains no query labels. |
|
A table keyed by Ref ID with, for each Ref ID, |
|
A string with the labels and values of instant queries and of threshold, reduce, math and classic condition expressions.
With several data sources it is a combined string, so the documentation prefers |
Two consequences follow. First, {{ $labels.team }} does not work for a label you configured yourself: $labels is
for query labels such as uri. Second, if query A is a range query (the usual Prometheus query for a graph), add a Reduce
expression as B and read $values.B.Value. The Ref ID is the lookup key, the alert name plays no role. Keys that start
with a digit need the index function, because $values.1B.Value is not valid and is printed as plain text:
{{ index $values "1B" }} CPU usage for {{ index $labels "1instance" }}
A Bookshelf per-route rule makes this concrete. Query A is
sum by (uri) (rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum by (uri) (rate(http_server_requests_seconds_count{application="bookshelf"}[5m])),
B is a Reduce (last) of A, and the condition is $B > 0.05. The annotations can then read:
summary: Route {{ $labels.uri }} returns 5xx for {{ humanizePercentage $values.B.Value }} of requests
description: Route {{ $labels.uri }} has failed for more than 5 minutes (currently {{ humanizePercentage $values.B.Value }}).
Go template built-ins (index, and, printf, len, if, eq, gt) are available, and so are the Prometheus-style
helpers in the following table. The reference lists more; these are the ones that matter for alert messages.
| Function | Example | Output |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
An Explore graph or table path |
Source: Grafana: Template annotations and labels, Grafana: Annotation and label template reference (variables and functions) and Grafana: Annotation and label template examples.
Testing a template
-
Annotations: let the alert fire and open the instance in the alert UI, which lists every annotation as rendered. As an alternative, build a notification template that prints all annotations and preview it against the instance.
-
Labels: in the rule form select Use notification policy, click Preview routing and read the resulting labels and the policies that would handle them.
Source: Grafana: Template annotations and labels (section "Testing and previewing").
Why query values must not go into labels
It is tempting to write severity or a "current value" label from the query result, because labels are what routing sees.
Grafana’s documentation warns against the second case in so many words: each distinct label set creates a separate alert
instance, so a label that carries a number produces a new instance every time the number changes, and a changed value maps to a
different instance while the previous one goes stale. For a latency value that moves on every evaluation that means an endless
series of instances that each fire once, resolve and are evicted, and a notification for each of them. Put the number in an
annotation ({{ $values.B.Value }}), where it is free to change.
Labels derived from a value are acceptable only when the derived value has a few stable bands, which is the dynamic label technique below, and even then it has a cost.
Source: Grafana: Template annotations and labels (section "Pitfalls with labels").
Dynamic labels
A single rule can assign a label from the value of a query instead of using three rules with three fixed thresholds. The
documented example sets severity from the numeric result of query B with one template:
{{/* $values.B.Value refers to the numeric result from query B */}}
{{- if gt $values.B.Value 90.0 -}}critical
{{- else if gt $values.B.Value 80.0 -}}warning
{{- else if gt $values.B.Value 70.0 -}}minor
{{- else -}}none
{{- end -}}
The rule’s condition is then the lowest band ($B > 70), values that map to none do not fire, and a notification policy
with child policies on severity routes each band to a different destination. For Bookshelf the same idea applies to the
p95 latency rule. With B the reduced p95 latency in seconds and the condition $B > 0.5, this label template gives
warning for slow and critical for very slow requests (the thresholds are illustrative):
{{- if gt $values.B.Value 2.0 -}}critical
{{- else if gt $values.B.Value 1.0 -}}warning
{{- else -}}info
{{- end -}}
The caveat is the one above, now made visible. Each distinct label set is a separate instance, so when the severity moves from
warning to critical the old instance goes missing and a new one starts from scratch. The documentation’s walk-through shows
both instances sending their own firing and resolved notifications for what is one underlying problem. Its mitigations are:
-
Stabilise the evaluation: a longer evaluation interval and pending period, and smoothed queries such as
avg_over_time. -
Use wider bands so that small changes in value do not switch the label.
-
Disable resolved notifications on the contact point when alerts resolve quickly.
-
Disable the Missing series evaluations setting (default 2) when it is not needed, which makes troubleshooting simpler.
-
Keep enough metadata to correlate related alerts.
-
Consider separate rules with static labels when the logic is complex or each case needs its own query.
To try it without Bookshelf, the page builds the rule on the TestData data source (Random Walk, one series, start value 51,
min 50, max 100, spread 100), a Reduce expression named B (function Last), the condition $B >= 50, an evaluation
interval of 10s and, under Configure notifications with Advanced options, Preview routing to watch the label change.
Source: Grafana: Examples of dynamic labels.
Dynamic thresholds
A rule has one condition, but a multi-dimensional rule can still apply a different threshold to each series. Grafana shows two ways to do it.
With a Math expression
Add a second query that returns one threshold per series, reduce the latency query to one number per series, and compare the two. The series are joined on shared labels:
-
A: the p95 latency query, one series per service. -
B: the thresholds per service. -
C: Reduce ofA(function Mean). -
Condition, a Math expression:
$C > $B
Each series in A must match exactly one series in B; a series with no match is dropped and a warning is shown. The label
sets do not need to be identical, one may be a subset of the other. For Bookshelf, per-route thresholds for the slowest-routes
alert can come from a TestData CSV query named B whose uri column equals the query label of A:
uri,value
/api/books,0.5
/api/search,1.5
/api/loans,0.8
Source: Grafana: Examples of dynamic thresholds (approach 1).
With a SQL expression
A SQL expression keeps the thresholds inside the query and can supply a default for services that have no entry, so they are
not dropped as they are in the Math approach. The documented form gives each series an alert_result of 1 when the value
exceeds its threshold and 0 otherwise:
SELECT
A.service AS service,
CASE
WHEN A.__value__ > COALESCE(B.threshold, 2) THEN 1
ELSE 0
END AS alert_result
FROM A
LEFT JOIN B ON A.service = B.service
Here A is the data and B a second query with service and threshold columns; LEFT JOIN keeps every row from A and
COALESCE supplies 2 when B has no matching service. The service column becomes the instance label and alert_result is
the numeric value that the alert condition evaluates. SQL expressions are enabled by default and an alert needs exactly one
numeric column (see
Transformations and Expressions). The page
also shows that the same idea extends to conditions that depend on traffic, with a PromQL or of two and clauses.
Source: Grafana: Examples of dynamic thresholds (approach 2 and "Combining multiple conditions").
What can go wrong
-
A label routes nothing. The matcher in the policy and the label on the rule differ in spelling or case (
Severityandseverity). The instance falls through to the Default policy. Use Preview routing before saving. -
$labels.teamrenders empty.$labelsholds query labels only, not the labels you configured on the rule. -
$values.A.Valuefails on a range query. Add a Reduce expression and read its Ref ID. -
A templated label multiplies instances. A label built from a number or from a high-cardinality value creates many instances and many notifications.
-
Two rules, one label set. Identical label sets from two rules make Grafana discard one of the instances.
-
The panel link is dead. Only one of
__dashboardUid__and__panelId__is set, or the panel id changed after the panel was recreated. -
A custom label is dropped. A configured label named
grafana_somethingclashes with the reserved prefix. -
Dynamic thresholds drop series. A series without exactly one match in the threshold query is dropped from the Math approach.
Verify it in the lab
With the grafana profile running (see Hands-on Lab) and the folder
bookshelf holding the five alerts:
-
Open the rule Bookshelf high 5xx ratio, add the label
severity: criticaland the annotationrunbook_url, then click Preview routing and confirm the labels listed includealertname,grafana_folder,application,teamandseverity. -
Add the dashboard link under Configure notification message and open the dashboard "Bookshelf service health": the panel should show the alert state. Remove one of the two annotations in the YAML version and confirm the link disappears.
-
Turn a per-route annotation template on (the
{{ $labels.uri }}example), switch on the load generator’s failing-request mode, and read the rendered annotation in the alert instance. -
Change the label template to the severity bands above, drive latency across a band boundary with the load generator’s slow mode, and look at the alert history: you should see two instances for one problem, the cost described above.
-
Misspell
severityassevertyon one rule and see which policy Preview routing shows, then fix it.
In the books
Salituro’s chapter 12 (Grafana 10) uses the same split: a severity label is set when the rule is created so that a
notification policy can send critical, normal and low alerts to PagerDuty, Slack and email, and annotations (summary,
description, runbook URL, dashboard and panel link) are filled with Go templates, with the actual value added to the summary.
The ideas are unchanged. What has changed since then is the surrounding detail: the rule form is reorganised, Recovering and
the missing-series handling affect how label changes behave, and the reference lists humanizePercentage, graphLink and the
other helpers. McCollam’s chapter 11 and Hernandez’s chapter 10 describe the Grafana 8 era, in which labels were already the
match input for policies. None of the books discusses dynamic thresholds with SQL expressions, which arrived later.