Home

Awesome

Kafka Streams Examples

This project contains code examples that demonstrate how to implement real-time applications and event-driven microservices using the Streams API of Apache Kafka aka Kafka Streams.

For more information take a look at the latest Confluent documentation on the Kafka Streams API, notably the Developer Guide


Table of Contents


<a name="available-examples"/>

Available examples

This repository has several branches to help you find the correct code examples for the version of Apache Kafka and/or Confluent Platform that you are using. See Version Compatibility Matrix below for details.

There are three kinds of examples:

<a name="examples-apps"/>

Examples: Runnable Applications

Additional examples may be found under src/main/.

Application NameConcepts usedJava 8+Java 7+Scala
WordCountDSL, aggregation, statefulJava 8+ exampleScala Example
MapFunctionDSL, stateless transformations, map()Java 8+ exampleScala Example
SessionWindowsSessionization of user events, user behavior analysisJava 7+ example
GlobalKTablejoin() between KStream and GlobalKTableJava 8+ example
GlobalStore"join" between KStream and GlobalStoreJava 8+ example
PageViewRegionjoin() between KStream and KTableJava 8+ exampleJava 7+ example
PageViewRegionGenericAvroWorking with data in Generic Avro formatJava 8+ exampleJava 7+ example
WikipediaFeedSpecificAvroWorking with data in Specific Avro formatJava 8+ exampleJava 7+ example
SecureKafkaStreamsSecure, encryption, client authenticationJava 7+ example
SumDSL, stateful transformations, reduce()Java 8+ example
WordCountInteractiveQueriesInteractive Queries, REST, RPCJava 8+ example
KafkaMusicInteractive Queries, State Stores, REST APIJava 8+ example
ApplicationResetApplication Reset Tool kafka-streams-application-resetJava 8+ example
MicroserviceMicroservice ecosystem, state stores, dynamic routing, joins, filtering, branching, stateful operationsJava 8+ example
<a name="examples-unit-tests"/>

Examples: Unit Tests

The stream processing of Kafka Streams can be unit tested with the TopologyTestDriver from the org.apache.kafka:kafka-streams-test-utils artifact. The test driver allows you to write sample input into your processing topology and validate its output.

See the documentation at Testing Streams Code.

<a name="examples-integration-tests"/>

Examples: Integration Tests

We also provide several integration tests, which demonstrate end-to-end data pipelines. Here, we spawn embedded Kafka clusters and the Confluent Schema Registry, feed input data to them (using the standard Kafka producer client), process the data using Kafka Streams, and finally read and verify the output results (using the standard Kafka consumer client).

Additional examples may be found under src/test/.

Tip: Run mvn test to launch the tests.

Integration Test NameConcepts usedJava 8+Java 7+Scala
WordCountDSL, aggregation, statefulJava 8+ ExampleScala Example
WordCountInteractiveQueriesInteractive Queries, REST, RPCJava 7+ Example
AggregateDSL, groupBy(), aggregate()Java 8+ ExampleScala Example
CustomStreamTableJoinDSL, Processor API, TransformersJava 8+ Example
EventDeduplicationDSL, Processor API, TransformersJava 8+ Example
GlobalKTableDSL, global stateJava 7+ Example
GlobalStoreDSL, global state, TransformersJava 7+ Example
HandlingCorruptedInputRecordsDSL, flatMap()Java 8+ Example
KafkaMusic (Interactive Queries)Interactive Queries, State Stores, REST APIJava 7+ Example
MapFunctionDSL, stateless transformations, map()Java 8+ Example
MixAndMatch DSL + Processor APIIntegrating DSL and Processor APIJava 8+ Example
PassThroughDSL, stream(), to()Java 7+ Example
PoisonPillDSL, flatMap()Java 8+ Example
ProbabilisticCounting***DSL, Processor API, custom state storesScala Example
Reduce (Concatenate)DSL, groupByKey(), reduce()Java 8+ ExampleScala Example
SessionWindowsDSL, windowed aggregation, sessionizationJava 7+ Example
StatesStoresDSLDSL, Processor API, TransformersJava 8+ Example
StreamToStreamJoinDSL, join() between KStream and KStreamJava 7+ Example
StreamToTableJoinDSL, join() between KStream and KTableJava 7+ ExampleScala Example
SumDSL, aggregation, stateful, reduce()Java 8+ Example
TableToTableJoinDSL, join() between KTable and KTableJava 7+ Example
UserCountsPerRegionDSL, aggregation, stateful, count()Java 8+ Example
ValidateStateWithInteractiveQueriesInteractive Queries for validating stateJava 8+ Example
GenericAvroWorking with data in Generic Avro formatJava 7+ ExampleScala Example
SpecificAvroWorking with data in Specific Avro formatJava 7+ ExampleScala Example

***demonstrates how to probabilistically count items in an input stream by implementing a custom state store (CMSStore) that is backed by a Count-Min Sketch data structure (with the CMS implementation of Twitter Algebird)

<a name="examples-docker"/>

Docker Example: Kafka Music demo application

This containerized example launches:

The Kafka Music application demonstrates how to build of a simple music charts application that continuously computes, in real-time, the latest charts such as latest Top 5 songs per music genre. It exposes its latest processing results -- the latest charts -- via Kafka’s Interactive Queries feature via a REST API. The application's input data is in Avro format, hence the use of Confluent Schema Registry, and comes from two sources: a stream of play events (think: "song X was played") and a stream of song metadata ("song X was written by artist Y").

You can find detailed documentation at https://docs.confluent.io/current/streams/kafka-streams-examples/docs/index.html.

<a name="event-streaming-platform"/>

Examples: Event Streaming Platform

For additional examples that showcase Kafka Streams applications within an event streaming platform, please refer to the examples GitHub repository.

<a name="requirements"/>

Requirements

<a name="requirements-kafka"/>

Apache Kafka

The code in this repository requires Apache Kafka 0.10+ because from this point onwards Kafka includes its Kafka Streams library. See Version Compatibility Matrix for further details, as different branches of this repository may have different Kafka requirements.

For the master branch: To build a development version, you typically need the latest trunk version of Apache Kafka (cf. kafka.version in pom.xml for details). The following instructions will build and locally install the latest trunk Kafka version:

$ git clone git@github.com:apache/kafka.git
$ cd kafka
$ git checkout trunk

# Now build and install Kafka locally
$ ./gradlew clean && ./gradlewAll install
<a name="requirements-confluent-platform"/>

Confluent Platform

The code in this repository requires Confluent Schema Registry. See Version Compatibility Matrix for further details, as different branches of this repository have different Confluent Platform requirements.

For the master branch: To build a development version, you typically need the latest master version of Confluent Platform's Schema Registry (cf. confluent.version in pom.xml, which is set by the upstream Confluent Common project). The following instructions will build and locally install the latest master Schema Registry version, which includes building its dependencies such as Confluent Common and Confluent Rest Utils. Please read the Schema Registry README for details.

$ git clone https://github.com/confluentinc/common.git
$ cd common
$ git checkout master

# Build and install common locally
$ mvn -DskipTests=true clean install

$ git clone https://github.com/confluentinc/rest-utils.git
$ cd rest-utils
$ git checkout master

# Build and install rest-utils locally
$ mvn -DskipTests=true clean install

$ git clone https://github.com/confluentinc/schema-registry.git
$ cd schema-registry
$ git checkout master

# Now build and install schema-registry locally
$ mvn -DskipTests=true clean install

Also, each example states its exact requirements at the very top.

<a name="requirements-ide"/>

Using IntelliJ or Eclipse

If you are using an IDE and import the project you might end up with a "missing import / class not found" error. Some Avro classes are generated from schema files and IDEs sometimes do not generate these classes automatically. To resolve this error, manually run:

$ mvn -Dskip.tests=true compile

If you are using Eclipse, you can also right-click on pom.xml file and choose Run As > Maven generate-sources.

<a name="requirements-java"/>

Java 8+

Some code examples require Java 8+, primarily because of the usage of lambda expressions.

IntelliJ IDEA users:

<a name="requirements-scala"/>

Scala

Scala is required only for the Scala examples in this repository. If you are a Java developer you can safely ignore this section.

If you want to experiment with the Scala examples in this repository, you need a version of Scala that supports Java 8 and SAM / Java lambda (e.g. Scala 2.11 with -Xexperimental compiler flag, or 2.12).

If you are compiling with Java 9+, you'll need to have Scala version 2.12+ to be compatible with the Java version.

<a name="packaging-and-running"/>

Packaging and running the Application Examples

The instructions in this section are only needed if you want to interactively test-drive the application examples under src/main/.

Tip: If you only want to run the integration tests (mvn test), then you do not need to package or install anything -- just run mvn test. These tests launch embedded Kafka clusters.

The first step is to install and run a Kafka cluster, which must consist of at least one Kafka broker as well as at least one ZooKeeper instance. Some examples may also require a running instance of Confluent schema registry. The Confluent Platform Quickstart guide provides the full details.

In a nutshell:

# Ensure you have downloaded and installed Confluent Platform as per the Quickstart instructions above.

# Start ZooKeeper
$ ./bin/zookeeper-server-start ./etc/kafka/zookeeper.properties

# In a separate terminal, start Kafka broker
$ ./bin/kafka-server-start ./etc/kafka/server.properties

# In a separate terminal, start Confluent Schema Registry
$ ./bin/schema-registry-start ./etc/schema-registry/schema-registry.properties

# Again, please refer to the Confluent Platform Quickstart for details such as
# how to download Confluent Platform, how to stop the above three services, etc.

The next step is to create a standalone jar ("fat jar") of the application examples:

# Create a standalone jar ("fat jar")
$ mvn clean package

# >>> Creates target/kafka-streams-examples-8.0.0-0-standalone.jar

Tip: If needed, you can disable the test suite during packaging, for example to speed up the packaging or to lower JVM memory usage:

$ mvn -DskipTests=true clean package

You can now run the application examples as follows:

# Run an example application from the standalone jar. Here: `WordCountLambdaExample`
$ java -cp target/kafka-streams-examples-8.0.0-0-standalone.jar \
  io.confluent.examples.streams.WordCountLambdaExample

The application will try to read from the specified input topic (in the above example it is streams-plaintext-input), execute the processing logic, and then try to write back to the specified output topic (in the above example it is streams-wordcount-output). In order to observe the expected output stream, you will need to start a console producer to send messages into the input topic and start a console consumer to continuously read from the output topic. More details in how to run the examples can be found in the java docs of each example code.

If you want to turn on log4j while running your example application, you can edit the log4j.properties file and then execute as follows:

# Run an example application from the standalone jar. Here: `WordCountLambdaExample`
$ java -cp target/kafka-streams-examples-8.0.0-0-standalone.jar \
  -Dlog4j.configuration=file:src/main/resources/log4j.properties \
  io.confluent.examples.streams.WordCountLambdaExample

Keep in mind that the machine on which you run the command above must have access to the Kafka/ZooKeeper clusters you configured in the code examples. By default, the code examples assume the Kafka cluster is accessible via localhost:9092 (aka Kafka's bootstrap.servers parameter) and the ZooKeeper ensemble via localhost:2181. You can override the default bootstrap.servers parameter through a command line argument.

<a name="development"/>

Development

This project uses the standard maven lifecycle and commands such as:

$ mvn compile # This also generates Java classes from the Avro schemas
$ mvn test    # Runs unit and integration tests
$ mvn package # Packages the application examples into a standalone jar
<a name="version-compatibility"/>

Version Compatibility Matrix

Branch (this repo)Confluent PlatformApache Kafka
5.4.x*5.4.0-SNAPSHOT2.4.0-SNAPSHOT
5.3.0-post5.3.02.3.0
5.2.2-post5.2.22.2.1
5.2.1-post5.2.12.2.1
5.1.0-post5.1.02.1.0
5.0.0-post5.0.02.0.0
4.1.0-post4.1.01.1.0
4.0.0-post4.0.01.0.0
3.3.0-post3.3.00.11.0

*You must manually build the 2.3 version of Apache Kafka and the 5.3.x version of Confluent Platform. See instructions above.

The master branch of this repository represents active development, and may require additional steps on your side to make it compile. Check this README as well as pom.xml for any such information.

<a name="help"/>

Where to find help

License

Usage of this image is subject to the license terms of the software contained within. Please refer to Confluent's Docker images documentation reference for further information. The software to extend and build the custom Docker images is available under the Apache 2.0 License.