The three shapes of anomaly
An anomaly is an observation that departs sharply from what a system normally produces, but the word hides three structurally different problems. A point anomaly is a single value that stands alone â one request that took 40 seconds in a stream of 200-millisecond calls. A contextual anomaly is only surprising given its surroundings â a 40 percent traffic drop at 3 a.m. is normal, the same drop at noon is not. A collective anomaly is a pattern that is strange as a sequence even though every individual value looks ordinary â latency creeping up two percent per day for a month.
Each shape rules out different methods. Point anomalies fall to simple statistics. Contextual anomalies require a baseline that knows the time, the day, and the season. Collective anomalies need windows and shape features rather than raw values, because no single reading contains the evidence. Most production incidents in ML systems are contextual or collective; the reason teams still start with point detection is that it is cheap, explainable, and catches the loudest failures.
A second distinction matters just as much: whether labels exist. With historical incident labels you can tune a detector against ground truth like any other classifier. Without them â which is the usual case â you are choosing a threshold on a continuous score and accepting that precision and recall are guesses until the first few incidents teach you something. Designing for that uncertainty is the real work.
Statistical baselines: Z-score and IQR
The Z-score asks how many standard deviations a value sits from the mean. Anything beyond three is conventionally interesting. It is fast, needs no training, and is trivial to explain in an incident channel. Its weakness is the assumption behind it: mean and standard deviation are computed from data that already contains anomalies, and both are pulled by the very outliers you are hunting. Heavy-tailed metrics â queue depth, retry counts, token usage per request â routinely violate the normality assumption badly enough that fixed thresholds flag the same two percent of traffic forever.
The interquartile range sidesteps the moments entirely. Compute the 25th and 75th percentiles, take their difference, and declare anything below Q1 â 1.5 Ã IQR or above Q3 + 1.5 Ã IQR unusual. Because percentiles are rank-based, a handful of extreme values cannot drag the fence. For skewed operational metrics this is usually the better default.
Both methods need a window. A global baseline fitted once will declare every Monday morning an anomaly if your traffic is weekly; a rolling window that re-estimates every hour adapts, but slowly enough that a genuine shift looks like drift rather than an event. The window length is a bias-variance trade-off you choose deliberately, not a default you inherit.
import numpy as np
class RollingDetector:
"""Windowed Z-score and IQR detection with a shared interface."""
def __init__(self, window: int = 240, z_threshold: float = 3.0,
iqr_multiplier: float = 1.5, method: str = "iqr"):
self.window = window
self.z_threshold = z_threshold
self.multiplier = iqr_multiplier
self.method = method
self.buffer = []
def score(self, value: float) -> float:
self.buffer.append(value)
if len(self.buffer) > self.window:
self.buffer.pop(0)
if len(self.buffer) < 20:
return 0.0
data = np.asarray(self.buffer, dtype=float)
if self.method == "zscore":
std = data.std()
if std < 1e-9:
return 0.0
return abs(value - data.mean()) / std
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
if iqr < 1e-9:
return 0.0
if value > q3 + self.multiplier * iqr:
return (value - (q3 + self.multiplier * iqr)) / iqr
if value < q1 - self.multiplier * iqr:
return ((q1 - self.multiplier * iqr) - value) / iqr
return 0.0
def is_anomaly(self, value: float) -> bool:
return self.score(value) >= 1.0
Note that the detector returns a continuous score, not just a flag. Persisting scores lets you chart distributions, compare thresholds offline, and answer the question that actually arrives in review: how much would loosening the threshold have saved us last month?
When distributions lie: unsupervised ML detectors
Multivariate metrics break univariate statistics. CPU and memory usually move together; when memory climbs alone, that is the signal â but two independent Z-scores cannot see the joint structure. Isolation forest addresses this by asking a different question: how many random splits does it take to isolate this point? Anomalies isolate in few splits because they sit in sparse regions, so short average path length yields a high anomaly score. It scales linearly, handles mixed feature types, and needs no labels.
Autoencoders approach the same problem from reconstruction. Train a network to compress and rebuild normal traffic; anything it cannot rebuild accurately â high reconstruction error â is unusual. This works well for dense, high-dimensional inputs such as request embeddings or per-feature vector snapshots, and it fails when the training window already contains the anomaly, because the network learns to reproduce it.
| Method | Handles multivariate data | Label requirement | Typical cost | Explainability |
|---|---|---|---|---|
| Z-score | No | None | Trivial | Excellent |
| IQR | No | None | Trivial | Excellent |
| Isolation forest | Yes | None | Low | Good |
| Autoencoder | Yes | None | High | Poor |
| Supervised classifier | Yes | Incident labels | Medium | Variable |
Start at the top of that table and move down only when the data forces you to. Every step down buys detection power and spends explainability, and in an incident the ability to say "this fired because p99 crossed Q3 plus 1.5 IQR" ends the argument quickly.
Thresholds are the real model
The detector chooses how to score; the threshold decides whether a human gets paged. With labels, sweep candidate percentiles and pick the point that maximises F1, then re-check it monthly as traffic shifts. Without labels, three practical anchors work well. Use a budget: if you can tolerate two false pages a week and you see ten thousand points a day, set the threshold at the 99.98th percentile. Use stability: pick the threshold where small movements stop changing the alert count, which reveals the natural gap between the bulk of the data and its tail. Use peer groups: a threshold fitted per endpoint, per tenant, or per hour of the day removes seasonality before it becomes noise.
Whichever anchor you pick, write it down with its rationale. Thresholds that appear in a config file with no explanation get changed by the next person who is annoyed by a page, and the system silently regresses.
import numpy as np
class ThresholdTuner:
"""Pick a threshold from an alert budget or a labelled sweep."""
def from_budget(self, scores: np.ndarray, alerts_per_day: float) -> float:
points_per_day = len(scores)
target_quantile = 1.0 - (alerts_per_day / max(points_per_day, 1))
return float(np.quantile(scores, target_quantile))
def from_labels(self, scores: np.ndarray, labels: np.ndarray) -> dict:
best = {"f1": 0.0, "threshold": 0.0}
for q in np.linspace(0.90, 0.999, 40):
threshold = float(np.quantile(scores, q))
predicted = scores >= threshold
tp = float(np.sum(predicted & labels))
fp = float(np.sum(predicted & ~labels))
fn = float(np.sum(~predicted & labels))
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
if f1 > best["f1"]:
best = {"f1": f1, "threshold": threshold, "precision": precision,
"recall": recall}
return best
Ensembles, cold starts, and operational placement
A single detector has a single blind spot, so production systems usually combine two or three and normalise their scores onto a common scale before averaging. Agreement between a statistical and a model-based detector is a much stronger signal than either alone, and disagreement is itself informative â it often means the statistical baseline has not caught up with a genuine change in behaviour.
Cold start deserves explicit handling. A detector deployed into a system it has never observed has no baseline; either suppress it for the length of one full window, or seed it from a comparable service. Silently scoring with an empty buffer produces a burst of anomalies on day one and trains everyone to ignore the channel.
Finally, place detection before alerting, not instead of it. The detector emits scored events; grouping, sustain windows, and severity mapping happen downstream. Keeping that boundary clean means you can re-tune thresholds or swap models without touching the escalation policy, and the alerting layer keeps working while you experiment.
Practical starting points by metric type
Not every metric deserves the same detector. Request latency is unimodal and stable enough that a rolling IQR per endpoint handles it well, with a longer window for low-traffic endpoints where percentiles are noisy. Queue depth and retry counts are heavy-tailed and bursty, so a log transform plus Z-score beats raw percentiles, and the window must span at least one full traffic cycle. Token usage per request is multimodal â different intents have genuinely different shapes â which is where isolation forest on a feature vector of length, history size, and model tier starts to earn its cost. Feature-vector drift in a serving pipeline is multivariate by definition, and a reconstruction-error autoencoder fitted on a clean week remains the strongest practical choice.
Whichever pairing you adopt, write the detector choice and its window into the metric's catalogue entry. A detector that nobody can explain during an incident will be disabled the first time it pages at an inconvenient hour, and a metric with no anomaly coverage quietly returns to the dashboard-noise category this lesson began with.
Common Mistakes
Fitting a global Z-score baseline to heavy-tailed metrics like queue depth
Fix: Use IQR with a rolling window, or log-transform the metric before scoring.
Choosing thresholds by convention (three sigma) without checking alert volume
Fix: Set the threshold from an alert budget or a percentile sweep, then review the false-positive rate monthly.
Training an autoencoder on a window that already contains the incident
Fix: Train on a verified clean period and hold out recent data for scoring.
Deploying a detector with no warm-up buffer
Fix: Suppress scoring until at least one full window of data has been collected.
Key Takeaways
- Match the method to the anomaly shape â point, contextual, and collective anomalies need different features and windows.
- IQR is the safer default for skewed operational metrics because percentiles resist outlier contamination.
- Prefer the simplest detector that works; each step toward ML trades explainability for detection power.
- The threshold, not the detector, controls paging â anchor it to an alert budget, a stability gap, or peer groups.
- Return continuous scores rather than booleans so thresholds can be re-tuned offline without re-running detection.
- Ensemble two detector families and treat their disagreement as a signal about baseline freshness.