
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.
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.
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.
No commands found
Try adjusting your search term
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.
http_requests_totalhttp_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.
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.
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.
http_requests_total{job="api"} # exactly equalhttp_requests_total{job!="api"} # not equalhttp_requests_total{job=~"api|web"} # regex matchhttp_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.
{__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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
(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.
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.
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]))promtool check rules rules/http.rules.ymlSUCCESS: 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.
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.
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?
Continue on this topic
The same subject, covered a different way from the cheatsheet above.
ArticleFull-Stack Observability with OpenTelemetry: Getting a Clear View of Your Systems
A full view of your complex systems using OpenTelemetry: the basics, the benefits, using it with Prometheus and Grafana, and answers to common questions.
QuizPrometheus & Grafana: Monitoring & Observability Fundamentals
Test your monitoring and observability skills with this quiz on Prometheus metrics, PromQL, Grafana dashboards, and alerting logic.
Dev TipKubernetes Monitoring with Prometheus and Grafana: Metrics, Dashboards, and Alerts
You'll learn what Prometheus actually scrapes and why nothing pushes to it, the four exporters that cover a cluster, how one careless label turns 600 time series into 120 million, and which alerts are worth waking someone up for.
Case StudyTaming a 3am Pager: SLOs and Error Budgets That Stuck
How a team traded dozens of noisy, cause-based alerts for a handful of SLO burn-rate pages, and used error budgets to actually change how it decided what to ship.
You might also enjoy
More posts on similar topics

Nginx
- Mohammad Abu Mattar
- Web Server
- Networking
- DevOps
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.

jq
- Mohammad Abu Mattar
- CLI Tool
- Config & Data Formats
- DevOps
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

GitHub Actions
- Mohammad Abu Mattar
- CI/CD
- DevOps
- GitHub
- Automation
- YAML
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,

Linux Networking
- Mohammad Abu Mattar
- Linux
- Networking
- DevOps
- CLI
- SysAdmin
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

AWS CLI
- Mohammad Abu Mattar
- Cloud Computing
- AWS
- DevOps
- CLI
- Automation
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

Docker
- Mohammad Abu Mattar
- DevOps
- Docker
- Containers
- Deployment
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
6 related posts