Sub topic 5
Keys, values and JSON serialization
This chapter assumes you know how topics, partitions and offsets work, and that you have a Spring Boot project with spring-kafka on the classpath and a broker reachable at localhost:9092. It covers what a record's key and value do, how they are turned into bytes, and how Spring's JSON support behaves, including its failure modes.
What a record contains
Kafka stores records as bytes. A record has a key, a value, headers, and a timestamp. The broker never looks inside the key or the value. Your applications must agree on how to turn objects into bytes and back. That conversion is serialization (object to bytes) and deserialization (bytes to object).
The key and value have different jobs:
| Part | Purpose | Typical content |
|---|---|---|
| Key | Chooses the partition and groups related records. It is optional. | An ID such as the order ID |
| Value | The payload your consumers process. | A JSON document describing an event |
| Headers | Metadata that travels with the record. | Trace IDs, content type, Java type name |
How the key chooses a partition
When a record has a key, the producer's default partitioner hashes the key bytes with the murmur2 algorithm and takes the result modulo the number of partitions. The same key therefore always goes to the same partition, as long as the partition count stays the same.
Records in one partition are read in the order they were written. Using the order ID as the key therefore keeps all events for one order in order. Kafka gives no ordering guarantee across partitions.
You can reproduce the calculation with the Kafka client library:
package com.example.orders;
import java.nio.charset.StandardCharsets;
import org.apache.kafka.common.utils.Utils;
public class PartitionDemo {
public static void main(String[] args) {
int partitions = 3;
for (String key : new String[] {"order-1", "order-2", "order-3", "order-1"}) {
byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
int partition = Utils.toPositive(Utils.murmur2(bytes)) % partitions;
System.out.println(key + " -> partition " + partition);
}
}
}order-1 prints the same partition both times. Run it with a different partitions value and the assignments change. That is the first gotcha.
Key gotchas
- Changing the partition count remaps keys. If you grow
ordersfrom 3 to 6 partitions, a key may hash to a different partition than before. Old and new records for one order can then sit in different partitions, and ordering for that key is lost across the change. Choose the partition count with growth in mind. - Hot keys. A key that carries a large share of traffic, such as a single large customer, overloads one partition and one consumer. Pick a key with many distinct values.
- Null keys. If you send without a key, the producer spreads records across partitions in batches. Throughput is good, but there is no per-entity ordering.
- Key serializer must be stable. Hashing happens on the serialized bytes. If you switch from a string key to a JSON-serialized key, the bytes differ and so does the partition. Use a plain
Stringkey for IDs. - Compacted topics need keys. Log compaction keeps the latest record per key, so records without keys cannot be compacted.
Choosing serializers
Kafka ships serializers for common types, such as StringSerializer, LongSerializer and ByteArraySerializer. Spring for Apache Kafka adds JsonSerializer and JsonDeserializer, which use Jackson. A common setup uses a string key and a JSON value.
The payload type for this tutorial is a record:
package com.example.orders;
public record OrderEvent(String orderId, long amountCents) {}Jackson 2.12 and later can serialize and deserialize Java records, so no annotations are needed. The serialized value looks like this:
{"orderId":"A-1001","amountCents":2599}Configuring JSON in application.yml
This configuration wires the serializers and deserializers:
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
properties:
enable.idempotence: true
consumer:
group-id: order-service
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventThe acks and idempotence lines belong to a later chapter on reliable delivery. This chapter focuses on the serializer lines and the two spring.json.* properties.
Type headers
By default, JsonSerializer adds a header named __TypeId__ to each record. Its value is the fully qualified class name of the payload, such as com.example.orders.OrderEvent. JsonDeserializer reads that header and instantiates that class.
This is convenient, but it couples the two applications. The consumer needs a class with the same fully qualified name on its classpath. If the consumer is a different service with its own OrderEvent in another package, deserialization fails with a ClassNotFoundException.
There are two ways to avoid this:
- Tell the consumer which class to use, regardless of headers. Set
spring.json.use.type.headers: falseandspring.json.value.default.typeto the consumer's own class. - Stop the producer from sending the header. Set
spring.json.add.type.headers: falsein the producer properties.
For services owned by different teams, option 1 or both together is safer. The JSON document becomes the contract, not the Java class name.
In the YAML above, spring.json.value.default.type is only a fallback. When a __TypeId__ header is present, the header wins. Add spring.json.use.type.headers: false under the consumer properties if you want the default type to always apply.
Trusted packages
The __TypeId__ header is data from the network. If a deserializer instantiated whatever class the header names, an attacker who can write to the topic could point it at a dangerous class. To prevent this, JsonDeserializer only creates classes from trusted packages.
If the record's type is outside spring.json.trusted.packages, deserialization fails with an IllegalArgumentException that says the package is not trusted. The setting * trusts everything. Avoid it outside local experiments, because it removes this protection.
Sending with a key
The publisher passes the order ID as the key, so one order's events stay on one partition:
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class OrderPublisher {
private static final Logger log = LoggerFactory.getLogger(OrderPublisher.class);
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public OrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void publish(OrderEvent event) {
kafkaTemplate.send("orders", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Send failed for order {}", event.orderId(), ex);
} else {
log.info("Sent order {} to partition {} at offset {}",
event.orderId(),
result.getRecordMetadata().partition(),
result.getRecordMetadata().offset());
}
});
}
}The generic types KafkaTemplate<String, OrderEvent> must match the configured serializers. Spring Boot creates the template from the spring.kafka.producer.* properties. A mismatch such as sending an OrderEvent through a StringSerializer fails at runtime, not at compile time, because the serializer class comes from configuration.
Poison pills and ErrorHandlingDeserializer
A poison pill is a record that cannot be deserialized, for example malformed JSON or an untrusted type. Deserialization happens inside the Kafka consumer, before your listener runs. If the deserializer throws, the consumer fails to read that record. It then retries the same offset on the next poll and fails again, so the partition is stuck.
Wrap the real deserializer in ErrorHandlingDeserializer. It catches the exception, hands the container a record that carries the failure, and lets the listener's error handler deal with it. That handler can route the record to a dead-letter topic, which a later chapter covers.
spring:
kafka:
consumer:
key-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
properties:
spring.deserializer.key.delegate.class: org.apache.kafka.common.serialization.StringDeserializer
spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventWrapping the key deserializer too is worthwhile, because a corrupt key causes the same stuck-partition behavior.
Evolving the payload
Producers and consumers are deployed at different times, so the JSON must tolerate change:
- Adding a field is usually safe if consumers ignore unknown properties. Spring's
JsonDeserializerdisables Jackson'sFAIL_ON_UNKNOWN_PROPERTIESby default, so an old consumer reading a new field does not fail. - A new consumer reading an old record gets
null(or0for primitives) for the missing field. Handle that in code. - Renaming or removing a field, or changing its type, breaks consumers. Add the new field first, migrate consumers, then remove the old one.
For strict contracts across many teams, a schema registry with Avro or Protobuf enforces compatibility rules. JSON with a documented convention is simpler and works well within one team.
Summary of decisions
| Decision | Recommended default |
|---|---|
| Key type | `String` ID of the entity whose ordering matters |
| Value format | JSON through `JsonSerializer` for simple cases |
| Cross-service topics | Disable type headers and set a default type per consumer |
| Trusted packages | List only your payload packages, never `*` in production |
| Consumer resilience | Wrap deserializers in `ErrorHandlingDeserializer` |
Exercise
A consumer service has its own class com.shop.billing.OrderEvent. The producer service sends com.example.orders.OrderEvent with the default JsonSerializer. The consumer fails with a class-not-found error. Name two property changes that fix this.
Show answer
The __TypeId__ header names com.example.orders.OrderEvent, which the billing service does not have. Fix it on the consumer by setting spring.json.use.type.headers: false and spring.json.value.default.type: com.shop.billing.OrderEvent, and add com.shop.billing to spring.json.trusted.packages. Alternatively, set spring.json.add.type.headers: false on the producer so the header is never sent, and still set the consumer's default type.
Exercise
The orders topic has 3 partitions and you use orderId as the key. A teammate raises the partition count to 6. What happens to ordering for an order whose key previously hashed to partition 1, and why?
Show answer
The partition is computed as the murmur2 hash of the key bytes modulo the partition count. Changing the count from 3 to 6 can change the result for a given key, so new events for that order may go to a different partition than its earlier events. Ordering holds only within one partition, so a consumer can see the old and new events of that order out of sequence.
Exercise
A producer writes the bytes {not json to orders. With a plain JsonDeserializer the consumer loops on the same offset and makes no progress. What do you change, and where does the failed record go next?
Show answer
Configure ErrorHandlingDeserializer as the value deserializer, with spring.deserializer.value.delegate.class set to JsonDeserializer. The deserialization failure is then passed to the container's error handler instead of being thrown inside the consumer poll. With a DefaultErrorHandler and a DeadLetterPublishingRecoverer, the record is published to the dead-letter topic (orders.DLT) and the consumer moves on.