Grafana Alert Rules: Queries and Conditions
|
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: the five lab rules load from a provisioning file, are exported back in the same format, evaluate against Prometheus and Loki, and fire and resolve when the load generator breaks Bookshelf; the HCL below passes terraform validate with provider 4.54.0.
To do this by hand, follow Create an Alert Rule.
An alert rule is a question asked on a schedule: "is any series in this query result above this threshold?". A good rule
answers it for the right unit (the service, the route, the node), with a number that means what the on-call engineer
thinks it means. Most broken rules are not broken in the notification path; they are broken in the query and the condition,
where a missing or on() vector(0), a reducer that hides a spike or a classic condition that collapses ten failing routes
into one alert quietly decides what can ever fire.
This page builds a Grafana-managed rule from the pieces Grafana provides: the queries, the expressions that turn query results into one number per series, the condition and its optional recovery threshold. The architecture around the rule is in Alerting Architecture. How often the rule runs, how long a breach must last and what happens when the data is missing are in Rule Evaluation, States and Missing Data; labels, annotations and templates are in Labels, Annotations and Rule Templates. The design questions (what to alert on, how to avoid fatigue) are in Designing Actionable Alerts. The Prometheus-focused view of the same rule form is in Grafana alerting (Prometheus section). The running example is the Bookshelf service (see Metrics and Observability).
Creating a Grafana-managed rule
Grafana-managed rules are the default and the way Grafana recommends creating rules. They extend the Prometheus alerting model with queries over several data sources, expressions, custom No Data and Error states and images in notifications. The data source must be a backend plugin with alerting enabled. Create a rule from Alerts & IRM > Alert rules > New alert rule, and edit or delete it with Edit permission on its folder (only admins can restore deleted rules).
The form is a fixed sequence, and both the Define query and condition and the Configure notifications sections have a Default and an Advanced view. You can switch at any time and Grafana remembers the last choice for the next rule; switching Advanced to Default can break queries or expressions that do not convert, and Grafana asks for confirmation first.
-
Name. It appears in the rule list and becomes the
alertnamelabel on every instance of the rule. -
Define query and condition. Pick the data source, write the query in the Builder or Code tab (depending on the data source) and define the condition. Details below.
-
Folder and labels. The folder carries permissions; labels organise rules and route notifications.
-
Evaluation behaviour. Evaluation group and interval, pending period, keep firing for, pause, No Data and Error handling and the missing-series setting.
-
Configure notifications. Default view: pick a contact point, which receives all notifications for the rule directly and bypasses the notification policies. Advanced view: notifications go through the policy tree by label; Preview routing shows which policies take the rule’s alerts.
-
Configure notification message. Summary, description, runbook URL, custom annotations and the dashboard and panel link.
Steps 4 to 6 are covered by the pages named in the introduction. This page stays with step 2.
Queries
An alerting query is the same query you would put in a panel. Grafana-managed alerts only work with data sources that have alerting enabled, and two result shapes are supported:
-
Time series: each series must be reduced to a single number before it can be compared with a threshold.
-
Tabular: the result must have exactly one numeric column, and every row must have a value.
Each time series or table row is evaluated as a separate alert instance. In the Advanced view the Options drop-down sets the time range, and only fixed relative ranges are supported (for example "last 24 hours to now"); absolute ranges and semi-relative ranges such as "start of day to now" are not. With Prometheus-compatible data sources, an instant vector and built-in PromQL functions can often replace extra expressions, which keeps the rule easier to read in the preview.
A rule is not limited to one query. The Advanced view lets you add queries with Add query, including queries on different data sources, and combine them with expressions. The switch to a data source-managed rule (Switch to data source-managed alert rule) is in the same place; what that gives up is listed in Alerting Architecture.
Expressions
Expressions are server-side operations that run on the results of the queries, and they exist only in Grafana-managed rules. They are the same expressions that panels can use, so the general reference is Transformations and Expressions; what follows is how they behave in an alert rule. Expressions work on time series or number data and only on backend data sources. If any queried data source returns no data, the whole result is No Data, and combining several queries needs identical timestamps.
| Expression | What it does in a rule |
|---|---|
Reduce |
Collapses each series to one number and keeps the labels. Functions: Min, Max, Mean, Median, Sum, Count, Last. The mode decides
what happens to non-numeric points (null, NaN, infinity): Strict returns NaN if any value in the series is non-numeric,
Drop Non-Numeric removes them before reducing, Replace Non-Numeric substitutes a value you choose. |
Math |
Free-form arithmetic and comparisons, for example |
Resample |
Realigns the timestamps of a series to a fixed interval so that series from different data sources can be used together in
Math. You choose how to downsample and how to fill windows with no points ( |
Threshold |
Compares a number with fixed values and returns |
SQL |
Runs MySQL-like queries over the results of earlier queries, to filter rows, join queries and aggregate before the condition. For alerting the final result must have exactly one numeric column. |
Classic condition (legacy) |
The legacy condition kept for compatibility, best avoided. It produces one alert instance however many series
match. Reducers: |
The Math label-join rule matters when a rule combines two queries. With A returning {host="web01"} 30 and
{host="web02"} 20, and B returning {host="web01"} 10 and {host="web02"} 0, the expression $A + $B gives
{host="web01"} 40 and {host="web02"} 20. If the labels of the two sides do not match, the join silently produces nothing,
and the rule shows No Data in the preview. That is the first thing to check when a ratio of two queries is empty.
The alert condition
The alert condition is the one query or expression whose result decides whether the rule fires; a rule has exactly one. In
the Default view the When input picks the reducer and the last input sets the threshold, so a rule needs nothing more than
"When last() of A is above 0.05". In the Advanced view you choose any query or expression with Set as alert condition,
typically a Threshold expression after a Reduce expression, or a Math expression such as $B > 70.
An instance is considered breached when the condition evaluates to true (1) for its series. Everything after that (pending, firing, recovering) is evaluation state, not condition logic.
Source: Grafana: Queries and conditions ("Alert condition").
Recovery threshold
A single threshold flaps when the value hovers around it. The custom recovery threshold (Advanced view, Custom recovery threshold) uses two thresholds: the instance enters Pending or Alerting when it crosses the alert threshold, and returns to Recovering or Normal only when it crosses the recovery threshold. Grafana’s example is an alert threshold of 1000 ms with a recovery threshold of 900 ms: the values 980, 1010, 990 and 1020 keep the alert firing, because 990 never crosses 900. Only one recovery threshold is allowed, and it must be part of the alert condition.
For Bookshelf this is the cheap fix for a p95 that bounces around the SLO: alert above 500 ms, recover below 450 ms, instead of lengthening the pending period until real incidents are missed. Keep firing for (see Rule Evaluation, States and Missing Data) solves the same problem in time rather than in value, and the two can be combined.
Source: Grafana: Queries and conditions ("Recovery threshold") and Grafana: Configure Grafana-managed alert rules (step 2, Advanced view).
Multi-dimensional alerts and instance labels
One rule produces one alert instance per unique label set, and Grafana evaluates each independently. Grafana’s example sums the non-idle CPU rate per core:
sum by(cpu) (
rate(node_cpu_seconds_total{mode!="idle"}[1m])
)
If the query returns cpu-0 at 95, cpu-1 at 30 and cpu-2 at 85, three instances exist, {cpu="cpu-0"}, {cpu="cpu-1"} and
{cpu="cpu-2"}, and a threshold of $A > 80 leaves two Firing and one Normal. A summary annotation such as
High CPU usage on {{ $labels.cpu }} names the affected component in each notification. The series have to be reduced to one value
each first: either in the query (as sum by does) or with a Reduce expression before the Threshold.
Source: Grafana: Multi-dimensional alerts.
Three consequences shape how rules are written:
-
The grouping clause of the query is the alerting granularity.
sum by (uri)gives one instance per route andsum(...)gives one for the service. Choose by who acts: a service-level symptom (the 5xx ratio) is one instance; a per-route latency rule is worth one instance per route only if a slow route is something the on-call engineer can act on. -
Labels returned by the query become instance labels, together with the rule’s own labels and
alertname. Aggregation drops labels:sum by (le, uri)leaves onlyuri, so a label likeapplication="bookshelf"has to be set on the rule (or kept in thebyclause) if a notification policy needs to match it. -
A Classic condition always produces one instance, which is the reason to avoid it: the second failing route cannot raise its own alert while the first is still firing.
Link a rule to a panel
A rule is linked to a panel with two annotations that must be set together: __dashboardUid__ (the dashboard UID) and
__panelId__ (the panel ID). In the rule form, Link dashboard and panel (in Configure notification message) selects an
existing dashboard and panel. In the other direction, the panel menu More… > New alert rule opens the rule form with the
annotations set and the panel’s query copied in. Notifications then include a link to the panel by default, and panel
screenshots can be enabled. From the panel editor, the Alert tab lists the linked rules, but only for time series panels.
The link is one-way for data: queries are not synced, so changing the query in the panel or in the rule means updating the
other by hand. For Bookshelf, link the 5xx rule to the 5xx stat panel of the "Bookshelf service health" dashboard (uid
bookshelf-service-health) so that the notification lands the responder on the right panel; see
Building Dashboards and
Annotations and Links.
Source: Grafana: Link alert rules to panels.
Migrating data source-managed rules
Alert and recording rules from Mimir and Loki data sources with the ruler API enabled, and Prometheus YAML rule files, can be
imported as Grafana-managed rules. In the UI that is Alerting > Alert rules > Import to Grafana-managed rules, which asks for
the import source (Existing data source-managed rules or Prometheus YAML file), the data source the imported rules will
query, and optionally a target folder, a namespace or group filter, whether to import alert and recording rules paused and the
target data source for recording rules. It needs the Rules Writer and Set provisioning status permissions, plus
Datasources Reader. Command-line import uses mimirtool (Mimir and Prometheus rules) or cortextool (Loki rules), 0.11.3 or
later, against <GRAFANA_BASE_URL>/api/convert/ with a service account token.
What to expect after an import:
-
The original rules stay where they were; copies are created in the target folder.
-
Imported rules run sequentially within each group, which differs from native Grafana-managed rules.
-
For alert rules, Grafana adds
prometheus_mathand threshold expressions so the alert stays Normal when the query returns no data, and sets Missing series evaluations to resolve to 1, mirroring Prometheus. A query offset is applied (from the group’squery_offset, else therule_query_offsetsetting, which is1m). -
Rules imported through the API or CLI are provisioned and not editable in the UI by default.
-
A rule group that uses the
limitoption makes the import fail, and rules with the__grafana_originlabel (created by plugins such as Kubernetes Monitoring and Synthetic Monitoring) are excluded. -
Notifications go through the existing Grafana policies unless you import the Alertmanager configuration first (a public preview in Grafana 13.3).
The Bookshelf rules
The lab’s first two alerts are symptom alerts on the data of the Bookshelf service: the share of requests that fail with a
5xx status, and the 95th percentile latency against the SLO. Both query the prometheus data source and use the label
application="bookshelf" and the Micrometer metrics from
Metrics and Observability. Both live in the folder bookshelf and are
owned by the bookshelf-sre team.
High 5xx ratio
The query is the share of requests with a 5xx status over the last five minutes:
(
sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m]))
or on() vector(0)
)
/
sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))
The or on() vector(0) is not decoration. When no request failed in the window, the 5xx selector matches no series, the
numerator is empty and so is the ratio; the rule would then report No Data exactly when the service is healthy. With the
fallback the numerator is 0 and the ratio is 0. The opposite case (no traffic at all) makes the denominator empty, and a
0/0 ratio can produce NaN: check both cases in Preview with the load generator stopped, and choose the Reduce mode (Strict,
Drop Non-Numeric or Replace Non-Numeric) on purpose. The lab’s separate "no data" alert is what catches a service that has
stopped reporting.
The condition is the Reduce last of the query, then a Threshold above 0.05 (5%), the same value as the red threshold of
the 5xx stat panel of the dashboard.
p95 latency above the SLO
The query is the 95th percentile of the request duration, per route:
histogram_quantile(
0.95,
sum by (le, uri) (
rate(http_server_requests_seconds_bucket{application="bookshelf"}[5m])
)
)
The result is in seconds. The rule uses a Threshold above 0.5, taking 500 ms as the lab SLO, and a custom recovery
threshold of 0.45. Because the query keeps uri, there is one instance per route and a notification can name the slow route
with {{ $labels.uri }}. The uri label holds the route template when the application is instrumented
as in the Spring Boot page; if it ever carries raw URLs the number of instances explodes, and the metric
cardinality is already a problem before the alert is.
As provisioning YAML
The following file defines both rules in one evaluation group. Put it in the provisioning/alerting directory of the Grafana
instance (YAML or JSON), and restart Grafana or reload the provisioned files through the Admin API.
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
datasourceUid: prometheus
relativeTimeRange:
from: 600
to: 0
model:
refId: A
datasource:
type: prometheus
uid: prometheus
expr: >-
(sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) or on() vector(0))
/ sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))
instant: false
range: true
intervalMs: 1000
maxDataPoints: 43200
- refId: B
datasourceUid: __expr__
relativeTimeRange:
from: 0
to: 0
model:
refId: B
type: reduce
expression: A
reducer: last
settings:
mode: dropNN
datasource:
type: __expr__
uid: __expr__
- refId: C
datasourceUid: __expr__
relativeTimeRange:
from: 0
to: 0
model:
refId: C
type: threshold
expression: B
conditions:
- evaluator:
type: gt
params:
- 0.05
datasource:
type: __expr__
uid: __expr__
noDataState: NoData
execErrState: Error
for: 2m
annotations:
summary: Bookshelf is returning 5xx for more than 5% of requests
__dashboardUid__: bookshelf-service-health
__panelId__: '2'
labels:
application: bookshelf
team: bookshelf-sre
severity: critical
Reference: Grafana: Provision alert rules with files
(file location, fields, noDataState and execErrState). In file provisioning the link to a dashboard panel is written as the annotations __dashboardUid__ and __panelId__; the
dashboardUid and panelId keys that the export shows are accepted by the file parser but did not set the link when tested on Grafana 13.3.0. The query, Reduce and Threshold model bodies are not described field by
field on that page; the reliable way to get the exact data block for a rule is to build it once in the UI and use the export
described in
Grafana: Export alerting resources
(Export rules, then YAML), then trim it. The panelId of 2 is the 5xx stat panel of the dashboard that the lab provisions (see
Bookshelf End to End); the lab’s own rule file already contains
these rules, so use this excerpt for study and do not mount both files.
Two details of that file are worth a sentence. execErrState is set explicitly because the file default (Alerting)
differs from the UI default (Set Error state). And the rule carries no notification settings, so its alerts follow the
policy tree by their labels, which is the Advanced view of Configure notifications.
The p95 rule is the same shape with a different query (the histogram_quantile above), a Threshold at 0.5, a rule uid such as
bookshelf-p95-latency, for: 5m and severity: warning, in the same group. A custom recovery threshold is set in the UI;
export the rule to see how Grafana stores it.
As Terraform
The grafana/grafana provider manages the same rules with the grafana_rule_group resource. Its rule block takes the
condition’s ref_id, for, keep_firing_for, no_data_state (OK, NoData, KeepLast, Alerting),
exec_err_state (OK, Error, KeepLast, Alerting), labels, annotations and one data block per query or expression,
each with ref_id, datasource_uid, model and relative_time_range (from and to in seconds).
variable "folder_uid" {
type = string
description = "uid of the folder bookshelf (generated when the lab's rule file creates it)"
}
resource "grafana_rule_group" "bookshelf_service_level" {
name = "bookshelf-service-level"
folder_uid = var.folder_uid
interval_seconds = 60
rule {
name = "Bookshelf high 5xx ratio"
condition = "C"
for = "2m"
no_data_state = "NoData"
exec_err_state = "Error"
annotations = {
summary = "Bookshelf is returning 5xx for more than 5% of requests"
}
labels = {
application = "bookshelf"
team = "bookshelf-sre"
severity = "critical"
}
data {
ref_id = "A"
datasource_uid = "prometheus"
relative_time_range {
from = 600
to = 0
}
model = jsonencode({
refId = "A"
expr = "(sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[5m])) or on() vector(0)) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[5m]))"
instant = false
range = true
intervalMs = 1000
maxDataPoints = 43200
})
}
data {
ref_id = "B"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
refId = "B"
type = "reduce"
expression = "A"
reducer = "last"
settings = { mode = "dropNN" }
})
}
data {
ref_id = "C"
datasource_uid = "__expr__"
relative_time_range {
from = 0
to = 0
}
model = jsonencode({
refId = "C"
type = "threshold"
expression = "B"
conditions = [{ evaluator = { type = "gt", params = [0.05] } }]
})
}
}
}
Reference: Terraform: grafana_rule_group
(argument reference). The folder bookshelf must exist (in the lab its uid is generated; look it up with GET /api/folders). Provisioning as a whole is
the subject of
Provisioning Alerting Resources and
Observability as Code.
What can go wrong
-
Empty is not zero. A numerator selector that matches nothing makes the whole ratio empty, which a rule reads as No Data. Add
or on() vector(0)where an empty result is a normal value. -
Labels that do not join. A Math expression over two queries joins by labels; different label sets give no result.
-
The reducer hides the problem.
Meanover ten minutes smooths a two-minute outage into a pass, andLastreports a single noisy sample as the truth. Pick the reducer from the failure you want to catch, and see Metric Types and Aggregation. -
Classic condition by habit. It gives one alert however many series fail, and it is only kept for compatibility.
-
Time range surprises. Only fixed relative ranges work in alert queries; absolute and semi-relative ranges are not supported.
-
Query drift. A rule linked to a panel keeps its own copy of the query.
-
NaN and infinity. Ratios and quantiles produce them when there is no traffic; choose the non-numeric mode on purpose.
-
UI-only rules. A rule deleted in the UI cannot be recovered by its author; keep them in files, Terraform or the API.
Verify it in the lab
In the lab (Hands-on Lab, profile grafana):
-
Create the 5xx rule in the UI, folder
bookshelf, Advanced view. Run Preview with the load generator in normal mode and confirm a value near 0 (not No Data). Removeor on() vector(0)and run the preview again to see No Data, then restore it. -
Stop the load generator and preview again; note what the NaN case looks like with each Reduce mode.
-
Start the load generator in failing-request mode and confirm the instance goes Pending and then Alerting after the pending period.
-
Create the p95 rule, start slow mode, and confirm that the preview lists one instance per
uri, with the route as a label. -
Replace the Threshold with a Classic condition on the same query and compare the number of instances; switch back.
-
Link the rule to the 5xx panel and open the dashboard: the panel shows the alert state.
-
Export the rule group (Export rule group, YAML), diff it against the file above and provision it into a clean Grafana.
In the books
Salituro (Learn Grafana 10.x) walks through a rule with a Reduce expression, an evaluation group and a pending period, and states that rules in one group are evaluated in sequence; Hernandez (Building IoT Visualizations using Grafana) lists the Classic condition, Math, Reduce and Resample operations and notes that the Classic condition gives a single alert while the others give one per series; McCollam (Getting Started with Grafana) describes the Grafana 8 form with a rule type field and one query per condition. The ideas (queries, reduction, condition, one alert per series) are unchanged. What differs: the form has a Default and an Advanced view, there are Threshold and SQL expressions and a custom recovery threshold, rules can be linked to panels and imported from Mimir, Loki and Prometheus, Grafana-managed rules in a group now run concurrently (the sequential order is kept for imported rules and data source-managed rules), and the Classic condition is legacy.