Adding Custom Headers in Kafka Message
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Apache Kafka, an open-source stream-processing software platform developed by LinkedIn and donated to the Apache Software Foundation, is primarily designed for handling real-time data feeds. Kafka is a robust system that effectively supports custom headers in messages, which can be very beneficial in several scenarios such as message filtering, routing, or tracking context-specific metadata. This feature was introduced in Kafka version 0.11, enhancing the flexibility and usability of the Kafka message.
What Are Kafka Headers?
Kafka headers consist of key-value pairs that are associated with the message (also known as a record in Kafka terminology). Headers provide a mechanism to include metadata or additional information alongside the payload of the message without modifying the payload itself.
Adding Custom Headers
To add custom headers to a Kafka message in a producer application, the Kafka client API provides the capability. Below is a Java example demonstrating how to use the Producer API to send messages with headers:
Use Cases for Headers in Kafka
- Routing: Kafka headers can be used to include routing information, allowing consumers to route or filter messages based on header values without needing to deserialize the entire message.
- Metadata: Extra information such as message encoding, content type, or even custom flags can be stored in headers.
- Tracking: Headers are ideal for passing trace or monitoring identifiers that help in tracking messages as they flow through different components or microservices.
How Consumers Use Headers
On the consumer side, accessing headers is straightforward. Following is a Java example of how to consume messages and access their headers:
Summary Table of Kafka Headers
| Property | Description | Example Usage |
| Header Key-Value Pairs | Allows storing metadata in key-value format | record.headers().add("key", "value") |
| Immutability | Once set, the headers are immutable for safe transmission | N/A |
| Serialization | Utilizes byte arrays to allow flexibility in data type | "exampleValue".getBytes() |
| Consumption | Easily accessible in consumer applications | record.headers() |
Conclusion
Kafka's support for custom headers provides a powerful mechanism to enrich messages with metadata that can drive more intelligent processing downstream. Whether used for routing, metadata encapsulation, or tracking, headers enhance the versatility and functionality of Kafka messaging solutions.

