# AI Anomaly Detection System | 30 Days of Building AI Systems, Day 17

> Build an AI anomaly detection system: streaming ingestion, statistical and ML detectors, scoring and thresholds, alerting, and LLM-written alert explanations.

Source: https://codeitronics.com/blogs/ai-systems-day-17-ai-anomaly-detection (published 2026-12-05)

Yesterday we built a recommendation system that learns what is normal for each user and predicts what they want next. Today we flip that idea: learn what is normal for a system, then flag what is not. The AI Anomaly Detection System watches metrics, transactions, logs, and sensor data, scores unusual behavior in real time, and triggers alerts people can act on. Like yesterday, this is a classic machine learning problem. Statistical and ML models do the detecting. LLMs help with explaining and triaging what was found.

![AI Anomaly Detection System — CodeITronics infographic](https://pub-206c6a53642c4bdb86310f0393204592.r2.dev/blogs/series/30-days-of-building-ai-systems/62-ai-systems-day-17-ai-anomaly-detection.png) *Save this sheet. The rest of this note walks through it section by section.*

## Table of Contents

* [What We Are Building](#what-we-are-building)
* [System Architecture](#system-architecture)
* [Key Components](#key-components)
* [Detection Approaches](#detection-approaches)
* [Scoring and Thresholds](#scoring-and-thresholds)
* [Where LLMs Fit](#where-llms-fit)
* [A Minimal Tech Stack](#a-minimal-tech-stack)
* [Production Concerns](#production-concerns)
* [Key Takeaways](#key-takeaways)
* [FAQs](#faqs)
* [Up Next](#up-next)

## What We Are Building

An anomaly detection system that:

* Monitors data and system behavior
* Detects anomalies in real time on time-series and categorical data
* Adapts to changing patterns
* Reduces false positives
* Triggers alerts and notifications with actionable context

Use cases: fraud detection, network intrusion, system health, payment and transaction monitoring, predictive maintenance, security threats, business KPI monitoring, and IoT sensors.

## System Architecture

```
Data Sources -> Ingestion -> Processing -> Feature Engineering
   -> ML Models (unsupervised and semi-supervised) -> Anomaly Scoring
   -> Alerts and Actions -> Visualization and Insights
```

The detailed flow on the sheet: collect data (real-time or batch), preprocess (clean, fill, encode), extract features (windowing, statistics, embeddings), run model inference to get an anomaly score, then ask "anomaly detected?" If yes, trigger an alert and take action. Either way, store results and logs, generate reports, monitor model performance, and feed labels back for retraining.

The user workflow is equally important: connect sources, let the system learn normal behavior, detect anomalies, score and validate them, alert, let a human investigate, then take action so the system learns. That human investigation step produces the labels that make the system better over time.

## Key Components

| Component                | Role                                                                |
| ------------------------ | ------------------------------------------------------------------- |
| Data connectors          | Databases, APIs, logs, metrics, IoT devices, queues, cloud services |
| Stream processing        | Kafka or Pulsar for real-time events                                |
| Feature store            | Windowed aggregates and statistics shared by training and scoring   |
| Model training pipeline  | Trains on recent normal data, scheduled or triggered                |
| Model registry           | Versions models so you can roll back                                |
| Real-time scoring engine | Scores each event or window as it arrives                           |
| Alerting system          | Routes alerts by severity to the right people                       |
| Monitoring and logging   | Tracks alert volume, model health, drift                            |

## Detection Approaches

| Family           | Examples                        | Use when                              |
| ---------------- | ------------------------------- | ------------------------------------- |
| Statistical      | Z-score, IQR, ESD               | Single metrics with stable behavior   |
| Machine learning | Isolation Forest, One-Class SVM | Many features at once, no labels      |
| Deep learning    | Autoencoders, LSTM              | Complex patterns, lots of data        |
| Time series      | Prophet, STL decomposition      | Strong seasonality and trend          |
| Hybrid           | Combinations of the above       | Production systems with mixed signals |

Start simple. A rolling z-score with seasonal baselines catches a surprising share of real problems and is easy to explain. Add ML when anomalies only show up as unusual combinations of features, such as a normal transaction amount at an unusual hour from a new device.

```python
import pandas as pd
from sklearn.ensemble import IsolationForest

# df: one row per minute, numeric columns like payments, error_rate, p95_latency
mean = df.rolling(60).mean().shift(1)   # baseline from the previous hour only
std = df.rolling(60).std().shift(1)
z_flag = ((df - mean) / std).abs().gt(4).any(axis=1)

model = IsolationForest(n_estimators=200, random_state=42)
model.fit(train_df)                      # a period you believe is mostly normal
iso_score = -model.score_samples(df[train_df.columns])  # higher = more unusual
```

The `shift(1)` matters: without it, the anomaly itself pulls the baseline toward it and hides.

## Scoring and Thresholds

The sheet's example shows a learned normal pattern next to an unusual one, with an anomaly score of 0.92 against a threshold of 0.70, so the status is anomaly. That is the right mental model: models output a score, and a threshold turns it into a decision.

Raw scores from different models are not comparable, so normalize them (for example, to a percentile of recent scores) before applying a threshold. Then set the threshold from your **alert budget**: how many alerts per day can the team realistically investigate? Work backwards from that number. A threshold chosen for mathematical elegance that produces a hundred alerts a day will be muted within a week.

Severity tiers help. A high score on a payment API might page someone. A medium score on a reporting job can wait for a daily digest.

## Where LLMs Fit

LLMs do not replace the detector. They are poor at spotting numerical outliers in streams, and they are too slow and costly to run on every event. They are useful after detection:

* **Alert explanations.** Pass the anomaly, the contributing features, and recent context to an LLM to write a short summary: what changed, when, and what else moved at the same time.
* **Triage and grouping.** Cluster related alerts from the same incident into one message.
* **Investigation assistant.** Let an analyst ask "what deployments happened before this spike?" with an agent that queries logs and change history through tools.
* **Log anomalies.** Embeddings can turn unstructured log lines into vectors so new, never-seen error patterns stand out.

The sheet lists natural language explanations as a future enhancement. In practice it is one of the cheapest, highest-value additions, because it shortens the time from alert to understanding.

## A Minimal Tech Stack

| Layer         | Minimal choice                                  |
| ------------- | ----------------------------------------------- |
| Detection     | Scikit-learn or PyOD, TensorFlow only if needed |
| Processing    | Pandas, Polars, NumPy                           |
| Streaming     | Kafka, or scheduled batch jobs to start         |
| Storage       | PostgreSQL with TimescaleDB for time series     |
| Visualization | Grafana or Superset                             |
| Alerting      | Prometheus Alertmanager, PagerDuty, Slack       |
| Backend       | Python (FastAPI)                                |

The sheet's sample dashboard shows total events, anomalies detected, anomaly rate, alerts triggered, anomalies over time, anomalies by source, top anomaly types (spike, drop, outlier, pattern change), and a recent anomalies table with score and status. That set of panels is a good default.

## Production Concerns

**False positives.** The top reason anomaly systems get abandoned. Use better features, tune thresholds to the alert budget, and close the loop with analyst feedback.

**Concept drift.** Normal changes: new features launch, traffic grows, seasons shift. Retrain on recent data regularly and use adaptive baselines.

**Imbalanced data and no labels.** Real anomalies are rare and usually unlabeled. Start unsupervised, then move to semi-supervised models as feedback labels accumulate.

**Scalability.** Use stream processing and distributed scoring for high-volume sources, and pre-aggregate where per-event scoring is unnecessary.

**Evaluation.** Inject synthetic anomalies into historical data to measure detection rate. Track precision from analyst labels and time to detect for real incidents.

The sheet's key insight puts it well: anomaly detection is not just about finding errors, it is about discovering the unknown before it causes impact.

## Key Takeaways

* Anomaly detection is a statistics and ML problem. Start with simple baselines.
* Thresholds should come from the team's alert budget.
* Analyst feedback turns an unsupervised system into a better semi-supervised one.
* LLMs add value after detection: explanations, grouping, and investigation.

## FAQs

### Which algorithm should I start with?

A rolling z-score or seasonal baseline per metric. Add Isolation Forest when you need to look at many features together.

### How do I evaluate without labels?

Inject known anomalies into historical data, review a sample of alerts with domain experts, and track how many alerts lead to action.

### Can an LLM detect anomalies in logs?

It can help classify and summarize log patterns, and embeddings help find novel messages. For volume and reliability, keep detection in dedicated models and use the LLM for interpretation.

## Up Next

Day 18 applies these ideas to physical equipment: the AI Predictive Maintenance System, which combines sensor data, anomaly detection, and remaining useful life models to predict failures before they happen and turn predictions into work orders. If you need anomaly detection on your own data, [talk to us](/contact).
