Kafka for Data Pipelines — Data Engineering

Kafka stores events in a topic, split into partitions; each message has a sequential offset in its partition, and reading doesn't delete messages (retention…

One checkout at Bookshop has to reach three places: the warehouse, the dashboard and the search index. Each reads at its own pace, and none may miss a message. That's the kind of job Apache Kafka is for. It stores streams of events as a log: a list you can only add to at the end, kept on several servers and read by many readers, each at its own pace. It's like the logbook at a security post. Every event goes on a new numbered line and is never erased. The manager, finance and the warehouse team each slip in their own bookmark: reading doesn't remove anything, and everyone knows which line they reached. So that many people can write and read at once, the notes are split across several books, and everything about one order always goes into the same book.

Topics, partitions, offsets

Messages don't disappear when read. That is the big difference from a plain queue, and why one topic can be read by the warehouse, the dashboard and the search index at the same time.

The key picks the partition

Every message has a key and a value. The producer picks the partition from the key: a murmur2 hash of the key, divided by the number of partitions, with the remainder as the partition number. Same key, same partition, so the order holds. Bookshop uses order_id as the key, so every line of an order lands in the same partition, in order. The result of kafka-python 3.0.11's partitioner (the same as the Java client) for the 19 order lines:

Partition Orders (key) Messages (offset: item)
0 1, 5, 7, 8, 11 0: item 1, 1: item 7, 2: item 10, 3: item 11, 4: item 15
1 4, 6, 10, 12, 13, 14 0: item 5, 1: item 6, 2: item 8, 3: item 9, 4: item 13, ... 9: item 19
2 2, 3, 9 0: item 2, 1: item 3, 2: item 4, 3: item 12

Producers and consumers

A producer with kafka-python 3.0.11 (there is no Kafka broker on this laptop, so this code wasn't run; the Lab models it):

import json
from kafka import KafkaProducer

producer = KafkaProducer(
    bootstrap_servers="localhost:9092",
    key_serializer=str.encode,
    value_serializer=lambda v: json.dumps(v).encode(),
    acks="all",
)
for line in order_lines:
    producer.send("order-lines", key=str(line["order_id"]), value=line)
producer.flush()

The consumer that fills the warehouse:

import json
from kafka import KafkaConsumer

consumer = KafkaConsumer(
    "order-lines",
    bootstrap_servers="localhost:9092",
    group_id="warehouse-loader",
    auto_offset_reset="earliest",
    enable_auto_commit=False,
    value_deserializer=json.loads,
)
for msg in consumer:
    upsert_order_line(msg.value)   # INSERT ... ON CONFLICT (item_id) DO UPDATE
    consumer.commit()              # commit the offset after it is stored

Consumer groups: sharing partitions

All consumers with the same group_id share the work: each partition is held by exactly one consumer in that group. With 1 consumer, it holds all three. With 2, the first gets partitions 0 and 1 and the second partition 2 (the range split, the client's default). With 3, one partition each.

What if the warehouse-loader group runs 4 consumers to go faster: how many actually do work? Only 3. The fourth consumer sits idle, because there are only 3 partitions. The number of partitions caps one group's parallelism, so decide it early. When a consumer dies, Kafka rebalances: its partitions are shared out again among the ones still alive, which carry on from the last committed offset. Another group (say dashboard) reads the same topic with offsets of its own.

At-least-once and idempotent consumers

The consumer holding partition 1 stores offsets 0 to 2, commits (offset 3), stores offsets 3 to 5 (items 9, 13, 14), then dies before committing again. Its replacement starts at offset 3, so those three messages are stored twice:

How it stores Rows in the warehouse
plain INSERT 22: items 9, 13, 14 doubled
upsert by item_id 19

It is this store-then-commit order, not Kafka itself, that picks "may be doubled" over "may be lost". The reverse order, commit first and store later (at-most-once), loses messages when the consumer dies halfway. So the consumer must be idempotent: storing the same message twice gives the same result. An upsert on a unique key, as in the CDC lesson, is the most common way. Kafka has transactions for exactly-once, but they apply between topics inside Kafka; when writing to another database, still rely on idempotent writes.

An upsert by item_id doesn't drop item 9: that is a duplicate from the source with its own item_id, a job for data quality checks, not for Kafka.

Kafka in a pipeline: Connect, Debezium and version 4

For Bookshop today, 19 lines in two weeks, Kafka is overkill: a database table plus a scheduled job is enough. Kafka makes sense when events arrive by the thousand per second, there are many readers, or data must arrive within seconds.

⚠️ Why are messages lost, doubled or out of order?

TL;DR: Kafka stores events in a topic, split into partitions; each message has a sequential offset in its partition, and reading doesn't delete messages (retention defaults to 7 days, replay is possible). The key picks the partition (murmur2), so the key order_id keeps all lines of one order in order; at Bookshop the 19 messages split 5, 10, 4. Consumers with the same group_id share partitions, one partition per consumer, so 4 consumers on 3 partitions means one sits idle. Committing after storing gives at-least-once: a message can arrive twice (22 rows with INSERT, 19 with an upsert), so consumers must be idempotent. Kafka Connect runs connectors such as Debezium; Kafka 4.x runs on KRaft without ZooKeeper; Redpanda and the managed services speak the same protocol.

⚡ Topic, partition, offset

Meaning: A topic is a named stream of events. A topic is split into partitions so it can be written and read in parallel, and every message has an offset, its sequence number in its partition. Reading doesn't delete messages, so they can be read again during retention.

⚡ The key picks the partition

Write:

producer.send("order-lines", key=str(line["order_id"]), value=line)

Meaning: Same key, same partition, so every line of one order stays in order. Ordering is only guaranteed inside one partition.

⚡ Consumer groups

Guess first: the warehouse-loader group runs 4 consumers to go faster. How many actually do work?

Only 3. The topic has only 3 partitions, and each partition is held by exactly one consumer in the group. The fourth consumer sits idle.

Meaning: The number of partitions caps one group's parallelism.

⚡ Store first, then commit

Write:

for msg in consumer:
    upsert_order_line(msg.value)   # INSERT ... ON CONFLICT (item_id) DO UPDATE
    consumer.commit()              # commit the offset after it is stored

Meaning: If the consumer dies between the two, the messages are read again (at-least-once). That's why storing must be idempotent: an upsert by item_id.

What you will learn