Message Serialization, Custom Serializers, and JSON
Understand byte-level serialization in Kafka, build custom serializers and deserializers, and evaluate JSON overhead in high-throughput systems.
Apache Kafka is data agnostic. The storage engine treats record keys and record values as opaque arrays of binary bytes (byte[]). Brokers do not parse, validate, or inspect your message contents; they write the raw byte buffers sequentially into partition log segments.
The responsibility of translating rich domain objects into raw bytes (and vice versa) falls entirely on client applications via Serializers and Deserializers.
How you serialize your events dictates network bandwidth utilization, broker storage capacity, serialization CPU overhead, and long-term evolutionary compatibility across decoupled microservices.
01The Kafka serializer and deserializer contract
Every producer must supply a Serializer<T> for its key and value, and every consumer must supply a matching Deserializer<T>. These interfaces belong to the org.apache.kafka.common.serialization package:
package org.apache.kafka.common.serialization;
import java.io.Closeable;
import java.util.Map;
public interface Serializer<T> extends Closeable {
default void configure(Map<String, ?> configs, boolean isKey) {}
byte[] serialize(String topic, T data);
default byte[] serialize(String topic, Headers headers, T data) {
return serialize(topic, data);
}
@Override
default void close() {}
}package org.apache.kafka.common.serialization;
import java.io.Closeable;
import java.util.Map;
public interface Deserializer<T> extends Closeable {
default void configure(Map<String, ?> configs, boolean isKey) {}
T deserialize(String topic, byte[] data);
default T deserialize(String topic, Headers headers, byte[] data) {
return deserialize(topic, data);
}
@Override
default void close() {}
}Standard built-in serializers
Kafka provides out-of-the-box implementations for primitive and standard types:
StringSerializer/StringDeserializer(UTF-8 encoding)ByteArraySerializer/ByteArrayDeserializer(raw pass-through)IntegerSerializer,LongSerializer,DoubleSerializer(fixed binary encodings)ByteBufferSerializer,UUIDSerializer
Loading the rest of the lesson…