Skip to main content

Question 18 of 50

What is a Message Key?

Mid-levelSenior

Question

"What is the Message Key, and what's its purpose?"

What the interviewer wants to assess

Whether you understand the key as a domain-modeling decision (which events need to be ordered), not just as a technical parameter of the send method.

Resposta rápida

Message key is an optional value the producer attaches to each message. Kafka uses that key (via hash) to decide which partition the message lands on — messages with the same key always go to the same partition, preserving their relative order.

Resposta nível Sênior

The right question when choosing a key isn't "which value distributes best across partitions," but "which events need to be ordered relative to each other." The key locks in that relationship: events with the same key stay on the same partition and are read in the order they were written; events with different keys have no guaranteed ordering relationship between them, even if published seconds apart. A high-cardinality key (like a UUID per message) distributes better across partitions, but eliminates any ordering guarantee between related messages — a common mistake made by people optimizing for distribution without considering the domain's real ordering requirement.

In-depth explanation

See "Choosing the key: the most important decision when modeling a topic" in Chapter 4.

Exemplo financeiro

On the faturas.eventos topic, using contaId as the key guarantees that FaturaFechada, PagamentoRegistrado, and FaturaReaberta for the same account reach the consumer in the correct order — processing them out of order would lead to a wrong conclusion about the outstanding balance.

"I always use a random UUID as the key to distribute well"

A random UUID per message maximizes distribution, but guarantees related messages (from the same order, the same account) land on different partitions — destroying any ordering guarantee between them. If relative ordering matters, that's a modeling bug.

Pode vir a seguir

Likely follow-ups: "how does ordering work in Kafka?" and "does Kafka guarantee global ordering?".

Related chapters