How is a message assigned to a partition, and why does the key matter?
Sketch your own answer first, then compare it with the one below.
A strong answer
The producer hashes the message key and takes the result modulo the number of partitions. Messages with the same key always go to the same partition. Without a key, messages are spread out for balance.
The key matters because it gives ordering. Messages for one account, order or device stay together and are read in the order they were sent.
Pick a key that groups what must stay in order and also spreads load evenly. A key that is too coarse overloads one partition.
Sources
- Jay Kreps, Neha Narkhede, Jun Rao (2011). Kafka: a distributed messaging system for log processing.
- Martin Kleppmann (2017). Designing Data-Intensive Applications.