Sheet ⁨04⁩ · ⁨Cheatsheets⁩Surveyed ⁨2026⁩
Cheatsheet image for PromQL - A practical PromQL reference. Instant and range vectors, label matchers, rate and increase on counters, aggregation with by and without, histogram_quantile for latency, vector matching, and recording and alerting rule patterns.
Cheatsheets

PromQL

A practical PromQL reference. Instant and range vectors, label matchers, rate and increase on counters, aggregation with by and without, histogram_quantile for latency, vector matching, and recording and alerting rule patterns.

6 Categories9 Sections24 ExamplesPublished: 27 Nov 2026Updated: 29 Nov 2026
PromQLPrometheusMetricsAlertingGrafanaSREObservability

PromQL

PromQL looks like a small language until a query returns nothing and the error mentions a type you did not know existed. Almost every one of those moments comes from the same place: an expression produced a range vector where an instant vector was needed, or the other way around.

Only an instant vector can be drawn. A range vector exists purely to be handed to a function. Those two facts explain why it is always sum(rate(x[5m])) and never the reverse, and the red panel covers the three mistakes that quietly break real dashboards.

The reference below is grouped the way the work splits: selecting the series you want, turning counters into rates, aggregating across series, pulling percentiles out of histograms, joining metrics together, and finally writing the recording and alerting rules that make all of it fast and actionable.

Selectors and Vector Types

Choosing series by name and label, and the difference between an instant vector and a range vector.

Instant vs Range Vectors

The single most important distinction in PromQL, and the source of most type errors.

An instant vector: one sample per series

Returns the most recent value for every series matching the metric name.

Code
http_requests_total
Output
http_requests_total{job="api", code="200"} 184213
  • This is the only type Grafana can render as a time series panel.
  • An empty panel usually means your outermost expression is not an instant vector.

A range vector: many samples per series

The square brackets select every sample in the last 5 minutes for each series.

Code
http_requests_total[5m]
  • You cannot graph this and you cannot do arithmetic on it.
  • Its only purpose is to be the argument to rate, increase, delta or an _over_time function.

Look at an earlier point in time with an offset

Shifts the evaluation back in time, which is how you compare against last week without changing the dashboard range.

Code
http_requests_total offset 1w
rate(http_requests_total[5m] offset 1d)
  • The offset modifier goes after the selector, and after the range if there is one.
  • Use it for week-over-week panels rather than duplicating a dashboard.

Label Matchers

Filtering series by label with equality, negation and regular expressions.

The four matcher operators

Matchers combine with commas and every one of them must hold.

Code
http_requests_total{job="api"} # exactly equal
http_requests_total{job!="api"} # not equal
http_requests_total{job=~"api|web"} # regex match
http_requests_total{job!~"canary-.*"} # regex not match
  • Regex matchers are fully anchored, as if wrapped in ^ and $.
  • Use =~"api.*" if you want a prefix match.

Match on the metric name itself

The metric name is just a label called __name__, so you can select on it like any other.

Code
{__name__=~"node_cpu_.*", instance="web-01:9100"}
  • Useful for exploration, slow for dashboards, because it cannot use the name index efficiently.

Exclude a label that may be absent

An empty string matches series where the label is not set at all, which is how you find series missing a label.

Code
kube_pod_info{created_by_kind=""}
  • This is the standard idiom for "label is absent", since there is no separate absent matcher.

Counters and Rates

Turning ever-increasing counters into per-second rates and totals, without being fooled by restarts.

rate() and irate()

The two ways to get a per-second rate, and why one of them belongs on dashboards and the other does not.

Requests per second, aggregated by job

rate() runs per series first, then sum collapses the result across labels.

Code
sum by (job) (rate(http_requests_total[5m]))
  • rate() always goes innermost. Summing counters before rating destroys reset detection.
  • The window must be at least 4 scrape intervals or the graph goes blank on a single missed scrape.

Error ratio, the standard SLO numerator over denominator

Both sides are rates over the same window, so the ratio is dimensionless and safe to alert on.

Code
sum(rate(http_requests_total{code=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
  • Use identical windows on both sides or the ratio is meaningless.
  • Wrap the whole thing in a recording rule if it appears on more than one dashboard.

irate() for a short, spiky view

Uses only the last two samples in the window, so it reacts instantly and is very noisy.

Code
irate(http_requests_total[5m])
  • Good for debugging a live incident at a 15 second refresh.
  • Never use irate in an alert. It will fire on a single spike and recover before anyone looks.

increase(), delta() and resets()

Totals over a window for counters, and change over a window for gauges.

How many errors in the last hour

increase() is rate() multiplied by the window, with the same counter reset handling.

Code
sum(increase(http_requests_total{code=~"5.."}[1h]))
  • Reads more naturally than rate for alert annotations and reports.
  • Still extrapolated, so expect 41.7 rather than 42.

How much did a gauge move

delta() reports first-to-last change on a gauge and can be negative, which increase() never is.

Code
delta(node_filesystem_free_bytes{mountpoint="/"}[1h])
  • Use predict_linear rather than delta when you want to alert on running out of disk.

Count how many times a process restarted

Counts counter resets in the window, which for a start time metric means restarts.

Code
resets(process_start_time_seconds[1h])
  • A cheap crash loop detector that needs no extra instrumentation.

Aggregation

Collapsing many series into few, and choosing which labels survive.

sum, avg, min, max, count

The core aggregation operators and the by and without modifiers.

Keep some labels, drop the rest

The first keeps exactly job and code. The second keeps everything except instance and pod.

Code
sum by (job, code) (rate(http_requests_total[5m]))
sum without (instance, pod) (rate(http_requests_total[5m]))
  • Prefer without in a dynamic environment. It survives someone adding a new label.
  • With no modifier at all, every label is dropped and you get a single series.

Count series rather than sum values

The first counts healthy targets per job. The second counts distinct metric names, which is a quick cardinality check.

Code
count by (job) (up == 1)
count(count by (__name__)({__name__=~".+"}))
  • count counts series. count_values counts how many series share a value.

The noisiest few, and everything else

topk and bottomk keep the k highest or lowest series and drop the rest.

Code
topk(5, sum by (pod) (rate(container_cpu_usage_seconds_total[5m])))
bottomk(3, node_memory_MemAvailable_bytes)
  • topk keeps the original labels, so the result is still usable in a legend.
  • Do not use topk in an alert. The membership changes between evaluations and alerts flap.

Histograms and Latency

Getting percentiles out of bucketed observations without lying to yourself.

histogram_quantile()

The standard p50, p95 and p99 pattern, and the rules that make it correct.

p99 latency across a whole service

Rate the buckets, sum them keeping le, then take the quantile once at the very end.

Code
histogram_quantile(
0.99,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
  • The order matters: rate innermost, sum by (le) next, histogram_quantile outermost.
  • Averaging quantiles from several instances gives a number that is not any percentile at all.

p95 per endpoint

Keep le plus whichever labels you want to break the panel down by.

Code
histogram_quantile(
0.95,
sum by (le, route) (rate(http_request_duration_seconds_bucket[5m]))
)
  • Every extra label multiplies the series count by the number of buckets. Be selective.

The SLO question histograms answer better than percentiles

The fraction of requests served faster than 300ms, read straight off a bucket boundary with no interpolation.

Code
sum(rate(http_request_duration_seconds_bucket{le="0.3"}[5m]))
/
sum(rate(http_request_duration_seconds_count[5m]))
  • This is exact rather than interpolated, which makes it the better basis for an SLO.
  • It only works if 0.3 is an actual bucket boundary in your histogram.

Operators and Vector Matching

Arithmetic, comparison, and joining two metrics that do not share the same labels.

Arithmetic and Comparison

Doing maths on vectors, and filtering with comparisons.

Filter with a comparison

Returns only the series below the threshold, which is exactly what an alert rule wants.

Code
node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.1
  • An empty result means nothing is wrong, which is why alert rules use this form.

Get 1 and 0 instead of a filter

The bool modifier turns the comparison into a value rather than a filter, so every series is kept.

Code
(rate(http_requests_total[5m]) > bool 100)
  • Use bool when you want to count how many series breach a threshold.
  • sum(x > bool 5) gives you that count directly.

Set operators for presence and absence

and, or and unless match on labels, and unless is the standard way to suppress alerts during maintenance.

Code
up == 0 unless on (instance) node_maintenance_mode == 1
  • Set operators ignore values entirely and work purely on label sets.

Recording and Alerting Rules

Pre-computing expensive queries, and turning an expression into a page.

Recording Rules

Evaluating a query on a schedule and storing the result as a new series.

Pre-compute an expensive aggregation

Each rule stores its result as a new metric, so dashboards query one cheap series instead of thousands.

Code
groups:
- name: http.rules
interval: 30s
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
- record: job:http_errors:ratio5m
expr: |
sum by (job) (rate(http_requests_total{code=~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total[5m]))
Execution
Terminal window
promtool check rules rules/http.rules.yml
Output
SUCCESS: 2 rules found
  • Rules inside a group run in order, so a later rule can use an earlier one.
  • Groups run in parallel, so never rely on ordering across groups.

Alerting Rules

The for clause, labels, annotations, and writing alerts that do not flap.

A complete alerting rule

The expression must stay true for the whole for duration before the alert fires.

Code
groups:
- name: http.alerts
rules:
- alert: HighErrorRate
expr: job:http_errors:ratio5m > 0.05
for: 10m
labels:
severity: page
team: platform
annotations:
summary: '{{ $labels.job }} is failing 5 percent of requests'
description: >-
Error ratio is {{ $value | humanizePercentage }}
over the last 5 minutes.
runbook_url: 'https://runbooks.example.com/high-error-rate'
  • Without for, a single bad scrape pages someone at 3am.
  • labels route the alert in Alertmanager, annotations are what the human reads.

Alert on absence, which is the one most people forget

Fires when the series does not exist at all, catching a target that vanished rather than one that failed.

Code
absent(up{job="payments"} == 1)
  • A threshold alert cannot fire on a metric that stopped being reported. absent can.
  • Use absent_over_time for metrics that are legitimately sparse.

Was this useful?

You might also enjoy

More posts on similar topics

Nginx

Nginx

Most nginx confusion comes from one place: the order it uses to pick a location block. It is not the order in the file, and it is not the first thing that matches.

#Nginx#Reverse Proxy#TLS+4 tags
read more
jq

jq

jq clicked for me the day I stopped thinking of it as a JSON string transformer. It is a stream of values, and every filter takes a stream in and emits a stream out. That one idea explains the parts t

#Jq#JSON#Shell+4 tags
read more
GitHub Actions

GitHub Actions

GitHub Actions runs your CI/CD directly from YAML files in .github/workflows/, and most of the job is knowing which key does what. A workflow reacts to events, splits into jobs that run on runners,

#GitHub Actions#Workflow#CI/CD+5 tags
read more
Linux Networking

Linux Networking

Every Linux box speaks the network through a small set of tools, and knowing them turns "the network is broken" into a specific, fixable answer. This cheatsheet covers the modern stack: ip for inter

#Linux networking#Ip command#Tcpdump+5 tags
read more
AWS CLI

AWS CLI

The AWS Command Line Interface (CLI) lets you orchestrate infrastructure, move cloud data, and configure security entirely from the terminal. This reference covers configuring identity profiles, manag

#AWS CLI#EC2#S3+4 tags
read more
Docker

Docker

Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run applicati

#Docker#Containers#Images+3 tags
read more

6 related posts