ML Basics for Anomaly Detection

Before an AI feature can explain an incident, something has to notice it. That something is usually plain statistics.

ML vocabulary in plain words

You've used ChatGPT or Claude. That's "AI" in the sense of a big language model. This section covers the other kind of AI: small, boring, fast statistical models that only do one job. Every term below gets a plain-English definition the first time it's used. The rest of this guide, and the domain chapters after it, assume you know them.

  • Model — a piece of code plus some numbers (called parameters) that turns an input into an output. A model that predicts "is this latency spike normal or not" is still a model, even if it's three lines of math and not a neural network.

  • Feature — one fact you give the model so it can make a guess. Think of a spreadsheet:

    • each column is one feature (one kind of fact, like "day of the week").
    • each row is one example (one moment you want a guess for).
    • the model reads a whole row at once. It never looks at one column by itself.

    For our latency example, each row describes one minute:

    Minute of day Day of week Requests this minute Latency 5 min ago
    14:05 Monday 1,200 180 ms
    14:06 Monday 1,350 190 ms
    03:00 Sunday 40 60 ms

    Each column helps in its own way:

    • Minute of day — traffic follows a daily pattern: busy at 2pm, quiet at 3am.
    • Day of week — Mondays behave differently from Sundays.
    • Requests this minute — more traffic usually means slower responses.
    • Latency 5 min ago — if things were slow a moment ago, they're probably still slow.

    Why the whole row matters: one fact alone can fool the model. 1,200 requests is normal on a Monday afternoon, but alarming at 3am on a Sunday. The model can only tell which one it is by seeing all the columns together.

    One simple test for whether something can be a feature: at the moment of the guess, do I already know this number? The clock, the request count, and the latency from five minutes ago all pass. This minute's latency does not. That's the answer the model is supposed to guess. Giving it to the model would be like handing a student the answer sheet.

  • Label — the "correct answer" for one row of data. It's used to teach or grade a model. For fraud, the label is "was this transaction actually fraud?" (yes/no). A human or a chargeback usually decides this later. Anomaly detection on metrics usually has no labels. Nobody manually tags every minute of latency as "normal" or "incident."

  • Training — the step where a model looks at past data (and labels, if it has them) and adjusts its internal numbers to match reality as closely as possible. This happens once, or on a schedule (nightly, weekly). It can take seconds (a threshold) or hours (a large classifier).

  • Inference — the step where a trained model looks at one new data point and produces an output, right now, in production. For a latency detector, inference happens every single minute: "is this new latency reading normal or not?" Inference has to be fast and cheap. It happens far more often than training.

  • Supervised learning — training a model using labeled examples ("this transaction was fraud, this one wasn't"). The model learns the pattern that separates the two.

  • Unsupervised learning — training a model with no labels at all. The model just learns "what does normal data usually look like," and flags anything that doesn't fit. Most metric anomaly detection (latency, error rate, CPU) is unsupervised. Nobody hand-labels every minute of every metric.

    So how does it know "normal" without labels? It doesn't, semantically — there's no notion of "correct." It just learns the recent statistical shape of the data (its mean, variance, daily/weekly seasonal pattern) and treats a big deviation from that shape as the anomaly signal. "Normal" here means common/frequent, not correct. That's why a genuinely new-but- benign pattern (a legit traffic spike from a marketing push) can get falsely flagged just for being rare, while a consistent, long-running bug gets learned as "normal" and never flagged. Detection methods, simplest first covers the concrete ways to turn this idea into a working detector: comparing to a rolling baseline (4.2-4.4), decomposing out trend/seasonality first (4.5), forecasting the next value and checking the residual (4.6), or measuring how easily a point isolates from its neighbors (4.7-4.8).

  • Semi-supervised learning — a middle ground. You have a few labels (say, the 20 incidents your team confirmed last quarter), but not nearly enough to train a full classifier. You use the unlabeled data to learn "normal," and the few labels to check or tune the detector.

  • Overfitting — when a model memorizes the specific data it was trained on instead of learning the general pattern. It does great on old data and badly on new data. Everyday analogy: a student who memorizes last year's exam answers instead of learning the subject. They ace a repeat of last year's exam and fail this year's, which asks the same concepts differently. In anomaly detection, an overfit model treats last month's one-off traffic spike as "normal" forever, and stops flagging real spikes that look similar.

One running example, end to end: every minute, your checkout API reports one number — p99 latency in milliseconds. That number, over time, is a time series. This whole chapter answers one question: given the last N minutes (or weeks) of this number, how do you decide, automatically, whether the newest reading is unusual?

What is an anomaly?

An anomaly is a data point (or set of points) that doesn't match the pattern the rest of the data follows. That's it. "Doesn't match the pattern" is a statistical statement, not a business one. This distinction matters a lot, so it gets its own warning:

There are three shapes of anomaly. Mixing them up is a common beginner mistake:

  • Point anomaly — one data point is way outside the normal range, on its own, no context needed. Latency is normally 80-120ms; one minute it's 4,000ms. That single value is wrong no matter when it happened.
  • Contextual anomaly — the value is normal in general but wrong for this specific context (time of day, day of week, which customer). Latency of 300ms is normal at 3pm on a Monday (peak traffic). The same value would be alarming at 3am on a Sunday (near-zero traffic). Same number, two very different meanings.
  • Collective anomaly — no single point looks unusual, but a sequence of points together is wrong. Say latency creeps from 80ms to 85ms to 91ms to 98ms over two hours. Each individual step is small and unremarkable. But the trend is a real, worsening problem, like a slow memory leak or a disk filling up.
Two days of a metric with a daily curve: low around 3am, high around 3pm. On day 2 at 3am the metric reads at its usual 3pm level. That value is normal in general but wrong for 3am, so it is a contextual anomaly.
A contextual anomaly: a normal value at the wrong time. Read it as: the red point would be ordinary at 3pm, so a fixed threshold never fires on it. It is only wrong for 3am. Catching it needs a baseline that knows what each hour normally looks like.

Most production detectors are built to catch contextual anomalies. Pure point anomalies (a number that's wrong at any hour of any day) are rare and easy. Pure collective anomalies usually need a trend or forecasting model (Detection methods, simplest first) rather than a single-point check.

Time series basics

A time series is just a sequence of numbers measured over time. Our latency-per-minute example is one. Almost every detection method in Detection methods, simplest first works by breaking a time series into three pieces and looking at what's left over:

  • Trend — the slow, long-term direction. Latency creeping up over months because traffic is growing is a trend. Ignoring trend makes a detector think "normal" latency six months ago is still "normal" today, when really the whole baseline shifted.
  • Seasonality — a pattern that repeats on a fixed schedule. It can be daily (busy at 9am-6pm, quiet at night), weekly (busy on weekdays, quiet on weekends), or sometimes yearly (retail traffic in December). Ignoring seasonality is the single most common cause of bad alerts. A detector that doesn't know "3am is always quiet" will scream every single night.
  • Noise — the small, random wiggle left over after you remove trend and seasonality. Real systems are never perfectly smooth. Some jitter is expected and should not trigger an alert.
Four days of latency in milliseconds. The line rises and falls once a day, the whole thing drifts slowly upward, and small random jitter rides on top. A dashed line marks the slow upward trend.
A raw series is trend, seasonality and noise mixed together. Read it as: the dashed line is the trend, the daily hump is seasonality, and the small wiggle is noise. A detector that doesn't know about the daily hump will alert every night when traffic drops.

Splitting a series into trend, seasonality, and noise is called decomposition, and it's useful on its own. But its real value here is this: once you subtract trend and seasonality, what's left (the noise) should look boring and predictable. An anomaly is a point where what's left over is too big to be noise. Every method below is a different way of answering "too big compared to what?"

Detection methods, simplest first

All of these answer the same question: "is this new value unusual?" Each one adds more machinery than the last. Start at the top of this list in production. Only move down when the simpler method demonstrably fails on your data.

Static thresholds

The simplest possible detector: pick a fixed number, alert if the metric crosses it. "Alert if p99 latency > 500ms."

import pandas as pd

def detect_static(latency: pd.Series, limit_ms: float = 500) -> pd.Series:
    return (latency > limit_ms).astype(int)

Go version. The Go examples in this chapter use only the standard library. Each one is a line-for-line translation of the Python above it. Go has no default arguments, so you pass every setting yourself, e.g. detectStatic(latency, 500).

func detectStatic(latency []float64, limitMs float64) []int {
	flags := make([]int, len(latency))
	for i, v := range latency {
		if v > limitMs {
			flags[i] = 1
		}
	}
	return flags
}

When it breaks: any metric with a daily or weekly pattern. A threshold set to catch daytime problems is either too loud at night or too quiet during the day. At night, "normal" is close to zero, so a small nighttime bump crosses the same absolute line as a real daytime problem. You also have to pick the number by hand and revisit it as traffic grows. It does not adapt on its own.

Rolling mean + z-score

Instead of one fixed number, compare each new reading to the last hour. Three ideas make this work:

  • Rolling average — the average of the last 60 readings. "Rolling" means the window slides forward every minute: the newest reading joins, the oldest one drops out. So the average keeps updating by itself as traffic changes.
  • Standard deviation — how much the readings usually wiggle around that average. If latency bounces between 95ms and 105ms, the wiggle is small. If it bounces between 50ms and 150ms, the wiggle is big.
  • Z-score — how far the new reading is from the average, counted in "wiggles" instead of milliseconds. In short: (new reading - average) / wiggle.

Note what gets compared. The average is not compared to the wiggle. The new reading's distance from the average is compared to the wiggle. Step by step, using the last 60 minutes:

  1. Average — latency was 100ms on average. This is what "normal" looks like right now.
  2. Wiggle — readings usually sit about 10ms away from that average.
  3. New reading — 140ms comes in.
  4. Distance — 140 - 100 = 40ms away from normal.
  5. Compare distance to wiggle — 40 / 10 = 4 wiggles. That number is the z-score.
  6. Decide — 4 is above the alert line of 3.5, so alert.

Each piece has one job:

  • the average says where normal is.
  • the wiggle says how far from normal is still OK.
  • the z-score says how far the new reading is, measured in wiggles.

Think of a dartboard: the average is the bullseye and the wiggle is the width of each ring. A reading four rings out is a miss.

The same hour, with two different new readings (average 100ms, wiggle 10ms):

New reading Distance from average Z-score (distance / 10ms) Alert? (threshold 3.5)
115ms 15ms 1.5 No — a normal wiggle
140ms 40ms 4.0 Yes — far outside the usual wiggle

Why count in wiggles instead of milliseconds? Because "40ms higher" means different things for different metrics. For a steady metric that barely moves, 40ms is huge. For a jumpy metric, 40ms is nothing. The z-score measures every metric on the same scale: "how unusual is this, compared to how much this metric normally moves?" A z-score above about 3 is rare in normal data, so it's a common place to set the alert line.

import pandas as pd

def detect_zscore(latency: pd.Series, window: int = 60, threshold: float = 3.5) -> pd.Series:
    rolling_mean = latency.rolling(window).mean()
    rolling_std = latency.rolling(window).std()
    z = (latency - rolling_mean) / rolling_std
    return (z.abs() > threshold).astype(int).fillna(0)

Go version. pandas' rolling(window) becomes a plain loop over the last window readings. Call it as detectZScore(latency, 60, 3.5).

import "math"

func mean(xs []float64) float64 {
	sum := 0.0
	for _, x := range xs {
		sum += x
	}
	return sum / float64(len(xs))
}

// stdDev divides by n-1, the same "sample" standard deviation pandas uses.
func stdDev(xs []float64) float64 {
	m := mean(xs)
	sum := 0.0
	for _, x := range xs {
		sum += (x - m) * (x - m)
	}
	return math.Sqrt(sum / float64(len(xs)-1))
}

func detectZScore(latency []float64, window int, threshold float64) []int {
	flags := make([]int, len(latency))
	for i := window - 1; i < len(latency); i++ {
		recent := latency[i-window+1 : i+1] // the last `window` readings, including this one
		m, s := mean(recent), stdDev(recent)
		if s == 0 {
			continue
		}
		z := (latency[i] - m) / s
		if math.Abs(z) > threshold {
			flags[i] = 1
		}
	}
	return flags
}

When it breaks: two ways. First, the mean and standard deviation are themselves dragged around by outliers. One big spike inflates rolling_std, which makes the next real spike look small by comparison. This is called "masking." Second, it still has no idea about daily/weekly seasonality. A rolling window of the last 60 minutes doesn't know that latency is supposed to be higher right now because it's 2pm on a Tuesday.

Median / MAD (robust to outliers)

Same idea as z-score, with two swaps that make it much harder to fool:

  • Median instead of average — sort the readings and take the one in the middle. With 97, 98, 99, 100, 101, 102, 2000, the median is 100. A spike can happen at any time, but once you sort, it always lands at one end of the list, so it can't move the middle.
  • MAD instead of standard deviation — MAD stands for median absolute deviation. It answers the same question as standard deviation ("how far from normal do readings usually sit?"), but uses the median at every step, so a spike can't blow it up.

How to work out MAD, using the same seven readings:

  1. Find the median. Sorted: 97, 98, 99, 100, 101, 102, 2000. Median = 100.

  2. Find how far each reading is from 100.

    Reading 97 98 99 100 101 102 2000
    Distance from 100 3 2 1 0 1 2 1900
  3. Take the median of those distances. Sorted: 0, 1, 1, 2, 2, 3, 1900. MAD = 2ms. In plain words: readings usually sit about 2ms from normal.

Standard deviation averages the distances, so the 1900 gets mixed in and drags the result up to 718ms. That says "readings usually sit 718ms from normal," which is wrong for six of the seven. MAD takes the middle distance, so the 1900 sits at the end of the list and gets ignored.

Question 4.2 (average way) 4.3 (median way)
Where is normal? average median
How far from normal is OK? standard deviation MAD

After that, both do the same check: "the new reading is X away from normal. How many wiggles is that?"

Why swap? Because one huge spike wrecks the average, but barely touches the median. Take the seven readings above, where six are normal and one is a 2,000ms spike:

Average-based (4.2) Median-based (4.3)
"Normal" level average = 371ms (dragged up by one spike) median = 100ms (ignores the spike)
Wiggle standard deviation = 718ms (blown up by one spike) MAD = 2ms (ignores the spike)

Everyday analogy: ten people in a room earn about $50k each. A billionaire walks in. The average salary jumps to about $90 million, which describes nobody in the room. The median is still about $50k, which describes almost everyone.

Now a real problem arrives. The next reading is 150ms, 50ms above normal. Step by step:

  1. Normal level — median = 100ms.
  2. Wiggle — MAD = 2ms. Readings usually sit about 2ms from the median.
  3. New reading — 150ms comes in.
  4. Distance — 150 - 100 = 50ms away from normal.
  5. Compare distance to wiggle — 50 / 2 = 25 wiggles. The code then multiplies by 0.6745, a fixed number that puts MAD on the same scale as standard deviation. That gives about 17.
  6. Decide — 17 is above the alert line of 5, so alert.

The average-based detector from 4.2 misses this one completely. It compares 150ms against an "average" of 371ms and a wiggle of 718ms. By that yardstick, 150ms looks below normal, not above it. This is the masking problem from 4.2: one spike hides the next real problem. Median and MAD don't get fooled, because a handful of extreme readings can't move the middle value.

import numpy as np
import pandas as pd

def detect_mad(latency: pd.Series, window: int = 60, threshold: float = 5.0) -> pd.Series:
    rolling_median = latency.rolling(window).median()
    # MAD: median of |value - median| in each window
    mad = latency.rolling(window).apply(lambda x: np.median(np.abs(x - np.median(x))))
    # 0.6745 rescales MAD so it's comparable to a standard deviation for normal data
    modified_z = 0.6745 * (latency - rolling_median) / mad.replace(0, np.nan)
    return (modified_z.abs() > threshold).astype(int).fillna(0)

Go version. Same loop as 4.2, with median in place of mean and stdDev. Call it as detectMAD(latency, 60, 5.0).

import (
	"math"
	"sort"
)

func median(xs []float64) float64 {
	sorted := append([]float64(nil), xs...) // copy, so the caller's slice isn't reordered
	sort.Float64s(sorted)
	mid := len(sorted) / 2
	if len(sorted)%2 == 0 {
		return (sorted[mid-1] + sorted[mid]) / 2
	}
	return sorted[mid]
}

func detectMAD(latency []float64, window int, threshold float64) []int {
	flags := make([]int, len(latency))
	distances := make([]float64, window)
	for i := window - 1; i < len(latency); i++ {
		recent := latency[i-window+1 : i+1]
		med := median(recent)
		// MAD: median of |value - median| in the window
		for j, v := range recent {
			distances[j] = math.Abs(v - med)
		}
		mad := median(distances)
		if mad == 0 {
			continue
		}
		// 0.6745 rescales MAD so it's comparable to a standard deviation for normal data
		modifiedZ := 0.6745 * (latency[i] - med) / mad
		if math.Abs(modifiedZ) > threshold {
			flags[i] = 1
		}
	}
	return flags
}

When it breaks: still ignores seasonality, same as z-score. Also, if more than half the window is anomalous (a long, sustained incident), the median itself shifts into "incident" territory. The detector then stops seeing anything wrong. It thinks the new normal is the incident.

Seasonal baselines (same hour last week)

Compare the current value not to recent minutes, but to the same minute on a previous, known-good period. Usually that means the same time yesterday, or the same time and day last week. This directly fixes the seasonality blind spot in 4.2 and 4.3.

import pandas as pd

def detect_seasonal(latency: pd.Series, period: int = 1440, threshold: float = 3.0) -> pd.Series:
    # period=1440 minutes = 1 day, for a 1-reading-per-minute series
    baseline = latency.shift(period)               # same minute, one period ago
    diff = latency - baseline
    diff_std = diff.rolling(period).std()           # how much this diff normally varies
    z = diff / diff_std
    return (z.abs() > threshold).astype(int).fillna(0)

Go version. Reuses stdDev from 4.2. Call it as detectSeasonal(latency, 1440, 3.0).

func detectSeasonal(latency []float64, period int, threshold float64) []int {
	flags := make([]int, len(latency))
	// diff[i] = this reading minus the same minute one period ago
	diff := make([]float64, len(latency))
	for i := period; i < len(latency); i++ {
		diff[i] = latency[i] - latency[i-period]
	}
	// the first diff exists at index `period`, so a full window of diffs starts at 2*period-1
	for i := 2*period - 1; i < len(latency); i++ {
		s := stdDev(diff[i-period+1 : i+1]) // how much this diff normally varies
		if s == 0 {
			continue
		}
		z := diff[i] / s
		if math.Abs(z) > threshold {
			flags[i] = 1
		}
	}
	return flags
}

When it breaks: needs at least one full clean period of history before it can compare against anything (see "cold start," Production realities). It also assumes last week was normal. If last Tuesday had its own incident at the same time, the detector will treat this Tuesday's identical incident as "expected," because it matches the (bad) baseline.

STL decomposition

The idea in one line: let a library do the Time series basics split for you, then only look at the leftover.

Time series basics said every series is trend + seasonality + noise mixed together. STL is a standard algorithm that pulls those apart. It hands you back three separate series that add up to the original:

Four stacked panels over the same four days. Raw latency equals trend, a slow drift such as growing traffic, plus seasonal, the repeating daily shape, quiet at 3am and busy at 2pm, plus residual, what is left: normal jitter plus any anomalies. One spike is invisible in the raw series but stands out in the residual.
STL hands back three series that add up to the original. Read it as: in the raw series the spike on day 4 is about as tall as an ordinary daily hump, so a threshold on raw latency can't tell them apart. In the residual it is the only big thing. That is why STL-based detectors check only the residual.

The residual is the only part you check. Trend and seasonality are "expected," so they're removed before you ask "is this weird?"

A worked example. Two readings, both around 180-190 ms:

Time Raw Trend Seasonal Expected (trend + seasonal) Residual (raw − expected) Verdict
Tue 2pm 190 ms 120 ms +65 ms (2pm is always busy) 185 ms +5 ms normal
Tue 3am 180 ms 120 ms −40 ms (3am is always quiet) 80 ms +100 ms anomaly

Almost the same raw number, opposite verdicts. A plain threshold on the raw value (4.1) can't tell these apart; STL can, because it knows what each time of day usually looks like.

How STL figures out trend and seasonal (roughly).

  1. Trend: smooth the series very heavily, so the daily bumps flatten out and only the slow drift remains.
  2. Seasonal: subtract the trend. Then take every "3:00am" value across all the days and average them, every "3:01am" value and average them, and so on. That gives one typical day's shape.
  3. Residual: raw − trend − seasonal. Whatever's left.

It repeats these steps a few times, each pass sharpening the others. The "L" in the name stands for Loess, the smoothing method it uses: for each point, fit a simple line through just its nearby neighbours. You don't need to know more than "it's a smoother." The full name is Seasonal-Trend decomposition using Loess.

Why robust=True matters. Without it, a big incident would drag the averages in step 2 and bend the "typical day" shape toward itself, partly hiding the very spike you want to catch. With it, STL gives unusually large points less weight, so one bad hour barely changes what "normal" looks like.

How it's better than 4.4. The seasonal baseline in 4.4 compares against one past day, so if that day had an incident, your baseline is broken. STL averages the shape across many days, so one bad day is outvoted. It also handles trend, which 4.4 ignores.

In code, it's one library call, then the same z-score check from 4.2, run on the residual instead of the raw series:

from statsmodels.tsa.seasonal import STL

def detect_stl(latency: pd.Series, period: int = 1440, threshold: float = 4.0) -> pd.Series:
    result = STL(latency, period=period, robust=True).fit()
    residual = result.resid
    z = (residual - residual.mean()) / residual.std()
    return (z.abs() > threshold).astype(int)

period=1440 tells STL "the pattern repeats every 1440 readings" (one day of per-minute data). The threshold is 4.0 rather than 3.0 because the residual is already cleaned up, so you can afford to be stricter and cut false alarms.

When it breaks:

  • Needs history. To average "every 3am," it needs several days of 3ams. Give it at least a few full cycles (a few days for a daily pattern), or the seasonal shape is guesswork.
  • Not built for real time. It looks at the whole window at once. To check each new minute as it arrives, you have to re-run it over a sliding window every time, which costs CPU.
  • One pattern only. It expects a single repeating cycle. A metric that has a daily shape and a weekday/weekend shape needs a variant that handles several at once (e.g., MSTL, "multiple STL").

Forecasting-based (predict, then compare)

Train a small forecasting model to predict what the next value should be. Then compare the actual value to the prediction. The gap between prediction and reality is called the residual; a big residual is the anomaly signal. This is the most general approach, because any forecasting model works:

  • Exponential smoothing — weights recent points more than old ones. Cheap and classic.
  • ARIMA-style statistical models — model the series as a function of its own past values.
  • Prophet — a Meta-built library that explicitly models trend, multiple seasonalities, and holidays. Popular for business metrics with weekly/yearly patterns.
from statsmodels.tsa.holtwinters import ExponentialSmoothing

def detect_forecast_residual(latency: pd.Series, period: int = 1440, threshold: float = 4.0) -> pd.Series:
    model = ExponentialSmoothing(latency, trend="add", seasonal="add", seasonal_periods=period)
    fitted = model.fit()
    residual = latency - fitted.fittedvalues
    z = (residual - residual.mean()) / residual.std()
    return (z.abs() > threshold).astype(int)

When it breaks: forecasting models are the most work to keep healthy. They need retraining as patterns shift (Production realities), and can be slow to fit on long history. A bad forecast (say, the model hasn't learned a new weekly pattern yet) produces a wrong residual, which looks exactly like a real anomaly. Good forecasts also give you something extra for free: capacity planning ("we'll hit our latency SLO in 3 weeks at this growth rate"), which pure anomaly detectors don't.

Isolation Forest (multi-feature data)

Everything above uses one number per minute. Real incidents usually show up across several metrics at once (latency and error rate and request count). Isolation Forest is an unsupervised algorithm that works on multiple features together. It builds random decision trees that split the data. Points that get isolated into their own tiny branch after very few splits are the outliers. Everyday analogy: an odd-one-out is quick to corner with a few yes/no questions, while a normal point takes many questions to separate from its neighbors.

from sklearn.ensemble import IsolationForest
import pandas as pd

def detect_isolation_forest(df: pd.DataFrame) -> pd.Series:
    # df has one row per minute, columns: latency_ms, error_rate, requests_per_min
    model = IsolationForest(n_estimators=200, contamination=0.01, random_state=0)
    model.fit(df)
    preds = model.predict(df)          # -1 = anomaly, 1 = normal
    return pd.Series((preds == -1).astype(int), index=df.index)

When it breaks: contamination (the expected fraction of anomalies) is a guess you have to set. Getting it wrong directly changes how many alerts you get. It also has no built-in notion of time or seasonality. Feed it raw latency_ms at 3am and 3pm and it treats them the same, unless you engineer time-aware features (e.g., "difference from same-hour-yesterday" as one of the input columns, borrowing from Seasonal baselines (same hour last week)).

Clustering / density-based methods (brief)

Algorithms like DBSCAN group points into dense clusters and label anything that doesn't fall into a cluster as an outlier. This is useful when "normal" isn't one blob but several. For example, normal behavior looks different for mobile vs. desktop clients, and you don't want to hand-pick a number of clusters upfront. The tradeoffs are similar to Isolation Forest: no built-in time-awareness, and performance degrades as the number of features grows. This is the "curse of dimensionality" — in high dimensions, most points end up looking roughly equally far from each other, so "dense" and "sparse" stop being meaningful. In practice this is used less often than Isolation Forest for metric anomaly detection, but it shows up in security (clustering login behavior, see the fraud/security chapters).

Comparison table

Method Learns seasonality? Multiple features? Robust to outliers in its own training window? Needs labels?
Static threshold No No No No
Rolling mean + z-score No No No No
Median / MAD No No Yes No
Seasonal baseline Yes (one period) No Partially No
STL decomposition Yes No Partially (with robust=True) No
Forecasting residual Yes With extra work (covariates) Partially No
Isolation Forest No (needs feature engineering) Yes Yes No
Clustering / density No (needs feature engineering) Yes Yes No
Gradient-boosted trees (Supervised detection when you have labels) Via features Yes Yes Yes

Rule of thumb used across the SaaS products in this guide: start with median/MAD or a seasonal baseline per metric. It's cheap, explainable, and needs no training step. Add Isolation Forest when you need to correlate several metrics at once. Only reach for a full forecasting model when you also want the forecast itself (capacity planning, SLO burn-rate prediction).

A note for Go developers. Static thresholds to Seasonal baselines (same hour last week) are plain loops and arithmetic, so they translate directly to Go (shown above). STL decomposition to Isolation Forest (multi-feature data) and Supervised detection when you have labels lean on statsmodels and scikit-learn. Go has no widely used equivalent of those libraries (gonum covers basic statistics and linear algebra, not STL or Isolation Forest). A common split is: train and experiment with the heavy methods in Python, and run the cheap detectors from 4.1-4.4 in Go, in the hot path, where they check every new reading.

Supervised detection when you have labels

Everything in Detection methods, simplest first assumes you don't know, ahead of time, which points are bad. Fraud and malware detection are different. Companies keep records of confirmed fraud (a chargeback, a manually reviewed case) and confirmed malware (an antivirus signature match, a sandbox detonation). That's a label. Once you have enough labels, this becomes a standard supervised classification problem. The industry's default tool is gradient-boosted trees — libraries like XGBoost and LightGBM.

In plain terms: a gradient-boosted model builds many small decision trees one after another. Each new tree focuses on the mistakes the previous trees made. Their combined vote is the final prediction. They're the workhorse here because they handle messy, mixed tabular data well (numbers and categories together, like transaction amount, merchant category, country, account age). They also train fast and are easier to inspect than a deep neural network.

from sklearn.ensemble import GradientBoostingClassifier
import pandas as pd

# features: transaction_amount, account_age_days, merchant_risk_score, is_new_device, ...
# label: is_fraud (1 or 0), decided by a human reviewer or a chargeback, weeks after the fact
def train_fraud_model(features: pd.DataFrame, labels: pd.Series) -> GradientBoostingClassifier:
    model = GradientBoostingClassifier(n_estimators=300, max_depth=4, learning_rate=0.05)
    model.fit(features, labels)
    return model

Class imbalance: fraud and malware are rare, often well under 1% of all transactions or files. A model trained naively on that data can get 99.5% accuracy by predicting "not fraud" every single time, which is useless. Standard fixes:

  • Class weights — tell the model to penalize missing a fraud case much more than a false alarm (class_weight="balanced" in scikit-learn, or a scale_pos_weight parameter in XGBoost).
  • Resampling — oversample the rare class, or undersample the common class. To oversample, you duplicate or synthesize more fraud examples, e.g. with SMOTE, which generates new synthetic fraud-like points between existing ones.
  • Judge on the right metric — never use accuracy for an imbalanced problem (see Measuring detectors). Precision, recall, and the precision-recall curve are the standard tools here.

Measuring detectors

A detector makes one of four calls on every data point:

Predicted anomaly Predicted normal
Actually anomaly True Positive (TP) False Negative (FN) — missed it
Actually normal False Positive (FP) — false alarm True Negative (TN)

From those four counts:

  • Precision — of everything the detector flagged, what fraction was a real anomaly? TP / (TP + FP). Low precision means lots of noisy alerts. That causes alert fatigue: the team starts ignoring the alert channel because it cries wolf.
  • Recall — of everything that was actually an anomaly, what fraction did the detector catch? TP / (TP + FN). Low recall means real incidents slip through silently.
  • F1 score — a single number combining precision and recall (their harmonic mean): 2 * P * R / (P + R). Useful for comparing detectors when you don't want to look at two numbers separately.
  • False positive rate (FPR) — of everything that was actually normal, what fraction did the detector wrongly flag? FP / (FP + TN). This sounds similar to precision but answers a different question. FPR is "how trigger-happy is the detector on normal data." Precision is "how trustworthy is an alert once it fires."

The base-rate problem, worked out with numbers. Say a metric produces 10,000 readings, and truly, 100 of them (1%) are real anomalies — 9,900 are normal. Your detector has 95% recall and 95% specificity (which means a 5% false positive rate). That sounds like a good detector. Here's what actually happens:

Of 10,000 readings, 100 are true anomalies: the detector catches 95 (true positives) and misses 5 (false negatives). 9,900 are normal: it wrongly flags 495 (false positives) and correctly ignores 9,405 (true negatives). The alerts it sends are 95 true plus 495 false, 590 in all, so precision is about 16%.
95% recall and 95% specificity, but 84% of alerts are false. Read it as: the bottom bar is every alert the detector sends, drawn to scale. Only the green sliver is real. Because real anomalies are rare, even a 5% false-positive rate on 9,900 normal readings swamps them.
  • precision = TP / (TP + FP) = 95 / (95 + 495) = 95 / 590, about 16%.
  • recall = TP / (TP + FN) = 95 / (95 + 5), 95%.
  • F1 = 2 * precision * recall / (precision + recall), about 27%.

Even with a 95%-accurate-sounding detector, 84% of the alerts it sends are false alarms. True anomalies are so rare (a low base rate) that even a small false-positive rate on the huge pool of normal data outnumbers the true positives. This is why "our model is 99% accurate" is close to meaningless for rare-event detection: accuracy counts all the easy true negatives too.

It's also the direct mechanism behind alert fatigue. An on-call engineer who gets paged and finds nothing wrong 5 times in a row will start dismissing the 6th page without looking, which is exactly when it's real. Tuning a detector is usually a precision/recall trade-off: raising the threshold reduces false positives, but also catches fewer real incidents. Most teams pick the trade-off based on how expensive a false positive is (a page at 3am) vs. a false negative (a missed incident) in their specific domain.

Production realities

Textbook detectors run once on a clean dataset. Production detectors run forever, on live, changing data, across many customers. A few realities that change the design:

  • Concept drift — the definition of "normal" changes over time (more users, a new feature shipped, a holiday shopping season). A detector trained in January doesn't know June's traffic pattern is the new normal. It will falsely flag June as anomalous until retrained.
  • Retraining — the fix for drift: periodically refit the baseline. Rolling windows naturally do this a little. Forecasting and ML models need an explicit retrain job, e.g. nightly or weekly. Retraining too often makes the detector chase noise; too rarely makes it stale.
  • Cold start — a brand-new customer, or a brand-new metric, has no history yet. Seasonal baselines (4.4) and forecasting (4.6) can't run at all until at least one full period of data exists. Common workarounds:
    • borrow a baseline from similar customers/metrics.
    • fall back to a simple threshold until enough history accumulates.
    • explicitly mark early data as "low confidence."
  • Per-tenant baselines at scale — a multi-tenant SaaS observability or security product might track millions of individual time series (one per customer per metric). You can't hand-tune a threshold for each one. This forces the simpler, cheap-to-run methods (median/MAD, seasonal baseline) into the hot path, because a heavy per-series forecasting model, run millions of times, doesn't fit any reasonable compute budget. Inferred: this compute-cost pressure is likely a major reason large observability vendors (see the observability chapter later in this guide) favor lightweight statistical detectors for the default, always-on tier. They likely reserve heavier ML for opt-in or higher-tier features instead. Vendors don't usually publish per-series compute budgets, so treat this as reasoning, not a confirmed fact.
  • Feedback loops — letting users mark an alert "not useful" or "yes this was real" turns every alert into a free label. Over time this small trickle of labels is exactly what lets a team move from unsupervised detectors (Detection methods, simplest first) toward a supervised model (Supervised detection when you have labels) that's tuned to what this team actually cares about. It also lets the system down-weight noisy detectors automatically.

Where the LLM comes in

Everything above finds that something is unusual. An LLM is good at the next step: turning a pile of numbers and context into a sentence a human can act on. Concretely, LLMs are used for:

  • Explaining — turning a detector's output plus surrounding facts into plain language. For example: "latency jumped from 90ms to 800ms at 14:32, right after a deploy at 14:30; this looks related."
  • Correlating across signals — a human (or an agent, covered in the builder track) pulls latency, error rate, recent deploys, and recent config changes. An LLM reasons over that bundle to suggest which one is the likely cause.
  • Choosing the next query — instead of a human deciding what dashboard to check next, an LLM-driven agent makes the call. It decides "check error logs for this service" or "look up recent deploys," then acts on the answer. (This is the agent loop from the builder track — see phase 1.)
  • Summarizing — turning ten related alerts into one incident summary for a status page or a handoff note.

Why you should not ask an LLM to eyeball raw numbers for anomalies. Two concrete reasons:

  1. Cost. Sending 10,000 raw latency readings to an LLM on every check, so it can "look for anomalies," burns tokens (and money). A laptop does the same arithmetic in microseconds, for free.
  2. Reliability. LLMs are language models, not calculators. They predict the next likely token; they don't run arithmetic circuits. Ask one to compute a rolling standard deviation over 500 numbers in its head (in text), and it will sometimes get it wrong, silently, with no error message. Detection needs to be exact and repeatable. Use code (numpy, pandas, scikit-learn) for that, and give the LLM only the already-computed anomaly plus a small amount of context to reason over, as in the pattern below.
Time series metrics go into detector code, statistics or ML from sections 4 and 5. The detector emits an anomaly plus context: metric name, value, baseline and time. Only that goes to the LLM, Claude Sonnet 5, which explains it and suggests the next check.
Code detects; the LLM only explains what code already found. Read it as: the LLM never scans raw metrics. Detection is exact, repeatable code; the model gets one already-found anomaly plus a little context, and its job is words, not numbers.

Emerging option: time-series foundation models. A newer idea is training one large, general-purpose model directly on time-series data (not text). It can then forecast or flag anomalies in a series it has never seen before, without per-series training. This is called "zero-shot" forecasting. As of September 2026, three real examples are worth knowing:

  • Amazon Chronos — a transformer model trained on time-series data. It turns numeric values into tokens the same way an LLM tokenizes words, then applies an LLM-style architecture to forecast. Open-weights, with a newer, smaller, more efficient version (Chronos-2) released in 2025.
  • Google TimesFM — a decoder-only foundation model for time-series forecasting, pretrained on hundreds of billions of real data points. It's also available directly inside Google Cloud's BigQuery. Google released a third generation, TimesFM-3, in August 2026, adding native multivariate forecasting (predicting several related series together instead of one at a time). Note: TimesFM-3's pretrained weights are licensed for non-commercial use only, so check the license before using it in a product.
  • Datadog Toto — an open-weights foundation model built specifically for observability metrics, trained heavily on Datadog's own telemetry data. A 2.0 version scaled the model up significantly. This is a concrete, published example of a vendor from this guide's own domain building its own foundation model rather than only using classical statistics.

These are genuinely new (all three had major releases in 2025-2026) and worth watching. But as of this writing, the methods in Detection methods, simplest first (thresholds, robust statistics, seasonal baselines, STL, Isolation Forest) remain the default in production. They're cheap, fast, and easy to explain to an on-call engineer at 3am. Treat foundation models here as a "watch this space," not yet a default replacement.

Build it yourself

A self-contained script does four things:

  • generates a synthetic seasonal latency series with known, injected incidents.
  • runs three detectors from Detection methods, simplest first.
  • prints precision/recall for each against the known truth.
  • ends with a small stub showing how you'd hand the top anomaly to Claude to explain.
"""
anomaly_lab.py — synthetic latency data + 3 classical detectors + a scoring harness.
Requires: numpy, pandas, statsmodels (pip install numpy pandas statsmodels)
"""
import numpy as np
import pandas as pd


def generate_series(days: int = 14, freq_per_day: int = 1440, seed: int = 0) -> pd.DataFrame:
    """One-reading-per-minute latency series: daily seasonality + slow trend + noise +
    5 injected incidents, with ground-truth labels for scoring."""
    rng = np.random.default_rng(seed)
    n = days * freq_per_day
    t = np.arange(n)

    hour_of_day = (t % freq_per_day) / freq_per_day * 24
    seasonal = 40 * np.sin((hour_of_day - 6) / 24 * 2 * np.pi) + 60   # daily busy/quiet cycle
    trend = t * 0.002                                                 # slow growth over 2 weeks
    noise = rng.normal(0, 5, n)
    latency = np.clip(seasonal + trend + noise, 10, None)

    labels = np.zeros(n, dtype=int)
    starts = rng.choice(np.arange(200, n - 200), size=5, replace=False)
    for start in starts:
        length = int(rng.integers(10, 30))
        magnitude = rng.uniform(80, 200)
        latency[start:start + length] += magnitude
        labels[start:start + length] = 1

    idx = pd.date_range("2026-08-01", periods=n, freq="1min")
    return pd.DataFrame({"latency_ms": latency, "is_incident": labels}, index=idx)


def detect_zscore(latency: pd.Series, window: int = 60, threshold: float = 3.5) -> pd.Series:
    m, s = latency.rolling(window).mean(), latency.rolling(window).std()
    z = (latency - m) / s
    return (z.abs() > threshold).astype(int).fillna(0)


def detect_mad(latency: pd.Series, window: int = 60, threshold: float = 5.0) -> pd.Series:
    med = latency.rolling(window).median()
    mad = latency.rolling(window).apply(lambda x: np.median(np.abs(x - np.median(x))))
    mz = 0.6745 * (latency - med) / mad.replace(0, np.nan)
    return (mz.abs() > threshold).astype(int).fillna(0)


def detect_seasonal(latency: pd.Series, period: int = 1440, threshold: float = 3.0) -> pd.Series:
    baseline = latency.shift(period)
    diff = latency - baseline
    z = diff / diff.rolling(period).std()
    return (z.abs() > threshold).astype(int).fillna(0)


def evaluate(pred: pd.Series, truth: pd.Series) -> tuple[float, float, float]:
    tp = int(((pred == 1) & (truth == 1)).sum())
    fp = int(((pred == 1) & (truth == 0)).sum())
    fn = int(((pred == 0) & (truth == 1)).sum())
    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
    return precision, recall, f1


if __name__ == "__main__":
    df = generate_series()
    detectors = {
        "z-score": detect_zscore(df["latency_ms"]),
        "median/MAD": detect_mad(df["latency_ms"]),
        "seasonal baseline": detect_seasonal(df["latency_ms"]),
    }
    for name, pred in detectors.items():
        p, r, f1 = evaluate(pred, df["is_incident"])
        print(f"{name:20s} precision={p:.2f}  recall={r:.2f}  f1={f1:.2f}")

Go version. Same lab in Go. Put this main.go in a folder next to a detectors.go that holds the functions from Static thresholds to Seasonal baselines (same hour last week) (all in package main), then run go run .. Go's random number generator differs from numpy's, so the injected incidents land in different places and your exact scores will differ from the Python run.

// anomaly_lab — synthetic latency data + 3 classical detectors + a scoring harness.
// Put this file next to detectors.go (the functions from sections 4.1-4.4), then: go run .
package main

import (
	"fmt"
	"math"
	"math/rand/v2"
)

// generateSeries builds a one-reading-per-minute latency series: daily seasonality + slow
// trend + noise + 5 injected incidents, with ground-truth labels for scoring.
func generateSeries(days, perDay int, seed uint64) (latency []float64, isIncident []int) {
	rng := rand.New(rand.NewPCG(seed, seed))
	n := days * perDay
	latency = make([]float64, n)
	isIncident = make([]int, n)

	for t := 0; t < n; t++ {
		hourOfDay := float64(t%perDay) / float64(perDay) * 24
		seasonal := 40*math.Sin((hourOfDay-6)/24*2*math.Pi) + 60 // daily busy/quiet cycle
		trend := float64(t) * 0.002                               // slow growth over 2 weeks
		noise := rng.NormFloat64() * 5
		latency[t] = math.Max(seasonal+trend+noise, 10)
	}

	used := map[int]bool{}
	for len(used) < 5 {
		start := 200 + rng.IntN(n-400)
		if used[start] {
			continue
		}
		used[start] = true
		length := 10 + rng.IntN(20)
		magnitude := 80 + rng.Float64()*120
		for i := start; i < start+length; i++ {
			latency[i] += magnitude
			isIncident[i] = 1
		}
	}
	return latency, isIncident
}

func evaluate(pred, truth []int) (precision, recall, f1 float64) {
	var tp, fp, fn float64
	for i := range pred {
		switch {
		case pred[i] == 1 && truth[i] == 1:
			tp++
		case pred[i] == 1 && truth[i] == 0:
			fp++
		case pred[i] == 0 && truth[i] == 1:
			fn++
		}
	}
	if tp+fp > 0 {
		precision = tp / (tp + fp)
	}
	if tp+fn > 0 {
		recall = tp / (tp + fn)
	}
	if precision+recall > 0 {
		f1 = 2 * precision * recall / (precision + recall)
	}
	return precision, recall, f1
}

func main() {
	latency, truth := generateSeries(14, 1440, 0)
	detectors := []struct {
		name string
		pred []int
	}{
		{"z-score", detectZScore(latency, 60, 3.5)},
		{"median/MAD", detectMAD(latency, 60, 5.0)},
		{"seasonal baseline", detectSeasonal(latency, 1440, 3.0)},
	}
	for _, d := range detectors {
		p, r, f1 := evaluate(d.pred, truth)
		fmt.Printf("%-20s precision=%.2f  recall=%.2f  f1=%.2f\n", d.name, p, r, f1)
	}
}

Running the Python version prints something like this (the Go version's numbers differ a little, but the ranking is the same):

z-score              precision=0.66  recall=0.16  f1=0.26
median/MAD           precision=1.00  recall=0.98  f1=0.99
seasonal baseline    precision=0.35  recall=0.65  f1=0.45

Median/MAD wins by a wide margin, and the "fancier" seasonal baseline comes last on precision. Each result traces back to a "When it breaks" note from Detection methods, simplest first:

  • Z-score catches only the start of each incident (low recall). The incident's own readings enter the 60-minute window and inflate the average and the wiggle. After a few minutes, the incident looks "normal" to the detector. This is the masking problem from 4.2.
  • Median/MAD is nearly perfect. Each incident lasts 10-30 minutes, which is under half of the 60-minute window, so the median and MAD stay on normal values (4.3). The daily curve barely moves within one hour, so ignoring seasonality costs nothing here.
  • Seasonal baseline raises false alarms (low precision). It compares each minute to the same minute yesterday. So an incident alerts twice: once when it happens, and again a day later, when a normal reading is compared to yesterday's incident and looks suspiciously low. In the run above, about 80% of this detector's false alarms are these day-later echoes. This is the "assumes last week was normal" problem from 4.4. It also can't flag anything in the first two days, because it needs a day of history for the comparison plus a day to learn the wiggle (cold start, Production realities).

The lesson matches the rule of thumb after the comparison table: start simple and test on your own data. More machinery only helps when it fixes a problem your data actually has. These synthetic incidents are short and the daily curve is gentle, so median/MAD's robustness matters more than the seasonal baseline's awareness of the daily cycle.

Now the LLM half. Take the single highest-scoring anomaly and hand it, with a little context, to Claude to turn into a sentence a human can read.

"""explain_anomaly.py — take one detected anomaly and ask Claude to explain it in plain English.
Requires: pip install anthropic ; set ANTHROPIC_API_KEY in your environment.
"""
import anthropic

def explain_anomaly(timestamp: str, value: float, baseline: float, recent_events: str) -> str:
    client = anthropic.Anthropic()
    prompt = (
        f"An anomaly was detected in checkout API latency.\n"
        f"Timestamp: {timestamp}\n"
        f"Observed value: {value:.1f} ms\n"
        f"Expected baseline (same time, prior period): {baseline:.1f} ms\n"
        f"Recent related events: {recent_events}\n\n"
        "In 2-3 short sentences: what could explain this, and what's one thing to check next?"
    )
    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=200,
        messages=[{"role": "user", "content": prompt}],
    )
    return response.content[0].text

if __name__ == "__main__":
    print(explain_anomaly(
        timestamp="2026-08-05 14:32",
        value=812.0,
        baseline=95.0,
        recent_events="Deploy of checkout-service v2.14.0 at 14:30 (2 minutes before the spike).",
    ))

Go version, using the official Anthropic Go SDK:

// explain_anomaly — take one detected anomaly and ask Claude to explain it in plain English.
// Requires: go get github.com/anthropics/anthropic-sdk-go ; set ANTHROPIC_API_KEY in your environment.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	"github.com/anthropics/anthropic-sdk-go"
)

func explainAnomaly(ctx context.Context, timestamp string, value, baseline float64, recentEvents string) (string, error) {
	client := anthropic.NewClient()
	prompt := fmt.Sprintf(
		"An anomaly was detected in checkout API latency.\n"+
			"Timestamp: %s\n"+
			"Observed value: %.1f ms\n"+
			"Expected baseline (same time, prior period): %.1f ms\n"+
			"Recent related events: %s\n\n"+
			"In 2-3 short sentences: what could explain this, and what's one thing to check next?",
		timestamp, value, baseline, recentEvents,
	)
	response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
		Model:     "claude-sonnet-5",
		MaxTokens: 200,
		Messages: []anthropic.MessageParam{
			anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
		},
	})
	if err != nil {
		return "", err
	}
	for _, block := range response.Content {
		if text, ok := block.AsAny().(anthropic.TextBlock); ok {
			return text.Text, nil
		}
	}
	return "", errors.New("no text in response")
}

func main() {
	explanation, err := explainAnomaly(
		context.Background(),
		"2026-08-05 14:32",
		812.0,
		95.0,
		"Deploy of checkout-service v2.14.0 at 14:30 (2 minutes before the spike).",
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(explanation)
}

Notice what's not in this second script: no raw time series, no arithmetic for Claude to get wrong. The detector (plain code) already did the numeric work. The LLM only receives the small, pre-computed summary it's actually good at reasoning over. This split, code for detection and LLM for explanation, is the pattern every later chapter in this guide builds on.

Check yourself

Question 1

Your on-call engineer says "the model is 99% accurate, why do we still get so many false alarms?" What's the likely explanation?

Show answer

The base-rate problem (Measuring detectors). If true anomalies are rare (say 1% of all data), a detector can be "99% accurate" mostly by correctly ignoring the huge pool of normal points. It can still generate far more false positives than true positives among its alerts. Precision, not accuracy, is the number that reflects "how trustworthy is an alert."

Question 2

Latency is 300ms. Is that a point anomaly? Why or why not?

Show answer

You can't tell from the number alone — it depends on context. If 300ms is normal for 3pm on a Monday, it's not an anomaly at all. If 300ms is way above what this API ever does at 3am on a Sunday, it's a contextual anomaly. A pure point anomaly (like -50ms, or 50,000ms) would be wrong at any time of day.

Question 3

Why does a rolling mean + z-score detector sometimes miss a second spike right after a first one?

Show answer

Masking: the first spike gets pulled into the rolling window used to compute the mean and standard deviation, inflating the standard deviation. The second spike is measured against that inflated standard deviation. That produces a smaller z-score, which can fall below the alert threshold. Median/MAD is more resistant to this, because the median and MAD barely move due to a small number of extreme points.

Question 4

You have a brand-new customer with 2 days of metric history. Which detection method from Detection methods, simplest first can you use immediately, and which can't you use yet?

Show answer

Static thresholds, rolling mean/z-score, and median/MAD can run with just a short window of recent data. Seasonal baseline needs at least one full period (e.g. a day or week) of prior history. STL/forecasting methods need several full seasonal cycles to estimate trend and seasonality reliably. Neither can run meaningfully yet — this is the cold-start problem from Production realities.

Question 5

Why not just send the last 10,000 latency readings to an LLM and ask "which of these are anomalies"?

Show answer

Two reasons (Where the LLM comes in). First, cost: you'd pay LLM token prices to do arithmetic a laptop does for free in microseconds. Second, reliability: LLMs predict likely next tokens, and don't reliably execute exact arithmetic like rolling averages or standard deviations over long numeric sequences. Errors can be silent. Use code for the numeric detection step, and give the LLM only the already-computed anomaly plus a little context to reason over.

Question 6

Fraud detection almost always uses gradient-boosted trees rather than an unsupervised method like Isolation Forest. Why?

Show answer

Because fraud teams typically have labels: confirmed fraud cases from chargebacks or manual review (Supervised detection when you have labels). When you have reliable labels, supervised learning generally outperforms unsupervised methods. Supervised learning directly learns the boundary between fraud and not-fraud from real examples. Unsupervised methods only learn "what does normal look like" and infer the rest.

Sources

Next

Next: How LLMs Work covers the model that sits on top of everything in this chapter. If you haven't read it yet, it's the other half of this guide's foundation. Once you have both foundations, move on to the hands-on builder track, where you build an agent from scratch that can use tools like the detectors above.