Kafka

Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 2:30 on Friday afternoon and the flash sale is still running. The clicks now flow through Kafka. Tess messages: the live count has gone flat for about a third of shoppers. No job has failed. You run one command and get a number: one reader is 233,386 messages behind. Is that a minute or a day? You cannot say until you know how Kafka cuts a log into pieces and deals them out.

You'll learn to

  • Explain topics, partitions, keys and offsets
  • Predict how a consumer group shares partitions and rebalances
  • Size a topic's partition count from measured numbers
  • Turn lag into minutes, and choose retention or compaction

Learn

Put a log in the middle

Three teams want the clicks: fraud, the live dashboard and the warehouse. If the app wrote to all three itself, checkout would be as slow as the slowest reader, and every new reader would mean changing the app.

So the app writes once, to a log in the middle, and does not care who reads. That log is Apache Kafka: the log of Lesson 15.1, spread over a group of servers called brokers. Programs that append are producers. Programs that read are consumers.

Messages are not deleted when they are read. They stay for a set time, 7 days by default, so a reader that was down catches up.

The clicks log on three brokers

Three brokers each hold the leader replica of one partition of the clicks topic and follower replicas of the other two, so every partition has three copies and leadership is spread.

Three brokers, and the clicks log cut into three pieces, clicks-0 to clicks-2 (the next section says why). Find clicks-0 in each box: one leader copy and two follower copies, on three different brokers. Clients talk to the leader, and the followers copy it, so losing a server loses no data (Lesson 15.5).

One log is too slow, so cut it up

One log on one server could not take every click from every shopper. So Kafka cuts each named stream, a topic such as orders or clicks, into several logs called partitions. Each partition has its own offsets, and partitions live on different brokers.

Which partition does a message go to? The producer hashes the message key: hash(key) % partitions. Think of a library that shelves books by the author's first letter: the same author always ends up on the same shelf.

So every message about order 1001 lands in one partition, in the order it was sent. A message with no key is spread around, a batch at a time, and has no order at all.

One message, from the app to a reader

A producer sends a message with key 1001 to the orders topic; the key picks partition 2, the message is appended at offset 1, and the consumer that owns partition 2 reads it and commits.

  1. The app has news. Order 1001 has shipped. The producer builds a message with key 1001 and value shipped.

  2. The key picks the partition. hash(1001) % 3 is 2, so the message is for partition 2. Every message about order 1001 gets the same answer.

  3. The leader appends it. The broker that leads partition 2 writes the message at the next free offset, 1. Its followers copy it.

  4. A consumer polls. The consumer that owns partition 2 asks for anything from offset 1 on (this asking is called a poll), and receives the message.

  5. It commits. Once the message is handled, the consumer stores 2 as its committed offset: the next one to read. The message stays in the partition for other readers.

Follow the message left to right: producer, partition, consumer. Offsets restart at 0 in every partition, so "offset 1" means nothing without its partition.

Send six order changes and look inside

import ministream as ms

broker = ms.Broker()
broker.create_topic('orders', partitions=3)

changes = [('1001', 'placed'), ('1002', 'placed'), ('1001', 'shipped'),
           ('1004', 'placed'), ('1002', 'cancelled'), ('1001', 'delivered')]
for order_id, status in changes:
    m = broker.produce('orders', key=order_id, value=status)
    print(f'{order_id} {status:<9} -> partition {m.partition}, offset {m.offset}')

for p in range(3):
    print('partition', p, [(m.offset, m.key, m.value) for m in broker.messages('orders', p)])
print('1001 always goes to', ms.partition_for('1001', 3))

ministream is a one-machine Kafka in plain Python that sits in your folder: open it any time. Each order's story sits in one partition, in order, but the topic cannot say whether 1004 placed came before 1001 shipped. (Kafka hashes the key bytes with murmur2, ministream with crc32: different numbers, same idea.)

Remember: Kafka keeps order inside a partition, never across a whole topic. If order matters for something (an order, a customer), make it the key.

A team of readers shares the partitions

One consumer cannot keep up with a busy topic, so you run a team. Give several consumers the same group.id and they form a consumer group. Kafka deals the partitions out among them: each partition is read by exactly one consumer of the group.

Two consumers on 3 partitions get two and one. A fourth consumer on 3 partitions gets nothing and waits, ready to take over.

Groups do not share with each other. The fraud group and the warehouse group each receive every message, each with its own offsets. Inside a group the work is split. Across groups everyone gets everything.

A topic with three partitions receiving keyed messages, each message getting the next offset in its partition, and a consumer group whose consumers each own some partitions and track a committed offset.

Send a few events: each customer's events line up in one partition, in order. Then add a consumer to the group and watch the partitions dealt out again, each with its own committed offset and lag.

A group grows, loses a member, and another group reads it all

import ministream as ms

broker = ms.Broker()
sent = ms.load_events(broker, 'clicks', partitions=3)   # data/events.jsonl keyed by user_id
print('sent', sent, 'per partition', broker.end_offsets('clicks'))

a = broker.consumer('warehouse', 'clicks')
print(a)
b = broker.consumer('warehouse', 'clicks')
print(a, b)
c = broker.consumer('warehouse', 'clicks')
d = broker.consumer('warehouse', 'clicks')
print(c, d)                     # 3 partitions, 4 consumers: one has nothing
b.crash()                       # b dies: the group rebalances
print(a, c, d)
print(broker.consumer('fraud', 'clicks'))   # another group: all partitions

Read the output line by line: one consumer owns all three partitions, then two share them, then a fourth gets nothing. When b crashes, the three that are left take one each, and the fraud group still gets all three. The 192 clicks split unevenly (60, 81, 51): there are only 15 logged-in users, and ministream deals out the keyless events of anonymous visitors in turn.

How many partitions? Do the sum

Now you can size a topic. The partition count is hard to change: you can add partitions, never remove them, and adding them moves keys to other partitions. So work it out from measurements.

The rule: partitions = max(T / p, T / c). T is the peak to carry, p what one partition takes from producers, c what one consumer handles.

SwiftKart plans for a peak of 20,000 clicks a second at 1 KB each:

  • T = 20 MB/s
  • a load test shows p = 10 MB/s, so producers need 20 / 10 = 2
  • one loader writes 2 MB/s to Delta, so consumers need 20 / 2 = 10
  • take the larger, 10, and allow 2x headroom: 24, which splits evenly over 2, 3, 4, 6, 8 or 12 consumers

Partitions for the clicks topic: the slower side decides

Three bars: producers alone would need 2 partitions, the consumers need 10, and the number chosen with headroom is 24.

The slower side sets the count, and that is usually the consumers. More is not free: every partition costs the brokers files and memory, gives more leaders to move when a broker fails, and makes producer batches smaller.

When the team changes, the work is dealt again

A deploy, a crash or a scale-up changes the team, so Kafka deals the partitions again. That is a rebalance.

The old way is eager. Every consumer puts down all its partitions, everyone rejoins, and new hands are dealt. Nothing is processed in between: a stop-the-world pause on every deploy.

The better way is cooperative. Consumers keep the partitions that are not moving. Only the ones that change owner pause, in a second short round.

Kafka 4.0 made a third way generally available, known as KIP-848 (group.protocol=consumer). The broker works out the assignment itself and changes it one member at a time, so one consumer joining or leaving no longer pauses everyone.

Consumer C3 joins: eager against cooperative

A timeline of three partitions under each protocol: in the eager rebalance every partition pauses while the group rejoins and two partitions change owner; in the cooperative rebalance only the partition that moves to C3 pauses.

The top three lanes are the eager way, the bottom three the cooperative way. C3 joins at 10 s and the new assignment is in place at 16 s. It is a schematic: the pause lasts as long as the slowest member takes to rejoin. The eager assignors (RangeAssignor, RoundRobinAssignor) also reshuffle two partitions here, where CooperativeStickyAssignor moves only P1.

Is 233,386 a minute or a day?

Now the number from this afternoon. For each group and partition, Kafka stores a committed offset: the next message the group has not finished. It keeps them in an internal topic, __consumer_offsets.

Lag is how far the group is behind on a partition: the offset at the end of the log, minus the committed offset.

Here is the command you ran at 2:30. Read the LAG column first, then look at who owns the partition that is behind.

Where is the warehouse loader, and how far behind?

Runs on a Kafka cluster:

kafka-consumer-groups --bootstrap-server localhost:9092 --describe --group warehouse-loader
GROUP             TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG     CONSUMER-ID                                    HOST         CLIENT-ID
warehouse-loader  clicks  0          1840212         1840250         38      loader-1-5b0c2a5e-8f6d-4e43-9c1a-2d7e8f0a1b3c  /10.0.1.17   loader-1
warehouse-loader  clicks  1          1838977         1839004         27      loader-1-5b0c2a5e-8f6d-4e43-9c1a-2d7e8f0a1b3c  /10.0.1.17   loader-1
warehouse-loader  clicks  2          1612004         1845390         233386  loader-2-0e9d7c11-4a2b-4f5e-8c3d-6b1a9e2f4d70  /10.0.1.18   loader-2

Partitions 0 and 1 are a few dozen messages behind: healthy. Partition 2 is 233,386 behind: loader-2 is stuck or too slow. Run this first when someone says "the dashboard is stale", and alert on the consumer's records-lag-max metric so you hear before they do.

Remember: lag in messages / (consume rate - produce rate) = lag in time. If the consumer is the slower one, it never catches up: at 500 a second against 600 arriving, lag grows by 100 a second, 8.64 million a day, until retention deletes messages it never read.

Why loader-2 stopped: the poll deadline

The log of loader-2 repeats one line: CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member.

A consumer works in a loop: poll() for records, handle them, commit, poll again. One poll() returns up to max.poll.records (500). If the next poll() does not come within max.poll.interval.ms (300,000 ms, 5 minutes), Kafka treats the consumer as failed and moves its partitions away.

So each record has a budget: 300,000 / 500 = 600 ms. This afternoon a lookup the loader calls slowed to 800 ms a record. 500 x 0.8 s = 400 s per poll. The loader is thrown out, its commit fails, and the next owner reads the same uncommitted batch again: a rebalance loop, with duplicates and no progress.

One poll that takes 400 seconds

A timeline of one poll: the loader handles 500 records for 400 seconds, the 300-second poll deadline passes, partition 2 is given to another consumer which reads the same batch again, and the late commit fails.

Read the top lane: the batch needs 400 s, and the deadline falls at 300 s. The fix is to fit inside the deadline: smaller polls (max.poll.records=100 gives each record 3 s), faster processing, or a longer interval.

Commit, read the lag, and fall behind retention

import ministream as ms

broker = ms.Broker()
ms.load_events(broker, 'clicks', partitions=3)
loader = broker.consumer('warehouse', 'clicks')
batch = loader.poll(max_records=50)      # one from each partition in turn
print('polled', len(batch))
loader.commit()                          # finished those 50
broker.describe_group('warehouse')

small = ms.Broker()
small.create_topic('alerts', partitions=1, retention=20)   # keep the newest 20
for i in range(5):
    small.produce('alerts', None, f'alert {i}')
slow = small.consumer('dashboard', 'alerts')
slow.poll(max_records=2)
slow.close()                             # commits offset 2, then stops
for i in range(5, 55):
    small.produce('alerts', None, f'alert {i}')   # 50 more while it is down
back = small.consumer('dashboard', 'alerts')
first = back.poll(max_records=1)[0]
print('resumed at offset', first.offset, 'missed', back.missed)

First half: after 50 records and a commit, the group is 43, 64 and 35 messages behind. Second half: a dashboard reader stops at offset 2, 50 more alerts arrive, and the topic keeps only the newest 20. The reader comes back at offset 35: offsets 2 to 34 were deleted before it read them.

What Kafka throws away, and when

That last run shows the other clock in Kafka. A topic does not grow for ever, and its cleanup.policy says what goes.

delete (the default) drops old messages by age: 7 days unless you change it. A reader that falls further behind than that loses messages for good. Use it for streams of events: clicks, payments, logs.

compact keeps at least the latest value of every key and removes older values in the background. A new reader replays the topic and gets every key's current value: the folded table of Lesson 15.1, kept as a log. Use it for latest state: customer profiles, CDC tables, and Kafka's own __consumer_offsets.

To delete a key from a compacted topic, send the key with a null value. That message is called a tombstone.

Compaction keeps the newest value per key

import ministream as ms

broker = ms.Broker()
broker.create_topic('customer_city', partitions=1, cleanup='compact')
for key, city in [('18', 'Munich'), ('6', 'Toronto'), ('18', 'Berlin'),
                  ('6', None), ('7', 'Lagos'), ('18', 'Paris')]:   # None is a tombstone
    broker.produce('customer_city', key, city)

show = lambda: [(m.offset, m.key, m.value) for m in broker.messages('customer_city', 0)]
print('before:', show())
broker.compact('customer_city')                        # the log cleaner runs
print('after: ', show())
broker.compact('customer_city', drop_tombstones=True)  # delete.retention.ms has passed
print('later: ', show())
print('end offset', broker.end_offsets('customer_city'))

Six messages go in; after the cleaner runs, three are left. Offsets keep their numbers: compaction leaves gaps and consumers skip them. Customer 6's tombstone survives the first cleaning, so a reader that is behind still learns of the delete.

Order holds inside a partition only. A consumer reading three partitions sees their messages interleaved, so never rely on order across keys. Two more traps. Adding partitions later changes hash(key) % partitions, so a key's new messages may land in a different partition from its old ones. And a key with a huge share of the traffic (keying clicks by event type, say) makes one hot partition that a single consumer must carry alone.

Numbers to remember

SettingDefaultWhat it does
retention.ms7 dayshow long a delete topic keeps messages. They go a whole segment at a time (a file, rolled at 1 GiB or 7 days), so some outlive it; retention.bytes, per partition, is unlimited by default
delete.retention.ms1 dayhow long a tombstone is kept in a compacted topic, so readers still see it
Disk for a topicrate x retention x replicas20 MB/s for 7 days is 12.1 TB per copy. A compacted topic takes keys x value size, plus what the cleaner has not reached yet
enable.auto.committrue, every 5 s (auto.commit.interval.ms=5000)commits in the background, whatever your code has done with the records; pipelines turn it off and commit after writing (Lesson 15.3)
max.poll.records500the most records one poll() returns
max.poll.interval.ms300,000 (5 minutes)the longest gap between two polls before the consumer is thrown out
session.timeout.ms45 swith static membership (group.instance.id), a consumer that restarts within it causes no rebalance at all
partition.assignment.strategy[RangeAssignor, CooperativeStickyAssignor]a group stays eager until a rolling restart removes RangeAssignor; in this classic protocol one consumer, the group leader, computes the assignment
group.protocolclassic on the client, in 4.4 tooconsumer turns on KIP-848; brokers have it on by default since 4.0, and a group converts online as upgraded consumers join, if its old assignor stored no custom metadata
KIP-848 timingheartbeat 5 s, session 45 sset on the broker (group.consumer.heartbeat.interval.ms, group.consumer.session.timeout.ms), replacing the client's heartbeat.interval.ms and session.timeout.ms
KIP-848 assignorsuniformor range, picked with group.remote.assignor; partition.assignment.strategy no longer applies and client-side assignors are not supported
Managed KafkaConfluent Cloud, Amazon MSKAzure Event Hubs and Redpanda speak the Kafka protocol; Amazon Kinesis (partitions are called shards) and Google Pub/Sub are close cousins

You do not need these by heart. Know that they exist, and which one to look up when a consumer misbehaves.

What changed at SwiftKart

By 2:45 the slow lookup is fixed, and you have set max.poll.records=100 so one slow spell cannot throw the loader out again. loader-2 now handles 900 clicks a second against 600 arriving. Thirteen minutes later the lag on partition 2 is back to a few dozen, and Tess's count moves again. You add an alert on lag, so next time you hear before she does.

One thing still bothers you. While the loader was being thrown out and let back in, the same batch was read more than once. Did the dashboard count those clicks twice? That is the next lesson: what a crash between "handle" and "commit" does to your numbers.

In one line

A topic is cut into partitions, the key picks the partition so order holds per key, a group gives each partition to one consumer, and lag only means something once you turn it into time.

Interview corner

How many partitions would you give a new topic?

I size it from measurements: partitions = max(T / p, T / c), where T is peak throughput, p what one partition takes from producers and c what one consumer instance processes. For 20 MB/s with consumers that each do 2 MB/s that is 10, and I would double it for growth to something like 24, which divides evenly across many consumer counts. The count caps a group's parallelism, since each partition has one consumer per group, and it is hard to change later: partitions can be added but not removed, and adding them moves keys. Too many costs broker memory, files and slower failover, and shrinks producer batches.

How does Kafka guarantee message order?

Only inside a partition: messages are appended and read in offset order. The producer chooses the partition by hashing the key, so all messages with the same key (say, one order id) stay in order. There is no order across partitions, so anything that must be ordered together has to share a key.

What is consumer lag, and what do you do when it grows?

Lag is the log-end offset minus the group's committed offset, per partition: the messages waiting to be processed. I check it with kafka-consumer-groups --describe or a lag metric in monitoring. If one partition is behind, I look for a stuck consumer or a hot key; if all are, I make processing faster or add consumers, up to the partition count.

What happens during a rebalance, and how do you make it hurt less?

When a member joins, leaves or misses its deadline, partitions are reassigned, and a moved partition restarts from the last committed offset, so uncommitted work is redone. With the classic eager protocol every consumer revokes everything and the whole group pauses; the cooperative sticky assignor revokes only the partitions that move, and the default assignor list stays eager until RangeAssignor is removed. Static membership with group.instance.id avoids rebalances on quick restarts, and the KIP-848 protocol, GA in Kafka 4.0 with group.protocol=consumer, moves assignment to the broker and makes it incremental. I also check max.poll.interval.ms, because a slow poll loop causes repeated rebalances.