Kafka Streams and Kafka Connect

Senior Differentiator 3 min

On this page

The question

What are Kafka Streams and Kafka Connect for?

30-second answer

Kafka Streams is a Java library for processing data inside your own application: it reads topics, filters, maps, joins, aggregates and windows them, keeps state in local stores backed by changelog topics, and writes results to topics, with exactly-once if enabled. Kafka Connect is a separate runtime that moves data between Kafka and other systems through configured connectors: sources such as Debezium for change data capture, sinks such as Elasticsearch or S3 (Simple Storage Service).

Understand it

One topic read as KStream and KTable

Compare

As a KStream, every record is an independent event, like a deposit. Summing per key gives alice 40 and bob 5; aggregations drop a record with no value.

View as text

Four records on one topic, in order: alice 10, bob 5, alice 30, and bob with a null value. Under each, what it does in the chosen reading; below, the result per key.

KStream: As a KStream, every record is an independent event, like a deposit. Summing per key gives alice 40 and bob 5; aggregations drop a record with no value. Events: alice deposited 10, then 30.

KTable: As a KTable, each record replaces the previous value of its key, like a balance. alice is 30, and the null value for bob is a tombstone that deletes him. State: alice now has 30.

Four records on one topic, in order: alice 10, bob 5, alice 30, and bob with a null value. Under each, what it does in the chosen reading; below, the result per key.

KStream: As a KStream, every record is an independent event, like a deposit. Summing per key gives alice 40 and bob 5; aggregations drop a record with no value. Events: alice deposited 10, then 30.

KTable: As a KTable, each record replaces the previous value of its key, like a balance. alice is 30, and the null value for bob is a tombstone that deletes him. State: alice now has 30.

Takeaway: A KStream treats each record as a new event; a KTable treats it as the latest value for its key. The bytes on the topic are the same; the meaning you choose decides the result.

Stream and table are two views of the same dataAggregating a stream of changes, keeping the latest value per key, gives a table. Writing every change to a table out as a changelog gives a stream again. Kafka Streams uses this to back up its state stores in compacted changelog topics.keep the latestper keyemit each update:the changelogStream:every changeTable:current state
Stream and table are two views of the same dataAggregating a stream of changes, keeping the latest value per key, gives a table. Writing every change to a table out as a changelog gives a stream again. Kafka Streams uses this to back up its state stores in compacted changelog topics.keep the latestper keyemit each update:the changelogStream:every changeTable:current state
Stream and table are two views of the same data

In code

StreamsBuilder builder = new StreamsBuilder();
KStream<String, Order> orders = builder.stream("orders", Consumed.with(Serdes.String(), orderSerde));
KTable<String, Customer> customers = builder.table("customers", Consumed.with(Serdes.String(), customerSerde));

orders.filter((id, o) -> o.totalCents() > 10_000)
      .selectKey((id, o) -> o.customerId())                    // re-key: Streams repartitions by customer
      .join(customers, (o, c) -> new BigOrder(o, c.tier()))    // the customer's value right now
      .to("big-orders", Produced.with(Serdes.String(), bigOrderSerde));

Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "big-orders");  // also its consumer group ID
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
new KafkaStreams(builder.build(), props).start();
Kafka Streams: enrich each order with the customer's current tier
orders.groupBy((id, o) -> o.customerId(), Grouped.with(Serdes.String(), orderSerde))
      .windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
      .count()                                                 // state kept in a local store
      .toStream()
      .filter((window, n) -> n > 10)
      .map((window, n) -> KeyValue.pair(window.key(), n))
      .to("suspicious-customers", Produced.with(Serdes.String(), Serdes.Long()));
A windowed count: more than 10 orders in 5 minutes
name=orders-db-source
connector.class=io.debezium.connector.postgresql.PostgresConnector
database.hostname=orders-db
database.port=5432
database.user=debezium
# Read from a secrets file; needs config.providers=file on the Connect worker
database.password=${file:/secrets/db.properties:password}
database.dbname=orders
topic.prefix=shop
table.include.list=public.orders
# A single message transform (SMT): keep only the row as it is after the change
transforms=unwrap
transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState
Kafka Connect: a Debezium source connector streams a table's changes into Kafka
// As a stream, alice's balance updates 10 and 30 are summed to 40
 Wrong builder.stream("balances").groupByKey().reduce(Integer::sum);

// As a table, each update replaces the last: alice is 30
 Right builder.table("balances");
Balances are latest values: reading them as a stream adds them up
A pipeline with Connect at the edges and Streams in the middleA Debezium source connector reads the orders database's change log into the topic shop.public.orders. A Kafka Streams application filters and enriches the orders into big-orders. An Elasticsearch sink connector writes big-orders into a search index. No custom code moves data in or out of Kafka.OutInOrders databaseDebeziumsource connectorshop.public.ordersKafka Streams appbig-ordersElasticsearchsink connector
A pipeline with Connect at the edges and Streams in the middleA Debezium source connector reads the orders database's change log into the topic shop.public.orders. A Kafka Streams application filters and enriches the orders into big-orders. An Elasticsearch sink connector writes big-orders into a search index. No custom code moves data in or out of Kafka.OutInOrders databaseDebeziumsource connectorshop.public.ordersKafka Streams appbig-ordersElasticsearchsink connector
A pipeline: Connect at the edges, Streams in the middle

Solve it

The stream-table join returns nothing for most orders

A Kafka Streams app joins orders, keyed by order ID, with the customers table, keyed by customer ID, to add the customer’s tier. Most output is missing. orders has 12 partitions and customers has 6. Explain why, and fix it.

  1. Check the keys. A stream-table join looks up the stream record’s key in the table. Orders are keyed by order ID, so the lookup asks for an order ID in a table of customers, and finds nothing.
  2. Re-key the stream. selectKey to the customer ID before the join. Kafka Streams then writes the re-keyed orders to an internal repartition topic, so each one lands where its customer is.
  3. Check co-partitioning. A KStream-KTable join needs key X in partition N on both sides: same key, same partition count, same partitioner. Streams sizes its repartition topic to match the table; two source topics with 12 and 6 partitions are rejected at startup.
  4. Choose the fix. Recreate customers with 12 partitions, or read it as a GlobalKTable: every instance holds the whole table, no co-partitioning needed, at the cost of memory, fine for a small table.
  5. Check. In a TopologyTestDriver test, pipe a customer, then an order for them, and assert the output carries the tier.
GlobalKTable<String, Customer> customers = builder.globalTable("customers", Consumed.with(Serdes.String(), customerSerde));
orders.join(customers,
        (orderId, o) -> o.customerId(),                       // which table key to look up
        (o, c) -> new BigOrder(o, c.tier()))
      .to("big-orders", Produced.with(Serdes.String(), bigOrderSerde));

@Test
void orderGetsTheCustomersTier() {
    customersIn.pipeInput("c-7", new Customer("c-7", "GOLD"));
    ordersIn.pipeInput("o-1", new Order("o-1", "c-7", 25_000));
    assertThat(bigOrdersOut.readValue().tier()).isEqualTo("GOLD");
}
Join on the customer ID, against a global table, and test it

How to answer

  • Streams needs no cluster of its own; it scales by running more instances with the same application ID.
  • Connect replaces hand-written import and export code with configuration.
  • Single message transforms adjust records in Connect; real processing belongs in Streams.

Common mistakes

  • Describing Kafka Streams as a server or cluster you deploy, like Flink. It is a library inside your app.
  • Writing a custom consumer to copy a topic into a database when a sink connector already does it.

Follow-up questions

What is the difference between a KStream and a KTable?

A KStream reads a topic as a sequence of independent events: every record is a new fact, so two records for alice are two deposits, and aggregating sums them. A KTable reads it as a changelog: each record replaces the value for its key, and a null value, a tombstone, deletes it, so alice holds her latest balance. Joining a stream with a table enriches each event with the current value for its key.

  • Aggregating a KStream produces a KTable.
  • A KTable topic is usually compacted, since only the latest value per key matters.
  • A GlobalKTable copies the whole table to every instance and needs no co-partitioning.

See it in the infographic: One topic read as KStream and KTable

Where does a Kafka Streams application keep its state, and what happens when an instance dies?

In local state stores, RocksDB by default, each backed up to a compacted changelog topic. When an instance dies, its tasks move to another instance, which restores the stores by replaying the changelog. Standby replicas keep warm copies to make that restore fast.

Check yourself

1. A topic holds alice 10, then alice 30. Read as a KTable, what is the value for alice?
Show answers
  • 30: Correct. Each record replaces the previous value for its key.
  • 40: Incorrect. That is a sum, which is what aggregating a KStream would give.
  • Both 10 and 30: Incorrect. A table keeps one current value per key.