> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PromQL Fundamentals

> Introduction to PromQL explaining queries, aggregation, rates, histograms, percentiles and practical patterns for transforming Prometheus metrics into alerts and dashboards

We've covered all four metric types; now it's time to learn PromQL.

PromQL (Prometheus Query Language) converts time-series metrics into actionable results used for alerting and dashboards (for example in Grafana). Learning PromQL lets you turn raw metrics into meaningful observability signals: rates, percentiles, SLIs, and aggregated views across services.

A quick note on scope:

This lesson/article provides practical patterns you'll use every day. It is not intended to be comprehensive Prometheus certification preparation.

## Basic queries

The simplest PromQL expression is just the metric name. This returns all time series with that metric over the selected time range:

```promql theme={null}
http_requests_total
```

When you enter a metric name in Prometheus, Grafana, or the Prometheus expression browser, the result is rendered as a set of time series.

### Filtering with label selectors

To narrow results, use label selectors. Label selectors support exact matches, negative matches, and regular expressions:

```promql theme={null}
http_requests_total{endpoint="/items", http_verb="GET"}
http_requests_total{response_code=~"5.."}   # matches all 5xx responses
```

Example sample metrics (for illustration):

```text theme={null}
# TYPE http_requests_total counter
http_requests_total{endpoint="/items", http_verb="GET"} 10
http_requests_total{endpoint="/items", http_verb="PUT"} 2
http_requests_total{endpoint="/search", http_verb="GET"} 4
http_requests_total{response_code="200"} 10
http_requests_total{response_code="201"} 2
http_requests_total{response_code="301"} 2
http_requests_total{response_code="500"} 2
http_requests_total{response_code="504"} 2
```

## Metric types (quick reference)

| Metric type | Typical use case | Example |
| - | - | - |
| Counter | Monotonic cumulative counts (requests, errors) | `http_requests_total` |
| Gauge | Instantaneous values (current in-progress jobs, temperature) | `process_cpu_seconds_total` |
| Histogram | Bucketed observation counts and sums for durations/size | `http_request_duration_seconds_bucket` |
| Summary | Quantile estimation per client for durations | `request_latency_seconds` |

## Working with counters: rate() and range vectors

Counters are cumulative and always increase. To show a meaningful value, compute the rate of change over a lookback window using `rate()`:

```promql theme={null}
rate(http_requests_total[5m])
```

* The expression `http_requests_total[5m]` is a range vector.
* `rate()` returns an instant vector representing the per-second increase computed over the last 5 minutes for each time series.

Always use `rate()` (or `irate()` when appropriate) for counters when you want a meaningful per-second rate. Plotting raw cumulative counters will produce unusable graphs.

## Aggregation

To aggregate across time series, use aggregation operators like `sum`, `avg`, `min`, `max`, etc. Aggregations are commonly wrapped around `rate()`:

* Total request rate across all label dimensions:

```promql theme={null}
sum(rate(http_requests_total[5m]))
```

* Request rate aggregated by `endpoint` (keeps `endpoint` label, drops others):

```promql theme={null}
sum by (endpoint) (rate(http_requests_total[5m]))
```

If you forget `by(...)`, the aggregation removes all label dimensions and returns a single scalar per instant.

## Arithmetic and SLIs

PromQL supports arithmetic on instant vectors. For example, compute a 2xx success rate percentage over the last 5 minutes:

```promql theme={null}
(
  sum(rate(http_requests_total{response_code=~"2.."}[5m]))
  /
  sum(rate(http_requests_total[5m]))
) * 100
```

This computes (successful requests) / (total requests) \* 100.

## Histograms and percentiles

Histogram bucket series are cumulative counters representing counts of observations that fell into each bucket boundary. To compute per-bucket rates, apply `rate()` and then aggregate by the `le` (less-or-equal) label:

![A slide showing a histogram titled "Histogram\_quantile()" that buckets HTTP request counts by request duration. The bars are tallest at 50ms and progressively smaller at 100ms, 250ms, 500ms and +INF.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Prometheus-and-Grafana-Introduction/PromQL-Fundamentals/histogram-quantile-http-duration-buckets.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=b719dadf36375e9fcfa3a0fd7ff14da8)

```promql theme={null}
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
```

Example histogram metric exposition:

```text theme={null}
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.05"} 1847
http_request_duration_seconds_bucket{le="0.1"} 2903
http_request_duration_seconds_bucket{le="0.25"} 3187
http_request_duration_seconds_bucket{le="0.5"} 3298
http_request_duration_seconds_bucket{le="+Inf"} 3345
http_request_duration_seconds_sum 412.83
http_request_duration_seconds_count 3345
```

To estimate latency percentiles (P50, P95, P99) from bucketed histograms, use `histogram_quantile()` with the aggregated bucket rates:

```promql theme={null}
histogram_quantile(0.5, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
```

Notes on `histogram_quantile()`:

* It uses linear interpolation across bucket counts to approximate percentiles.
* Accuracy depends on your bucket boundaries and their density. You cannot recover exact values beyond the bucket granularity — only an approximation.

When designing buckets, choose boundaries that capture the SLO-relevant regions (e.g., many tight buckets around your target latency). This improves percentile accuracy where it matters.

## Common PromQL functions and operators

| Category | Example | Purpose |
| -: | - | - |
| Rate/derivative | `rate()`, `irate()` | Compute per-second rate from counters |
| Histogram | `histogram_quantile()` | Estimate percentiles from histogram buckets |
| Aggregation | `sum`, `avg`, `max`, `min` | Combine time series; use `by()` to preserve labels |
| Arithmetic | `+ - * /` | Combine vectors, compute ratios, percentages |

## Practical tips

* Use `rate()` with a window appropriate for your traffic volume: high-volume services can use shorter windows (1m), low-volume may need longer windows (5m or 15m) to smooth spikes.
* When aggregating across instances or jobs, explicitly control the label dimensions with `by(...)` or `without(...)` to avoid accidental double-counting.
* For alerting, prefer more conservative window sizes and consider `increase()` for absolute counts over a time window.

## Links and references

* Prometheus docs: [https://prometheus.io/docs/](https://prometheus.io/docs/)
* PromQL reference: [https://prometheus.io/docs/prometheus/latest/querying/basics/](https://prometheus.io/docs/prometheus/latest/querying/basics/)
* Grafana: [https://grafana.com/](https://grafana.com/)

Common Helm charts are often used to deploy Prometheus and Grafana together.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/86c79392-532c-42b7-8908-18bf0a84210b/lesson/55307077-db2e-4e91-a0cf-565d131d04d2)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.