Video in progress

What decides which partition a producer sends a message to?

If the message has a key, the partition is chosen by the hash of the key, so the same key always lands in the same partition. Without a key, the default partitioner spreads messages across partitions (in newer versions, in a sticky way).

📖 Answer

There are three cases:

  1. You set the partition number explicitly in the ProducerRecord: the message goes there.
  2. There's a key: murmur2(key) % number_of_partitions.
  3. There's no key: since Kafka 2.4 the sticky partitioner writes to one partition until a batch is full, then switches to another. This makes batches bigger and saves network.
// orderId as the key: all events of this order go to one partition, so the order is preserved
kafkaTemplate.send("orders", order.getId().toString(), event);

In practice, pick the key like this: the identifier of the object whose ordering matters (orderId, accountId). One catch, though: if a single key is very "hot" (say, one huge customer), that partition gets more load than the others.