Kafka Streams: Real-Time Stream Processing
5 min read
Welcome to the internal workings of Kafka Streams. Unlike the Kafka Brokers we discussed previously, which are effectively "storage and transport" systems, Kafka Streams is the "brain" that analyzes that data.
Let us explore how to process data in motion.
1. Kafka Streams Intro: Real-Time Processing Native to Kafka
Definition:
Kafka Streams is a client library for building applications and microservices, where the input and output data are stored in Kafka clusters.
The Problem:
In the past, processing streams of data required heavy, separate clusters (like Apache Spark or Flink). You had to maintain a Kafka cluster and a processing cluster. This introduced latency (time delay), operational complexity, and the "Dual-Cluster" problem.
The Solution:
Kafka Streams is a Java/Scala library, not a separate cluster. You write a standard Java application, import the library, and it runs. If you need to scale, you simply run more instances of your Java application. It uses the Kafka cluster itself for coordination.
Interesting Fact:
π‘ LinkedIn, the creators of Kafka, process over 2 trillion messages per day. Kafka Streams was designed to handle this scale without needing a massive external processing engine.
Getting Started (Dependencies):
To use Kafka Streams, you must add the dependency to your project.
Maven (pom.xml):
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>3.7.0</version> <!-- Always check for the latest stable version -->
</dependency>Basic Configuration:
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "my-first-streams-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
// ... logic goes here ...
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.start();2. Stateless Transformations: Map, Filter, and Split
Definition:
Stateless transformations are operations that do not require knowledge of previous events. The result depends only on the current message being processed.
The Problem:
Raw data streams are often noisy. You might receive a stream of all user logins, but you only care about successful logins from a specific region, or you need to convert JSON data into a simple String.
The Solution:
We use functional programming concepts to transform the stream.
- Filter: Discard messages that do not match a condition.
- Map/MapValues: Transform the structure of the message (e.g., lowercase to uppercase).
- Split (formerly Branch): Route messages to different places based on logic.
Example Code:
KStream<String, String> textLines = builder.stream("text-input");
// 1. Filter: Keep only lines usually longer than 5 characters
KStream<String, String> longLines = textLines.filter(
(key, value) -> value.length() > 5
);
// 2. MapValues: Convert to Uppercase
KStream<String, String> uppercased = longLines.mapValues(
value -> value.toUpperCase()
);
// 3. Split: Send error logs to one topic, success logs to another
// Note: "branch()" is deprecated. Use "split()" in modern Kafka Streams.
Map<String, KStream<String, String>> branches = textLines
.split(Named.as("log-"))
.branch((key, value) -> value.contains("ERROR"), Branched.as("error"))
.branch((key, value) -> value.contains("SUCCESS"), Branched.as("success"))
.defaultBranch(Branched.as("other"));
// branches.get("log-error").to("error-topic");3. Stateful Operations and Local State Stores (RocksDB)
Definition:
Stateful operations require remembering the past. To count how many times a user has logged in, the application must remember the previous count.
The Problem:
If your application crashes or restarts, memory is wiped. How do you remember that "Alice" had 5 clicks before the crash without querying a slow external database?
The Solution:
Kafka Streams uses State Stores. By default, it uses RocksDB, a high-performance embedded database that saves data to the local disk of your application.
- Fault Tolerance: If your machine burns down, how is the state recovered? Kafka Streams automatically backs up the State Store to a hidden internal Kafka Topic (called a "changelog topic"). When a new instance starts, it replays this topic to restore RocksDB.
Example Code (Word Count):
KStream<String, String> textLines = builder.stream("text-input");
KTable<String, Long> wordCounts = textLines
.flatMapValues(text -> Arrays.asList(text.toLowerCase().split("\\W+")))
.groupBy((key, word) -> word) // Group by the word itself
.count(); // STATEFUL operation: requires a State Store
wordCounts.toStream().to("word-count-output", Produced.with(Serdes.String(), Serdes.Long()));π Note: Stateful operations (
count,reduce,aggregate) requiregroupByorgroupByKeyfirst to ensure data partitioning is correct.
4. Stream-Table Duality: KStream vs. KTable
Definition:
This is the central philosophy of Kafka Streams.
- KStream: Represents a flow of events (facts).
- KTable: Represents the current state (snapshot).
The Problem:
Developers often struggle to decide whether to view data as a series of actions or a current status.
The Solution:
Kafka treats them as two sides of the same coin (Duality).
- Stream as Table: If you replay all changes in a stream from the beginning, you get a Table.
- Table as Stream: If you capture every change made to a table, you get a Stream.
| Feature | KStream (Event) | KTable (State) |
|---|---|---|
| Analogy | A Ledger of transactions | A Bank Balance |
| Data Nature | Infinite, immutable history | Current snapshot at a point in time |
| Handling Null | Just another record | null value deletes the key (Tombstone) |
| Example | "Alice sent 2" | "Alice has $7" |
Visual Imagination:
Imagine a chess game.
- KStream: The list of moves written on paper (e4, e5, Nf3...).
- KTable: The board as it looks right now.
5. Time is Relative: Windowing and Aggregations
Definition:
Windowing allows you to group events together based on time.
The Problem:
A stream never ends. You cannot calculate the "sum of all clicks" because the clicks keep coming. You can only calculate "sum of clicks per hour."
The Solution:
Kafka Streams provides several window types to slice time:
- Tumbling Window: Fixed size, non-overlapping.
- Example: "Number of clicks every 5 minutes." (00:00-00:05, 00:05-00:10).
- Hopping Window: Fixed size, overlapping.
- Example: "Every minute, give me the count of the last 5 minutes."
- Session Window: Based on activity gaps.
- Example: "Group clicks until the user stops clicking for 30 minutes." (Useful for user behavior tracking).
Example Code (Tumbling Window):
// Count clicks per user, in 1-minute windows
KTable<Windowed<String>, Long> windowedCounts = clicks
.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(1)))
.count();Time Semantics:
- Event Time: When the event actually happened (timestamp inside the message). Preferred.
- Processing Time: When the server received the message.
Reference & Further Reading
- Official Kafka Streams Documentation π
- Kafka Streams Architecture ποΈ
- Developer Guide: DSL π»
Pro Tip: In production, always monitor your "Consumer Lag". If your processing logic is too complex (slow), your stream application will fall behind the producer, and latency will skyrocket. π’ -> π
Challenge
Kafka Streams: Windowed User Activity Counter
You are tasked with building a real-time analytics pipeline using Kafka Streams. Your application will process a stream of user click events from a Kafka topic named user-clicks-topic.
The incoming messages are key-value pairs where the key is the userId (String) and the value is the pageUrl (String) the user visited.
Your goal is to implement a stream processing topology that counts the number of clicks for each user within fixed, non-overlapping 5-minute windows. However, you must exclude any clicks to the /login page from your count.
Requirements:
- Consume the
KStream<String, String>from theuser-clicks-topic. - Apply a stateless transformation to filter out any records where the
pageUrlvalue is"/login". - Group the filtered stream by the existing message key (
userId). - Apply a stateful, windowed aggregation to count the occurrences for each key.
- The windowing strategy must be a tumbling window with a duration of 5 minutes.
- The final output of your topology should be a
KTablewhere the key is the windowed user ID (Windowed<String>) and the value is the click count (Long).
Expected result
Your solution should be a completed Java method that correctly implements the Kafka Streams topology. The code must:
- Chain the appropriate methods on the initial
KStreamobject. - Use the
filter()method to exclude records. - Use the
groupByKey()method for partitioning the data before aggregation. - Use the
windowedBy()method, specifically withTimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5))to create the 5-minute tumbling windows. - Use the
count()method to perform the final stateful aggregation. - Return the resulting
KTable<Windowed<String>, Long>. No other supporting classes or main methods are needed.