Kafka Streams Interactive Queries, Testing, Deployment and Monitoring

Apache Kafka 17 min min read Updated: Nov 17, 2026 Advanced
Kafka Streams Interactive Queries, Testing, Deployment and Monitoring
Advanced Topic 3 of 4

Interactive Queries

State stores are not only internal. You can query them directly from your application, for example to power a REST endpoint that returns 'orders per customer' without reading another database.

java // state store was created with Materialized.as("orders-per-customer") ReadOnlyKeyValueStore<String, Long> store = streams.store( StoreQueryParameters.fromNameAndType("orders-per-customer", QueryableStoreTypes.keyValueStore())); Long count = store.get("customer-42"); // single key try (KeyValueIterator<String, Long> all = store.all()) { // all local entries (close the iterator!) while (all.hasNext()) { KeyValue<String, Long> kv = all.next(); System.out.println(kv.key + " = " + kv.value); } }
State is partitioned: Each instance holds only some keys. For a key owned by another instance, find the owner and forward the request to it.
java // set per-instance address so instances can find each other props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, "orders-app-1.internal:8080"); KeyQueryMetadata md = streams.queryMetadataForKey("orders-per-customer", "customer-42", Serdes.String().serializer()); HostInfo owner = md.activeHost(); if (owner.equals(thisHost)) { return store.get("customer-42"); } else { return httpClient.get("http://" + owner.host() + ":" + owner.port() + "/orders/customer-42"); // forward to the owner }
  • Queries can fail during rebalances (InvalidStateStoreException). Retry with a short delay
  • The state store is read-only for queries. Only the topology updates it
  • Use streams.state() to check the app is RUNNING before serving queries

Testing Without a Broker: TopologyTestDriver

xml <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-streams-test-utils</artifactId> <version>4.0.0</version> <scope>test</scope> </dependency>
java class WordCountTest { private TopologyTestDriver driver; private TestInputTopic<String, String> input; private TestOutputTopic<String, Long> output; @BeforeEach void setup() { Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "test"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:1234"); driver = new TopologyTestDriver(WordCountApp.buildTopology(), props); // pass your Topology (extract it into a method) input = driver.createInputTopic("text-lines", new StringSerializer(), new StringSerializer()); output = driver.createOutputTopic("word-counts", new StringDeserializer(), new LongDeserializer()); } @AfterEach void teardown() { driver.close(); } @Test void countsWords() { input.pipeInput("hello kafka hello"); Map<String, Long> result = output.readKeyValuesToMap(); assertEquals(2L, result.get("hello")); assertEquals(1L, result.get("kafka")); } }
Design for testing: Put topology building in a static method that takes a StreamsBuilder (or returns a Topology). Then unit tests run in milliseconds with no broker. For windowed tests use pipeInput(key, value, timestamp) to control time and advanceWallClockTime for punctuations. Add a few integration tests with Testcontainers Kafka.

Error Handling

TypeHandler or approach
Deserialization error (bad bytes)default.deserialization.exception.handler = LogAndContinueExceptionHandler or a custom handler that sends the record to a dead letter topic
Production error (send to topic fails)default.production.exception.handler
Exception in your processing codestreams.setUncaughtExceptionHandler(ex -> StreamThreadExceptionResponse.REPLACE_THREAD) (or SHUTDOWN_CLIENT, SHUTDOWN_APPLICATION). Catch expected business errors inside the topology and route them to an error topic
java streams.setUncaughtExceptionHandler(ex -> { log.error("Stream thread failed", ex); return StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.REPLACE_THREAD; // start a new thread and continue }); streams.setStateListener((newState, oldState) -> log.info("State {} -> {}", oldState, newState));

Deployment

  • One container image, run several replicas. The number of useful threads is limited by the number of input partitions
  • Use a persistent volume for state.dir (StatefulSet in Kubernetes) so restarts do not rebuild the state from scratch
  • Set num.standby.replicas=1 and use rolling updates with maxUnavailable=1
  • Use static membership (group.instance.id) and a longer session.timeout.ms to avoid rebalances during short restarts
  • Give the JVM enough memory for RocksDB off-heap usage. Container memory must be above heap + RocksDB caches
  • Handle SIGTERM: call streams.close(Duration) in a shutdown hook
yaml apiVersion: apps/v1 kind: StatefulSet metadata: { name: orders-streams } spec: serviceName: orders-streams replicas: 3 selector: { matchLabels: { app: orders-streams } } template: metadata: { labels: { app: orders-streams } } spec: containers: - name: app image: registry.example.com/orders-streams:1.4.0 env: - { name: STATE_DIR, value: /data/kafka-streams } - { name: APPLICATION_SERVER, value: "$(POD_NAME).orders-streams:8080" } - { name: POD_NAME, valueFrom: { fieldRef: { fieldPath: metadata.name } } } volumeMounts: [ { name: state, mountPath: /data } ] resources: { requests: { memory: 2Gi, cpu: "1" }, limits: { memory: 3Gi } } volumeClaimTemplates: - metadata: { name: state } spec: { accessModes: ["ReadWriteOnce"], resources: { requests: { storage: 20Gi } } }

Changing a Topology

  • Internal topic and store names depend on the topology. Adding or reordering operations may change generated names. Name your operators explicitly (Named.as, Materialized.as, Grouped.as) to keep them stable
  • Incompatible changes may need a new application.id (reprocess from the beginning) or a reset
bash # Reset a stopped application to reprocess input from the start (deletes internal topics and resets offsets) bin/kafka-streams-application-reset.sh --application-id wordcount-app --bootstrap-server $BS --input-topics text-lines # then clear local state on each instance: streams.cleanUp() before start, or delete the state.dir folder

Monitoring

MetricWhy
stream-thread-metrics process-rate, process-latencyThroughput and speed per thread
commit-latency-avg, poll-ratioTime spent processing versus waiting
dropped-records-rate (late records)Grace period too small or clock issues
restore records and state of tasksTime spent restoring state after restart
Consumer lag of the application groupIs the app keeping up?
record-e2e-latency-avgEnd-to-end latency from source record timestamp
state (REBALANCING, RUNNING, ERROR)App health

Typical Production Problems

ProblemFix
Frequent rebalancesSlow processing exceeding max.poll.interval.ms, long GC, restarts. Use static membership, reduce batch work, tune poll settings
Very long restartsState restore. Use persistent volumes, standby replicas, smaller state
Memory growthRocksDB off-heap. Configure a RocksDBConfigSetter with bounded memory
Data skewHot keys make one task slow. Improve key choice or pre-aggregate
Wrong join resultsCheck co-partitioning and key types

Conclusion

Use interactive queries to serve state from your stream app (forwarding to the owning instance), test topologies fast with TopologyTestDriver, run on persistent volumes with standby replicas, name operators for stable internals, and monitor lag, restore time, dropped records and rebalances.

Quick Summary: IQ: find the owner instance; TopologyTestDriver; StatefulSet + PVC; name operators; monitor restore/rebalance.

Get Newsletter

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