Video in progress
What are the key and headers of a Kafka message for? What metadata do you add to an event?
The key chooses the partition: messages with the same key land in one partition and keep their order; in a compacted topic the latest value per key is kept. Headers hold metadata that doesn't mix with the business body: event ID, type, schema version, traceparent.
📖 Answer
If you leave the key empty, Kafka spreads messages across partitions (in newer clients with the sticky partitioner, by batch). The Created and Paid events of one order land in different partitions, and the consumer may see them in reverse order. That's why the key is usually the aggregate ID (orderId).
For headers I usually use this set:
ProducerRecord<String, OrderEvent> record =
new ProducerRecord<>("orders", order.id().toString(), event);
record.headers()
.add("event-id", eventId.toString().getBytes(UTF_8))
.add("event-type", "OrderPaid".getBytes(UTF_8))
.add("schema-version", "2".getBytes(UTF_8));
kafkaTemplate.send(record);
event-id: for dedup on the consumer side. It's created once in the producer and doesn't change on a retry.event-type: if one topic carries several event types, the consumer decides without parsing the payload.schema-version: to tell old and new messages apart when the format changes.traceparent: you don't add this by hand; Spring Kafka adds it itself when observation is enabled.
So that each team doesn't name the same fields its own way, it's useful to look at the CloudEvents standard: its Kafka binding defines header names like ce_id, ce_type, ce_source.
One warning: don't put large things or personal data in headers; they also get copied into logs, the DLT and monitoring tools.
Sign up to mark studied questions and save your progress.