Kafka Stream
Kafka Streams is a lightweight Java library provided by Apache Kafka that helps you process data in real time. It allows you to read data from Kafka topics, perform operations on that data, and write the results back to Kafka topics.
In simple words, Kafka Streams is used when you want to analyze, transform, or filter data as it flows through Kafka, instead of storing it first and processing it later.
Kafka Streams is mainly used for tasks like real-time analytics, monitoring, fraud detection, data transformation, and event-driven applications.
Key Features of Kafka Streams
- Real-Time Processing: Kafka Streams processes data as soon as it arrives in Kafka topics, making it ideal for real-time use cases.
- Simple Java API: It uses plain Java code. No need to learn a new framework or language.
- No Separate Cluster Required: Unlike other stream processing tools, Kafka Streams runs inside your application. You don’t need to manage a separate processing cluster.
- Scalable and Fault-Tolerant: Kafka Streams automatically scales with Kafka partitions and handles failures gracefully.
- Stateful Processing: It can store state (like counts, aggregations, or windows) locally and still remain reliable.
- Exactly-Once Processing: Kafka Streams ensures that data is processed exactly once, avoiding duplicate results.
- Seamless Kafka Integration: It works directly with Kafka topics, producers, and consumers without extra connectors.
Simple Kafka Streams Example
Let’s understand Kafka Streams with a simple example.
Use Case: Word Count
Imagine messages are coming into a Kafka topic called input-topic. Each message contains a sentence. We want to count how many times each word appears and store the result in another topic called output-topic.
How It Works
- Read messages from input-topic.
- Split sentences into words.
- Count occurrences of each word.
- Write the word count result to output-topic.
Sample Code
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream("input-topic");
textLines
.flatMapValues(value -> Arrays.asList(value.toLowerCase().split(" ")))
.groupBy((key, word) -> word)
.count()
.toStream()
.to("output-topic", Produced.with(Serdes.String(), Serdes.Long()));
In this example, Kafka Streams continuously processes data and updates the word count in real time as new messages arrive.
Where Kafka Streams Is Commonly Used
- Real-time analytics dashboards
- Fraud detection systems
- Log and event processing
- Data enrichment and transformation
- Monitoring and alerting systems
Summary
Kafka Streams is a powerful yet simple tool for real-time data processing. It allows developers to build stream-processing applications using plain Java, without managing complex infrastructure.
If you are already using Apache Kafka and want to process data as it flows, Kafka Streams is a great choice. It is fast, reliable, scalable, and easy to maintain, making it suitable for both small applications and large enterprise systems.
Frequently Asked Questions (FAQ)
Q1. What is Kafka Streams in simple words?
Kafka Streams is a Java library for processing data that flows through Kafka. Your application reads records from Kafka topics, transforms, filters, joins or aggregates them, and writes the results back to Kafka topics, continuously and in real time.
Q2. Is Kafka Streams a separate server or cluster?
No. Kafka Streams is just a library (kafka-streams) that you add to a normal Java application. You run that application like any other: on a server, in a container or in Kubernetes. The only cluster it needs is the Kafka cluster itself.
Q3. What is the difference between Kafka Streams and a normal Kafka consumer?
A consumer only reads records; you must write your own code for state, joins, windows, error recovery and scaling. Kafka Streams builds on consumers and producers and adds all of these as ready-made, fault-tolerant features with a simple, high-level API.
Q4. What is a KStream?
A KStream is an unbounded stream of independent events. Every record is a new fact, for example "user A clicked a button". If two records have the same key, both are kept and processed.
Q5. What is a KTable?
A KTable is a changelog view of a topic where each key has only its latest value, like a database table that is updated as new records arrive. For example, a table of the current address of each customer.
Q6. What is the difference between KStream and KTable?
- KStream: every record is an independent event (insert).
- KTable: a record with an existing key replaces the old value (update).
Counting page views is a stream problem; knowing each user's current balance is a table problem.
Q7. What is a GlobalKTable?
A GlobalKTable is a table whose full data is copied to every application instance, instead of being split by partitions. It is useful for small reference data, such as a list of countries or product categories, that every instance needs for lookups.
Q8. What is a topology in Kafka Streams?
A topology is the graph of processing steps in your application: sources (input topics), processors (such as filter, map, count) and sinks (output topics). You define it with StreamsBuilder, and Kafka Streams runs it for you.
Q9. What are stateless and stateful operations?
Stateless operations look at one record at a time, such as filter, map and flatMapValues. Stateful operations remember earlier records, such as count, aggregate, reduce, joins and windows.
Q10. Where does Kafka Streams keep its state?
In local state stores, by default RocksDB databases on the instance's disk. Every change is also written to an internal, compacted Kafka changelog topic, so the state can be rebuilt on another instance if one fails.
Q11. What is windowing?
Windowing groups records by time so you can aggregate them per period, for example "orders per minute". Kafka Streams supports:
- Tumbling windows: fixed, non-overlapping periods (every 1 minute).
- Hopping windows: fixed periods that overlap (5 minutes, moving every 1 minute).
- Sliding windows: based on the time difference between records.
- Session windows: periods of activity separated by gaps of inactivity.
Q12. Can Kafka Streams join data from different topics?
Yes. It supports stream-stream joins (within a time window), stream-table joins (enrich each event with the latest table value) and table-table joins. For example, you can join an orders stream with a customers table to add customer details to every order.
Q13. How does Kafka Streams scale?
Work is split into tasks, one per input partition. When you start more instances of the same application (with the same application.id), Kafka spreads the tasks across them automatically. The maximum parallelism equals the number of input partitions.
Q14. What happens if one Kafka Streams instance fails?
Its tasks are reassigned to the remaining instances. They restore any needed state from the changelog topics (or from standby replicas, if configured) and continue processing from the last committed offsets.
Q15. What is application.id?
It is the unique name of a Kafka Streams application. It is used as the consumer group ID, as the prefix of internal topic names, and for the local state directory. All instances of the same application must use the same application.id.
Q16. How do I enable exactly-once processing?
Set processing.guarantee=exactly_once_v2 in the Streams configuration. Kafka Streams then uses Kafka transactions so that reading, processing, updating state and writing results happen atomically, without duplicates, even after failures.
Q17. What are Serdes?
A Serde combines a serializer and a deserializer for one data type. Kafka Streams uses Serdes to convert keys and values between bytes and Java objects, for example Serdes.String(), Serdes.Long(), or a JSON or Avro Serde for your own classes.
Q18. How do I test a Kafka Streams application without a Kafka cluster?
Use TopologyTestDriver from the kafka-streams-test-utils library. It runs your topology in memory, lets you pipe test records into input topics and read the results from output topics, all in a fast unit test.
Q19. Can I use Kafka Streams with Spring Boot?
Yes. Spring for Apache Kafka supports Kafka Streams: add @EnableKafkaStreams, configure spring.kafka.streams.application-id and the bootstrap servers, and define your topology in a bean method that receives a StreamsBuilder. Spring starts and stops the streams for you.
Q20. When should I use Kafka Streams instead of Apache Flink or Spark?
Choose Kafka Streams when your data is in Kafka and you want stream processing inside ordinary Java applications, with no extra cluster to run. Choose Flink or Spark when you need to process data from many different sources, run very large jobs on a dedicated processing cluster, or use languages other than Java and Scala.