Grafana: Recording Rules

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 recording rule below was created through the provisioning HTTP API and wrote its series into the lab’s Prometheus.

To do this by hand, follow Silence, Schedule and Review Alerts.

Some queries are too expensive to run every few seconds. A dashboard with twenty panels that each aggregate millions of samples, or an alert that evaluates the same ratio every minute, repeats the same work for every viewer and every evaluation. A recording rule does that work once, on a schedule, and stores the result as a new time series, one data point per evaluation. Dashboards and alert rules then read the cheap, pre-aggregated series. The idea comes from Prometheus (see Recording and Alerting Rules); Grafana Alerting adds two flavours of it. This page explains both, what the target data source is, and how to alert on a recorded series without creating a new failure mode. The wider concept is introduced in Alerting Fundamentals, the evaluation machinery in Rule Evaluation, States and Missing Data, and the rule editor in Alert Rules: Queries and Conditions. The running example is the Bookshelf service (see Metrics and Observability) in the Hands-on Lab.

What a recording rule does

A recording rule runs on a fixed evaluation interval, for example every minute or every five minutes, and writes one value as a new data point of the recorded metric. The rule must therefore return a single value: either an instant query, or a range query combined with a Reduce expression. Grafana lists these reasons to use them:

  • Faster queries on heavy aggregations or large data sets.

  • Lower load on the system when many simultaneous queries would otherwise run.

  • Simpler alerts and dashboards, because a complex aggregation becomes one metric.

  • Reuse: one query serves several alert rules and dashboards, which reduces cost.

Two caveats come with the technique. A recorded metric may not match the raw data exactly, because of the aggregation in the query and because of evaluation lag; a shorter evaluation interval narrows the gap by improving resolution. And a recording rule is itself something that can stop working, which matters most when an alert depends on its output (see Alerting on recorded series).

Two kinds of recording rules

Grafana-managed Data source-managed

Status in the docs

The recommended option.

Available for Prometheus-based data sources.

Queries

Any data source that Grafana Alerting supports, plus expressions (Reduce, Math, Resample, Classic condition).

Prometheus-based data sources such as Mimir and Loki. The query always runs as an instant query.

Where the rule runs

In Grafana, which writes the result to a target data source.

In the data source’s own ruler (Mimir, Loki, Prometheus-compatible rulers).

Storage

Grafana has no time series database of its own: you need a Prometheus-compatible database as the target.

The data source that owns the rule.

Created from

Alerts & IRM, Alerting, Alert rules, More, New Grafana recording rule.

Alerts & IRM, Alerting, Alert rules, More, New Data source recording rule.

Organisation

Folder and evaluation group.

Namespace and group.

Grafana 13.3 also introduces the Prometheus Alerting app plugin, which takes over the management of rules for Prometheus, Mimir and Loki data sources while Grafana-managed alerting stays in core; it is a public preview on Cloud and OSS and experimental on Enterprise.

Grafana-managed recording rules

Enabling and the target data source

In Grafana Cloud recording rules are enabled by default. In Grafana OSS and Enterprise, the "Before you begin" section of the page applies, and it concerns the write target. Each rule has a Target data source, the Prometheus-compatible database that receives the recorded series. A rule that has no explicit target, for example a rule created before Grafana 12.1, falls back to the data source named in the [recording_rules] section of the configuration:

[recording_rules]
default_datasource_uid = prometheus

Reference: Grafana: Create Grafana-managed recording rules ("Before you begin"). The value is the data source UID; prometheus is the UID used for the lab’s Prometheus data source.

The older way of configuring a write target, the url and basic_auth_* options of the [recording_rules] section, is no longer supported. The page names two ways out: set default_datasource_uid, or, before upgrading to Grafana 12.1, turn on the grafanaManagedRecordingRulesDatasources feature flag and set a target data source on each rule. On Grafana Cloud, a blank target writes to the managed grafanacloud-prom data source, which may not be the data source your dashboards read, so select the target explicitly when it matters. The Terraform provider documents the record block as requiring Grafana 11.2 or later and the grafanaManagedRecordingRules feature toggle on self-managed instances; the quickest check on an instance is whether New Grafana recording rule appears under More.

For the lab’s Prometheus (or Mimir) to accept the written samples it must expose the remote write receiver; see Telemetry Collection Pipelines, where Prometheus is started with --web.enable-remote-write-receiver so that /api/v1/write accepts pushed data. The target data source in Grafana must point at the same server, and its prometheusType must be set (the lab data source file sets prometheusType: Prometheus): with the type missing, the lab’s rule failed every evaluation with remote write failed ... actual=404, and after the type was set and the data sources reloaded the recorded series appeared in Prometheus within a minute. On Grafana 13.3.0 the rule was accepted without enabling any feature toggle.

Creating the rule in the UI

  1. Open Alerts & IRM, Alerting, Alert rules, then More, New Grafana recording rule.

  2. Enter the rule name and the metric name. The metric name must be a valid Prometheus metric name and contain no whitespace.

  3. Select the data source to query. This is the source of the data, not the place where the result is written.

  4. Set the time range in the Options dropdown. Only fixed relative ranges are supported (for example now-24hr: now); absolute and semi-relative ranges (now/d) are not.

  5. Add queries with Add query and, if needed, expressions: Classic condition for a single output, or Math, Reduce or Resample. With Prometheus, an instant vector and built-in functions can make extra expressions unnecessary.

  6. Click Preview to check the output, then Set as recording rule output on the query or expression whose result should become the stored metric.

  7. Choose a folder and an evaluation group (or create them). Rules in a group run concurrently at the same interval with an aligned evaluation time. If another rule depends on this one, an explicit evaluation order is available only through the API or Terraform (see Rule Evaluation, States and Missing Data for rule sequences).

  8. Optionally pause the rule, add labels (they are added to the resulting metric) and select the Target data source.

  9. Click Save rule or Save rule and exit. The metric then becomes available to dashboards and alert rules.

The scheduler’s min_interval (default 10s) sets the minimum time between evaluations and applies to alert rules and recording rules alike. A rule frequency below it, or one that is not a multiple of the 10 second scheduler interval, is adjusted, so a one-second recording rule is not possible.

Source: Grafana: Create Grafana-managed recording rules ("Steps" and "Advanced: minimum interval").

Naming the recorded metric

The metric name is yours to choose, and a convention keeps recorded series recognisable. The Prometheus guidance is the form level:metric:operations: the aggregation level and labels, the metric name, and the operations applied, newest first. It also advises aggregating the numerator and the denominator separately and then dividing, instead of averaging a ratio, which is statistically not valid. The Bookshelf 5xx ratio follows both:

application:http_server_requests_5xx:ratio_rate5m

Bookshelf example as code

The query behind the recorded 5xx ratio is the same one the lab alert uses, run as an instant query against the data source with UID prometheus. The Grafana alerting provisioning API creates the rule with a record block; there are no condition, noDataState or execErrState fields, because recording rules do not support them. The target_datasource_uid is optional and, if omitted, the [recording_rules] default_datasource_uid fallback is used.

POST /api/v1/provisioning/alert-rules
Accept: application/json
Content-Type: application/json
Authorization: Bearer GRAFANA_TOKEN

{
  "title": "bookshelf_5xx_ratio_rate5m",
  "ruleGroup": "bookshelf-recording",
  "folderUID": "REPLACE_WITH_FOLDER_UID",
  "for": "0s",
  "orgId": 1,
  "uid": "",
  "labels": {
    "service": "bookshelf"
  },
  "data": [
    {
      "refId": "A",
      "queryType": "",
      "relativeTimeRange": { "from": 600, "to": 0 },
      "datasourceUid": "prometheus",
      "model": {
        "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,
        "intervalMs": 1000,
        "maxDataPoints": 43200,
        "refId": "A"
      }
    }
  ],
  "record": {
    "metric": "application:http_server_requests_5xx:ratio_rate5m",
    "from": "A",
    "target_datasource_uid": "prometheus"
  }
}

Reference: Grafana: Provision alerting resources with the HTTP API (recording rule example). The folder uid of the lab is generated when the rule file creates the folder bookshelf; look it up with curl -s -u admin:admin http://localhost:3000/api/folders | jq -r '.[] | select(.title=="bookshelf") | .uid' and use it as folderUID, which puts the rule in the same folder as the lab alerts. A folderUID that does not exist is refused with invalid alert rule: folder does not exist. In the lab use basic authentication (-u admin:admin) instead of the bearer token shown.

The Terraform provider expresses the same rule as a rule with a record block in a grafana_rule_group. The record attributes are metric and from (required) and target_datasource_uid (optional); the rest follows the alert rule example on Observability as Code.

resource "grafana_rule_group" "recording" {
  name             = "bookshelf-recording"
  folder_uid       = grafana_folder.bookshelf.uid
  interval_seconds = 60

  rule {
    name = "bookshelf_5xx_ratio_rate5m"

    record {
      metric                = "application:http_server_requests_5xx:ratio_rate5m"
      from                  = "A"
      target_datasource_uid = var.prometheus_uid
    }

    labels = {
      service = "bookshelf"
    }

    data {
      ref_id         = "A"
      datasource_uid = var.prometheus_uid
      relative_time_range {
        from = 600
        to   = 0
      }
      model = jsonencode({
        refId   = "A"
        instant = true
        expr    = "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[5m])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[5m]))"
      })
    }
  }
}

Reference: Terraform: grafana_rule_group. The folder resource and var.prometheus_uid are the ones defined in the Observability as Code example.

Data source-managed recording rules

A data source-managed rule lives in the ruler of a Prometheus-based data source such as Mimir or Loki. It is the right choice when the rule should keep running without Grafana, or when the same ruler already holds the organisation’s other rules. The form asks for the rule name (a Prometheus metric name without whitespace), the data source and query (always an instant query), a namespace (organisation only; it can hold several groups), a group (rules in a group run sequentially at a regular interval with the same evaluation time) and optional labels.

Prerequisites worth checking before blaming the form:

  • Write permission on the Prometheus or Loki data source; without it rules cannot be created or updated.

  • The ruler API must be enabled in Mimir and Loki. Loki’s default local rule storage supports only viewing rules, so editing needs another storage type.

  • For Mimir, use the /prometheus prefix; the query API and the ruler API must share one URL because a separate ruler URL cannot be set.

Alert rules and recording rules in the same group evaluate sequentially, which is what guarantees that a recording rule runs before an alert rule that reads its output.

Alerting on recorded series

A recorded series is cheaper to alert on, and it is where the failure modes move. Grafana’s guidance:

  • Use frequent evaluation intervals. A long interval such as an hour can leave the metric stale and misalign the alerts, in particular with a long pending period.

  • Align the alert rule’s evaluation frequency with the recording rule’s interval, so the alert acts on fresh data.

  • For instant queries, use _over_time functions such as max_over_time(my_metric[5m]) to obtain an aggregated value without a range query and a Reduce expression.

For Bookshelf, the 5xx alert can read application:http_server_requests_5xx:ratio_rate5m instead of the two rate queries, with the same $B > 0.05 condition. Two things then have to be true for the alert to be trustworthy. The recording rule must keep producing data, so add a no-data alert on the recorded metric (a missing recorded series makes the alert go quiet instead of firing, see Designing Actionable Alerts); and the alert should be evaluated no more often than the recording interval, otherwise it reads the same data point several times.

Source: Grafana: Create recording rules ("Alerting on recorded metrics").

What can go wrong

  • Nothing is written. The target data source does not accept remote write (the Prometheus flag is missing), the target is blank on Cloud and goes to grafanacloud-prom, or the rule has no target and no default_datasource_uid.

  • An old configuration stops working. Rules configured with the removed url and basic_auth_* options need default_datasource_uid or a per-rule target.

  • The rule is rejected. The metric name has whitespace or is not a valid Prometheus name, or the time range is absolute or semi-relative.

  • The value is stale. The recording interval is long compared with the alert interval or the pending period.

  • The numbers differ from the raw query. Expected: aggregation and evaluation lag. Compare over a window that is long compared with the interval.

  • The alert fires before the recording exists. The alert and the recording rule are in different groups with no ordering. Put them in one group of a data source-managed ruler, or define an explicit order for Grafana-managed rules (API or Terraform only).

  • min_interval overrides the rule. The configured interval is raised to the minimum.

  • Loki rules cannot be edited. The local rule storage is read-only.

Verify it in the lab

  1. Start the grafana profile (see Hands-on Lab) with the load generator running, so that http_server_requests_seconds_count moves.

  2. Create the recording rule with the API call above (or New Grafana recording rule in the UI) with a one-minute group.

  3. After two evaluations open Explore on the Prometheus data source and query application:http_server_requests_5xx:ratio_rate5m. The series must exist and carry the label service="bookshelf".

  4. Compare it with the raw ratio query over the same window: the values should be close, not identical.

  5. Switch the lab’s 5xx alert to the recorded series, drive 5xx failures with the load generator and confirm that the alert fires within the pending period plus one recording interval.

  6. Stop the rule (pause it) and confirm what your no-data handling does for the alert that reads it.

  7. Remove the target data source from the rule and check that writes go to the [recording_rules] default_datasource_uid data source.

In the books

Chapman’s chapter on platform cost and data (Observability with Grafana) mentions Grafana’s recording rule functionality as a way to pre-compute a query and store it as a new time series, using a daily unique-user count for a BI platform as the example. Hernandez’s chapter 10 (Grafana 8 era) lists "Cortex/Loki managed recording rule" as one of three rule creation choices, which is the data source-managed kind above; the Grafana-managed kind, the target data source and the default_datasource_uid fallback came later, so the books do not cover them.