TExcelTAD
Home › Observability: Prometheus, Grafana, Loki & OpenTelemetry › Dashboard Variables & Templating

Dashboard Variables & Templating

One "linkly" dashboard should work for staging and production, for one pod or all of them. Variables make that possible: dropdowns at the top of the dashboard whose values are substituted into every query.

Variable types

Type Values come from Example
Query a data source query label_values(up{job="linkly"}, instance)
Custom a fixed comma-separated list p50,p90,p99
Data source all data sources of a type switch between Prometheus-eu and Prometheus-us
Interval a list of durations 1m,5m,15m,1h
Constant / Text box a fixed or typed value a hidden cluster constant, a free-text filter
Filters (ad hoc) any label of the data source add route="/links" to every query on the fly

Prometheus query variables use helper functions: label_values(label), label_values(metric, label), metrics(regex) and query_result(query). Chain them so each dropdown narrows the next:

text
env       label_values(up{job="linkly"}, env)
instance  label_values(up{job="linkly", env="$env"}, instance)      ← depends on $env

Using variables in queries

promql
sum by (code) (rate(http_requests_total{job="linkly", env="$env", instance=~"$instance"}[$__rate_interval]))

With Multi-value or Include All enabled, a variable can hold several values; Grafana then formats them as a regex alternation, which is why multi-value variables are used with =~, never =. The format can be chosen explicitly: ${instance:regex}, ${instance:pipe}, ${instance:csv}, ${instance:json}. Include All with a custom all value of .* keeps queries short when there are hundreds of pods.

Built-in variables

Variable Value
$__interval the time between graph points: time range ÷ max data points (respecting the panel's min interval)
$__rate_interval max($__interval + scrape interval, 4 × scrape interval): always safe for rate()
$__range the dashboard's whole time range, e.g. 6h: increase(x[$__range]) for "total in the selected period"
$__from, $__to range start/end in ms; in links: ${__from:date:iso}
$__dashboard, ${__user.login} for titles and links

The scrape interval Grafana uses is the data source's Scrape interval setting (timeInterval in provisioning), 15 s by default. If it's wrong, $__rate_interval is wrong too.

This model follows Grafana's interval calculation (with a simplified table of the "nice" steps Grafana rounds to) for a 1,000-point-wide panel at different zoom levels, and shows what goes wrong with a fixed [1m] or with $__interval:

python · try it yourself
SCRAPE = 15            # seconds, the data source's scrape interval
MAX_POINTS = 1000      # roughly the panel width in pixels
NICE = [1, 2, 5, 10, 15, 20, 30, 60, 120, 300, 600, 900, 1200, 1800, 3600, 7200, 10800, 21600, 43200, 86400]

def interval(range_s, min_interval=SCRAPE):
    raw = range_s / MAX_POINTS
    nice = next((n for n in NICE if n >= raw), NICE[-1])     # Grafana rounds to a "nice" step
    return max(nice, min_interval)

def rate_interval(range_s):
    i = interval(range_s)
    return max(i + SCRAPE, 4 * SCRAPE)

def fmt(s):
    return f"{s // 3600}h" if s % 3600 == 0 else f"{s // 60}m" if s % 60 == 0 else f"{s}s"

print("time range  $__interval  $__rate_interval  samples per window   with [1m]: points skipped")
for label, r in (("15m", 900), ("1h", 3600), ("6h", 21600), ("24h", 86400), ("7d", 604800), ("30d", 2592000)):
    i, ri = interval(r), rate_interval(r)
    skipped = max(0, i - 60)
    print(f"{label:>10}  {fmt(i):>11}  {fmt(ri):>16}  {ri // SCRAPE:>17}   "
          f"{'no gaps' if skipped == 0 else f'{skipped // SCRAPE} of every {i // SCRAPE} samples ignored'}")
time range  $__interval  $__rate_interval  samples per window   with [1m]: points skipped
       15m          15s                1m                  4   no gaps
        1h          15s                1m                  4   no gaps
        6h          30s                1m                  4   no gaps
       24h           2m              135s                  9   4 of every 8 samples ignored
        7d          15m              915s                 61   56 of every 60 samples ignored
       30d           1h             3615s                241   236 of every 240 samples ignored
  • At short ranges $__interval is the scrape interval (15 s), and rate(x[15s]) would contain fewer than two samples: no data. $__rate_interval never goes below 4 scrapes.
  • At long ranges, a fixed [1m] only looks at one minute out of every step and ignores the rest: a spike between two points is invisible. $__rate_interval grows with the step, so every sample is inside some window.

Repeating panels and rows

A panel or row can repeat for each value of a multi-value variable: one latency panel per route, one row per instance. Use sparingly; 40 repeated panels make a slow dashboard. A single panel with by (route) is often clearer.

Links between dashboards

Panel and data links can carry variables and the time range to another dashboard:

text
/d/linkly-pod/linkly-pod?var-instance=${__field.labels.instance}&${__url_time_range}

Clicking a pod's line in the fleet dashboard opens that pod's detailed dashboard at the same time. This "drill-down" structure (overview → service → instance) keeps each dashboard small and fast.

Test yourself

A multi-value $instance variable is used as instance="$instance" and shows no data when two pods are selected. Why?

  1. Grafana bug
  2. Multi-values are formatted as a regex alternation (a|b), which only works with =~
  3. Variables can't be used in labels
  4. The data source is wrong

Why use $__rate_interval instead of $__interval in rate()?

  1. It's shorter
  2. It's never smaller than four scrape intervals, so rate() always has enough samples
  3. It is the dashboard's whole range
  4. It only works in Grafana Cloud

Which query fills a dropdown with linkly's instances in the selected environment?

  1. label_values(up{job="linkly", env="$env"}, instance)
  2. sum(up) by (instance)
  3. metrics(instance)
  4. $instance