Video in progress
What are Kafka record headers for, and how do you write and read them in Spring Kafka?
Headers are key-value pairs (the value is a byte[]) added to a message without touching the payload. They carry technical metadata such as a trace ID, event type, tenant or schema version; Spring also keeps __TypeId__ and DLT information in headers.
📖 Answer
The payload is business data; the headers are "the writing on the envelope". A consumer can decide based on a header without deserializing the message: for example, skipping an event type it doesn't need.
Writing:
var record = new ProducerRecord<>("orders", order.id(), event);
record.headers()
.add("event-type", "OrderPaid".getBytes(StandardCharsets.UTF_8))
.add("tenant", tenantId.getBytes(StandardCharsets.UTF_8));
kafkaTemplate.send(record);
Reading, most reliably through ConsumerRecord:
@KafkaListener(topics = "orders", groupId = "audit")
void on(ConsumerRecord<String, OrderEvent> rec) {
Header h = rec.headers().lastHeader("tenant");
String tenant = h == null ? null : new String(h.value(), StandardCharsets.UTF_8);
audit.save(tenant, rec.value());
}
You can also take it directly as a parameter with @Header("tenant"), but a header sent by another (non-Spring) producer often arrives as byte[], and if the type doesn't match you get a conversion error.
One catch: headers count toward the message size and are repeated in every message. Don't stuff a big JSON into a header. And don't make a header the only source of truth for business logic. Data that belongs in the payload should be there, otherwise you get confusion when the message passes through log compaction or other tools.
Sign up to mark studied questions and save your progress.