Kafka serialization: from objects to bytes and back
Kafka only stores bytes, so producers and consumers must agree on how objects become bytes, and nothing in Kafka checks it. This page shows what the built-in serializers write, runs JSON and Avro with a schema registry through a schema change, and handles a record that cannot be deserialized.
Contents
What serialization means in Kafka
Kafka brokers store and move bytes. They never look inside a record's key or value, and they do not know whether the bytes are a string, a number, JSON or Avro. Turning objects into bytes is the job of the producer's serializers, and turning bytes back into objects is the job of the consumer's deserializers. The producer and every consumer of a topic must agree on the format, and nothing in Kafka checks that they do.
A Serializer<T>byte[] serialize(String topic, T data)Deserializer<T>send()poll()Serde<T>key.serializervalue.serializerkey.deserializervalue.deserializer
| Format | Comes from | Schema | Best for |
|---|---|---|---|
| String, Integer, Long, UUID, byte[] | kafka-clientsSerdes | None | Keys, simple values, raw passthrough |
| JSON | Your own class with Jackson, or Spring's JSON serializers | Implicit in the code | Teams that own both ends, readable data |
| JSON Schema | Confluent KafkaJsonSchemaSerializer | In a schema registry | JSON with enforced contracts |
| Avro | Confluent KafkaAvroSerializer | In a schema registry | Shared topics, compact data, schema evolution |
| Protobuf | Confluent KafkaProtobufSerializer | In a schema registry | Organisations that already use Protobuf |
The examples use kafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-test
The built-in serializers, byte by byte
Printing the bytes of a few typical values shows what the built-in serializers really write. The string contains non-ASCII letters, and the long is chosen so that its bytes happen to be readable text:
import java.util.HexFormat;
import java.util.UUID;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
public class BuiltInSerializers {
public static void main(String[] args) {
show("String", Serdes.String(), "Grüße");
show("Integer", Serdes.Integer(), 258);
show("Long", Serdes.Long(), -1L);
show("Double", Serdes.Double(), 0.1);
show("Boolean", Serdes.Boolean(), true);
show("UUID", Serdes.UUID(), UUID.fromString("123e4567-e89b-12d3-a456-426614174000"));
show("ByteArray", Serdes.ByteArray(), new byte[] {1, 2, 3});
// null passes through: that is how a tombstone (a delete) is written
System.out.println("String serializer, null -> "
+ Serdes.String().serializer().serialize("t", null));
// the bytes carry no type information: the reader must know what to expect
byte[] eight = Serdes.Long().serializer().serialize("t", 4702111234474983745L);
System.out.println("the same 8 bytes read as a String: \""
+ Serdes.String().deserializer().deserialize("t", eight) + "\"");
try {
Serdes.Integer().deserializer().deserialize("t", eight);
} catch (RuntimeException e) {
System.out.println("read as an Integer: " + e.getClass().getSimpleName() + ": "
+ e.getMessage());
}
}
static <T> void show(String name, Serde<T> serde, T value) {
Serializer<T> serializer = serde.serializer();
Deserializer<T> deserializer = serde.deserializer();
byte[] bytes = serializer.serialize("topic", value);
T back = deserializer.deserialize("topic", bytes);
String shown = back instanceof byte[] b ? HexFormat.of().formatHex(b) : back.toString();
System.out.printf("%-9s %-38s -> %2d bytes: %s%n", name, shown, bytes.length,
HexFormat.ofDelimiter(" ").formatHex(bytes));
}
}
String Grüße -> 7 bytes: 47 72 c3 bc c3 9f 65
Integer 258 -> 4 bytes: 00 00 01 02
Long -1 -> 8 bytes: ff ff ff ff ff ff ff ff
Double 0.1 -> 8 bytes: 3f b9 99 99 99 99 99 9a
Boolean true -> 1 bytes: 01
UUID 123e4567-e89b-12d3-a456-426614174000 -> 36 bytes: 31 32 33 65 34 35 36 37 2d 65 38 39 62 2d 31 32 64 33 2d 61 34 35 36 2d 34 32 36 36 31 34 31 37 34 30 30 30
ByteArray 010203 -> 3 bytes: 01 02 03
String serializer, null -> null
the same 8 bytes read as a String: "AAAAAAAA"
read as an Integer: SerializationException: Size of data received by IntegerDeserializer is not 4
- "Grüße" took 7 bytes for 5 characters:
writes UTF-8, where ü and ß take two bytes each. The encoding can be changed withStringSerializer , but both sides must then agree.serializer.encoding - Integer 258 became the four bytes
, big-endian. Long -1 is eight00 00 01 02 bytes in two's complement.ff - The UUID took 36 bytes because
writes its text form. Sixteen raw bytes would hold the same value, which matters for keys stored billions of times.UUIDSerializer - A
value stayednull . That is how tombstones are written, so a custom serializer should also returnnull fornull .null - The same eight bytes read as a String gave "AAAAAAAA", without any error: the bytes carry no type. Read as an Integer, they failed only because the length was not 4.
That last point is the core risk of serialization in Kafka. A wrong deserializer often does not fail; it produces plausible nonsense. The format of each topic must be documented, or better, enforced by a schema registry.
JSON with Jackson, and how it evolves
Kafka ships no JSON serializer, so most applications write a small generic one. The interesting part is what happens when the record type changes: here a newer producer adds a currency
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;
public class JsonSerde {
record OrderV1(String id, int cents) {
}
record OrderV2(String id, int cents, String currency) {
}
// one generic pair for any type; Jackson's ObjectMapper is thread-safe once configured
static class JsonSerializer<T> implements Serializer<T> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public byte[] serialize(String topic, T data) {
try {
return data == null ? null : mapper.writeValueAsBytes(data);
} catch (IOException e) {
throw new SerializationException("cannot write " + data, e);
}
}
}
static class JsonDeserializer<T> implements Deserializer<T> {
private final ObjectMapper mapper;
private final Class<T> type;
JsonDeserializer(Class<T> type, boolean failOnUnknown) {
this.type = type;
this.mapper = new ObjectMapper().configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknown);
}
@Override
public T deserialize(String topic, byte[] data) {
try {
return data == null ? null : mapper.readValue(data, type);
} catch (IOException e) {
throw new SerializationException("cannot read " + type.getSimpleName(), e);
}
}
}
public static void main(String[] args) {
byte[] v1 = new JsonSerializer<OrderV1>().serialize("orders", new OrderV1("o-1", 1999));
System.out.println("v1 bytes (" + v1.length + "): "
+ new String(v1, StandardCharsets.UTF_8));
System.out.println("v1 read back: "
+ new JsonDeserializer<>(OrderV1.class, true).deserialize("orders", v1));
// a newer producer adds a field; old consumers still expect OrderV1
byte[] v2 = new JsonSerializer<OrderV2>().serialize("orders",
new OrderV2("o-2", 500, "EUR"));
System.out.println("v2 bytes (" + v2.length + "): "
+ new String(v2, StandardCharsets.UTF_8));
try {
new JsonDeserializer<>(OrderV1.class, true).deserialize("orders", v2);
} catch (SerializationException e) {
System.out.println("old consumer, Jackson defaults: " + e.getMessage() + ", cause "
+ e.getCause().getClass().getSimpleName());
}
System.out.println("old consumer, unknown fields ignored: "
+ new JsonDeserializer<>(OrderV1.class, false).deserialize("orders", v2));
// and an old producer's record read by a new consumer
System.out.println("new consumer reading v1: "
+ new JsonDeserializer<>(OrderV2.class, true).deserialize("orders", v1));
}
}
v1 bytes (25): {"id":"o-1","cents":1999}
v1 read back: OrderV1[id=o-1, cents=1999]
v2 bytes (41): {"id":"o-2","cents":500,"currency":"EUR"}
old consumer, Jackson defaults: cannot read OrderV1, cause UnrecognizedPropertyException
old consumer, unknown fields ignored: OrderV1[id=o-2, cents=500]
new consumer reading v1: OrderV2[id=o-1, cents=1999, currency=null]
- The v1 order became 25 bytes of JSON, and was read back into an equal record.
- With Jackson's defaults, an old consumer failed on the v2 record with
: adding a field broke every consumer that had not been redeployed first. This is the most common JSON trap in Kafka.UnrecognizedPropertyException - With
turned off, the old consumer read the v2 record and ignored the currency.FAIL_ON_UNKNOWN_PROPERTIES - A new consumer reading an old record got
. Jackson 2 fills missing fields withcurrency=null or zero, so the new code must handle the field being absent.null
Turn off FAIL_ON_UNKNOWN_PROPERTIESIOExceptionSerializationException
Avro with a schema registry
With Avro, the schema is stored once in a schema registry, and each record carries only a small schema id. Confluent's serializers register the schema on first use and check new versions for compatibility. The mock://
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AvroWireFormat {
static final String V1 = """
{"type": "record", "name": "Order", "namespace": "shop", "fields": [
{"name": "id", "type": "string"},
{"name": "cents", "type": "int"}]}""";
// v2 adds a field WITH a default, a backward-compatible change
static final String V2 = """
{"type": "record", "name": "Order", "namespace": "shop", "fields": [
{"name": "id", "type": "string"},
{"name": "cents", "type": "int"},
{"name": "currency", "type": "string", "default": "EUR"}]}""";
public static void main(String[] args) throws Exception {
// the serializers log their whole configuration at INFO; keep only errors.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
// mock:// keeps an in-memory registry in this JVM instead of calling a server
Map<String, Object> config = Map.of("schema.registry.url", "mock://shop");
try (KafkaAvroSerializer serializer = new KafkaAvroSerializer();
KafkaAvroDeserializer deserializer = new KafkaAvroDeserializer()) {
serializer.configure(config, false);
deserializer.configure(config, false);
GenericRecord order = new GenericData.Record(new Schema.Parser().parse(V1));
order.put("id", "o-1");
order.put("cents", 1999);
byte[] bytes = serializer.serialize("orders", order);
System.out.println("v1 record, " + bytes.length + " bytes: "
+ HexFormat.ofDelimiter(" ").formatHex(bytes));
ByteBuffer buffer = ByteBuffer.wrap(bytes);
System.out.println(" magic byte : " + buffer.get());
System.out.println(" schema id : " + buffer.getInt());
System.out.println(" Avro body : "
+ HexFormat.ofDelimiter(" ").formatHex(Arrays.copyOfRange(bytes, 5,
bytes.length)));
String json = "{\"id\":\"o-1\",\"cents\":1999}";
System.out.println(" the same as JSON: "
+ json.getBytes(StandardCharsets.UTF_8).length + " bytes");
System.out.println("read back: " + deserializer.deserialize("orders", bytes));
GenericRecord order2 = new GenericData.Record(new Schema.Parser().parse(V2));
order2.put("id", "o-2");
order2.put("cents", 500);
order2.put("currency", "USD");
byte[] bytes2 = serializer.serialize("orders", order2);
System.out.println("v2 record, schema id " + ByteBuffer.wrap(bytes2, 1, 4).getInt()
+ ", read back: " + deserializer.deserialize("orders", bytes2));
var registry = MockSchemaRegistry.getClientForScope("shop");
for (String subject : registry.getAllSubjects()) {
System.out.println("registry subject " + subject + ", versions "
+ registry.getAllVersions(subject));
}
}
}
}
v1 record, 11 bytes: 00 00 00 00 01 06 6f 2d 31 9e 1f
magic byte : 0
schema id : 1
Avro body : 06 6f 2d 31 9e 1f
the same as JSON: 25 bytes
read back: {"id": "o-1", "cents": 1999}
v2 record, schema id 2, read back: {"id": "o-2", "cents": 500, "currency": "USD"}
registry subject orders-value, versions [1, 2]
- The whole record took 11 bytes, against 25 for the same data in JSON.
- Byte 0 is the magic byte, 0. Bytes 1 to 4 are the schema id, 1, as a big-endian int. A consumer uses the id to fetch the writer's schema from the registry, once, and caches it.
- The Avro body is only 6 bytes:
is the length of "o-1" (3, zigzag-encoded), then its 3 bytes, then06 , the variable-length encoding of 1999. Avro writes no field names, only values in schema order.9e 1f - The v2 schema got id 2. Its new field has a default, so it is a backward-compatible change and the registry accepted it. The consumer read the v2 record with the schema it was written with, including
.currency=USD - Both versions sit under the subject
: by default the subject is the topic name plusorders-value or-value , and compatibility is checked per subject.-key
The registry's compatibility mode, BACKWARDauto.register.schemas=false
A poison record: when deserialization fails
A consumer that cannot deserialize a record is stuck, because the record is still at its position the next time it polls. A buggy producer writes the text "twelve" into a topic of 4-byte integers between two good records:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.RecordDeserializationException;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class PoisonPill {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try {
broker.addTopics("quantities");
// a producer that writes 4-byte ints, and one buggy producer that writes text
try (KafkaProducer<String, byte[]> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", ByteArraySerializer.class))) {
producer.send(new ProducerRecord<>("quantities", "a", new byte[] {0, 0, 0, 5}));
producer.send(new ProducerRecord<>("quantities", "b",
"twelve".getBytes(StandardCharsets.UTF_8)));
producer.send(new ProducerRecord<>("quantities", "c", new byte[] {0, 0, 0, 7}));
}
try (KafkaConsumer<String, Integer> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "stock",
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", IntegerDeserializer.class))) {
consumer.subscribe(List.of("quantities"));
int handled = 0;
int failures = 0;
while (handled < 3) {
try {
for (ConsumerRecord<String, Integer> r
: consumer.poll(Duration.ofSeconds(1))) {
System.out.println("offset " + r.offset() + ": " + r.key() + " = "
+ r.value());
handled++;
}
} catch (RecordDeserializationException e) {
failures++;
System.out.println("poll() threw " + e.getClass().getSimpleName()
+ " (" + e.origin() + ") at " + e.topicPartition() + " offset "
+ e.offset() + ": " + e.getCause().getMessage());
if (failures == 1) {
continue; // polling again does not help: it fails on the same record
}
byte[] raw = new byte[e.valueBuffer().remaining()];
e.valueBuffer().get(raw);
System.out.println(" raw value \"" + new String(raw,
StandardCharsets.UTF_8) + "\"; skipping it with seek()");
consumer.seek(e.topicPartition(), e.offset() + 1);
handled++;
}
}
}
} finally {
broker.destroy();
}
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
// one broker cannot hold the default 3 copies of the transaction log
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
Map.of("transaction.state.log.replication.factor", "1",
"transaction.state.log.min.isr", "1"));
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
offset 0: a = 5
poll() threw RecordDeserializationException (VALUE) at quantities-0 offset 1: Size of data received by IntegerDeserializer is not 4
poll() threw RecordDeserializationException (VALUE) at quantities-0 offset 1: Size of data received by IntegerDeserializer is not 4
raw value "twelve"; skipping it with seek()
offset 2: c = 7
- Offset 0 was read normally.
then threwpoll() . ItsRecordDeserializationException says the value failed, not the key, and it names the partition and offset 1.origin()- Polling again threw the same exception for the same offset. Without handling, the consumer would loop on this record for ever: this is a poison pill.
- The exception carries the raw bytes. The program printed them ("twelve") and called
to move past the bad record, and the next poll returned offset 2.seek(offset + 1)
The raw key, value and headers in the exception (added by KIP-1036) make it possible to publish the bad record to a dead letter topic before skipping it, as the ByteArrayDeserializertryErrorHandlingDeserializer
Size and speed of the formats
Format choice affects the bytes stored and sent, and the CPU spent per record. The program writes one order of five fields a million times in three formats, without compression or the registry's 5-byte prefix:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.EncoderFactory;
public class SizeAndSpeed {
record Order(String id, String customer, long cents, int items, boolean express) {
}
interface Format {
byte[] write(Order o) throws IOException;
}
static final Schema SCHEMA = new Schema.Parser().parse("""
{"type": "record", "name": "Order", "fields": [
{"name": "id", "type": "string"}, {"name": "customer", "type": "string"},
{"name": "cents", "type": "long"}, {"name": "items", "type": "int"},
{"name": "express", "type": "boolean"}]}""");
public static void main(String[] args) throws IOException {
Order order = new Order("o-123456", "customer-42", 129900, 3, true);
ObjectMapper mapper = new ObjectMapper();
GenericDatumWriter<GenericRecord> avroWriter = new GenericDatumWriter<>(SCHEMA);
Format json = mapper::writeValueAsBytes;
Format avro = o -> {
GenericRecord r = new GenericData.Record(SCHEMA);
r.put("id", o.id());
r.put("customer", o.customer());
r.put("cents", o.cents());
r.put("items", o.items());
r.put("express", o.express());
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
avroWriter.write(r, encoder);
encoder.flush();
return out.toByteArray();
};
Format binary = o -> { // hand-written: lengths, then fixed-size fields
byte[] id = o.id().getBytes(StandardCharsets.UTF_8);
byte[] customer = o.customer().getBytes(StandardCharsets.UTF_8);
return ByteBuffer.allocate(2 + id.length + 2 + customer.length + 8 + 4 + 1)
.putShort((short) id.length).put(id)
.putShort((short) customer.length).put(customer)
.putLong(o.cents()).putInt(o.items()).put((byte) (o.express() ? 1 : 0))
.array();
};
System.out.println("one order, rough comparison, best of 3 runs of 1,000,000 writes:");
measure("JSON (Jackson)", json, order);
measure("Avro binary", avro, order);
measure("hand-written binary", binary, order);
System.out.println("JSON text: " + new String(json.write(order), StandardCharsets.UTF_8));
}
static void measure(String name, Format format, Order order) throws IOException {
int size = format.write(order).length;
long best = Long.MAX_VALUE;
long sink = 0;
for (int run = 0; run < 3; run++) {
long start = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
sink += format.write(order).length;
}
best = Math.min(best, System.nanoTime() - start);
}
System.out.printf(" %-20s %3d bytes, %4d ns per record%s%n", name, size,
best / 1000000, sink == 0 ? "!" : "");
}
}
one order, rough comparison, best of 3 runs of 1,000,000 writes:
JSON (Jackson) 82 bytes, 373 ns per record
Avro binary 26 bytes, 644 ns per record
hand-written binary 36 bytes, 34 ns per record
JSON text: {"id":"o-123456","customer":"customer-42","cents":129900,"items":3,"express":true}
- JSON took 82 bytes, the largest by far, because every record repeats the five field names and writes numbers as text.
- Avro took 26 bytes, under a third of the JSON size: no field names, variable-length integers and one byte for the boolean. Building a
for every write made it the slowest of the three here; generatedGenericRecord classes avoid much of that cost.SpecificRecord - The hand-written binary format took 36 bytes, because it writes the long and the int at full width, and it was about ten times faster than JSON. It has no schema, no versioning and no support in other languages unless you write it.
These are rough comparisons: best of 3 runs on a 2-core Linux container, timing serialization only. Producer compression shrinks JSON much more than Avro, because the repeated names compress well, so the gap on the wire is smaller than the gap per record. For most applications the size difference matters more than the CPU time, which is small next to network and disk I/O.
Choosing a format
| Situation | Format |
|---|---|
| Keys: ids, names, numbers | StringSerializerLongSerializer |
| One team owns producer and consumers, readability matters | JSON, with unknown properties ignored |
| Topics shared between teams or languages | Avro or Protobuf with a schema registry |
| JSON documents that need a contract | JSON Schema with a schema registry |
| Very high volume, small records | Avro or Protobuf, plus producer compression |
| Pass-through or routing services | ByteArraySerializer |
| Consumers that must survive bad records | Catch RecordDeserializationException |
Related pages: