Kafka Streams interactive queries: reading state stores directly
Every Kafka Streams aggregation already holds its results in a local state store. Interactive queries let the application read those stores directly, so a count or a balance can be served over HTTP without writing it to a database first. This page explains how the stores are spread across instances, then runs key, range and window queries, routing between two instances and the newer IQv2 API on a Kafka 4.2 broker.
Contents
What interactive queries are
A Kafka Streams aggregation keeps its current result in a state store: the number of orders per customer, the logins per user per five minutes. The usual way to make such results available to other services is to write them to an output topic and from there into a database. Interactive queries skip that step. The application asks its own state stores for a key, a range of keys or a time range, and serves the answer, for example over HTTP.
The catch is that the state is partitioned. Each task owns the store for one input partition, and the tasks are spread over all running instances of the application. A query for one key therefore has three parts:
- Find which instance holds the key. Every instance knows the whole assignment, because instances exchange their
address, a host and port you configure, during rebalancing.application.server hashes the key the same way the producer did and returns the active host, plus any standby hosts.queryMetadataForKey - If the key is local, read the local store through a read-only view.
- If not, send the query to the other instance yourself. Kafka Streams has no network layer for queries: you provide the HTTP, gRPC or other endpoint.
| API | Entry point | Store types | Notes |
|---|---|---|---|
| Interactive queries (IQv1) | streams.store(StoreQueryParameters) | keyValueStore()windowStore()sessionStore() | Returns a read-only view across all local partitions; stable API |
| IQv2 (KIP-796) | streams.query(StateQueryRequest) | Query classes: KeyQueryRangeQueryWindowKeyQueryWindowRangeQuery | Results per partition, with positions for consistency; marked @Evolving |
Every program starts a single-node Kafka 4.2 broker inside the JVM with EmbeddedKafkaKraftBrokerspring-kafka-testKafkaStreamsTopologyTestDriver
Querying a key-value store
A count of orders per customer is the simplest queryable store. The program names the store with Materialized.asstart()
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StoreQueryParameters;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.InvalidStateStoreException;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class KeyValueQueries {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1))).all().get();
}
StreamsBuilder builder = new StreamsBuilder();
builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.count(Materialized.as("orders-per-customer")); // a named, queryable store
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-counts");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("streams").toString());
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
try (KafkaStreams streams = new KafkaStreams(builder.build(), props);
var producer = new KafkaProducer<String, String>(producerProps(servers))) {
streams.start();
StoreQueryParameters<ReadOnlyKeyValueStore<String, Long>> params =
StoreQueryParameters.fromNameAndType("orders-per-customer",
QueryableStoreTypes.keyValueStore());
try {
streams.store(params).get("ann"); // straight after start()
} catch (InvalidStateStoreException e) {
System.out.println("queried in state " + streams.state() + ": "
+ e.getClass().getSimpleName());
}
while (streams.state() != KafkaStreams.State.RUNNING) {
Thread.sleep(100);
}
String[] customers = {"ann", "bob", "cid", "dan", "eve", "ann", "bob", "ann"};
for (String c : customers) {
producer.send(new ProducerRecord<>("orders", c, "order")).get();
}
ReadOnlyKeyValueStore<String, Long> store = streams.store(params);
while (store.get("ann") == null || store.get("ann") < 3) {
Thread.sleep(100); // wait until the application has processed the orders
}
System.out.println("get(ann) = " + store.get("ann"));
System.out.println("get(zoe) = " + store.get("zoe"));
List<String> range = new ArrayList<>();
try (KeyValueIterator<String, Long> it = store.range("bob", "dan")) {
it.forEachRemaining(kv -> range.add(kv.key + "=" + kv.value));
}
System.out.println("range(bob, dan), sorted here: " + range.stream().sorted().toList());
for (int partition = 0; partition < 2; partition++) {
ReadOnlyKeyValueStore<String, Long> one =
streams.store(params.withPartition(partition));
List<String> all = new ArrayList<>();
try (KeyValueIterator<String, Long> it = one.all()) {
it.forEachRemaining(kv -> all.add(kv.key + "=" + kv.value));
}
System.out.println("partition " + partition + " all(): " + all);
}
System.out.println("approximateNumEntries() = " + store.approximateNumEntries());
try {
store.getClass().getMethod("put", Object.class, Object.class);
System.out.println("the store view has a put method");
} catch (NoSuchMethodException e) {
System.out.println("the store view is read-only: no put method");
}
}
broker.destroy();
}
static Properties producerProps(String servers) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
queried in state REBALANCING: InvalidStateStoreException
get(ann) = 3
get(zoe) = null
range(bob, dan), sorted here: [bob=2, cid=1, dan=1]
partition 0 all(): [ann=3, bob=2, cid=1, eve=1]
partition 1 all(): [dan=1]
approximateNumEntries() = 0
the store view is read-only: no put method
- Straight after
, the application was stillstart() .REBALANCING returned a view, but the firststore() threwget , because no task had been assigned yet. A query endpoint must expect this during every rebalance, and retry or return a 503.InvalidStateStoreException returned 3 andget(ann) returnedget(zoe) : a missing key is not an error.null returned bob, cid and dan, the keys from bob to dan inclusive. The program sorts them before printing, because the view walks the store of each local partition in turn: across partitions, the order is not sorted, and in test runs it changed from run to run.range(bob, dan)- With
,withPartition read one partition's store at a time. Partition 0 holds ann, bob, cid and eve in key order; dan landed in partition 1.all() returned 0 although there are five keys. It is an estimate from RocksDB, and the counts were still in the record cache, which is flushed to RocksDB on commit. In a separate run that waited 30 seconds for the next commit, it reported 5.approximateNumEntries()- The view has no
: interactive queries can only read. All writes go through the topology.put
Reads go through the cache, so get
Querying a window store
A windowed aggregation stores one value per key and window. Logins are counted per user in 5-minute tumbling windows, with event times set on each record. Bob's first login is sent after ann's later ones, to show what a window store does with a late record:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StoreQueryParameters;
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.Materialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyWindowStore;
import org.apache.kafka.streams.state.WindowStoreIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class WindowQueries {
static final Instant T0 = Instant.parse("2026-03-01T09:00:00Z");
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
admin.createTopics(List.of(new NewTopic("logins", 1, (short) 1))).all().get();
}
StreamsBuilder builder = new StreamsBuilder();
builder.stream("logins", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
.count(Materialized.as("logins-per-5min"));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "login-counts");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("streams").toString());
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
try (KafkaStreams streams = new KafkaStreams(builder.build(), props);
var producer = new KafkaProducer<String, String>(producerProps(servers))) {
streams.start();
while (streams.state() != KafkaStreams.State.RUNNING) {
Thread.sleep(100);
}
// minutes after 09:00 at which each user logged in
send(producer, "ann", 1, 2, 4, 6, 12, 13);
send(producer, "bob", 3, 11);
ReadOnlyWindowStore<String, Long> store = streams.store(StoreQueryParameters
.fromNameAndType("logins-per-5min", QueryableStoreTypes.windowStore()));
while (store.fetch("ann", T0.plus(Duration.ofMinutes(10)).toEpochMilli()) == null) {
Thread.sleep(100);
}
Thread.sleep(500);
System.out.println("ann, windows starting 09:00 to 09:15:");
try (WindowStoreIterator<Long> it =
store.fetch("ann", T0, T0.plus(Duration.ofMinutes(15)))) {
it.forEachRemaining(kv ->
System.out.println(" " + time(kv.key) + " count " + kv.value));
}
System.out.println("ann, newest first, windows starting 09:05 to 09:15:");
try (WindowStoreIterator<Long> it = store.backwardFetch("ann",
T0.plus(Duration.ofMinutes(5)), T0.plus(Duration.ofMinutes(15)))) {
it.forEachRemaining(kv ->
System.out.println(" " + time(kv.key) + " count " + kv.value));
}
System.out.println("window starting 09:10, all users:");
try (var it = store.fetchAll(T0.plus(Duration.ofMinutes(10)),
T0.plus(Duration.ofMinutes(10)))) {
it.forEachRemaining(kv -> System.out.println(" " + kv.key.key() + " count "
+ kv.value + ", window " + time(kv.key.window().start())
+ " to " + time(kv.key.window().end())));
}
System.out.println("bob at the window starting 09:00: "
+ store.fetch("bob", T0.toEpochMilli()));
}
broker.destroy();
}
static void send(KafkaProducer<String, String> producer, String user, int... minutes)
throws Exception {
for (int m : minutes) {
long ts = T0.plus(Duration.ofMinutes(m)).toEpochMilli();
producer.send(new ProducerRecord<>("logins", null, ts, user, "login")).get();
}
}
static String time(long epochMillis) {
return Instant.ofEpochMilli(epochMillis).toString().substring(11, 16);
}
static Properties producerProps(String servers) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
ann, windows starting 09:00 to 09:15:
09:00 count 3
09:05 count 1
09:10 count 2
ann, newest first, windows starting 09:05 to 09:15:
09:10 count 2
09:05 count 1
window starting 09:10, all users:
ann count 2, window 09:10 to 09:15
bob count 1, window 09:10 to 09:15
bob at the window starting 09:00: null
returned ann's windows whose start time is between 09:00 and 09:15: 3 logins from 09:00, 1 from 09:05 and 2 from 09:10. The window at 09:15 is empty, so it does not appear.fetch(key, from, to) returned the same kind of result newest first, which suits "show the last N windows" queries.backwardFetch returned every key's window starting at 09:10, with the window bounds in thefetchAll(from, to) key.Windowed- Bob logged in at 09:03, but that record was sent after ann's login at 09:13 had moved stream time on. The window starting at 09:00 has no grace period, so it was already closed and the record was dropped, and
returnedfetch(bob, 09:00) . Bob's login at 09:11 was counted.null
The time arguments are window start times, not record times. A window store keeps windows only for its retention period, at least the window size plus grace, so a query for older windows finds nothing even though the input is still in Kafka. The
Several instances: finding the key and forwarding
With two instances, each holds half of the store, and a query can arrive at either. The program runs two instances in one JVM, each with its own state directory and a small JDK HTTP server whose port it publishes as application.server
import ch.qos.logback.classic.Level;
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyQueryMetadata;
import org.apache.kafka.streams.StoreQueryParameters;
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.Materialized;
import org.apache.kafka.streams.state.HostInfo;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class TwoInstances {
static final String STORE = "orders-per-customer";
static final HttpClient HTTP = HttpClient.newHttpClient();
// one application instance: Kafka Streams plus a small HTTP server that answers queries
record Instance(String name, KafkaStreams streams, HttpServer http, HostInfo self) {
static Instance start(String name, String servers) throws Exception {
HttpServer http = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
HostInfo self = new HostInfo("localhost", http.getAddress().getPort());
StreamsBuilder builder = new StreamsBuilder();
builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey().count(Materialized.as(STORE));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-counts");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG,
Files.createTempDirectory("streams-" + name).toString());
// tells the other instances where to send queries for this instance's keys
props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, self.host() + ":" + self.port());
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
Instance instance = new Instance(name, new KafkaStreams(builder.build(), props),
http, self);
http.createContext("/count/", exchange -> {
String key = exchange.getRequestURI().getPath().substring("/count/".length());
byte[] body = instance.answer(key).getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
});
http.start();
instance.streams.start();
return instance;
}
// answers from the local store when this instance owns the key, otherwise forwards
String answer(String key) {
KeyQueryMetadata md = streams.queryMetadataForKey(STORE, key,
Serdes.String().serializer());
if (md.activeHost().equals(self)) {
ReadOnlyKeyValueStore<String, Long> store = streams.store(StoreQueryParameters
.fromNameAndType(STORE, QueryableStoreTypes.keyValueStore()));
return "local:" + store.get(key);
}
return "forwarded:" + get(md.activeHost(), key);
}
int localTasks() {
return streams.metadataForLocalThreads().iterator().next().activeTasks().size();
}
void stop() {
streams.close();
http.stop(0);
}
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
admin.createTopics(List.of(new NewTopic("orders", 4, (short) 1))).all().get();
}
Instance a = Instance.start("A", servers);
Instance b = Instance.start("B", servers);
// wait until both run and the 4 tasks are split between them
while (a.streams.state() != KafkaStreams.State.RUNNING
|| b.streams.state() != KafkaStreams.State.RUNNING
|| a.localTasks() + b.localTasks() != 4 || a.localTasks() == 0
|| b.localTasks() == 0) {
Thread.sleep(200);
}
System.out.println("tasks: A has " + a.localTasks() + ", B has " + b.localTasks());
List<String> customers = List.of("ann", "bob", "cid", "dan", "eve", "fay");
try (var producer = new KafkaProducer<String, String>(producerProps(servers))) {
for (int i = 0; i < customers.size(); i++) {
for (int n = 0; n <= i; n++) { // ann orders once, bob twice, and so on
producer.send(new ProducerRecord<>("orders", customers.get(i), "order"));
}
}
}
while (!a.answer("fay").endsWith(":6")) {
Thread.sleep(200);
}
for (String c : customers) {
String viaA = get(a.self, c); // "local:N", or "forwarded:local:N"
String viaB = get(b.self, c);
boolean exactlyOneLocal = viaA.startsWith("local") != viaB.startsWith("local");
System.out.println(c + ": via A " + count(viaA) + ", via B " + count(viaB)
+ ", answered locally by exactly one instance: " + exactlyOneLocal);
}
a.stop();
b.stop();
broker.destroy();
}
static String count(String answer) {
return answer.substring(answer.lastIndexOf(':') + 1);
}
static String get(HostInfo host, String key) {
try {
URI uri = URI.create("http://" + host.host() + ":" + host.port() + "/count/" + key);
return HTTP.send(HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.ofString()).body();
} catch (Exception e) {
return "error:" + e.getMessage();
}
}
static Properties producerProps(String servers) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
tasks: A has 2, B has 2
ann: via A 1, via B 1, answered locally by exactly one instance: true
bob: via A 2, via B 2, answered locally by exactly one instance: true
cid: via A 3, via B 3, answered locally by exactly one instance: true
dan: via A 4, via B 4, answered locally by exactly one instance: true
eve: via A 5, via B 5, answered locally by exactly one instance: true
fay: via A 6, via B 6, answered locally by exactly one instance: true
- The input topic has 4 partitions, so there are 4 tasks, and the rebalance gave each instance 2.
- Every customer's count came back the same through A and through B: ann 1, bob 2, up to fay 6. A client does not need to know where a key lives.
- For each key, exactly one of the two requests was answered locally; the other instance looked up the active host with
and forwarded the request over HTTP. Which instance owns which customer depends on the assignment, which can differ from run to run, so the program checks the rule instead of printing owners.queryMetadataForKey
Three details matter in a real deployment. The application.serverlocalhostInvalidStateStoreException
Standby replicas and stale reads
By default only the active task's store can be queried. KeyQueryMetadatanum.standby.replicasStoreQueryParameters.enableStaleStores()
ReadOnlyKeyValueStore<String, Long> store = streams.store(StoreQueryParameters
.fromNameAndType("orders-per-customer", QueryableStoreTypes.keyValueStore())
.enableStaleStores()); // may read a standby copy that lags behind
That keeps queries working during a failover, at the price of answers that may be a few seconds old. withPartition(n)KeyQueryMetadata.partition()
IQv2: per-partition results and read-your-writes
A client that has just written a record often wants to read its own write. With IQv1 there is no way to know whether the store has processed that offset yet. IQv2 attaches a position to each result, the input offsets the store has processed, and accepts a bound. The program writes an order, asks for ann's count with a bound at that write's offset, then with a bound one offset further:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Bytes;
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.Materialized;
import org.apache.kafka.streams.query.FailureReason;
import org.apache.kafka.streams.query.KeyQuery;
import org.apache.kafka.streams.query.Position;
import org.apache.kafka.streams.query.PositionBound;
import org.apache.kafka.streams.query.QueryResult;
import org.apache.kafka.streams.query.RangeQuery;
import org.apache.kafka.streams.query.StateQueryRequest;
import org.apache.kafka.streams.query.StateQueryResult;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class QueriesV2 {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1))).all().get();
}
StreamsBuilder builder = new StreamsBuilder();
builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as(
"orders-per-customer").withCachingDisabled());
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-counts");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("streams").toString());
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
try (KafkaStreams streams = new KafkaStreams(builder.build(), props);
var producer = new KafkaProducer<String, String>(producerProps(servers))) {
streams.start();
while (streams.state() != KafkaStreams.State.RUNNING) {
Thread.sleep(100);
}
for (String c : List.of("ann", "bob", "cid", "bob")) {
producer.send(new ProducerRecord<>("orders", c, "order")).get();
}
// read-your-writes: remember where the last write for ann landed
RecordMetadata written =
producer.send(new ProducerRecord<>("orders", "ann", "order")).get();
Position afterWrite = Position.emptyPosition()
.withComponent("orders", written.partition(), written.offset());
StateQueryRequest<Long> annAfterWrite = StateQueryRequest
.inStore("orders-per-customer")
.withQuery(KeyQuery.<String, Long>withKey("ann"))
.withPartitions(Set.of(written.partition()))
.withPositionBound(PositionBound.at(afterWrite));
QueryResult<Long> first = query(streams, annAfterWrite);
while (first.isFailure()) { // the application has not processed that offset yet
Thread.sleep(50);
first = query(streams, annAfterWrite);
}
System.out.println("ann, including the write at offset " + written.offset()
+ " of partition " + written.partition() + ": " + first.getResult());
// a bound one offset beyond anything written yet cannot be met
Position future = Position.emptyPosition()
.withComponent("orders", written.partition(), written.offset() + 1);
QueryResult<Long> tooNew = query(streams, StateQueryRequest
.inStore("orders-per-customer")
.withQuery(KeyQuery.<String, Long>withKey("ann"))
.withPartitions(Set.of(written.partition()))
.withPositionBound(PositionBound.at(future)));
System.out.println("bound at offset " + (written.offset() + 1) + ": "
+ tooNew.getFailureReason());
StateQueryResult<KeyValueIterator<String, Long>> range = streams.query(
StateQueryRequest.inStore("orders-per-customer")
.withQuery(RangeQuery.<String, Long>withNoBounds()
.withDescendingKeys()));
range.getPartitionResults().forEach((partition, result) -> {
System.out.print("partition " + partition + ", descending:");
try (KeyValueIterator<String, Long> it = result.getResult()) {
it.forEachRemaining(kv -> System.out.print(" " + kv.key + "=" + kv.value));
}
System.out.println();
});
System.out.println("position of the whole result: " + range.getPosition());
}
broker.destroy();
}
// retries while the partition's store is not yet available for queries
static QueryResult<Long> query(KafkaStreams streams, StateQueryRequest<Long> request)
throws InterruptedException {
while (true) {
// getOnlyPartitionResult() returns only successful results, so read the map
QueryResult<Long> result = streams.query(request).getPartitionResults()
.values().stream().findFirst().orElse(null);
if (result != null && (result.isSuccess()
|| result.getFailureReason() == FailureReason.NOT_UP_TO_BOUND)) {
return result;
}
Thread.sleep(50);
}
}
static Properties producerProps(String servers) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return p;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup: both are silenced.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
ann, including the write at offset 4 of partition 0: 2
bound at offset 5: NOT_UP_TO_BOUND
partition 0, descending: cid=1 bob=2 ann=2
partition 1, descending:
position of the whole result: Position{position={orders={0=4}}}
- The query bound at offset 4 of partition 0, where the second order for ann was written, returned 2, including that write. Until the store had processed offset 4, the same query failed with
, and the program retried.NOT_UP_TO_BOUND - The bound at offset 5, which nothing had been written to yet, failed with
, instead of returning an answer that might be stale.NOT_UP_TO_BOUND - The
with no bounds and descending order returned one result per partition: cid, bob and ann from partition 0, nothing from partition 1, where no order landed.RangeQuery - The position of the whole result says the stores had processed up to offset 4 of
partition 0.orders
Two details differ from IQv1. getOnlyPartitionResult()nullgetPartitionResults()queryRangeQueryKeyQuery
Designing a query layer
- Name the stores: only stores with a name from
or the Processor API are queryable by a stable name.Materialized.as - Handle rebalances: catch
, retry with a short back-off, and return an error to the client after a limit.InvalidStateStoreException - Bound the scans:
and unbounded ranges read every local partition; expose them only for small stores, and page through large ones with ranges.all() - Know the freshness: an answer reflects what the store has processed, which lags the input topic by the consumer lag. IQv2 position bounds make that explicit.
- Keep it internal: a query endpoint exposes the store's contents directly; put authentication in front of it like any other API.
Choosing how to serve Kafka Streams state
| Situation | Use |
|---|---|
| One instance, simple lookups | streams.store(...)getrange |
| Several instances | application.serverqueryMetadataForKey |
| Results per time window | windowStore()fetchbackwardFetch |
| Read-your-writes, or partition-level control | IQv2 StateQueryRequestPositionBound |
| Availability during failover matters more than freshness | num.standby.replicasenableStaleStores() |
| Complex queries, joins across keys, or many readers | Write the results to a topic and into a database; interactive queries are lookups, not SQL |
The stores themselves are built on the