Kafka Streams joins: streams, tables, global tables and foreign keys
A join in Kafka Streams combines records from two topics by key, but what "matching" means depends on whether each side is a stream of events or a table of current values. This page explains the join types and the rules underneath them, then runs each one with exact timings, including a partition mismatch that produces wrong results without any error.
Contents
How joins work in Kafka Streams
A join in a database looks at two tables at one moment. A join in Kafka Streams runs forever, as records arrive on either side, so it has to answer a different question: when a record arrives, what is it matched against? The answer depends on the two sides:
- Stream with stream: both sides are events, and there is no "current value" to look up. Each record is kept in a window store for a while, and records from the two sides match when their keys are equal and their timestamps are close enough.
- Stream with table: the table holds the latest value per key. Each stream record looks up the table at the moment it is processed. Table updates change future lookups but never trigger output.
- Table with table: both sides are state. An update on either side produces a new joined row, and a deletion produces a deletion.
Every join except those with a GlobalKTableu1
| Left side | Right side | Inner, left, outer | Windowed | Co-partitioning needed | Triggered by |
|---|---|---|---|---|---|
KStream | KStream | All three | Yes | Yes | Records on either side |
KStream | KTable | Inner, left | No | Yes | Stream records only |
KStream | GlobalKTable | Inner, left | No | No | Stream records only |
KTable | KTable | All three | No | Yes | Updates on either side |
KTable | KTable | Inner, left | No | No | Updates on either side |
Most programs run their topology in TopologyTestDriverkafka-streams-test-utilsEmbeddedKafkaKraftBrokerspring-kafka-test
Stream-stream joins and their window
Orders and payments are both events keyed by order id, and a payment belongs to an order if it arrives within 5 minutes of it. The input covers each case once: a payment in time, an order never paid, a payment with no order, and a payment 6 minutes late. The program runs the inner, left and outer joins on the same records:
import ch.qos.logback.classic.Level;
import java.time.Duration;
import java.time.Instant;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
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.JoinWindows;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.StreamJoined;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamStreamJoin {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
// both streams are keyed by order id
KStream<String, String> orders = builder.stream("orders", strings);
KStream<String, String> payments = builder.stream("payments", strings);
JoinWindows fiveMinutes = JoinWindows.ofTimeDifferenceAndGrace(
Duration.ofMinutes(5), Duration.ZERO);
StreamJoined<String, String, String> serdes =
StreamJoined.with(Serdes.String(), Serdes.String(), Serdes.String());
orders.join(payments, (o, p) -> o + " + " + p, fiveMinutes, serdes.withName("inner"))
.to("inner", Produced.with(Serdes.String(), Serdes.String()));
orders.leftJoin(payments, (o, p) -> o + " + " + p, fiveMinutes, serdes.withName("left"))
.to("left", Produced.with(Serdes.String(), Serdes.String()));
orders.outerJoin(payments, (o, p) -> o + " + " + p, fiveMinutes,
serdes.withName("outer"))
.to("outer", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-payments");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var o = driver.createInputTopic("orders",
new StringSerializer(), new StringSerializer());
var p = driver.createInputTopic("payments",
new StringSerializer(), new StringSerializer());
Instant t0 = Instant.parse("2026-01-01T10:00:00Z");
send(o, "o1", "order o1", t0, 0);
send(p, "o1", "paid o1", t0, 2); // 2 minutes later: inside the window
send(o, "o2", "order o2", t0, 3); // never paid
send(p, "o3", "paid o3", t0, 4); // a payment with no order
send(o, "o4", "order o4", t0, 5);
send(p, "o4", "paid o4", t0, 11); // 6 minutes later: outside the window
send(o, "o5", "order o5", t0, 20); // moves stream time on, closing the windows
for (String topic : new String[] {"inner", "left", "outer"}) {
System.out.println(topic + ":");
driver.createOutputTopic(topic, new StringDeserializer(), new StringDeserializer())
.readKeyValuesToList().forEach(kv -> System.out.println(" " + kv.value));
}
}
}
static void send(TestInputTopic<String, String> topic, String key, String value,
Instant t0, int minute) {
topic.pipeInput(key, value, t0.plus(Duration.ofMinutes(minute)));
}
static void quietLogs() {
// 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);
}
}
inner:
order o1 + paid o1
left:
order o1 + paid o1
order o2 + null
order o4 + null
outer:
order o1 + paid o1
order o2 + null
null + paid o3
order o4 + null
null + paid o4
- The inner join produced only o1, whose payment came 2 minutes after the order. The o4 payment, 6 minutes after its order, is outside the 5-minute window and matched nothing.
- The left join added o2 and o4 with a null payment. Those results were not emitted when the orders arrived, but once stream time passed the end of their window: a payment could still have come until then.
- The outer join added the unmatched payments too, o3 and the late o4, with a null order.
- o5 at minute 20 appears in none of the outputs. It only moved stream time forward, and its own window is still open, so its left result would come later.
JoinWindows.ofTimeDifferenceAndGrace(5 minutes, 0)JoinWindows.of(...)
Stream-table joins: enrichment with timing
Enriching click events with the user's current tier is the classic stream-table join. The order of events matters here, so the program interleaves profile changes and clicks and prints what each step produced:
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamTableJoin {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
KStream<String, String> clicks = builder.stream("clicks", strings); // key: user id
KTable<String, String> users = builder.table("users", strings); // key: user id
clicks.join(users, (page, tier) -> page + " by " + tier + " user")
.to("inner", Produced.with(Serdes.String(), Serdes.String()));
clicks.leftJoin(users, (page, tier) -> page + " by " + tier + " user")
.to("left", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "click-enricher");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var click = driver.createInputTopic("clicks",
new StringSerializer(), new StringSerializer());
var user = driver.createInputTopic("users",
new StringSerializer(), new StringSerializer());
TestOutputTopic<String, String> inner = driver.createOutputTopic("inner",
new StringDeserializer(), new StringDeserializer());
TestOutputTopic<String, String> left = driver.createOutputTopic("left",
new StringDeserializer(), new StringDeserializer());
step("click before the profile exists", inner, left,
() -> click.pipeInput("u1", "/home"));
step("profile u1 = gold", inner, left, () -> user.pipeInput("u1", "gold"));
step("click", inner, left, () -> click.pipeInput("u1", "/cart"));
step("profile u1 = platinum", inner, left, () -> user.pipeInput("u1", "platinum"));
step("click", inner, left, () -> click.pipeInput("u1", "/checkout"));
step("profile u1 deleted", inner, left,
() -> user.pipeInput("u1", (String) null));
step("click", inner, left, () -> click.pipeInput("u1", "/help"));
}
}
static void step(String what, TestOutputTopic<String, String> inner,
TestOutputTopic<String, String> left, Runnable input) {
input.run();
System.out.printf("%-32s inner: %-28s left: %s%n", what,
inner.isEmpty() ? "-" : inner.readValue(), left.isEmpty() ? "-" : left.readValue());
}
static void quietLogs() {
// 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);
}
}
click before the profile exists inner: - left: /home by null user
profile u1 = gold inner: - left: -
click inner: /cart by gold user left: /cart by gold user
profile u1 = platinum inner: - left: -
click inner: /checkout by platinum user left: /checkout by platinum user
profile u1 deleted inner: - left: -
click inner: - left: /help by null user
- The first click arrived before the profile existed. The inner join dropped it; the left join emitted it with a null tier.
- Creating, changing and deleting the profile produced no output on either join. Only the stream side triggers a stream-table join.
- Each later click joined the profile as it was at that moment: gold, then platinum, then none after the deletion.
- The table is not consulted again later. The
click stays unenriched even after the profile appears, because a stream-table join never revisits past records./home
On a real broker, the order between the two topics is decided by record timestamps: Kafka Streams processes the record with the smaller timestamp first, across the partitions of a task. When the profile topic lags behind, clicks can be processed before the profile update they should see. max.task.idle.msStores.persistentVersionedKeyValueStore
GlobalKTable joins: lookups by any field
Orders keyed by order id need the product name, but the product id is inside the order's value, not its key. A GlobalKTable
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.GlobalKTable;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalTableJoin {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
// orders keyed by order id, value "productId,quantity"
KStream<String, String> orders = builder.stream("orders", strings);
// products keyed by product id; every instance gets a full copy
GlobalKTable<String, String> products = builder.globalTable("products", strings);
orders.join(products,
(orderId, order) -> order.split(",")[0], // which product to look up
(order, product) -> order.split(",")[1] + " x " + product)
.to("order-lines", Produced.with(Serdes.String(), Serdes.String()));
Topology topology = builder.build();
System.out.print(topology.describe());
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "order-lines");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(topology, props)) {
var product = driver.createInputTopic("products",
new StringSerializer(), new StringSerializer());
var order = driver.createInputTopic("orders",
new StringSerializer(), new StringSerializer());
product.pipeInput("p-7", "keyboard");
product.pipeInput("p-9", "monitor");
order.pipeInput("order-1", "p-9,2");
order.pipeInput("order-2", "p-7,1");
order.pipeInput("order-3", "p-404,5"); // unknown product: an inner join drops it
driver.createOutputTopic("order-lines",
new StringDeserializer(), new StringDeserializer())
.readKeyValuesToList().forEach(kv -> System.out.println(kv));
}
}
static void quietLogs() {
// 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);
}
}
Topologies:
Sub-topology: 0
Source: KSTREAM-SOURCE-0000000000 (topics: [orders])
--> KSTREAM-LEFTJOIN-0000000004
Processor: KSTREAM-LEFTJOIN-0000000004 (stores: [])
--> KSTREAM-SINK-0000000005
<-- KSTREAM-SOURCE-0000000000
Sink: KSTREAM-SINK-0000000005 (topic: order-lines)
<-- KSTREAM-LEFTJOIN-0000000004
Sub-topology: 1 for global store (will not generate tasks)
Source: KSTREAM-SOURCE-0000000002 (topics: [products])
--> KTABLE-SOURCE-0000000003
Processor: KTABLE-SOURCE-0000000003 (stores: [products-STATE-STORE-0000000001])
--> none
<-- KSTREAM-SOURCE-0000000002
KeyValue(order-1, 2 x monitor)
KeyValue(order-2, 1 x keyboard)
- The topology has a separate sub-topology "for global store", which generates no tasks. A dedicated global thread reads every partition of
into the store on each instance.products - The join itself is in sub-topology 0, right after the orders source, with no repartition topic. The orders were not rekeyed; the key selector
chose the product id for the lookup.order.split(",")[0] - Order 3 asked for an unknown product and was dropped by the inner join;
would have kept it with a null product.leftJoin - The processor is named
even though the code callsKSTREAM-LEFTJOIN . The DSL reuses that generated name for global table joins; it has no effect on the result.join
The trade-off is size and startup. Every instance stores and reads the whole table, and an application does not start processing until each global store has caught up with the end of its topic. Global tables suit reference data such as products, currencies or countries, not tables with tens of millions of rows. Since global stores are bootstrapped before processing starts, there is also no timestamp synchronization with the stream side.
Table-table joins by foreign key
Orders and products are both tables, and each order refers to a product by id in its value. A foreign-key join keeps the priced order up to date when either side changes. The program changes a price, moves an order to another product and deletes products, printing each update:
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.TableJoined;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ForeignKeyJoin {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
KTable<String, String> orders = builder.table("orders", strings); // "productId,qty"
KTable<String, String> products = builder.table("products", strings); // price in cents
orders.join(products,
order -> order.split(",")[0], // the foreign key
(order, price) -> order.split(",")[1] + " x " + price + " cents",
TableJoined.as("order-product"))
.toStream().to("priced-orders", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "pricing");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var order = driver.createInputTopic("orders",
new StringSerializer(), new StringSerializer());
var product = driver.createInputTopic("products",
new StringSerializer(), new StringSerializer());
TestOutputTopic<String, String> out = driver.createOutputTopic("priced-orders",
new StringDeserializer(), new StringDeserializer());
step("products p-1 = 500, p-2 = 900", out, () -> {
product.pipeInput("p-1", "500");
product.pipeInput("p-2", "900");
});
step("orders o-1 and o-2 for p-1, o-3 for p-2", out, () -> {
order.pipeInput("o-1", "p-1,2");
order.pipeInput("o-2", "p-1,1");
order.pipeInput("o-3", "p-2,4");
});
step("p-1 price changes to 450", out, () -> product.pipeInput("p-1", "450"));
step("o-3 switches to p-1", out, () -> order.pipeInput("o-3", "p-1,4"));
step("p-2 deleted", out, () -> product.pipeInput("p-2", (String) null));
step("p-1 deleted", out, () -> product.pipeInput("p-1", (String) null));
}
}
static void step(String what, TestOutputTopic<String, String> out, Runnable input) {
input.run();
System.out.println(what + ":");
if (out.isEmpty()) {
System.out.println(" (no output)");
}
out.readKeyValuesToList()
.forEach(kv -> System.out.println(" " + kv.key + " = " + kv.value));
}
static void quietLogs() {
// 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);
}
}
products p-1 = 500, p-2 = 900:
(no output)
orders o-1 and o-2 for p-1, o-3 for p-2:
o-1 = 2 x 500 cents
o-2 = 1 x 500 cents
o-3 = 4 x 900 cents
p-1 price changes to 450:
o-1 = 2 x 450 cents
o-2 = 1 x 450 cents
o-3 switches to p-1:
o-3 = 4 x 450 cents
p-2 deleted:
(no output)
p-1 deleted:
o-1 = null
o-2 = null
o-3 = null
- Loading products alone produced nothing: no order referred to them yet.
- Each new order produced one joined row with its product's price.
- The price change on p-1 updated both orders that refer to it, o-1 and o-2, but not o-3. This is what a stream-table join cannot do.
- When o-3 switched to p-1, it was re-joined with the new product.
- Deleting p-2 produced nothing, because no order referred to it any more. Deleting p-1 produced tombstones, null values, for all three orders: in an inner join, a row without a match is deleted.
Underneath, Kafka Streams sends a subscription for each order to the partition that owns its product, through internal topics, and sends responses back, so neither input needs to be co-partitioned. That costs extra topics and state. Records whose foreign-key extractor returns null are ignored. For two tables that share the same primary key, such as a user and a user's settings, use the plain KTable.join(KTable, joiner)
The co-partitioning trap
Co-partitioning is easy to break: a team creates the clicks topic with 3 partitions and the users topic with 2. The program does exactly that, starts a stream-table left join, loads six profiles and then sends one click for each user:
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.TreeMap;
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.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class CoPartitioning {
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))) {
// the mistake: the two sides of the join have different partition counts
admin.createTopics(List.of(new NewTopic("clicks", 3, (short) 1),
new NewTopic("users", 2, (short) 1))).all().get();
}
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
KStream<String, String> clicks = builder.stream("clicks", strings);
KTable<String, String> users = builder.table("users", strings);
Map<String, String> joined = new TreeMap<>();
clicks.leftJoin(users, (page, tier) -> page + " by " + tier + " user")
.foreach((user, result) -> {
synchronized (joined) {
joined.put(user, result);
}
});
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "click-enricher");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("streams").toString());
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);
}
System.out.println("application state: " + streams.state());
for (int i = 0; i < 6; i++) {
producer.send(new ProducerRecord<>("users", "u" + i, "gold")).get();
}
Thread.sleep(2000); // give the table time to load every profile
for (int i = 0; i < 6; i++) {
producer.send(new ProducerRecord<>("clicks", "u" + i, "/home")).get();
}
while (true) {
synchronized (joined) {
if (joined.size() == 6) {
break;
}
}
Thread.sleep(100);
}
joined.forEach((user, result) -> System.out.println(user + ": " + result));
}
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);
}
}
}
application state: RUNNING
u0: /home by null user
u1: /home by null user
u2: /home by gold user
u3: /home by null user
u4: /home by gold user
u5: /home by null user
- The application reached
. In this run with Kafka Streams 4.2.2, nothing stopped the join, although the documentation says the partition counts of a join's inputs are verified and a mismatch throws an exception.RUNNING - Every user had a gold profile, yet four of the six clicks were joined with null. Task 0_p joins partition p of clicks with partition p of users; a key goes to partition hash % 3 in one topic and hash % 2 in the other.
- u2 and u4 happened to land on the same partition number in both topics, which is why they matched. A test with only those keys would have passed.
Fix the partitioning, not the join. Create both topics with the same partition count, or repartition one side to match the other with repartition(Repartitioned.numberOfPartitions(2))GlobalKTable
Traps that cost correctness
- Null keys: stream records with a null key are dropped by stream-table joins. Set the key with
before the join, which also triggers a repartition.selectKey - Rekeying before a join: after
ormap , Kafka Streams inserts a repartition topic so that the rekeyed stream is co-partitioned with the other side. Name it withselectKey orStreamJoined to keep upgrades safe.Repartitioned - Bootstrapping a table: when an application starts on topics that already hold data, Kafka Streams interleaves the two sides by timestamp. If the profiles carry newer timestamps than the clicks, for example because they were re-imported, the clicks are processed first and join with nothing.
- Window size: a stream-stream window that is too short silently drops late matches; one that is too long multiplies state. Size it from measured delays between the two events.
- Join results as tables: a KTable join emits updates and tombstones. Write them to a compacted topic, or a consumer that treats them as events will double-count.
Choosing a join
| Situation | Join |
|---|---|
| Two kinds of events that belong together within a time span | KStream.join(KStream, ..., JoinWindows)leftJoinouterJoin |
| Add the current state of an entity to each event | KStream.join(KTable)leftJoin |
| The same, with small reference data or a key inside the value | KStream.join(GlobalKTable, keySelector, joiner) |
| The state as it was when the event happened | Stream-table join against a versioned store |
| Two tables with the same key | KTable.join(KTable) |
| A table that refers to another table by id | Foreign-key KTable.join(KTable, fkExtractor, joiner) |
| Inputs with different partition counts | repartition() |
The state stores behind joins are explained on the