Video in progress

What is the key of a Kafka message for, and can you leave it null?

The key does two things: it sends messages with the same key to the same partition to preserve order, and in compacted topics it says which object the "latest value" belongs to. If you don't need ordering, you can leave it null.

📖 Answer

For example, user profile changes:

kafkaTemplate.send("user-updates", userId, updateEvent);

Because userId is the key, all changes for one user land in one partition and the consumer receives them in the order they were written. Without a key, the "name changed" and "name changed again" events could go to different partitions and be processed in reverse order.

When is a null key fine? Logs, metrics, clicks: every message is independent and the order doesn't matter. Then messages are spread more evenly across partitions.

A common mistake is using the toString() of the whole object, or a random UUID, as the key. That is almost the same as sending without a key: you lose the ordering guarantee.