Kafka: Headers carry metadata without touching the payload

Trace ids, schema versions and type hints belong here, not in the business event.

Code
var record = new ProducerRecord<>("orders", "order-42", payload);
record.headers().add("traceId", traceId.getBytes(UTF_8));
record.headers().add("schemaVersion", "2".getBytes(UTF_8));

// consumer
Header h = record.headers().lastHeader("traceId");
String traceId = h == null ? null : new String(h.value(), UTF_8);
Output
The payload stays a clean domain event,
and a consumer that does not care about tracing never has to parse it.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11