Dec 3, 2026

Anomaly detection with Apache Kafka® Streams on Aiven Runtime

Find outlier messages in Apache Kafka® topics with an editable Kafka Streams template, deploy it on Aiven Runtime, and get some pointers on windows and state.

Tibs (Tony Ibbs) |

RSS Feed

Product Advocate at Aiven

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.

If you have not written Java since before streams existed, Cay Horstmann's Core Java for the Impatient covers streams very clearly, with the section on lambda expressions especially helpful.

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 peek call logs each message. It's useful during development, but should be dropped in production.
  • The outsideBounds method is given the current message (value), extracts the field named by fieldName, and checks its value against the minimum and maximum bounds. It returns true if that value is out of bounds.
  • filter keeps the messages for which the test returns true, the anomalies, and to passes 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:

  1. Fork the repository. Runtime deploys from a GitHub account connected to your Aiven organization.

  2. Create an Aiven for Apache Kafka service with the Karapace schema registry enabled. The free and developer tiers both work.

  3. Create the topics metric_data and anomaly_data.

  4. Run produce_avro.py to write 500 sample messages with a temperature field.

  5. In the Aiven Console, open Runtime, choose Deploy application, select your fork, pick the compose.aiven.yaml manifest 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.

  6. 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:

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