---
title: Streams DSL
description: Kafka Streams DSL API for defining stream processing logic.
weight: 3
tags: ['kafka', 'docs']
aliases:
keywords:
type: docs
---
The Kafka Streams DSL (Domain Specific Language) is built on top of the Streams Processor API. It is recommended for most users, especially beginners. Most data processing operations can be expressed in just a few lines of DSL code.
* Aggregating
* Joining
* Join co-partitioning requirements
* KStream-KStream Join
* KTable-KTable Equi-Join
* KTable-KTable Foreign-Key Join
* KStream-KTable Join
* KStream-GlobalKTable Join
* Windowing
* Hopping time windows
* Tumbling time windows
* Sliding time windows
* Session Windows
* Window Final Results
* Applying processors (Processor API integration)
* Transformers removal and migration to processors
* Naming Operators in a Streams DSL application
* Controlling KTable update rate
* Using timestamp-based semantics for table processors
* Writing streams back to Kafka
* Testing a Streams application
* Kafka Streams DSL for Scala
* Sample Usage
* Implicit Serdes
* User-Defined Serdes
# Overview
In comparison to the [Processor API](../processor-api#streams-developer-guide-processor-api), only the DSL supports:
* Built-in abstractions for [streams and tables](../../core-concepts#streams_concepts_duality) in the form of KStream, KTable, and GlobalKTable. Having first-class support for streams and tables is crucial because, in practice, most use cases require not just either streams or databases/tables, but a combination of both. For example, if your use case is to create a customer 360-degree view that is updated in real-time, what your application will be doing is transforming many input _streams_ of customer-related events into an output _table_ that contains a continuously updated 360-degree view of your customers.
* Declarative, functional programming style with stateless transformations (e.g. `map` and `filter`) as well as stateful transformations such as aggregations (e.g. `count` and `reduce`), joins (e.g. `leftJoin`), and windowing (e.g. session windows).
With the DSL, you can define [processor topologies](../../core-concepts#streams_topology) (i.e., the logical processing plan) in your application. The steps to accomplish this are:
1. Specify one or more input streams that are read from Kafka topics.
2. Compose transformations on these streams.
3. Write the resulting output streams back to Kafka topics, or expose the processing results of your application directly to other applications through [interactive queries](../interactive-queries#streams-developer-guide-interactive-queries) (e.g., via a REST API).
After the application is run, the defined processor topologies are continuously executed (i.e., the processing plan is put into action). A step-by-step guide for writing a stream processing application using the DSL is provided below.
For a complete list of available API functionality, see also the [Streams](/{version}/javadoc/org/apache/kafka/streams/package-summary.html) API docs.
### KStream
Only the **Kafka Streams DSL** has the notion of a `KStream`.
A **KStream** is an abstraction of a **record stream** , where each data record represents a self-contained datum in the unbounded data set. Using the table analogy, data records in a record stream are always interpreted as an "INSERT" \-- think: adding more entries to an append-only ledger -- because no record replaces an existing row with the same key. Examples are a credit card transaction, a page view event, or a server log entry.
To illustrate, let's imagine the following two data records are being sent to the stream:
("alice", 1) --> ("alice", 3)
If your stream processing application were to sum the values per user, it would return `4` for `alice`. Why? Because the second data record would not be considered an update of the previous record. Compare this behavior of KStream to `KTable` below, which would return `3` for `alice`.
### KTable
Only the **Kafka Streams DSL** has the notion of a `KTable`.
A **KTable** is an abstraction of a **changelog stream** , where each data record represents an update. More precisely, the value in a data record is interpreted as an "UPDATE" of the last value for the same record key, if any (if a corresponding key doesn't exist yet, the update will be considered an INSERT). Using the table analogy, a data record in a changelog stream is interpreted as an UPSERT aka INSERT/UPDATE because any existing row with the same key is overwritten. Also, `null` values are interpreted in a special way: a record with a `null` value represents a "DELETE" or tombstone for the record's key.
To illustrate, let's imagine the following two data records are being sent to the stream:
("alice", 1) --> ("alice", 3)
If your stream processing application were to sum the values per user, it would return `3` for `alice`. Why? Because the second data record would be considered an update of the previous record.
**Effects of Kafka's log compaction:** Another way of thinking about KStream and KTable is as follows: If you were to store a KTable into a Kafka topic, you'd probably want to enable Kafka's [log compaction](http://kafka.apache.org/documentation.html#compaction) feature, e.g. to save storage space.
However, it would not be safe to enable log compaction in the case of a KStream because, as soon as log compaction would begin purging older data records of the same key, it would break the semantics of the data. To pick up the illustration example again, you'd suddenly get a `3` for `alice` instead of a `4` because log compaction would have removed the `("alice", 1)` data record. Hence log compaction is perfectly safe for a KTable (changelog stream) but it is a mistake for a KStream (record stream).
We have already seen an example of a changelog stream in the section [streams and tables](../../core-concepts#streams_concepts_duality). Another example are change data capture (CDC) records in the changelog of a relational database, representing which row in a database table was inserted, updated, or deleted.
KTable also provides an ability to look up _current_ values of data records by keys. This table-lookup functionality is available through **join operations** (see also **Joining** in the Developer Guide) as well as through **Interactive Queries**.
### GlobalKTable
Only the **Kafka Streams DSL** has the notion of a **GlobalKTable**.
Like a **KTable** , a **GlobalKTable** is an abstraction of a **changelog stream** , where each data record represents an update.
A GlobalKTable differs from a KTable in the data that they are being populated with, i.e. which data from the underlying Kafka topic is being read into the respective table. Slightly simplified, imagine you have an input topic with 5 partitions. In your application, you want to read this topic into a table. Also, you want to run your application across 5 application instances for **maximum parallelism**.
* If you read the input topic into a **KTable** , then the "local" KTable instance of each application instance will be populated with data **from only 1 partition** of the topic's 5 partitions.
* If you read the input topic into a **GlobalKTable** , then the local GlobalKTable instance of each application instance will be populated with data **from all partitions of the topic**.
GlobalKTable provides the ability to look up _current_ values of data records by keys. This table-lookup functionality is available through `join operations`. Note that a GlobalKTable has **no** notion of time in contrast to a KTable.
Benefits of global tables:
* More convenient and/or efficient **joins** : Notably, global tables allow you to perform star joins, they support "foreign-key" lookups (i.e., you can lookup data in the table not just by record key, but also by data in the record values), and they are more efficient when chaining multiple joins. Also, when joining against a global table, the input data does not need to be **co-partitioned**.
* Can be used to "broadcast" information to all the running instances of your application.
Downsides of global tables:
* Increased local storage consumption compared to the (partitioned) KTable because the entire topic is tracked.
* Increased network and Kafka broker load compared to the (partitioned) KTable because the entire topic is read.
# Creating source streams from Kafka
You can easily read data from Kafka topics into your application. The following operations are supported.
|
Reading from Kafka
|
Description
|
|
**Stream**
* _input topics_ -> KStream
|
Creates a KStream from the specified Kafka input topics and interprets the data as a record stream. A `KStream` represents a _partitioned_ record stream. [(details)](/{version}/javadoc/org/apache/kafka/streams/StreamsBuilder.html#stream\(java.lang.String\))
In the case of a KStream, the local KStream instance of every application instance will be populated with data from only **a subset** of the partitions of the input topic. Collectively, across all application instances, all input topic partitions are read and processed.
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
StreamsBuilder builder = new StreamsBuilder();
KStream wordCounts = builder.stream(
"word-counts-input-topic", /* input topic */
Consumed.with(
Serdes.String(), /* key serde */
Serdes.Long() /* value serde */
);
If you do not specify Serdes explicitly, the default Serdes from the [configuration](../config-streams#streams-developer-guide-configuration) are used.
You **must specify Serdes explicitly** if the key or value types of the records in the Kafka input topics do not match the configured default Serdes. For information about configuring default Serdes, available Serdes, and implementing your own custom Serdes see [Data Types and Serialization](../datatypes#streams-developer-guide-serdes).
Several variants of `stream` exist. For example, you can specify a regex pattern for input topics to read from (note that all matching topics will be part of the same input topic group, and the work will not be parallelized for different topics if subscribed to in this way).
|
|
**Table**
* _input topic_ -> KTable
|
Reads the specified Kafka input topic into a KTable. The topic is interpreted as a changelog stream, where records with the same key are interpreted as UPSERT aka INSERT/UPDATE (when the record value is not `null`) or as DELETE (when the value is `null`) for that key. [(details)](/{version}/javadoc/org/apache/kafka/streams/StreamsBuilder.html#table-java.lang.String\(java.lang.String\))
In the case of a KTable, the local KTable instance of every application instance will be populated with data from only **a subset** of the partitions of the input topic. Collectively, across all application instances, all input topic partitions are read and processed.
You must provide a name for the table (more precisely, for the internal [state store](../../architecture#streams_architecture_state) that backs the table). This is required for supporting [interactive queries](../interactive-queries#streams-developer-guide-interactive-queries) against the table. When a name is not provided the table will not be queryable and an internal name will be provided for the state store.
If you do not specify Serdes explicitly, the default Serdes from the [configuration](../config-streams#streams-developer-guide-configuration) are used.
You **must specify Serdes explicitly** if the key or value types of the records in the Kafka input topics do not match the configured default Serdes. For information about configuring default Serdes, available Serdes, and implementing your own custom Serdes see [Data Types and Serialization](../datatypes#streams-developer-guide-serdes).
Several variants of `table` exist, for example to specify the `auto.offset.reset` policy to be used when reading from the input topic.
|
|
**Global Table**
* _input topic_ -> GlobalKTable
|
Reads the specified Kafka input topic into a GlobalKTable. The topic is interpreted as a changelog stream, where records with the same key are interpreted as UPSERT aka INSERT/UPDATE (when the record value is not `null`) or as DELETE (when the value is `null`) for that key. [(details)](/{version}/javadoc/org/apache/kafka/streams/StreamsBuilder.html#globalTable-java.lang.String\(java.lang.String\))
In the case of a GlobalKTable, the local GlobalKTable instance of every application instance will be populated with data from **all** the partitions of the input topic.
You must provide a name for the table (more precisely, for the internal [state store](../../architecture#streams_architecture_state) that backs the table). This is required for supporting [interactive queries](../interactive-queries#streams-developer-guide-interactive-queries) against the table. When a name is not provided the table will not be queryable and an internal name will be provided for the state store.
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.GlobalKTable;
StreamsBuilder builder = new StreamsBuilder();
GlobalKTable wordCounts = builder.globalTable(
"word-counts-input-topic",
Materialized.>as(
"word-counts-global-store" /* table/store name */)
.withKeySerde(Serdes.String()) /* key serde */
.withValueSerde(Serdes.Long()) /* value serde */
);
You **must specify Serdes explicitly** if the key or value types of the records in the Kafka input topics do not match the configured default Serdes. For information about configuring default Serdes, available Serdes, and implementing your own custom Serdes see [Data Types and Serialization](../datatypes#streams-developer-guide-serdes).
Several variants of `globalTable` exist to e.g. specify explicit Serdes.
|
# Transform a stream
The KStream and KTable interfaces support a variety of transformation operations. Each of these operations can be translated into one or more connected processors into the underlying processor topology. Since KStream and KTable are strongly typed, all of these transformation operations are defined as generic functions where users could specify the input and output data types.
Some KStream transformations may generate one or more KStream objects, for example: \- `filter` and `map` on a KStream will generate another KStream \- `split` on KStream can generate multiple KStreams
Some others may generate a KTable object, for example an aggregation of a KStream also yields a KTable. This allows Kafka Streams to continuously update the computed value upon arrivals of [out-of-order records](../../core-concepts#streams_concepts_aggregations) after it has already been produced to the downstream transformation operators.
All KTable transformation operations can only generate another KTable. However, the Kafka Streams DSL does provide a special function that converts a KTable representation into a KStream. All of these transformation methods can be chained together to compose a complex processor topology.
These transformation operations are described in the following subsections:
* Stateless transformations
* Stateful transformations
## Stateless transformations
Stateless transformations do not require state for processing and they do not require a state store associated with the stream processor. Kafka 0.11.0 and later allows you to materialize the result from a stateless `KTable` transformation. This allows the result to be queried through [interactive queries](../interactive-queries#streams-developer-guide-interactive-queries). To materialize a `KTable`, each of the below stateless operations [can be augmented](../interactive-queries#streams-developer-guide-interactive-queries-local-key-value-stores) with an optional `queryableStoreName` argument.
|
Transformation
|
Description
|
|
**Branch**
* KStream -> BranchedKStream
|
Branch (or split) a `KStream` based on the supplied predicates into one or more `KStream` instances. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#split\(\)))
Predicates are evaluated in order. A record is placed to one and only one output stream on the first match: if the n-th predicate evaluates to true, the record is placed to n-th stream. If a record does not match any predicates, it will be routed to the default branch, or dropped if no default branch is created.
Branching is useful, for example, to route records to different downstream topics.
KStream stream = ...;
Map> branches =
stream.split(Named.as("Branch-"))
.branch((key, value) -> key.startsWith("A"), /* first predicate */
Branched.as("A"))
.branch((key, value) -> key.startsWith("B"), /* second predicate */
Branched.as("B"))
.defaultBranch(Branched.as("C")) /* default branch */
);
// KStream branches.get("Branch-A") contains all records whose keys start with "A"
// KStream branches.get("Branch-B") contains all records whose keys start with "B"
// KStream branches.get("Branch-C") contains all other records
|
|
**Broadcast/Multicast**
* no operator
|
Broadcasting a `KStream` into multiple downstream operators.
A record is sent to more than one operator by applying multiple operators to the same `KStream` instance.
KStream stream = ...;
KStream<...> stream1 = stream.map(...);
KStream<...> stream2 = stream.mapValue(...);
KStream<...> stream3 = stream.flatMap(...);
Multicasting a `KStream` into multiple downstream operators.
In contrast to **branching** , which sends each record to at most one downstream branch, a multicast may send a record to any number of downstream `KStream` instances.
A multicast is implemented as a broadcast plus filters.
KStream stream = ...;
KStream<...> stream1 = stream.filter((key, value) -> key.startsWith("A")); // contains all records whose keys start with "A"
KStream<...> stream2 = stream.filter((key, value) -> key.startsWith("AB")); // contains all records whose keys start with "AB" (subset of stream1)
KStream<...> stream3 = stream.filter((key, value) -> key.contains("B")); // contains all records whose keys contains a "B" (superset of stream2)
|
|
**Filter**
* KStream -> KStream
* KTable -> KTable
|
Evaluates a boolean function for each element and retains those for which the function returns true. ([KStream details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#filter-org.apache.kafka.streams.kstream.Predicate-), [KTable details](/{version}/javadoc/org/apache/kafka/streams/kstream/KTable.html#filter-org.apache.kafka.streams.kstream.Predicate-))
KStream stream = ...;
// A filter that selects (keeps) only positive numbers
KStream onlyPositives = stream.filter((key, value) -> value > 0);
|
|
**Inverse Filter**
* KStream -> KStream
* KTable -> KTable
|
Evaluates a boolean function for each element and drops those for which the function returns true. ([KStream details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#filterNot-org.apache.kafka.streams.kstream.Predicate-), [KTable details](/{version}/javadoc/org/apache/kafka/streams/kstream/KTable.html#filterNot-org.apache.kafka.streams.kstream.Predicate-))
KStream stream = ...;
// An inverse filter that discards any negative numbers or zero
KStream onlyPositives = stream.filterNot((key, value) -> value <= 0);
|
|
**FlatMap**
* KStream -> KStream
|
Takes one record and produces zero, one, or more records. You can modify the record keys and values, including their types. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#flatMap-org.apache.kafka.streams.kstream.KeyValueMapper-))
**Marks the stream for data re-partitioning:** Applying a grouping or a join after `flatMap` will result in re-partitioning of the records. If possible use `flatMapValues` instead, which will not cause data re-partitioning.
KStream stream = ...;
KStream transformed = stream.flatMap(
// Here, we generate two output records for each input record.
// We also change the key and value types.
// Example: (345L, "Hello") -> ("HELLO", 1000), ("hello", 9000)
(key, value) -> {
List> result = new LinkedList<>();
result.add(KeyValue.pair(value.toUpperCase(), 1000));
result.add(KeyValue.pair(value.toLowerCase(), 9000));
return result;
}
);
|
|
**FlatMapValues**
* KStream -> KStream
|
Takes one record and produces zero, one, or more records, while retaining the key of the original record. You can modify the record values and the value type. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#flatMapValues-org.apache.kafka.streams.kstream.ValueMapper-))
`flatMapValues` is preferable to `flatMap` because it will not cause data re-partitioning. However, you cannot modify the key or key type like `flatMap` does.
// Split a sentence into words.
KStream sentences = ...;
KStream words = sentences.flatMapValues(value -> Arrays.asList(value.split("\s+")));
|
|
**Foreach**
* KStream -> void
* KStream -> void
* KTable -> void
|
**Terminal operation.** Performs a stateless action on each record. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#foreach-org.apache.kafka.streams.kstream.ForeachAction-))
You would use `foreach` to cause _side effects_ based on the input data (similar to `peek`) and then _stop_ _further processing_ of the input data (unlike `peek`, which is not a terminal operation).
**Note on processing guarantees:** Any side effects of an action (such as writing to external systems) are not trackable by Kafka, which means they will typically not benefit from Kafka's processing guarantees.
KStream stream = ...;
// Print the contents of the KStream to the local console.
stream.foreach((key, value) -> System.out.println(key + " => " + value));
|
|
**GroupByKey**
* KStream -> KGroupedStream
|
Groups the records by the existing key. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#groupByKey--))
Grouping is a prerequisite for aggregating a stream or a table and ensures that data is properly partitioned ("keyed") for subsequent operations.
**When to set explicit Serdes:** Variants of `groupByKey` exist to override the configured default Serdes of your application, which **you** **must do** if the key and/or value types of the resulting `KGroupedStream` do not match the configured default Serdes.
**Note**
**Grouping vs. Windowing:** A related operation is windowing, which lets you control how to "sub-group" the grouped records _of the same key_ into so-called _windows_ for stateful operations such as windowed aggregations or windowed joins.
**Causes data re-partitioning if and only if the stream was marked for re-partitioning.** `groupByKey` is preferable to `groupBy` because it re-partitions data only if the stream was already marked for re-partitioning. However, `groupByKey` does not allow you to modify the key or key type like `groupBy` does.
KStream stream = ...;
// Group by the existing key, using the application's configured
// default serdes for keys and values.
KGroupedStream groupedStream = stream.groupByKey();
// When the key and/or value types do not match the configured
// default serdes, we must explicitly specify serdes.
KGroupedStream groupedStream = stream.groupByKey(
Grouped.with(
Serdes.ByteArray(), /* key */
Serdes.String()) /* value */
);
|
|
**GroupBy**
* KStream -> KGroupedStream
* KTable -> KGroupedTable
|
Groups the records by a _new_ key, which may be of a different key type. When grouping a table, you may also specify a new value and value type. `groupBy` is a shorthand for `selectKey(...).groupByKey()`. ([KStream details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#groupBy-org.apache.kafka.streams.kstream.KeyValueMapper-), [KTable details](/{version}/javadoc/org/apache/kafka/streams/kstream/KTable.html#groupBy-org.apache.kafka.streams.kstream.KeyValueMapper-))
Grouping is a prerequisite for aggregating a stream or a table and ensures that data is properly partitioned ("keyed") for subsequent operations.
**When to set explicit Serdes:** Variants of `groupBy` exist to override the configured default Serdes of your application, which **you must** **do** if the key and/or value types of the resulting `KGroupedStream` or `KGroupedTable` do not match the configured default Serdes.
**Note**
**Grouping vs. Windowing:** A related operation is windowing, which lets you control how to "sub-group" the grouped records _of the same key_ into so-called _windows_ for stateful operations such as windowed aggregations or windowed joins.
**Always causes data re-partitioning:** `groupBy` always causes data re-partitioning. If possible use `groupByKey` instead, which will re-partition data only if required.
KStream stream = ...;
KTable table = ...;
// Group the stream by a new key and key type
KGroupedStream groupedStream = stream.groupBy(
(key, value) -> value,
Grouped.with(
Serdes.String(), /* key (note: type was modified) */
Serdes.String()) /* value */
);
// Group the table by a new key and key type, and also modify the value and value type.
KGroupedTable groupedTable = table.groupBy(
(key, value) -> KeyValue.pair(value, value.length()),
Grouped.with(
Serdes.String(), /* key (note: type was modified) */
Serdes.Integer()) /* value (note: type was modified) */
);
|
|
**Cogroup**
* KGroupedStream -> CogroupedKStream
* CogroupedKStream -> CogroupedKStream
|
Cogrouping allows to aggregate multiple input streams in a single operation. The different (already grouped) input streams must have the same key type and may have different values types. [KGroupedStream#cogroup()](/{version}/javadoc/org/apache/kafka/streams/kstream/KGroupedStream.html#cogroup) creates a new cogrouped stream with a single input stream, while [CogroupedKStream#cogroup()](/{version}/javadoc/org/apache/kafka/streams/kstream/CogroupedKStream.html#cogroup) adds a grouped stream to an existing cogrouped stream. A `CogroupedKStream` may be [windowed](/{version}/javadoc/org/apache/kafka/streams/kstream/CogroupedKStream.html#windowedBy) before it is [aggregated](/{version}/javadoc/org/apache/kafka/streams/kstream/CogroupedKStream.html#aggregate).
Cogroup does not cause a repartition as it has the prerequisite that the input streams are grouped. In the process of creating these groups they will have already been repartitioned if the stream was already marked for repartitioning.
KStream stream = ...;
KStream stream2 = ...;
// Group by the existing key, using the application's configured
// default serdes for keys and values.
KGroupedStream groupedStream = stream.groupByKey();
KGroupedStream groupedStream2 = stream2.groupByKey();
CogroupedKStream cogroupedStream = groupedStream.cogroup(aggregator1).cogroup(groupedStream2, aggregator2);
KTable table = cogroupedStream.aggregate(initializer);
KTable table2 = cogroupedStream.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMillis(500))).aggregate(initializer);
|
|
**Map**
* KStream -> KStream
|
Takes one record and produces one record. You can modify the record key and value, including their types. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#map-org.apache.kafka.streams.kstream.KeyValueMapper-))
**Marks the stream for data re-partitioning:** Applying a grouping or a join after `map` will result in re-partitioning of the records. If possible use `mapValues` instead, which will not cause data re-partitioning.
KStream stream = ...;
// Note how we change the key and the key type (similar to `selectKey`)
// as well as the value and the value type.
KStream transformed = stream.map(
(key, value) -> KeyValue.pair(value.toLowerCase(), value.length()));
|
|
**Map (values only)**
* KStream -> KStream
* KTable -> KTable
|
Takes one record and produces one record, while retaining the key of the original record. You can modify the record value and the value type. ([KStream details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#mapValues-org.apache.kafka.streams.kstream.ValueMapper-), [KTable details](/{version}/javadoc/org/apache/kafka/streams/kstream/KTable.html#mapValues-org.apache.kafka.streams.kstream.ValueMapper-))
`mapValues` is preferable to `map` because it will not cause data re-partitioning. However, it does not allow you to modify the key or key type like `map` does.
KStream stream = ...;
KStream uppercased = stream.mapValues(value -> value.toUpperCase());
|
|
**Merge**
* KStream -> KStream
|
Merges records of two streams into one larger stream. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#merge-org.apache.kafka.streams.kstream.KStream-))
There is no ordering guarantee between records from different streams in the merged stream. Relative order is preserved within each input stream though (ie, records within the same input stream are processed in order)
KStream stream1 = ...;
KStream stream2 = ...;
KStream merged = stream1.merge(stream2);
|
|
**Peek**
* KStream -> KStream
|
Performs a stateless action on each record, and returns an unchanged stream. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#peek-org.apache.kafka.streams.kstream.ForeachAction-))
You would use `peek` to cause _side effects_ based on the input data (similar to `foreach`) and _continue_ _processing_ the input data (unlike `foreach`, which is a terminal operation). `peek` returns the input stream as-is; if you need to modify the input stream, use `map` or `mapValues` instead.
`peek` is helpful for use cases such as logging or tracking metrics or for debugging and troubleshooting.
**Note on processing guarantees:** Any side effects of an action (such as writing to external systems) are not trackable by Kafka, which means they will typically not benefit from Kafka's processing guarantees.
KStream stream = ...;
KStream unmodifiedStream = stream.peek(
(key, value) -> System.out.println("key=" + key + ", value=" + value));
|
|
**Print**
* KStream -> void
|
**Terminal operation.** Prints the records to `System.out`. See Javadocs for serde and `toString()` caveats. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#print--))
Calling `print()` is the same as calling `foreach((key, value) -> System.out.println(key + ", " + value))`
`print` is mainly for debugging/testing purposes, and it will try to flush on each record print. Hence it **should not** be used for production usage if performance requirements are concerned.
KStream stream = ...;
// print to sysout
stream.print();
// print to file with a custom label
stream.print(Printed.toFile("streams.out").withLabel("streams"));
|
|
**SelectKey**
* KStream -> KStream
|
Assigns a new key - possibly of a new key type - to each record. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#selectKey-org.apache.kafka.streams.kstream.KeyValueMapper-))
Calling `selectKey(mapper)` is the same as calling `map((key, value) -> mapper(key, value), value)`.
**Marks the stream for data re-partitioning:** Applying a grouping or a join after `selectKey` will result in re-partitioning of the records.
KStream stream = ...;
// Derive a new record key from the record's value. Note how the key type changes, too.
KStream rekeyed = stream.selectKey((key, value) -> value.split(" ")[0])
|
|
**Table to Stream**
* KTable -> KStream
|
Get the changelog stream of this table. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KTable.html#toStream--))
KTable table = ...;
// Also, a variant of `toStream` exists that allows you
// to select a new key for the resulting stream.
KStream stream = table.toStream();
|
|
**Stream to Table**
* KStream -> KTable
|
Convert an event stream into a table, or say a changelog stream. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#toTable--))
KStream stream = ...;
KTable table = stream.toTable();
|
|
**Repartition**
* KStream -> KStream
|
Manually trigger repartitioning of the stream with desired number of partitions. ([details](/{version}/javadoc/org/apache/kafka/streams/kstream/KStream.html#repartition--))
Kafka Streams will manage the topic for `repartition()`. Generated topic is treated as internal topic, as a result data will be purged automatically as any other internal repartition topic. In addition, you can specify the desired number of partitions, which allows to easily scale in/out downstream sub-topologies. `repartition()` operation always triggers repartitioning of the stream, as a result it can be used with embedded Processor API methods (like `process()` et al.) that do not trigger auto repartitioning when key changing operation is performed beforehand.
KStream stream = ... ;
KStream repartitionedStream = stream.repartition(Repartitioned.numberOfPartitions(10));
|
## Stateful transformations
Stateful transformations depend on state for processing inputs and producing outputs and require a [state store](../../architecture#streams_architecture_state) associated with the stream processor. For example, in aggregating operations, a windowing state store is used to collect the latest aggregation results per window. In join operations, a windowing state store is used to collect all of the records received so far within the defined window boundary.
**Note:** Following store types are used regardless of the possibly specified type (via the parameter `materialized`):
* non-windowed aggregations and non-windowed KTables use [TimestampedKeyValueStore](/{version}/javadoc/org/apache/kafka/streams/state/TimestampedKeyValueStore.html)s or [VersionedKeyValueStore](/{version}/javadoc/org/apache/kafka/streams/state/VersionedKeyValueStore.html)s, depending on whether the parameter `materialized` is versioned
* time-windowed aggregations and KStream-KStream joins use [TimestampedWindowStore](/{version}/javadoc/org/apache/kafka/streams/state/TimestampedWindowStore.html)s
* session windowed aggregations use [SessionStore](/{version}/javadoc/org/apache/kafka/streams/state/SessionStore.html)s (there is no timestamped session store as of now)
**Headers-aware state stores ([KIP-1285](https://cwiki.apache.org/confluence/x/4ow8G)):** Set [`dsl.store.format=HEADERS`](../config-streams#dsl-store-format) to make supported DSL operators use headers-aware state stores. These stores can keep record headers together with the value and timestamp.
This config only changes the state store format. It does not define how DSL operators create headers for output records. Current behavior is:
* aggregations, KTable-KTable joins, materialized `KTable.mapValues`, `KStream.toTable()`, and `StreamsBuilder.table()` write empty headers to their materialized stores
* KStream-KStream join window stores keep source-record headers, but join result records do not get computed or merged headers; they may carry the headers from the record that triggered the result
* left/outer [KStream-KStream joins](#kstream-kstream-join) use a non-headers-aware buffer store for not-yet-matched records, so records passing through that buffer lose their headers
A follow-up KIP will define how DSL result headers are computed.
Note, that state stores are fault-tolerant. In case of failure, Kafka Streams guarantees to fully restore all state stores prior to resuming the processing. See [Fault Tolerance](../../architecture#streams_architecture_recovery) for further information.
Available stateful transformations in the DSL include:
* Aggregating
* Joining
* Windowing (as part of aggregations and joins)
* Applying custom processors and transformers, which may be stateful, for Processor API integration
The following diagram shows their relationships:

Stateful transformations in the DSL.
Here is an example of a stateful application: the WordCount algorithm.
WordCount example:
// Assume the record values represent lines of text. For the sake of this example, you can ignore
// whatever may be stored in the record keys.
KStream