Kafka Streams Basics: KStream, KTable, Topology and Your First Streams App

Apache Kafka 18 min min read Updated: Nov 17, 2026 Intermediate
Kafka Streams Basics: KStream, KTable, Topology and Your First Streams App
Intermediate Topic 1 of 4

What Is Kafka Streams?

Kafka Streams is a Java library (not a server or cluster) for building applications that read from Kafka topics, process the data and write results back to Kafka. You package it inside your normal application. To scale, you start more instances of the same app.

FeatureMeaning
Library onlyNo extra cluster. Deploy like any microservice (Docker, Kubernetes)
Stateful processingCounts, joins and windows with local state stores backed by Kafka changelog topics
Fault tolerantState is rebuilt from changelog topics after a crash
Exactly-onceprocessing.guarantee=exactly_once_v2
ScalingInstances share the work through the consumer group protocol. Parallelism is limited by input partitions

KStream and KTable

KStreamKTable
ModelA stream of events (every record is a fact)A table of latest value per key (changelog)
Insert same key twiceTwo separate eventsSecond one updates the first
ExampleEvery order placed, every clickCurrent customer profile, current stock level
Kafka topicNormal topicOften a compacted topic
text topic records: (alice,10) (bob,5) (alice,20) as KStream: 3 events as KTable: alice -> 20, bob -> 5 (latest per key) Stream-table duality: a table is a stream of updates; a stream can be aggregated into a table.
TypeUse
KStream<K,V>Event processing, transformations
KTable<K,V>Partitioned state, one value per key
GlobalKTable<K,V>Small reference data fully copied to every instance (join without co-partitioning)

Project Setup

xml <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-streams</artifactId> <version>4.0.0</version> </dependency>

Example 1: Word Count

java import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.*; import org.apache.kafka.streams.kstream.*; import java.util.Arrays; import java.util.Properties; public class WordCountApp { public static void main(String[] args) { Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-app"); // also the consumer group id and state prefix 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(); KStream<String, String> lines = builder.stream("text-lines"); KTable<String, Long> counts = lines .flatMapValues(line -> Arrays.asList(line.toLowerCase().split("\\W+"))) // split into words .filter((key, word) -> !word.isBlank()) .groupBy((key, word) -> word) // re-key by word (creates repartition topic) .count(Materialized.as("word-counts-store")); // stateful: local store + changelog topic counts.toStream().to("word-counts", Produced.with(Serdes.String(), Serdes.Long())); KafkaStreams streams = new KafkaStreams(builder.build(), props); Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); // clean shutdown streams.start(); } }
bash bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic text-lines --partitions 3 bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic word-counts --partitions 3 # run the app, then: bin/kafka-console-producer.sh --bootstrap-server localhost:9092 --topic text-lines > hello kafka hello streams bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic word-counts --from-beginning \ --property print.key=true --property value.deserializer=org.apache.kafka.common.serialization.LongDeserializer # hello 2 # kafka 1 # streams 1

Stateless Operations

OperationWhat it doesExample
filter / filterNotKeep or drop recordsorders.filter((k, o) -> o.total() > 100)
mapValuesChange the value, keep the key (no repartition).mapValues(o -> o.toUpperCase())
mapChange key and value (may force repartition).map((k, v) -> KeyValue.pair(v.id(), v))
selectKeySet a new key.selectKey((k, v) -> v.customerId())
flatMapValuesOne record into zero or manysplit text into words
peekSide effect such as loggingdebugging
split / branchRoute into several streams by predicatesee below
mergeCombine streams of the same typea.merge(b)
to / throughWrite to a topic.to("out")
Prefer mapValues: Changing the key with map, selectKey or groupBy makes Streams create an internal repartition topic so records with the same new key meet in the same partition. That costs extra network and storage, so use mapValues when you do not need a new key.

Example 2: Routing Orders

java KStream<String, Order> orders = builder.stream("shop.orders.created.v1", Consumed.with(Serdes.String(), orderSerde)); orders.split(Named.as("route-")) .branch((k, o) -> o.total() >= 1000, Branched.withConsumer(s -> s.to("orders.high-value", Produced.with(Serdes.String(), orderSerde)))) .branch((k, o) -> "EU".equals(o.region()), Branched.withConsumer(s -> s.to("orders.eu", Produced.with(Serdes.String(), orderSerde)))) .defaultBranch(Branched.withConsumer(s -> s.to("orders.standard", Produced.with(Serdes.String(), orderSerde))));

Serdes

Streams needs a Serde (serializer plus deserializer) for every key and value type. Set defaults in the config, or pass them explicitly with Consumed.with, Produced.with, Grouped.with, Materialized.with. For JSON create a Serde with Jackson, for Avro or Protobuf use the Schema Registry serdes.

java Serde<Order> orderSerde = Serdes.serdeFrom(new JsonSerializer<>(), new JsonDeserializer<>(Order.class)); // your own small classes with Jackso

Topology Description

java Topology topology = builder.build(); System.out.println(topology.describe()); // Topologies: // Sub-topology: 0 // Source: KSTREAM-SOURCE-0000000000 (topics: [text-lines]) // Processor: KSTREAM-FLATMAPVALUES-... // Processor: KSTREAM-FILTER-... // Sink: KSTREAM-SINK-... (topic: word-counts-repartition)

Print the topology to see sub-topologies, state stores and repartition topics. Paste the text into a topology visualizer to get a diagram.

Important Configuration

SettingNotes
application.idUnique per application. Names the consumer group, internal topics (<app>-<store>-changelog) and state directory
num.stream.threadsThreads per instance. Total threads across all instances should not exceed the number of tasks (input partitions)
processing.guaranteeat_least_once (default) or exactly_once_v2
state.dirLocal RocksDB state location, use a persistent volume in containers
commit.interval.msHow often progress is committed and caches flushed (30000 default, 100 with exactly-once)
num.standby.replicasWarm copies of state on other instances for faster failover
default.deserialization.exception.handlerWhat to do with unreadable records: fail (default) or log and continue

Scaling and Failure

  • Streams creates one task per input partition. Tasks are spread over threads and instances
  • Start a second instance with the same application.id and work is rebalanced automatically
  • If an instance dies, its tasks move and local state is restored from the changelog topics (faster with standby replicas)
  • Create input topics before starting the app, and make sure joined topics have the same number of partitions

Conclusion

Kafka Streams is a library that turns your Java app into a scalable stream processor. KStream models events, KTable models current state per key, stateless operations (filter, mapValues, flatMapValues, split) are cheap, and key-changing operations cause repartitioning.

Quick Summary: library; KStream events vs KTable latest; mapValues cheap, key change repartitions; application.id; tasks = partitions.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators