ML Anomaly Detection for Metrics: Beyond Static Thresholds

Static thresholds page you when traffic peaks and sleep through real regressions. ML-based anomaly detection learns what normal looks like for each metric, so alerts fire on deviation instead of an arbitrary line. By the end of this post you will pick a model, score real Prometheus series in Python, and gate pages on SLO burn rate, so only user-facing pain wakes anyone up.
Why static thresholds fail on real traffic
Most alert rules start as a single line: page when p99 latency exceeds 900 ms. Real traffic is seasonal. Your checkout API is busy at midday and quiet at 4 a.m., so no single line is right for both. Set it high and you miss the slow regression that only shows during quiet hours. Set it low and every lunch peak becomes a false page.
The chart below shows a week of p99 latency for one service. The dashed amber line is the classic static threshold. The green band is a learned seasonal baseline: what the metric usually does at that hour, plus or minus three standard deviations. On day six a bad deploy doubles quiet-hours latency: under the static line, so threshold alerting says nothing, but straight through the band.
That gap is the whole argument for learned baselines. It is also the honest scope of AIOps: narrow, well-defined wins like alert noise, not magic. I wrote about that framing in AIOps without the hype, and it applies directly here.
How anomaly detection fits into your monitoring
The pattern is a loop. Prometheus already stores weeks of history. A small hourly job reads a metric back through the Prometheus HTTP API, scores each point, and pushes an anomaly score between 0 and 1 to a Pushgateway. Prometheus scrapes that score like any other metric, and an alert rule combines it with your SLO burn rate.
You need three things: Prometheus with at least two weeks of retention and query access (the easy Kubernetes monitoring setup works fine), Python 3.11 or newer with scikit-learn and requests, and a Pushgateway. The Pushgateway fits because scoring is a batch job, the one case its official guidance recommends it for.
Choosing an anomaly detection model
Three families cover most SRE needs. The moving-average family (z-score, MAD) compares each point with a recent window: trivial to compute, but blind to seasonality. Decomposition and forecasting models (STL, Prophet) learn daily and weekly patterns explicitly and answer "is this point surprising for this hour?". Isolation forests take another angle: they learn which feature combinations are rare, so they handle odd shapes and several signals at once.
| Model | Seasonality | Multivariate | Cost | Best for |
|---|---|---|---|---|
| Z-score / MAD on a moving window | No | No | Trivial | Steady metrics: queue depth, disk usage |
| STL decomposition + robust z-score | Daily / weekly | No | Low | One clearly seasonal metric |
| Prophet-style forecaster | Yes, incl. holidays | Regressors | Medium, one fit per series | Business metrics with a weekly rhythm |
| Isolation forest | Implicit, via time features | Yes | Low-medium | Many series, odd shapes, latency + traffic together |
Start with the simplest model that matches the metric's shape; a z-score you understand beats a forest you do not. Whichever you pick, treat it like any model in MLOps: version the training code, retrain on a schedule, and measure its false-positive rate like an eval.
Worked example: anomaly scoring on Prometheus data
Here is the loop made concrete. The job below pulls fourteen days of checkout p99 latency at five-minute resolution, builds three features per point (value, hour of day, day of week), trains an IsolationForest, and pushes the score for the latest point. Install the two dependencies with pip install scikit-learn requests, then save this as score.py:
import time, requests
from sklearn.ensemble import IsolationForest
PROM = "http://localhost:9090"
QUERY = 'histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{service="checkout"}[5m])) by (le))'
now = time.time()
resp = requests.get(f"{PROM}/api/v1/query_range", params={
"query": QUERY, "start": now - 14 * 86400, "end": now, "step": 300}).json()
values = resp["data"]["result"][0]["values"] # [[unix_ts, "value"], ...]
rows = []
for ts, v in values:
t = time.gmtime(ts)
rows.append([float(v), t.tm_hour, t.tm_wday]) # value + time context
model = IsolationForest(contamination=0.02, random_state=42).fit(rows)
score = -model.decision_function([rows[-1]])[0] # higher = more anomalous
# grouping keys become labels; service="checkout" lets PromQL join on it
requests.post("http://localhost:9091/metrics/job/anomaly-detector/service/checkout",
data=f"metrics_anomaly_score {score:.3f}\n")
print(f"trained on {len(rows)} points, latest score {score:.2f} pushed")
The query_range endpoint returns one entry per series, each holding values: timestamp and string-value pairs, which the loop reshapes into feature rows. With hour and weekday as features, the forest learns the joint shape of "latency at this hour", so 300 ms at 4 a.m. can score higher than 800 ms at noon. decision_function runs higher for normal points, so the sign flip makes 1.0 mean "most anomalous". contamination=0.02 tells the model to expect about two percent outliers. Run it and you should see:
trained on 4032 points, latest score 0.87 pushed
Fourteen days at a five-minute step is 4,032 points. Two failures are common. A KeyError or empty result means the query matched no series, so check the service label spelling first. A score that is always high means your training window included the incident you are trying to catch; retrain on clean days. Schedule the job hourly with cron or a Kubernetes CronJob so the score stays fresh.
Gate anomaly detection alerts on SLO burn rate
A raw score still pages too often: real systems produce small anomalies constantly. The fix is to page only when an anomaly coincides with user pain, which your error budget already measures. The flowchart below shows the decision: a high score alone becomes a dashboard annotation, score plus elevated burn rate becomes a page.
The rule pair below implements that gate. The recording rule computes the one-hour ratio of 5xx responses per service, and the alert fires only when the anomaly score and the burn rate are both high for the same service. This and-gating idea is what I leaned on while running a 30M+ active-series observability stack, and it was the single biggest pager-noise reducer we shipped.
groups:
- name: anomaly-detection
rules:
- record: service:error_burn_rate_1h
expr: sum(rate(http_requests_total{status=~"5.."}[1h])) by (service)
/ sum(rate(http_requests_total[1h])) by (service)
- alert: AnomalyWithBurn
# 0.002 = 2x the monthly budget of a 99.9% SLO
expr: metrics_anomaly_score > 0.8 and on(service) service:error_burn_rate_1h > 0.002
for: 15m
labels: {severity: page}
annotations:
summary: "anomalous latency with elevated 5xx burn rate"
The and on(service) clause does the real work: it joins the two series on the service label, which is why the Python job pushes with service/checkout as a grouping key. for: 15m absorbs one-off spikes, and 0.002 means "burning budget twice as fast as a 99.9% SLO allows". Validate the file before reloading Prometheus, then confirm both rules loaded:
promtool check rules anomaly.yml
# SUCCESS: 2 rules found
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[].rules[].name'
# service:error_burn_rate_1h
# AnomalyWithBurn
What does the gate buy? On one illustrative checkout service, the before and after look like this: the same six real incidents still page, but weekly pages drop from twenty-three to four because the noise no longer reaches anyone.
Common pitfalls
- Training on incidents. If the window includes the outage, the model learns that outages are normal. Exclude known incidents, or retrain after big events.
- Alerting on the raw score. Scores measure surprise, not impact. Always pair them with burn rate or another user-facing signal before paging anyone.
- One model for every metric. A latency histogram and a queue depth behave differently. Group metrics by shape and pick the simplest model per group.
- Forgetting Pushgateway staleness. Pushed samples never expire, so a dead scorer leaves a frozen score behind. Alert on the job's own
push_time_secondstoo. - Scoring high-cardinality series. Per-pod scores multiply your series count. Score service-level aggregates; cardinality discipline is what let me cut a metrics bill by up to 50% with the OpenTelemetry Collector.
Key takeaways
- Seasonal baselines catch what static thresholds miss, especially quiet-hours regressions.
- Pick the simplest model that fits the metric's shape: z-score first, isolation forest for multivariate cases.
- Score Prometheus history in Python and push the score back as just another metric.
- Page only when anomaly score and SLO burn rate agree; everything else is a ticket or a dashboard mark.
- Run detectors like models: versioned, retrained on a schedule, and measured by false-positive rate.
Wiring this into a wider observability stack, or tuning the models team by team, is where an observability consulting engagement usually starts.
Related articles

RAG Chunking, Embeddings and Hybrid Search Done Right
Vector search alone misses error codes and flag names. Chunk runbooks by structure, pick an embedding model on purpose, fuse BM25 and vectors with reciprocal rank fusion, then filter and re-rank, in Python you can run.

From Runbook to Robot: Executable Runbooks as Code
Prose runbooks drift until they fail you at 3 a.m. Write executable runbooks in YAML with pre-checks, dry runs and approval gates, run them with a small Python executor, and let an LLM draft them from your old wiki pages.

AI Incident Triage: A Co-Pilot for the First 10 Minutes
Wire Alertmanager to a small Python worker that queries Prometheus, your deploy log and a RAG index of post-mortems, then posts a cited triage summary to Slack. Read-only by design: humans approve every change.