---
title: "PromQL"
description: "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."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/promql
---

# 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 four PromQL types, and the two rules that follow from them_

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.

**Keywords:** instant vector, range vector, PromQL

#### An instant vector: one sample per series

```promql
http_requests_total
```

_output_
```text
http_requests_total{job="api", code="200"}  184213
```

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

- 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

```promql
http_requests_total[5m]
```

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

- 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

```promql
http_requests_total offset 1w

rate(http_requests_total[5m] offset 1d)
```

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

- 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.

**Best practices:**

- Read every expression from the inside out and name the type at each step.
- If a function complains about an expected type, you have either added or forgotten a range.

**Common errors:**

- **parse error: expected type range vector in call to function rate, got instant vector**: Add a range to the selector: rate(metric[5m]) rather than rate(metric).
- **A panel renders in the table view but is blank as a graph**: Your expression returns a range vector. Wrap it in a function that reduces it, such as rate or avg_over_time.

**Advanced notes:**

- **Subqueries produce a range vector from an instant vector:** max_over_time(rate(errors_total[5m])[1h:1m]) evaluates the inner rate every minute across an hour, then takes the maximum. The [1h:1m] is a subquery and it is expensive, so prefer a recording rule for anything on a dashboard.

### Label Matchers

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

**Keywords:** label matching, regex, selectors

#### The four matcher operators

```promql
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
```

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

- Regex matchers are fully anchored, as if wrapped in ^ and $.
- Use =~"api.*" if you want a prefix match.

#### Match on the metric name itself

```promql
{__name__=~"node_cpu_.*", instance="web-01:9100"}
```

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

- Useful for exploration, slow for dashboards, because it cannot use the name index efficiently.

#### Exclude a label that may be absent

```promql
kube_pod_info{created_by_kind=""}
```

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

- This is the standard idiom for "label is absent", since there is no separate absent matcher.

**Best practices:**

- Prefer an equality matcher over a regex when you know the exact value. It uses the index directly.
- Never select on a label with unbounded values such as a user ID or a full URL path.

**Common errors:**

- **A regex matcher returns nothing even though the value looks right**: Matchers are anchored. job=~"api" only matches exactly "api". Use job=~"api.*" for a prefix.
- **A query is slow and Prometheus warns about too many samples**: You are selecting on a high cardinality label. Narrow with job or namespace first, then filter.

**Advanced notes:**

- **Cardinality is the real cost:** Every unique combination of label values is a separate time series stored in memory. A label with 10,000 possible values multiplies your series count by 10,000. Check with count(count by (__name__)({__name__=~".+"})) and treat any single metric over a few thousand series as a design problem.

## 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.

**Keywords:** rate(), irate(), counters

#### Requests per second, aggregated by job

```promql
sum by (job) (rate(http_requests_total[5m]))
```

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

- 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

```promql
sum(rate(http_requests_total{code=~"5.."}[5m]))
  /
sum(rate(http_requests_total[5m]))
```

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

- 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

```promql
irate(http_requests_total[5m])
```

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

- 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.

**Best practices:**

- Set the range to at least 4 times your scrape interval, so [2m] for a 30s scrape.
- Put rate() inside and sum() outside, every single time.

**Common errors:**

- **A graph shows an enormous negative spike when a pod restarts**: You summed before rating. Move rate() inside the sum so each series gets its own reset handling.
- **rate() returns nothing for a metric that clearly has data**: A range vector needs at least two samples. Either the window is shorter than the scrape interval or the series is new.

**Advanced notes:**

- **rate() extrapolates, so results are rarely round numbers:** rate() fits across the window and extrapolates to its edges, which means a counter incremented exactly 10 times in 10 seconds may report 1.04 rather than 1. This is deliberate and correct for graphing. When you need an exact count for billing or reporting, use increase() over an aligned window and accept the same caveat, or query the raw counter difference.

### increase(), delta() and resets()

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

**Keywords:** increase(), delta(), gauges

#### How many errors in the last hour

```promql
sum(increase(http_requests_total{code=~"5.."}[1h]))
```

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

- 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

```promql
delta(node_filesystem_free_bytes{mountpoint="/"}[1h])
```

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

- Use predict_linear rather than delta when you want to alert on running out of disk.

#### Count how many times a process restarted

```promql
resets(process_start_time_seconds[1h])
```

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

- A cheap crash loop detector that needs no extra instrumentation.

**Best practices:**

- Use increase for human-facing numbers and rate for anything you divide or compare.
- Reach for predict_linear on disk and quota alerts instead of alerting on the current value.

**Common errors:**

- **increase() on a gauge returns odd results**: increase() assumes monotonic growth and treats every decrease as a reset. Use delta() for gauges.
- **An hourly report never matches the application logs exactly**: increase() extrapolates to the window edges. For exact counts, query the counter values at both ends and subtract, accepting that resets are then yours to handle.

**Advanced notes:**

- **predict_linear is the disk alert you actually want:** predict_linear(node_filesystem_free_bytes[6h], 4 * 3600) < 0 fires when the last 6 hours of trend suggest the disk fills within 4 hours. It gives you time to act, and it does not page when a volume simply sits at 85 percent forever.

## 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.

**Keywords:** aggregation, by, without

#### Keep some labels, drop the rest

```promql
sum by (job, code) (rate(http_requests_total[5m]))

sum without (instance, pod) (rate(http_requests_total[5m]))
```

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

- 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

```promql
count by (job) (up == 1)

count(count by (__name__)({__name__=~".+"}))
```

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

- count counts series. count_values counts how many series share a value.

#### The noisiest few, and everything else

```promql
topk(5, sum by (pod) (rate(container_cpu_usage_seconds_total[5m])))

bottomk(3, node_memory_MemAvailable_bytes)
```

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

- 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.

**Best practices:**

- Aggregate away instance and pod on any dashboard that should survive a scale event.
- Use without rather than by when new labels are likely to appear.

**Common errors:**

- **A panel legend fills with hundreds of entries after a deploy**: You aggregated with by and a new label appeared. Switch to without and name what you want gone.
- **An average of averages looks wrong**: avg of a per-instance average weights small instances equally with large ones. Sum the numerator and denominator separately, then divide.

**Advanced notes:**

- **The _over_time family aggregates across time, not across series:** avg_over_time, max_over_time, min_over_time, stddev_over_time and quantile_over_time each take a range vector and reduce one series over its window. max(x) finds the biggest series right now, while max_over_time(x[1h]) finds the biggest value each series reached in an hour. These are different questions and mixing them up is common.

## 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.

**Keywords:** histogram_quantile, percentiles, latency

#### p99 latency across a whole service

```promql
histogram_quantile(
  0.99,
  sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
```

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

- 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

```promql
histogram_quantile(
  0.95,
  sum by (le, route) (rate(http_request_duration_seconds_bucket[5m]))
)
```

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

- Every extra label multiplies the series count by the number of buckets. Be selective.

#### The SLO question histograms answer better than percentiles

```promql
sum(rate(http_request_duration_seconds_bucket{le="0.3"}[5m]))
  /
sum(rate(http_request_duration_seconds_count[5m]))
```

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

- 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.

**Best practices:**

- Choose bucket boundaries around your SLO thresholds before you need them. You cannot add them retroactively.
- Prefer "fraction under threshold" to a p99 when defining an SLO.

**Common errors:**

- **histogram_quantile returns NaN**: The le label was aggregated away, or there is no traffic in the window so every bucket rate is zero.
- **p99 reports exactly the value of your largest finite bucket**: Real latency exceeds your highest bucket, so everything lands in +Inf and interpolation clamps. Add higher buckets.

**Advanced notes:**

- **Quantiles are interpolated inside a bucket:** histogram_quantile assumes values are spread evenly between bucket boundaries, so with buckets at 0.1 and 1.0 a p99 can land anywhere in that range with no real evidence. The accuracy of your percentile is entirely a property of your bucket layout. Native histograms in Prometheus 2.40 and later remove most of this problem by using exponential buckets.

## 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.

**Keywords:** operators, comparison, bool

#### Filter with a comparison

```promql
node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.1
```

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

- An empty result means nothing is wrong, which is why alert rules use this form.

#### Get 1 and 0 instead of a filter

```promql
(rate(http_requests_total[5m]) > bool 100)
```

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

- 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

```promql
up == 0 unless on (instance) node_maintenance_mode == 1
```

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

- Set operators ignore values entirely and work purely on label sets.

**Best practices:**

- Use the filtering form in alert rules and the bool form in dashboards.
- Reach for unless to build maintenance windows rather than editing rules.

**Common errors:**

- **A panel goes blank whenever the condition is false**: A bare comparison filters. Add bool to keep the series and plot 1 and 0.
- **Dividing two metrics returns no data at all**: The label sets do not match exactly. Use on or ignoring to say which labels should be compared.

**Advanced notes:**

- **group_left is how you attach metadata to a metric:** Joining a metric to an info metric is the most useful advanced pattern in PromQL. sum by (pod) (rate(container_cpu_usage_seconds_total[5m])) * on (pod) group_left(owner) kube_pod_labels attaches the owner label from one metric to the values of another. group_left means the left side may match many series on the right, and the parenthesised labels are the ones copied across.

## 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.

**Keywords:** recording rules, Prometheus, performance

#### Pre-compute an expensive aggregation

```yaml
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]))
```

_exec_
```bash
promtool check rules rules/http.rules.yml
```

_output_
```text
SUCCESS: 2 rules found
```

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

- 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.

**Best practices:**

- Record any expression that appears on more than one dashboard or inside an alert.
- Follow the level:metric:operation naming convention so the aggregation level is self-documenting.

**Common errors:**

- **A recording rule produces gaps**: The group interval is longer than the range in the expression. Keep the interval well under the window.
- **A rule name collides with a real metric**: Use the colon convention. Colons are reserved for recording rules and exporters never emit them.

**Advanced notes:**

- **Recording rules are the fix for slow dashboards:** A query that touches 50,000 series takes the same work every time someone loads the dashboard, and a wall-mounted screen on a 10 second refresh runs it 8,640 times a day. A recording rule runs it once per interval and stores a handful of series. This is usually a much bigger win than tuning the query itself.

### Alerting Rules

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

**Keywords:** alerting, for, annotations

#### A complete alerting rule

```yaml
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'
```

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

- 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

```promql
absent(up{job="payments"} == 1)
```

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

- A threshold alert cannot fire on a metric that stopped being reported. absent can.
- Use absent_over_time for metrics that are legitimately sparse.

**Best practices:**

- Always set a for duration proportional to how long you would want to wait before acting.
- Point every paging alert at a runbook URL in its annotations.
- Alert on symptoms your users feel, not on causes such as CPU being high.

**Common errors:**

- **An alert flaps between firing and resolved**: The for duration is too short for the metric range. Make for at least twice the rate window.
- **An alert never fires even though the dashboard shows the problem**: The expression returns no series when the condition is false, which is correct, but check that it returns series when true. Test it in the expression browser first.
- **A service went completely down and nothing alerted**: Your expression filters on a metric that stopped arriving. Add a companion absent() rule.

**Advanced notes:**

- **Multi-window multi-burn-rate alerts:** The SRE workbook pattern combines a fast window and a slow window so that a sharp burn pages immediately while a slow burn still gets caught. A page fires when both a 5m and a 1h window exceed a 14.4x burn rate, and a ticket fires when both a 30m and a 6h window exceed 6x. It costs four recording rules per SLO and it removes most alert noise.
