Rok Zabukovec
All projects

ActivityReporter

Origin
Personal project
Status
In progress
Stack
Python, Kafka, Flink, ClickHouse, Prometheus, Grafana, Docker Compose
Outcome
114/116 labelled anomalies found by MAD · 108/116 by EWMA

Overview

A streaming pipeline that scores numerical metrics for anomalies as they arrive, on Kafka, Flink and ClickHouse. A labelled benchmark tests the two detectors. The write-up records each decision that the benchmark forced.

  1. 01 Agent

    Exposes machine metrics over an HTTP API.

  2. 02 Collector

    Scrapes every target each second and validates the result.

  3. 03 Kafka

    The queue between every step: raw metrics, machines and evaluations.

  4. 04 Flink

    Scores every value with MAD and EWMA.

  5. 05 ClickHouse writer

    Writes rows in batches, then commits the offsets.

  6. 06 ClickHouse

    Stores each value beside its score.

  7. 07 Observability

    Grafana draws the bands. Prometheus watches every part.

About

ActivityReporter processes numerical time series as a stream and scores every value for anomalies with simple statistical algorithms. The stack is Python, Kafka for messaging, Flink for stream processing, and ClickHouse as the time-series store.

It has two detectors today, MAD and EWMA. Machine-learning detectors are in development. Every component exposes Prometheus metrics, and Grafana dashboards show the results.

Architecture

Agent

The pipeline accepts any numerical metric. For development and tests it includes an agent process that exposes an API with basic machine metrics: CPU usage, memory usage and uptime. A second endpoint returns stable machine information: hostname, OS and version, architecture, CPU and core count, total memory, total disk and last boot.

Collector

The collector holds the list of targets and calls each agent’s API in a loop, with a fixed 1-second gap between rounds. A scrape interval for each target would be better, but configuration was not a priority yet. The collector adds an idempotency key and the pipeline start timestamp to each result.

Kafka

The collector validates each scrape result against a contract. An invalid result goes to a dead-letter topic, where it can be examined and replayed. A valid result is split into separate metric values. The collector writes to two topics: raw_metrics gets one message per metric value, and machines gets the stable machine information every 5 minutes. Each topic has a _dlq twin for invalid input. Flink writes the third topic, evaluations.

Kafka is the backbone of the whole thing. It decouples collecting from scoring and scoring from storing, so each part can be down, restarted or replayed without losing data. To be honest, for a few home machines this is more than needed, but learning Kafka was one of the goals of the project.

The Flink job reads raw_metrics and keys the stream by series, which is the pair of machine id and metric name. For every series it keeps the last 20 values in state and runs both detectors on every new value. The output is one evaluation per value per algorithm, anomalous or not, with the baseline, the lower and upper band and the anomaly flag. Evaluations go to the evaluations topic.

The job runs in Application Mode, so the jobmanager starts it by itself when the container starts. Same as Kafka, Flink is here mostly as a learning goal. A plain Kafka consumer would do the job at this scale.

Algorithms

MAD (median absolute deviation) looks at how far the value is from the median of the window, measured in the typical spread of the window. It flags in both directions and needs 20 values before it starts scoring.

EWMA (exponentially weighted moving average) looks at how far the value rises above a moving average. It flags only rises and needs 11 values.

On their own, both algorithms flag tiny steps on a series that barely moves. A CPU that sits at 2% and jumps to 3% is not an anomaly. That is why CPU and memory have a minimum deviation: CPU needs to move at least 10 percentage points, memory at least 2% of its level. Adding a new algorithm means writing one class and adding it to the detector list. The table and the dashboard stay the same.

ClickHouse writer

The writer is one process with one sink per topic: metrics, evaluations and machines. Each sink runs on its own thread, collects rows into batches and commits the Kafka offsets only after the batch is written to ClickHouse. If the writer dies in the middle of a batch, the batch is read again and written again. Duplicates are not a problem, because all tables are ReplacingMergeTree and collapse the repeated rows into one on merge.

ClickHouse

There are three tables:

  • metrics: one row per value, as the agent reported it.
  • evaluations: one row per value per algorithm, linked to the metric by metric_id. A new algorithm is a new value in the algorithm column, not a schema change.
  • machines: the latest description of each machine.

The schema is versioned with golang-migrate migrations. The project actually started on TimescaleDB, but it moved to ClickHouse early on.

Observability

Every component exposes Prometheus metrics: messages published, rows written, dead-letter counts and pipeline timings. Grafana has two provisioned dashboards. The first one is a metrics explorer, where you pick a host and see its series with the bands and the anomalies drawn on top. The second one shows the performance of the pipeline itself.

Benchmarking with NAB

Live metrics from my own machines are not enough to tell if a detector works. Nobody labelled them, so I don’t know where the real anomalies are. For that I used the Numenta Anomaly Benchmark (NAB): 58 series, about 365,000 values and 116 labelled anomaly windows, from AWS CloudWatch metrics and NYC taxi demand to Twitter volume.

There are two ways to run it:

  • replay.py publishes the whole corpus to Kafka, shifted so that it ends “now”, and the data goes through the real pipeline: Kafka, Flink, writer and ClickHouse. Publishing takes about 38 seconds, writing the metrics into ClickHouse about 4.5 minutes.
  • score.py runs the same detector classes offline, without Kafka or Flink, in about 10 seconds.

The offline scorer turned out to be the most useful tool in the project. It gives the same result every time, it is fast, and I check it with two fake detectors: “always flag” must hit 116 of 116 windows and “never flag” must hit 0. Note that a window counts as hit when any flag falls inside it, so this is not the official NAB score, which also rewards early detection.

The current numbers, with a window of 20 values:

Detector Windows hit Flagged outside a window
MAD 114 of 116 (98%) 6.0%
EWMA 108 of 116 (93%) 4.7%

Recall is good. False positives are now the weak point: about 5 to 6% of all scored values are flagged where NAB says nothing happened.

Decisions

Most of the interesting work was not writing new features, but finding out why something that worked on live data broke on NAB. I kept a note for each decision. These are the main ones.

Partitioning ClickHouse tables

The tables were partitioned by hour of the event time, with a 24-hour TTL. It looked right for live data: 24 small partitions and the TTL drops one whole hour at a time.

Then I loaded about 38,000 NAB rows and ClickHouse ran out of memory. Every query, insert and merge failed. system.parts showed 16,059 active parts for 38,000 rows, so 2 to 3 rows per part. The reason: NAB keeps its original timestamps from 2013 to 2015 and one file covers weeks of data. Every writer batch touched hundreds of hourly partitions, ClickHouse writes one part per partition per insert, and it never merges parts across partitions. Each part has a fixed memory cost, and together they used the whole 2 GB container.

Raising the memory limit would only hide it, and bigger batches would still split into the same partitions. I switched to daily partitions, which gave about 24 times fewer partitions.

The second problem came right after. The replay shifts all series to end “now”, so they start about a month back, and the 24-hour TTL deleted everything but the last day. I could not debug the whole dataset. I removed the TTL, and since the hourly partitions were still on my local stack, ClickHouse ran out of memory again, this time with 8,713 parts. Locally I went to monthly partitions, and the whole corpus ended up in 32 parts. The repository today partitions by day and keeps no TTL.

Lesson: the partition key is a physical storage decision, not a query filter. And a partition key and a TTL belong together. If you change one, check the other.

Sizing the detection window

The window was originally the last hour of event time. On live data with a value every few seconds, that is hundreds of values. On NAB, MAD detected 0 of 116 anomalies.

Most NAB series have one value every 5 minutes, so one hour holds 12 values, and MAD needs 20. Series with 30- or 60-minute intervals had 1 or 2 values in the window and were never scored at all. The window was set in time, but the detectors need a count of values, and the sample interval belongs to the source, not to the job.

I changed the window to the last 360 values (one hour of live data, so live behaviour stayed the same). MAD went from 0 to 103 of 116 windows, EWMA from 85 to 98. On the way I also found that EWMA divided by zero on a perfectly flat series, which would crash the Flink job.

Later I lowered the window to 20 values. 360 values covers 15 days of an hourly series, which is longer than the 7 days Kafka keeps data by default, so after a restart the window would never fill up again. I expected a less stable baseline with only 20 values, but the NAB run showed the opposite: MAD went to 114 and EWMA to 108 of 116 windows. I only tested 20 and 360, so 20 is not proven to be the best size, it is just better than 360 on this corpus.

The job saved its state every second, while the data came in much slower, so most checkpoints saved nothing new. Worse, Flink tolerates zero failed checkpoints by default, so one slow checkpoint failed the whole job. I moved to a 10-second interval and allowed 3 failed checkpoints. The checkpointing mode stays EXACTLY_ONCE, because a replayed value must not enter the window twice. The Kafka sink on the other hand is AT_LEAST_ONCE. Exactly-once there would need a transactional sink and read_committed consumers, and ClickHouse already deduplicates.

Removing the watermarks

The job had a watermark strategy with 5 seconds of out-of-orderness and a Python timestamp assigner. When I asked which operator uses it, the answer was none. There is no window, no timer, nothing reads the event time. On top of that, a record with a bad timestamp failed the task and the restart strategy replayed the same record forever. I removed it. I know now when I would add it back: for comparisons by time (“same hour yesterday”), reordering late records, or an alert when a series goes silent.

What’s next

  • Fewer false positives. Tune the thresholds against the NAB score, and run the official NAB scorer to compare with published results.
  • ML detectors. The statistical ones are the baseline the ML approaches will have to beat.
  • Alerting. Anomalies are only visible on the dashboard.
  • Anomaly episodes. Each anomalous value is its own row. Consecutive ones should be grouped into one event.
  • Downsampling. Without a TTL, rows are kept at full resolution forever and the disk use grows without limit.
  • Limit the Flink restart strategy, so one bad record can’t restart the job forever.
  • Authentication on the agent and secrets outside the compose file.