Prometheus Advanced Queries

Comprehensive guide for prometheus advanced queries covering essential concepts, practical examples, and production best practices.

Prometheus Advanced Queries are essential for diagnosing complex performance issues, uncovering subtle trends across services, and building self-service observability. They matter when basic metrics are insufficient—when you need to correlate time-series behavior across multiple dimensions, detect anomalies beyond thresholds, or extract precise data from high-cardinality metrics. Use them during incident response, for deep-dive root cause analysis, or in automated dashboards that require dynamic filtering and computation.

Time-Series Manipulation and Aggregation

Transforming raw time-series data into meaningful views requires precise control over aggregation, alignment, and windowing. The rate() function is fundamental but often misapplied.

rate(http_requests_total{job="api-server"}[5m])

This computes the per-second rate of requests over the last 5 minutes. However, rate() assumes evenly spaced samples, and under high load or irregular scrape intervals, it underestimates. Use irate() for more responsive, per-second changes:

irate(http_requests_total{job="api-server"}[1m])

irate() uses only the last two samples to compute the rate, making it sensitive to short-lived spikes. For a balanced approach, combine both:

sum by (method) (
  rate(http_requests_total{job="api-server"}[10m])
  + 
  irate(http_requests_total{job="api-server"}[1m])
)

Use histogram_quantile() to extract percentiles from histogram metrics. The http_request_duration_seconds_bucket metric, for example, requires explicit quantile computation:

histogram_quantile(0.95, 
  rate(http_request_duration_seconds_bucket{job="api-server"}[5m]))

This gives the 95th percentile of request duration over the last 5 minutes, assuming the buckets are defined as 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0.

Windowing and Sliding Windows

For analyzing trends over time, use increase() and delta() with care. increase() computes the total increase over a duration, but it assumes the counter starts at zero. If the counter is not reset, use rate() for per-second rates.

increase(http_requests_total{job="api-server"}[1h])

To compute the total number of requests in the last hour, including rescaled counters, use rate() with sum(), then sum() over time:

sum by (method) (
  increase(http_requests_total{job="api-server"}[1h])
)

For sliding windows, group() and by() are critical. To compare average response times across services, align by common labels and compute per-group metrics:

avg by (service, environment) (
  histogram_quantile(0.99, 
    rate(http_request_duration_seconds_bucket{job="api-server"}[10m])
)

This groups all 99th percentile latencies by service and environment, enabling side-by-side comparison.

Label Manipulation and Filtering

Label manipulation is central to querying across heterogeneous systems. Use label_join() to combine labels into a single one, and label_replace() to extract or transform values.

label_replace(
  http_requests_total{job="api-server"},
  "region", 
  "$1-$2",
  "zone", 
  "(.+)-(\\d+)"
)

This extracts the region from zone=us-west-1 into a new label region=us-west, using the pattern to capture two groups.

Use topk() and bottomk() to find the most or least active series.

topk(5, 
  rate(http_requests_total{job="api-server"}[5m])
)

This returns the top 5 HTTP request sources by rate. To rank across multiple metrics, group() the metrics first:

topk(10, 
  sum by (service) (
    rate(http_requests_total{job="api-server"}[10m])
    +
    rate(http_errors_total{job="api-server"}[10m])
  )
)

Filtering with PromQL Functions

without() removes labels from a time series, while group() aggregates across multiple dimensions.

sum by (method) (http_requests_total{job="api-server"}) 
  without (job, instance)

This computes total requests per method, collapsing all job and instance labels into a single row.

Use count(), count_values(), and count_over_time() to explore cardinality and frequency.

count_over_time(
  http_requests_total{job="api-server", method="POST"}[1h]
)

This counts the number of time series that have at least one sample in the last hour.

For filtering by label values, on() and ignoring() refine matching behavior. on() requires labels to match exactly, while ignoring() matches on all labels except the specified ones.

sum by (job) (
  http_requests_total{job="api-server"} 
    * 
  sum by (job, instance) (
    rate(http_request_duration_seconds_sum{job="api-server"}[5m])
  )
)

This joins request counts with sum of duration per job and instance, then sums over job.

Advanced Aggregation and Grouping

For multi-dimensional analysis, group() with by() and group_left() are essential. group_left() allows left-joining time series, preserving the left-side labels.

group_left(environment) 
  rate(http_requests_total{job="api-server"}[5m])
  on (service)
  group_left(region)
  rate(http_errors_total{job="api-server"}[5m])
  on (service, environment)

This joins request rates with error rates, enriching the result with environment and region labels from the error query.

Use quantile() and histogram_quantile() with group() to compute per-group percentiles.

histogram_quantile(0.95,
  sum by (service, environment) (
    rate(http_request_duration_seconds_bucket{job="api-server"}[10m])
  )
)

This computes the 95th percentile of request duration per service and environment.

Multi-Step Aggregation

Chain aggregations for complex analysis. To find the average response time for the top 5 services by request volume:

avg by (service) (
  histogram_quantile(0.95,
    rate(http_request_duration_seconds_bucket{job="api-server"}[10m])
  )
) 
* 
topk(5, 
  sum by (service) (
    rate(http_requests_total{job="api-server"}[5m])
  )
)

This combines the top services with their 95th percentile latencies.

Anomaly Detection and Forecasting

Prometheus does not have built-in forecasting, but you can implement anomaly detection using predict_linear().

predict_linear(
  rate(http_request_duration_seconds_sum{job="api-server"}[5m]),
  3600
)

This predicts the sum of request durations over the next hour, based on linear regression of the last 5 minutes.

Use changes() and delta() to detect when a metric crosses thresholds.

changes(http_requests_total{job="api-server"}[1h])

This returns the number of times the counter changed in the last hour. Use changes() to detect configuration drift or deployment events.

Detecting Spikes and Dips

Use rate() with stddev() and avg() to detect deviations.

stddev_over_time(
  rate(http_request_duration_seconds_sum{job="api-server"}[10m])
  [5m]
)

This computes the standard deviation of the per-second rate over the last 5 minutes.

To flag a spike, compare current rate to historical average:

rate(http_request_duration_seconds_sum{job="api-server"}[5m])
  / 
  avg_over_time(
    rate(http_request_duration_seconds_sum{job="api-server"}[5m])
    [1h]
  )
  > 1.5

This returns a boolean series indicating when the current rate is more than 1.5 times the hourly average.

Cross-System Correlation and Joining

Join time series across different jobs, services, and metrics. Use join() and group() to correlate metrics from different sources.

sum by (service, environment) (
  group_left()
  rate(http_requests_total{job="api-server"}[5m])
  on (service, environment)
  group_left()
  rate(database_query_duration_seconds_sum{job="db"}[5m])
  on (service, environment)
)

This joins HTTP request rates with database query duration sums, aligning by service and environment.

Use vector() to create scalar time series from label sets.

vector(
  1234,
  label_set("service", "user-service"),
  label_set("environment", "prod")
)

This creates a single time series with a constant value of 1234, labeled service=user-service, environment=prod.

Handling High Cardinality and Memory Pressure

High-cardinality metrics (e.g., http_requests_total{job="api-server", instance="api-01", service="auth"}) can cause memory pressure in Prometheus. Use on() and group() to reduce dimensionality.

sum by (service, environment) (
  rate(http_requests_total{job="api-server"}[5m])
) 
* 
sum by (service, environment) (
  rate(http_errors_total{job="api-server"}[5m])
)

This reduces the number of time series by grouping by common labels.

To monitor memory usage of queries, use query_duration() and query_over_time().

query_duration(
  "rate(http_requests_total{job=\"api-server\"}[5m])",
  1h
)

This returns the duration of the query over the past hour.

Failure Modes and Sharp Edges

Use label_replace() with regex and substitution to extract labels from strings.

label_replace(
  http_requests_total,
  "service", 
  "$1", 
  "job", 
  "(.+)-server"
)

This extracts service from job=api-server as service=api.

Prometheus queries are powerful but require care. The difference between rate() and irate(), between group() and group_left(), and between sum by() and sum ignoring() are subtle but critical. Use vector() and label_join() to create reusable label sets. Combine functions to build expressive, maintainable, and performant queries across diverse systems.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.