Excellent question. This is a very common and important challenge in observability. You've correctly identified the goal—consolidating signals into a single, high-density view—and the limitations of a naive approach.
The core problem is that you're trying to translate continuous time-series data into discrete states (OK, Warning, Critical) and your current PromQL strategy isn't robust enough.
Let's break down the problems and build a proper solution using PromQL and Grafana.
The Core Concept: From Values to States
Instead of plotting the raw values of metrics, you want to plot their state. A state is defined by a set of conditions. Your Grafana widget will then simply display the state for each service over time. The best widgets for this are State timeline (newer and generally better) or Status history.
The key is to write PromQL queries that return a 1 when a condition is met (i.e., a problem exists) and return nothing (or 0) otherwise.
Solving Your Specific Problems
Here’s how to address each of your failed attempts with better PromQL.
1. Problem: "Detector can be triggered by problems that happened 24 hours ago"
This happens because you're misusing the offset keyword. A query like rate(my_metric[5m] offset 24h) literally asks, "What was the rate of my_metric during a 5-minute window 24 hours ago?" It doesn't compare the past to the present.
The Correct Approach: Compare Now vs. The Past
To detect an anomaly (e.g., "the current rate is 50% higher than last week"), you compare the current value with an offset value.
Example: Detect a sudden spike in errors compared to last week.
# This query returns a 1 for any service whose error rate is 2x higher than the same time last week.
# It returns nothing otherwise.
sum by (service) (rate(http_requests_total{status="error"}[5m]))
>
2 * sum by (service) (rate(http_requests_total{status="error"}[5m] offset 1w))
sum by (service) (...): This is crucial. It calculates the rate for each service individually. Without by (service), you'd get one single value for all services combined, losing all visibility.
... > 2 * ... offset 1w: This is the boolean logic. It returns a vector of 1s for services where the condition is true. This is the foundation of anomaly detection.
2. Problem: "It doesn't detect zero events gaps as incidents"
This is a classic Prometheus behavior. If a service goes down and stops sending metrics, a query like rate(http_requests_total[5m]) simply returns no data. Since there's no data, it can't be greater than a threshold, so no alert is triggered.
The Correct Approach: Use the absent() function
The absent() function is designed specifically for this. It takes a vector as input and returns a 1 if that vector has no elements.
Example: Detect if a service has stopped sending metrics.
Let's assume every service should be reporting the up metric or a specific application metric like http_requests_total.
# Option A: The standard way, checks if the Prometheus job is down.
absent(up{job="my-service-name"})
# Option B: More specific, checks if a key metric has disappeared.
# This is useful if the instance is up but the app is frozen.
absent(http_requests_total{job="my-service-name"})
You would use this as a separate, high-priority condition for your "Critical" state.
3. Problem: "Detector is triggered by events not present in the queries" & Poor Recognition
This is almost certainly a labeling and aggregation issue. If your query is sum(rate(errors[5m])), it boils all services down to a single number. When that number crosses a threshold, you can't tell which service was the cause.
The Correct Approach: Always Aggregate by (label)
As shown in the examples above, you must use aggregation clauses like sum by (service, other_label), avg by (job), etc. This preserves the labels that distinguish your services, and the query will return a separate time series for each service.
The State timeline panel in Grafana is designed to handle this perfectly. If your query returns 10 series (one for each service), the panel will create 10 distinct rows, making recognition instant.
A Complete, Practical Solution: The "State Engine" Dashboard
Let's build a robust "state engine" in a single Grafana State timeline panel. This panel allows you to layer multiple queries and map them to states.
Panel Type: State timeline
Legend/Display Name: {{service}} (This will use the service label from your query to name each row)
You will create multiple queries, ordered from most to least severe. Grafana will use the value from the first query that returns a result for a given service.
Query A: Critical State (Value: 2)
This query combines multiple critical conditions using the OR operator.
# Condition 1: Error rate is over 10%
(
sum by (service) (rate(http_requests_total{status="error"}[5m])) /
sum by (service) (rate(http_requests_total[5m]))
> 0.1
)
OR
# Condition 2: The service is completely down (no metrics)
(
absent(http_requests_total{job=~".*your-services-pattern.*"})
)
# Multiply by 2 to give it a "Critical" value
* 2
Query B: Warning State (Value: 1)
This query checks for less severe conditions.
# Condition 1: Error rate is over 2%
(
sum by (service) (rate(http_requests_total{status="error"}[5m])) /
sum by (service) (rate(http_requests_total[5m]))
> 0.02
)
OR
# Condition 2: P95 latency is over 500ms
(
histogram_quantile(0.95, sum by (le, service) (rate(http_request_duration_seconds_bucket[5m]))) > 0.5
)
# The result is already 1 because of the boolean logic, no multiplication needed.
Panel Configuration
- Queries: Add Query A and Query B to your panel. Hide the "No Data" query if you've explicitly created one with
absent().
- Thresholds:
- Base: Green (Color) / OK (Text)
- Value:
1, Color: Orange, Text: Warning
- Value:
2, Color: Red, Text: Critical
- Value Mappings (Alternative to Thresholds):
1 -> Warning
2 -> Critical
null -> OK
- Display Name: In the "Legend" options, set the display name to
{{service}} or {{job}}. This is the magic that gives you a clean row for each service.
Summary of the Strategy
- Use the Right Panel: Switch to State timeline or Status history.
- Think in States, Not Values: Write PromQL queries that use boolean logic (
>, <, OR) to define what constitutes a "problem." These queries should return 1 on a problem, and nothing otherwise.
- Preserve Dimensions: Use
sum by (service) or avg by (job) to ensure you get a separate result for each entity you want to monitor.
- Detect Missing Data: Use
absent(metric{...}) as a high-priority condition to catch services that have gone silent.
- Detect Anomalies: For "unusual" behavior, compare a metric's current value against its past value using
offset: current_rate > N * past_rate.
- Layer Your Queries: In Grafana, create separate queries for different severity levels (Warning, Critical) and use thresholds or value mappings to assign colors and text. Order them from most to least severe.
By following this model, you can create a single, dense, and highly effective widget that allows SREs to instantly see the health of all services at a glance without losing context or being misled by flawed queries.