Lesson 1 · About 15 minutes
Where does an event land?
By the end, you can look at a key and a partition count and say what Kafka does and does not promise about order.
Most ordering questions come down to one thing: which partition an event went to. Four rules cover it.
The four rules
toPositive(murmur2(keyBytes)) % numPartitions. The reverse isn't true: different keys can share a partition.
Kafka source: BuiltInPartitioner
batch.size bytes have gone to it, then moves on. There is no per-key order to rely on.
Apache Kafka: partitioner.class
RoundRobinPartitioner spreads consecutive records. Both descriptions agree that keyless events spread across partitions with no ordering guarantee.Try it: break an ordering guarantee
This simulator routes keys with Kafka's real hash. Say your prediction out loud before each step.
- Send
alicetwice, thenbob, thencarol. Which two keys collide? Does that break anything? - Click Remove partition. What happens?
- Click Add partition, then send
aliceagain. Where does it go, and did the old events move? - Click Send without key eight times. What pattern do you see?
Now on a real broker
Run this from the learn-kafka folder with Docker running. It starts its own throwaway broker and won't touch your other containers.
source assets/kafka-lab.sh
kafka_lab_up
k kafka-topics.sh --create --topic orders \
--partitions 3 --replication-factor 1
printf 'alice:o1\nbob:o2\nalice:o3\ncarol:o4\nalice:o5\nbob:o6\n' | \
k kafka-console-producer.sh --topic orders \
--reader-property parse.key=true --reader-property key.separator=:
k_peek orders 3
Compare the output with the simulator. Next, try to shrink the topic, grow it, and send more events. Predict where alice lands first.
k kafka-topics.sh --alter --topic orders --partitions 2
k kafka-topics.sh --alter --topic orders --partitions 4
printf 'alice:o7\nbob:o8\ncarol:o9\n' | \
k kafka-console-producer.sh --topic orders \
--reader-property parse.key=true --reader-property key.separator=:
k_peek orders 4
kafka_lab_down
You should see the shrink fail with InvalidPartitionsException, and alice split across partitions 0 and 1. Each k_peek takes a few seconds per partition.
Check yourself
Answer from memory without scrolling up. Getting these slightly wrong now is useful, because the effort of recalling is what makes it stick.
Keep going
Read next: the "Main Concepts and Terminology" section of the Apache Kafka introduction. It's short and comes from the project itself.
Keep for review: Keys and partitions cheat sheet.
Ask your teacher: anything unclear is worth asking about in the chat, however small. When you finish, send your quiz score and which questions you missed, so the next lesson starts in the right place.