Kafka Streams: Real-Time Stream Processing Applications
Kafka Streams is a client library for real-time stream processing. Learn stream primitives, state stores, exactly-once processing, and scaling.
Kafka Streams runs inside a Java application and uses Kafka topics for input, output, and state recovery. This guide covers KStream and KTable, windowed state, Kafka transactions, partition-based scaling, and interactive queries. It also shows how to estimate local state, test late events, observe rebalances, and choose between Kafka Streams and a separate engine such as Flink.
Kafka Streams: Building Real-Time Stream Processing Applications
Introduction
The examples in this article target the Kafka Streams 4.2.x client API and the matching Kafka 4.2 documentation. Check the broker compatibility guidance before mixing client and broker releases.
Kafka Streams is a Java library, not a separate processing cluster. The application reads from Kafka, processes records, and writes results back to Kafka. You still operate the application instances and Kafka resources; you simply run the processing code in the application fleet.
The examples cover stream and table operations, local state, Kafka transactions, scaling, and interactive queries. A sizing worksheet and two tests show how to check window lateness and task reassignment before production.
Stream Processing Basics
A stream is an unbounded sequence of records. A stream processor reads from input streams, applies transformations, and writes to output streams.
flowchart LR
Input[Input Topic] --> KS[Kafka Streams App]
KS --> Output1[Output Topic 1]
KS --> Output2[Output Topic 2]
Kafka Streams programs define processing logic using the Streams DSL or the Processor API. The DSL provides functional-style operations on streams. The Processor API gives you lower-level control when you need it.
The Streams DSL
The Streams DSL exposes KStream and KTable abstractions.
KStream: An unbounded sequence of record events. Each event is an independent occurrence. The same key can appear multiple times.
KTable: A mutable view of a changelog stream. Updates to a key replace the previous value. A KTable is backed by a state store that maintains the latest value for each key.
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Grouped;
StreamsBuilder builder = new StreamsBuilder();
// KStream: unbounded sequence of page view events
KStream<String, PageViewEvent> pageViews = builder.stream("page-views");
// KTable: latest customer info per customer ID
KTable<String, CustomerInfo> customers = builder.table("customer-info",
Materialized.as("customer-info-store"));
// Join page views to customer info
KStream<String, EnrichedPageView> enrichedPageViews = pageViews
.filter((userId, event) -> event.getDuration() > 10) // filter long sessions
.join(customers, (event, info) -> new EnrichedPageView(event, info));
// Aggregate page views per user
KTable<String, Long> viewCounts = pageViews
.groupBy((userId, event) -> userId)
.count(Materialized.as("view-counts-store"));
// Write to output topics
enrichedPageViews.to("enriched-page-views");
viewCounts.toStream().to("view-counts");
Stateful Operations
Kafka Streams keeps state in local RocksDB databases by default. Each instance stores the current state for the partitions it handles.
Stateful operations include:
- join: Join two streams or a stream with a table
- aggregate: Maintain running aggregates (count, sum, max)
- reduce: Combine records with the same key
// Aggregate each key in five-minute windows; accept events up to 30 seconds late.
KStream<String, Event> events = builder.stream("events");
events
.groupByKey(Grouped.with(Serdes.String(), eventSerde))
.windowedBy(TimeWindows.ofSizeAndGrace(
Duration.ofMinutes(5), Duration.ofSeconds(30)))
.aggregate(
() -> new WindowState(0, Instant.MIN),
(key, event, state) -> state.addEvent(event),
(key, left, right) -> left.merge(right),
Materialized.as("window-store")
)
.toStream()
.to("session-output");
Each task owns the state for its assigned partitions. If an instance fails, another instance takes those tasks and restores logged state from the changelog topic.
Exactly-once processing
In Kafka Streams 4.2, set processing.guarantee to exactly_once_v2 to have Kafka transactions atomically commit consumed offsets, Kafka output records, and state-store updates. A downstream consumer must use read_committed isolation to hide aborted transactional output. The broker must be version 2.5 or newer; the default transaction-state topic settings expect at least three brokers for production. A one-broker development setup needs adjusted transaction topic replication settings and does not provide production fault tolerance. See the Kafka 4.2 processing guarantee configuration.
// Kafka Streams 4.2.x client; broker compatibility and transaction settings still apply.
Properties props = new Properties();
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "my-exactly-once-app");
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> input = builder.stream("input-topic");
KStream<String, String> output = input.mapValues(value -> process(value));
output.to("output-topic", Produced.with(Serdes.String(), Serdes.String()));
This guarantee stops at Kafka’s transaction boundary. If a processor writes to an external database and then crashes before Kafka commits the input offset, the database write may happen again when the record is replayed. Make that write idempotent or coordinate it with the database’s transaction model. An outbox pattern addresses a different boundary: it publishes a database change to Kafka from an outbox record written in the same database transaction.
For the application-to-Kafka case, see Exactly-Once Semantics.
Scaling Kafka Streams applications
Kafka Streams runs multiple instances of the same application and assigns tasks among them. Adding instances can increase parallelism while the topology has unassigned tasks.
flowchart LR
subgraph Kafka[Kafka Cluster]
P0[Partition 0]
P1[Partition 1]
P2[Partition 2]
end
subgraph Instances[Kafka Streams App]
I1[Instance 1: P0, P1]
I2[Instance 2: P2]
end
P0 --> I1
P1 --> I1
P2 --> I2
Kafka Streams assigns tasks across instances as membership changes. Task parallelism depends on the partitions of each source and repartition topic, so an instance count above the available task count leaves some instances idle. When a task moves, its local state is restored from its changelog unless a usable standby copy is available.
For a simple topology with one source topic, the source partition count limits the active task count. More complex topologies can have different task counts in different subtopologies, so inspect the built topology and its repartition topics before choosing an instance count.
Interactive Queries
Kafka Streams exposes state stores through interactive queries. An instance can query its local state without reading the source topic again.
// Expose state store as a queryable API
ReadOnlyKeyValueStore<String, CustomerInfo> store =
streams.store(
QueryableStoreTypes.keyValueStore(),
StoreQueryParameters.fromNameWithType("customer-info-store", CustomerInfo.class)
);
CustomerInfo customer = store.get("customer-123");
Interactive queries read state from the local application instance. For a distributed topology, an application needs routing or an RPC layer to reach the instance that owns the requested key; the API does not turn local stores into one shared database. See the Kafka 4.2 interactive queries guide.
Common pitfalls
Sizing state stores
Kafka Streams uses local state stores, with RocksDB as the default for many DSL stores. A single safe size limit does not exist: serialized key and value sizes, retained windows, updates, tombstones, compaction, changelog recovery, and the available disk all affect the result. The examples below use Kafka Streams 4.2 configuration names; they are not a promise that RocksDB will stay below a particular disk size.
Start with a workload estimate, then measure it under representative traffic:
- Count the expected live keys per task. For a keyed store, divide the estimated live key count by the number of tasks that own that store, not blindly by the source partition count.
- Measure serialized key and value sizes, including the largest realistic values. For a window store, estimate how many windows per key remain inside the configured retention period.
- Multiply live entries by their measured serialized sizes to get a first-pass data estimate. Treat it as a baseline; indexes, tombstones, record-cache behavior, and RocksDB compaction change on-disk use.
- Run a load test long enough to reach steady state. Record each task’s store directory size, disk free space, compaction activity, write stalls, and input rate.
- Measure restore throughput by restarting an instance or moving a task in a test cluster. Estimate recovery time from changelog bytes or records divided by the measured restore rate, then check whether the result fits the recovery objective.
- Repeat with expected retention, key growth, and peak input rate. Reserve disk headroom based on the measured compaction and restore peaks for this workload.
Window retention and grace solve different problems. Retention controls how long a window store keeps data; grace controls how late an event may arrive and still update a window. Configure both deliberately, and test the boundary. A zero grace period closes a window as soon as stream time passes its end; it does not mean a session window has no gap. Session windows use SessionWindows, while TimeWindows defines fixed-size windows.
Do not treat RocksDB compaction options as a hard store-size cap. Kafka Streams exposes RocksDB customization through rocksdb.config.setter, but tune options only after measurements and against the RocksDB version bundled with the chosen Kafka release. Likewise, statestore.cache.max.bytes bounds the Streams record cache in memory; it does not cap local disk usage. See the Kafka 4.2 configuration reference and Kafka 4.2 RocksDB metrics.
For Kafka Streams 4.2, useful RocksDB JMX attributes include total-sst-files-size, estimate-pending-compaction-bytes, compaction-pending, num-running-compactions, cur-size-all-mem-tables, and write-stall-duration-avg. Several RocksDB statistics are recorded at the debug level and collected periodically, so enable them with care and check the recording level in the release documentation.
Late events and window retention
Windowed operations use event timestamps and stream time. Records arriving after a window’s grace period are dropped for that window; late data does not create an endless window. Set the event timestamp extractor and grace period from the observed lateness distribution, then test records on both sides of the close boundary.
Handling out-of-order data
Kafka guarantees ordering within a partition. If your processing logic depends on temporal ordering across partitions, you must handle out-of-order arrivals explicitly.
Partition ordering reflects the order records were appended, not necessarily their event timestamps. Retries and upstream buffering can change arrival order. A window or time-based join may then produce an unexpected result without throwing an exception.
Use the event’s timestamp when the domain defines event time, and configure grace from measured out-of-order arrival. Records that arrive after the window closes are dropped. Watch the Streams task metrics record-lateness-avg, record-lateness-max, dropped-records-rate, and dropped-records-total; the last two count dropped records and are not specific to late-window records.
For joins, co-partitioning input topics on the same key is required for the relevant join operations; it does not establish event-time order across partitions. A stream-table join uses the table’s current state at processing time, so it is not a substitute for an event-time join when historical ordering matters.
Using global state stores when partitioned would work
Global state stores replicate all data to every Kafka Streams instance. They are convenient but do not scale. Use partitioned state stores whenever possible.
Testing late events and rebalances
Kafka 4.2’s TopologyTestDriver runs a topology without a broker, which makes it useful for checking event-time window behavior. Add org.apache.kafka:kafka-streams-test-utils:4.2.0 with test scope, and keep kafka-streams on the same version. This JUnit 5 example accepts a record inside the grace period and ignores one after stream time has closed the window:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.state.WindowStore;
import org.apache.kafka.streams.state.WindowStoreIterator;
import org.junit.jupiter.api.Test;
class LateEventTopologyTest {
@Test
void acceptsLateRecordWithinGraceAndIgnoresOneAfterClose() {
StreamsBuilder builder = new StreamsBuilder();
builder.stream("events", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey(Grouped.with(Serdes.String(), Serdes.String()))
.windowedBy(TimeWindows.ofSizeAndGrace(
Duration.ofMinutes(5), Duration.ofSeconds(30)))
.count(Materialized.as("event-counts"));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "late-event-test");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG,
Serdes.StringSerde.class.getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,
Serdes.StringSerde.class.getName());
try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
TestInputTopic<String, String> input = driver.createInputTopic(
"events", Serdes.String().serializer(), Serdes.String().serializer());
WindowStore<String, Long> store = driver.getWindowStore("event-counts");
input.pipeInput("user-1", "first", 0L);
input.pipeInput("user-2", "advance-stream-time", Duration.ofMinutes(5)
.plusSeconds(20).toMillis());
input.pipeInput("user-1", "within-grace", Duration.ofMinutes(4)
.plusSeconds(50).toMillis());
try (WindowStoreIterator<Long> values = store.fetch("user-1", 0L, 0L)) {
assertTrue(values.hasNext());
assertEquals(2L, values.next().value);
}
input.pipeInput("user-3", "close-window", Duration.ofMinutes(6).toMillis());
input.pipeInput("user-1", "after-grace", Duration.ofMinutes(4)
.plusSeconds(55).toMillis());
try (WindowStoreIterator<Long> values = store.fetch("user-1", 0L, 0L)) {
assertTrue(values.hasNext());
assertEquals(2L, values.next().value);
}
}
}
}
TopologyTestDriver does not model Kafka’s group coordinator, so it cannot prove task reassignment. Use a broker-backed integration test for that case. Start a local Kafka 4.2 broker and create a two-partition input topic:
kafka-topics.sh --bootstrap-server localhost:9092 \
--create --topic events --partitions 2 --replication-factor 1
Add kafka-streams 4.2.0 and JUnit 5 to the test project, then run this test with KAFKA_BOOTSTRAP_SERVERS=localhost:9092. It starts two instances with the same application ID and separate state directories, observes reassignment when the second joins, and checks that the remaining instance returns to RUNNING after the first closes:
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.Materialized;
import org.junit.jupiter.api.Test;
class RebalanceIntegrationTest {
private static final Duration TIMEOUT = Duration.ofSeconds(30);
@Test
void reassignsTasksWhenAnInstanceJoinsAndLeaves() throws Exception {
String bootstrap = System.getenv().getOrDefault(
"KAFKA_BOOTSTRAP_SERVERS", "localhost:9092");
String applicationId = "rebalance-test-" + UUID.randomUUID();
StreamsBuilder builder = new StreamsBuilder();
builder.stream("events", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey(Grouped.with(Serdes.String(), Serdes.String()))
.count(Materialized.as("event-counts"));
Path firstStateDir = Files.createTempDirectory("streams-first-");
Path secondStateDir = Files.createTempDirectory("streams-second-");
KafkaStreams first = new KafkaStreams(builder.build(),
properties(applicationId, bootstrap, firstStateDir));
KafkaStreams second = new KafkaStreams(builder.build(),
properties(applicationId, bootstrap, secondStateDir));
AtomicInteger firstRebalances = new AtomicInteger();
AtomicInteger secondRebalances = new AtomicInteger();
first.setStateListener((newState, oldState) -> {
if (newState == KafkaStreams.State.REBALANCING) {
firstRebalances.incrementAndGet();
}
});
second.setStateListener((newState, oldState) -> {
if (newState == KafkaStreams.State.REBALANCING) {
secondRebalances.incrementAndGet();
}
});
try {
first.start();
assertTrue(await(() -> first.state() == KafkaStreams.State.RUNNING, TIMEOUT));
int firstCount = firstRebalances.get();
second.start();
assertTrue(await(() -> firstRebalances.get() > firstCount
&& second.state() == KafkaStreams.State.RUNNING, TIMEOUT));
int secondCount = secondRebalances.get();
first.close(Duration.ofSeconds(10));
assertTrue(await(() -> secondRebalances.get() > secondCount
&& second.state() == KafkaStreams.State.RUNNING, TIMEOUT));
} finally {
second.close(Duration.ofSeconds(10));
first.close(Duration.ofSeconds(10));
}
}
private static Properties properties(String applicationId, String bootstrap,
Path stateDir) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationId);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap);
props.put(StreamsConfig.STATE_DIR_CONFIG, stateDir.toString());
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG,
Serdes.StringSerde.class.getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,
Serdes.LongSerde.class.getName());
return props;
}
private static boolean await(BooleanSupplier condition, Duration timeout)
throws InterruptedException {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return true;
}
Thread.sleep(50);
}
return condition.getAsBoolean();
}
}
The two-instance test checks group membership and task reassignment, while the TopologyTestDriver test checks window grace behavior. Keep the broker-backed test isolated from production clusters; add record production and changelog restore assertions when the application has recovery requirements beyond the state transition itself. See the Kafka 4.2 testing guide and configuration reference for the test driver, application.id, and state.dir.
When Kafka Streams fits
Use Kafka Streams when:
- Your entire pipeline is Kafka-based (sources and sinks are Kafka topics)
- You want to embed processing in your application rather than operate a separate cluster
- You need exactly-once within the Kafka ecosystem
- Your processing is relatively straightforward (filter, map, join, aggregate)
Another engine may fit better when:
- You need a CEP engine or event-time trigger behavior beyond the window and grace semantics in Kafka Streams
- Most of your inputs and outputs are outside Kafka and connector support drives the design
- Your team needs a separate processing cluster with its own resource and deployment controls
Comparing Kafka Streams with Flink and Spark Structured Streaming
| Decision | Kafka Streams | Flink or Spark Structured Streaming |
|---|---|---|
| Deployment | Library embedded in a Java application; you operate that application and Kafka. | A separately managed processing runtime can provide independent deployment and resource controls. |
| State and recovery | Local task state is backed by Kafka changelog topics and restored when tasks move. | State backends and recovery behavior depend on engine configuration and checkpoint settings. |
| Sources and sinks | A natural fit when Kafka topics are the main input and output boundary. | Connector ecosystems may suit workloads with several non-Kafka systems. |
| Event-time logic | Windowing uses stream time, window retention, and grace periods. | The available window, trigger, and late-data behavior depends on the selected engine and configuration. |
Compare the failure model, connectors, operational ownership, and required event-time behavior for the specific versions you plan to run. Latency and throughput depend on the topology and deployment, so benchmark representative data instead of relying on a generic framework ranking.
Production Failure Scenarios
Stateful topologies add local storage and restoration to the failure path. Include those dependencies in the diagnosis when an instance restarts or a task moves.
State store corruption
Disk errors or an unclean shutdown can leave a local RocksDB store unusable. The application may then fail while opening the store or reading records.
The failure may appear as a RocksDBException during startup or a read error during processing. Check the RocksDB and host logs before assuming the changelog is damaged; a failing disk can reproduce the problem after a restore.
Check the application and RocksDB logs, then confirm the underlying disk is healthy before rebuilding state. Kafka Streams can restore logged state stores from their changelog topics, but recovery time depends on how much data must be replayed and the measured restore rate. A simple estimate is remaining changelog records / measured restore records per second; validate it under load because broker throughput, local disk writes, and compaction all affect recovery.
If the disk is failing, a rebuilt store can fail again. Move state storage to healthy disk and replace degraded storage before restarting repeatedly.
Rebalance loop after a processing failure
An unclean shutdown, such as an OOM kill, changes group membership and can trigger task reassignment. If a processing bug caused the failure, the next instance may hit it too.
If each reassigned task hits the same failure, the application can keep restarting. Look for repeated task revocation and assignment, restarts, and growing input lag rather than treating one log message as a diagnosis.
Look for shared resource bottlenecks under load. A saturated connection pool or a lock held across a slow call can stall a stream thread; reassignment may put the same work on another instance without fixing the cause.
Keep processing bounded and avoid blocking stream threads on slow external calls. Make external side effects idempotent because a task may replay records after failure. For Kafka input and output, exactly_once_v2 makes offset and output commits atomic; it does not prevent a processing bug or make an external database write transactional. Check the Kafka Streams 4.2 configuration reference before copying consumer settings into an application, since Streams controls some consumer behavior itself.
Duplicate output from crash during stateful join
A stateful join holds state in a repartition topic and co-partitioned state store. If the instance crashes after writing to the output topic but before committing the offset, the offset rolls back. On restart the join re-executes and produces duplicates.
With at-least-once processing, a crash after an output write but before the input offset commit can replay the record. The join runs again, and the output topic may receive a duplicate. The exact timing depends on the commit configuration and the point of failure.
Network delays, long garbage-collection pauses, or slow external calls can make replay more likely. Use the Kafka Streams version’s documented configuration and metrics when diagnosing it.
Mitigation: with exactly_once_v2, Kafka output records and consumed offsets commit in the same Kafka transaction. A consumer using read_committed sees committed output only. A database write made outside that transaction can still repeat, so make the database operation idempotent or coordinate it with a supported transaction pattern.
Late records after a window closes
Records with timestamps older than a window’s close boundary are dropped for that window. Kafka Streams advances stream time from processed record timestamps; it does not use Flink’s watermark API.
Test the timestamp extractor with known event timestamps. Choose grace from observed arrival delay, then watch the Kafka 4.2 task metrics record-lateness-avg, record-lateness-max, dropped-records-rate, and dropped-records-total. The dropped-record metrics are not late-record-only counters; correlate them with the topology and application logs. Kafka Streams does not expose Flink’s WatermarkStrategy or late-record-dropping metric.
Security and Compliance Notes
Kafka Streams applications inherit Kafka’s access boundaries, and their internal topics are part of that boundary. Grant the application identity only the topic and consumer-group permissions its topology needs. Include generated repartition and changelog topics in the ACL plan; a workload that can read an input topic but cannot restore its state will fail during startup or reassignment, while broad wildcard access can expose unrelated data.
Treat changelog and repartition records as copies of the data being processed. Keep credentials and unnecessary personal data out of event values and keys. Require TLS for client and broker traffic, and encrypt broker disks and the hosts that hold local RocksDB state. If the application persists sensitive values locally, decide how to protect disks and backups and how to remove state securely when instances are retired.
Set retention for changelog, repartition, and source topics with recovery and replay needs in mind. Restrict who can reset consumer offsets, change retention, or read archived topics, since those actions can expose old payloads or trigger large-scale reprocessing. Keep sensitive fields out of logs, traces, and interactive-query responses unless the caller is authorized to see them; audit administrative access and test recovery permissions before a production rollout.
Performance and observability
There is no useful records-per-second figure for every Streams topology. A stateless filter, a windowed aggregate, and a join with large state have different CPU, memory, network, and disk profiles. Benchmark with representative keys, serialized values, partition counts, retention, and recovery. Keep the input rate, hardware, broker layout, and topology beside the result so later comparisons stay meaningful.
These Kafka Streams 4.2 JMX attribute names come from the Streams monitoring reference. Task latency, restore, and RocksDB statistics are recorded at DEBUG; enable metrics.recording.level=DEBUG only after considering the extra metric collection cost.
| Question | Kafka Streams 4.2 metrics to inspect |
|---|---|
| Is a task processing records? | process-rate, process-latency-avg, and process-latency-max |
| Are records arriving outside expected event-time order? | record-lateness-avg, record-lateness-max, dropped-records-rate, and dropped-records-total |
| Is a task restoring state? | restore-rate |
| Is RocksDB falling behind on compaction? | compaction-pending, num-running-compactions, estimate-pending-compaction-bytes, total-sst-files-size, and write-stall-duration-avg |
| Is the process running out of local disk? | Measure the state directory and filesystem free space at the host or container level; Kafka Streams does not expose one JMX attribute for total state-store disk use. |
Set alerts from the service’s recovery-time and processing-lag objectives, then tune them against a steady-state baseline. A task’s latency or a growing compaction backlog needs context from input rate, available disk, and restore capacity; one fixed threshold will not fit every topology.
Quick Recap
- Kafka Streams runs in the application process and uses Kafka topics for input, output, and recovery.
- Estimate local state from the workload, then check disk use and restore time under load.
exactly_once_v2covers Kafka transactions. External database writes need idempotency or their own coordination.- Task count and partitioning set the topology’s parallelism.
- Rebalances can pause task processing while assignments and local state recover.
- Use release-documented metrics and host-level disk measurements to monitor the application.
Interview Questions
exactly_once_v2, Kafka Streams commits Kafka output and consumed offsets in one Kafka transaction. A write to an external database sits outside that transaction and may be repeated, so make it idempotent or coordinate it with the database transaction model.Further Reading
- Apache Kafka: topics, partitions, and consumer groups used by Kafka Streams.
- Apache Flink: compare a separate processing engine with Kafka Streams.
- Event-Driven Architecture: connect stream processing to a larger event-driven system.
- Outbox Pattern: publish a database change to Kafka from an outbox record committed with the change.
- Kafka Streams 4.2 documentation: the official API and configuration reference for these examples.
Conclusion
Kafka Streams embeds processing in an application and fits pipelines whose inputs and outputs are Kafka topics. Its stateful operations rely on local stores and changelog recovery, while Kafka transactions provide exactly-once behavior within Kafka. Partition count, state-store size, and rebalance behavior set practical limits in production; workloads that need broader connectors or richer event-time processing may fit a dedicated engine better.
Category
Related Posts
Change Data Capture: Tracking Database Changes with CDC
Compare log-based, trigger-based, and polling CDC. See how snapshot handoff, offsets, duplicates, ordering, schema changes, and deletes affect consumers.
Exactly-Once Semantics in Stream Processing
Exactly-once processing means results appear once within a boundary. Learn how Kafka transactions, checkpoints, and idempotent sinks shape that guarantee.
CPU Affinity & Real-Time Operating Systems
Learn how CPU affinity changes task placement, how Linux real-time policies differ, and why deadline guarantees depend on workload, configuration, and hardware.