Metrics and Alerts
On this page
Metrics compress large volumes of system events into comparable time series, while alerts convert some of those changes into human action. The former is primarily a measurement problem: what is being measured, what is the time window, and what is the denominator? The latter is primarily a decision problem: under what circumstances, who needs to act, and within what timeframe?
This article discusses measurement and reasoning methods. For specific Prometheus commands, see the Prometheus Operations Manual. For causal analysis of individual requests, see Distributed Tracing.
Reverse-Engineering Measurement from User Problems
"Is the service healthy?" must be made concrete. Taking a query API as an example, we can define: the proportion of successful requests completed within 300 ms among valid requests. Here, there are at least four choices: what constitutes a valid request; which responses count as successful; where latency timing begins; and how long the statistical window is.
Application ingress instrumentation sees requests entering the application but cannot see DNS, TLS, or gateway failures before they reach the application. If the goal is end-to-end availability, edge observability or external probes must be combined. Directly calling the application's success rate "user availability" will miss failures outside the measurement boundary.
Whether 4xx errors count as errors is not a fixed answer: error parameters may not be the service's responsibility, while error authentication configurations causing all normal users to be rejected are service faults. Business definitions should be written clearly first, followed by query expressions.
Counter, Gauge, and Distributions
| Type | Records | Typical Usage | Common Misinterpretation |
|---|---|---|---|
| Counter | Cumulative event count, may reset on restart | Request count, failure count, processed bytes | Treating cumulative values as per-second rates |
| Gauge | Current state, can go up or down | Queue length, in-flight requests, remaining space | Taking rate on any gauge and calling it throughput |
| Histogram | Distribution and count of observed values | Latency, response size | Looking only at the average and ignoring the tail |
| Summary | Count, sum, and optional client-side quantiles | Per-instance distribution statistics | Directly averaging quantiles from multiple instances |
When calculating rate from a Counter, you should first apply rate to each series, then aggregate by service, allowing restart resets to be handled at the instance level. The following examples assume http_requests_total has service, instance, and status labels:
# Request rate per service
sum by (service) (rate(http_requests_total[5m]))
# 5xx ratio per service; interpret results only when the service has requests
sum by (service) (rate(http_requests_total{status=~"5.."}[5m]))
/
sum by (service) (rate(http_requests_total[5m]))
You should pre-initialize the required error label series, or explicitly handle missing data in rules; "no error series" and "error rate is exactly zero" are not the same data shape. With zero traffic, the denominator is zero, and this should not be disguised as 100% availability.
Aggregating Counters First Spreads Resets from One Instance to Others
Assume three simultaneous scrapes. A's counts are 100, 110, 5; B's are 100, 120, 130. A restarts between the last two scrapes, and the value after restart is 5; B does not restart. Handling resets per instance, the observed increases are A: 10+5=15, B: 20+10=30, totaling 45.
If summed first, the series becomes 200, 230, 135. Treating the drop as a reset for the entire aggregated counter yields 30+135=165, incorrectly counting B's remaining cumulative value as new events.
return
, = ,
assert + == 45
assert == 165
This is just a reset model for discrete samples and does not implement Prometheus rate's time extrapolation. Events that occurred before a restart within a scrape interval but were not observed cannot be fully recovered from these three samples. The point of the example is to preserve the lifecycle boundary of each Counter before aggregating rates, rather than creating a precise full ledger from samples.
Why You Cannot Average P99
Assume one instance handles 100 requests, and another handles 10,000 requests. Even if their P99 values are the same, this does not tell us the exact P99 after mixing all requests; quantiles discard information about the internal distribution. Simple averaging additionally ignores sample weights.
Classic Histograms save cumulative bucket counts, allowing buckets to be aggregated first and then estimating overall quantiles. Bucket boundaries must be preserved in aggregation:
histogram_quantile(
0.99,
sum by (service, le) (
rate(http_request_duration_seconds_bucket[5m])
)
)
This assumes instances use compatible classic bucket boundaries. Estimation error is related to bucket width; if the target threshold is 300 ms, configuring a 0.3-second bucket can directly count the proportion within the threshold, without needing to estimate P99 first. Native Histograms have different representation and query forms; choose according to the actual metric type. See Prometheus Histograms and Summaries.
The mean still has value: total time divided by request count describes average workload; quantiles describe tail experience; the proportion exceeding the target threshold directly connects to service goals. The three answer different questions.
Even Weighted by Request Count, Local Quantiles Cannot Be Merged
Using the nearest-rank definition: P99 takes the ceil(0.99*N)-th sample after sorting. Instance A's 10,000 requests are all 1 ms, and Instance B's 100 requests are all 1000 ms. Local P99s are 1 and 1000 respectively, but the 9999th sample in the merged set is still in A's fast requests, so the overall P99 is 1 ms.
return
, = * 10000, * 100
assert == 1 and == 1000
assert == 1
=
=
assert ==
assert ==
assert != and !=
This does not mean the 100 slow requests are unimportant. If the goal is to identify local instance degradation, B's distribution is valuable; if the goal is the quantile of overall user requests, it must be calculated based on the overall distribution. Different statistical software has different quantile interpolation conventions, but none can universally recover full quantiles by averaging local quantiles.
If a common 300 ms bucket is used, the proportion of requests within the threshold for this example can be directly obtained by adding the cumulative buckets of both instances to 10000/10100 ≈ 99.01%. It clearly exposes that about 0.99% of requests exceed the threshold, while the overall P99 remains 1 ms; threshold compliance rate and quantiles retain different information.
RED and USE: Service Results and Resource Interpretation
RED observes Rate, Errors, and Duration, i.e., how much the service processes, how many fail, and how long it takes. USE observes Utilization, Saturation, and Errors, i.e., resource usage, waiting pressure, and errors. The former helps discover user-side symptoms, while the latter helps explain resource bottlenecks.
| Object | Utilization | Saturation / Waiting | Errors |
|---|---|---|---|
| CPU | Busy time proportion | Runnable task queue, CPU pressure | Related hardware or scheduling anomalies observed separately |
| Memory | Working set and available space | Reclamation, swapping, memory pressure | OOM events, allocation failures |
| Storage | Device busy and other utilization metrics | Queue depth, wait time | I/O errors |
| Thread Pool | Active thread count | Pending task queue | Rejected tasks, execution failures |
OOM score is process selection-related information and cannot directly replace memory saturation. High CPU usage is not necessarily a fault: if throughput is high, queues are stable, and latency meets targets, it may simply be effective resource utilization. Conversely, a single-thread bottleneck may keep the machine's average CPU very low while causing severe request queuing. Related methods are in the USE Method and Google SRE Monitoring Signals.
SLI, SLO, SLA, and Error Budget
SLI is the metric measured according to a defined scope; SLO is the target to be achieved within a window; SLA is the external agreement and related consequences. The three cannot replace each other.
If the 30-day request success rate SLO is 99.9%, the allowed failure proportion is 0.1%. For one million valid requests, the budget is one thousand failures. This is a request count budget and cannot be directly converted to "allowing 43.2 minutes of downtime": request traffic may vary over time. Minute conversion only has corresponding meaning when using time-measured availability scopes.
Define burn rate B = Current Bad Event Proportion / (1 - SLO). If SLO is 99.9% and current bad events account for 1%, then B=10. If the measurement scope and traffic distribution are approximately stable, maintaining this speed will consume the 30-day budget in about 3 days. Window changes and traffic spikes will affect this prediction.
Short windows are sensitive but easily affected by spikes; long windows are robust but slow to recover. Multi-window strategy applies the same burn rate condition to both long and short windows, confirming that the problem is persistent and has not yet recovered. Specific thresholds should be derived from budget consumption and response time, referencing Google SRE: Alerting on SLOs.
A Threshold of 14.4x Can Be Reverse-Calculated from Budget Consumption
Assume the budget window is 30 days, i.e., 720 hours, and use stable traffic to approximate consumption speed. If "consuming 2% of the total budget in one hour" triggers a high-priority response, the threshold satisfies B×1/720=0.02, so B=14.4. For a 99.9% target, the corresponding observed error proportion is 1.44%.
= 30 * 24
= * / 1
= *
assert == # 14.4
assert == # 1.44%
return > and >
assert
assert not # Long window still high, recently recovered
assert not # Short spike has not yet formed the same long-term consumption
The short window can be a small part of the long window, used to confirm that consumption is still rapid; here we only demonstrate the combination logic and do not stipulate that all services should use the same threshold. For strong daily cycle traffic or very low request volumes, the short window error proportion may be very unstable, and the time proportion may not accurately represent the request budget proportion; adjust alerting strategies based on actual event volumes. Google SRE Budget Alerting Methods
Why Is Budget Consumption Different for the Same Burn Rate?
Burn rate B is a ratio of proportions, not the percentage of budget already spent. With fixed window total requests N, observed segment requests n, and bad event proportion e in that segment, the budget contribution is ne/[N(1−SLO)]=B·n/N. Only when traffic is approximately stable can we further approximate n/N using time proportion. Below, keeping the error proportion constant while changing the request volume directly shows B remaining unchanged while budget consumption changes.
Burn rate compares bad event proportion with allowed proportion; the actual consumed request budget also depends on how many requests were processed during this period. Time proportion cannot unconditionally replace request proportion.
From Charts to Actionable Alerts
High-priority notifications should correspond to impacts or impending risks that require timely intervention, including errors, latency, data correctness, capacity exhaustion, etc. You cannot stipulate "only notify for 4xx/5xx": a service returning 200 but with latency of tens of seconds can also severely violate goals.
Alert rules should specify the service and owner, user impact, observation window, priority, first-step check entry, and recovery judgment. Short-term fluctuations can be filtered using for or other persistence conditions, but extending for also increases detection latency; you cannot rely on infinite postponement to silence reports.
You must also clarify the semantics of missing data. Scraping failures may cause business series to disappear; series disappearance cannot be automatically treated as business recovery. Monitor whether targets are scrapable, whether rule evaluation is normal, and whether the notification chain is functioning separately.
Label Cardinality: One Classification is a Set of Time Series
Assume a metric has 20 routes, 5 status categories, and 50 instances; the complete combination already reaches 5,000 series. Adding 100,000 user IDs as labels will rapidly amplify potential combinations. Even if not all combinations appear, continuously growing labels increase storage and query pressure.
Use stable route templates instead of full URLs; request IDs, order IDs, etc., are suitable for logs or traces, avoiding use as unbounded metric labels. See Prometheus Metric and Label Naming for units, naming, and label design.
Prometheus High Availability: Every Instance Has State
Prometheus saves local time series, WAL, and rule-related runtime state, so it cannot be called a stateless service. Dual instances usually scrape the same targets independently; the query layer identifies replicas according to configuration to avoid duplicate calculations; the alert layer handles aggregation and notification deduplication separately. Query high availability and notification high availability are not the same thing.
Remote write, long-term storage, and local retention policies are independent design dimensions. Dual replicas do not automatically back up all historical data, nor do they guarantee that remote write never backs up. See Prometheus Storage for the storage model. Configure replica labels, deduplication algorithms, and failure behaviors for specific query backends according to their documentation.
References
- Prometheus: Histograms and Summaries
- Prometheus: Naming and Labels
- Prometheus: Storage
- Google SRE: Monitoring Distributed Systems
- Google SRE Workbook: Alerting on SLOs
- Brendan Gregg: USE Method
Keywords: Counter, Gauge, Histogram, P99, RED, USE, SLI, SLO, Error Budget, Burn Rate, Label Cardinality, Prometheus HA