What is anomaly detection?
Anomaly detection is identifying data that is unexpected or unwanted.
For instance:
- A point anomaly is a single data point that is outside the expected normal range. For instance, an unexpectedly large temperature.
- A contextual anomaly is data points that don't fit the current context. For instance a temperature reading that is normal in summer but not in winter.
- A collective anomaly is a related collection of data points that are abnormal when taken together. For instance, a continuous long period of slightly raised temperatures, or an unexpected pattern of temperatures over a network of devices.
Anomaly detection and Apache Kafka® Streams
In Deploying Apache Kafka® Streams next to your data I introduced the use of Kafka Streams to filter streaming data - to look at individual messages and decide whether to send them (or an amended version of them) to another topic.
This idea readily extends itself to anomaly detection, and I created a separate repository specifically for demonstrating that, at anomaly-detection-example.
- It provides a single example application, checking for an integer value being within a specified range (the example takes this as the temperature of a freezer). This is point anomaly detection, which is the simplest of the anomaly types.
- It takes the name of a value and a range, and copies any messages where that value is out of range into an "anomaly" topic.
- Like the general example, it works with Avro messages that use the Confluent Wire format.
- A Python script is provided to generate sample data.
Why is it a template?
Actual anomaly detection is necessarily specific to a particular purpose, so it's not practical to provide a generalised "one size fits all" solution using Kafka Streams - at least not without creating a configuration language to describe anomalies and the actions to take. At which point you've got a new language to learn, and you have to hope it actually covers all the cases you care about. Writing just the code you need in Java is more direct.
Instead, the anomaly detection template provides the common code, the generic parts you need for any program like this: setting up the Avro Serdes and the streams, handling command line arguments, defining the build infrastructure, and making sure it all works with Docker and other container based systems, including Aiven Runtime.
To demonstrate that it can actually be useful, it also contains a point anomaly demonstration, checking for out-of-bound temperatures.
How is this different from kafka-streams-example?
The kafka-streams-example introduced in the "Deploying Kafka Streams" article is intended to teach the mechanics of using Kafka Streams. As such, it provides increasingly complex examples that log, copy and filter Avro messages using generic and specific Serdes.
The anomaly detection example is focussed on this one use case, without the "extras".
Use the first to learn about Kafka Streams in general, use the second to start implementing an actual anomaly detector.
What the template does
The application reads Avro messages that use the Confluent Wire format, and looks the message schema up in a Karapace schema registry. It checks one named field of type int or long against a minimum and a maximum. A message goes to the output topic when its value is below the minimum, above the maximum, null, or not the expected type.
The core of the stream processing is as follows (taken from
AnomalyDetectorApp.java):
sourceStream .peek((key, value) -> log.info("LOOKING AT: Value='{}'", value)) .filter((key, value) -> outsideBounds(value, fieldName, minBound, maxBound)) .to(outputTopic, Produced.with(Serdes.String(), avroMessageSerde));
- The
peekcall logs each message. It's useful during development, but should be dropped in production. - The
outsideBoundsmethod is given the current message (value), extracts the field named byfieldName, and checks its value against the minimum and maximum bounds. It returnstrueif that value is out of bounds. filterkeeps the messages for which the test returnstrue, the anomalies, andtopasses them on to the output topic.
Deploy it on Runtime
The README explains in detail how to run the application in a variety of ways, including deploying it on Aiven Runtime.
In summary:
-
Fork the repository. Runtime deploys from a GitHub account connected to your Aiven organization.
-
Create an Aiven for Apache Kafka service with the Karapace schema registry enabled. The free and developer tiers both work.
-
Create the topics
metric_dataandanomaly_data. -
Run
produce_avro.pyto write 500 sample messages with atemperaturefield. -
In the Aiven Console, open Runtime, choose Deploy application, select your fork, pick the
compose.aiven.yamlmanifest and click Scan. Link the Kafka service, then edit the application environment variables.-
Set the following:
INPUT_TOPIC=metric_data OUTPUT_TOPIC=anomaly_data FIELD_NAME=temperature MIN_BOUND=-50 MAX_BOUND=-30 -
Add the
SCHEMA_REGISTRY_host, port and password from the Schema registry tab on your Kafka service, and mark the password as a secret.
-
-
Click Deploy.
The runtime logs show each message the application examines, and what decisions the outsideBounds method makes.
To see the "bad" messages, open the anomaly_data topic in the console, set the format to avro and fetch messages: you should see all the readings outside the range -50 to -30.
Going further: Windows and state
Range checks work for point anomalies, and with added configuration to give the context can work for finding contextual anomalies, but collective anomalies need more information. Catching "this sensor drifted over the last ten minutes" needs a record of past events.
I found Confluent's tutorial on sliding windows with Kafka Streams to be an interesting starting point. The latter part talks specifically about running a Confluent service, but the same principles apply.
By default, Kafka Streams keeps such state in RocksDB on local disk and backs it up to a changelog topic in Kafka. After a crash, the application rebuilds the local copy from the changelog, and a large store takes a while to rebuild. It can be an advantage to move the state store out of the application, for instance into Aiven for Valkey™ or Aiven for PostgreSQL®. This does have a cost in increased latency, and connection handling needs care, but it also takes advantage of the Runtime application being in the same project network as the database.
That's definitely beyond the scope of this blog post, but I think the
following are useful starting points for more investigation:
-
Managing State in Kafka Streams with RocksDB, Redis, and External Databases looks at handling this explicitly, by caching to the external store in the user (streams) code.
-
Integrating External Databases as State Stores in Kafka Streams: Hands-On Examples goes further and looks at getting Kafka Streams itself to use an external store instead of RocksDB.
Other approaches
Sometimes real-time anomaly detection is not actually necessary.
For observability, see Observability is a data problem.
It shows how to use Kafka, ClickHouse® and OpenSearch® together to manage metrics, logs and traces - key forms of data where anomaly detection matters, but an analytics approach, with its ability to form complex queries, pays off.
Try it
Fork the repository, deploy it against a free or developer tier Aiven for Apache Kafka service, and run the sample data through it. Then try changing the outsideBounds method and look for different anomalies.
The Kafka Streams DSL documentation lists all streams operations, and I recommend it.
Get building: Deploy Kafka Streams on Aiven Runtime

