Kafka Schema Registry: schemas, subjects and serializers

Kafka stores bytes and knows nothing about their structure. Schema Registry gives producers and consumers a shared, versioned contract for those bytes, at the cost of five bytes per record. This page explains how the serializers, the registry and the record format fit together, then runs Avro and JSON Schema examples with Confluent's 8.4 serializers on a Kafka 4.2 broker.

Share

Contents

Why Kafka needs a schema registry

A Kafka broker stores keys and values as bytes and never looks inside them. The producer's serializer decides what the bytes mean, and every consumer must use a deserializer that agrees. With plain JSON strings, that agreement lives in documentation and in the code of each team. When a producer renames a field, consumers find out in production.

A schema registry is a separate service that stores versioned schemas and checks new versions against old ones. Confluent Schema Registry, the most widely used one, works like this:

  1. The producer's serializer derives the schema of the value, Avro, JSON Schema or Protobuf, and registers it under a subject, such as orders-value. The registry returns a numeric id, the same id for the same schema.
  2. The serializer writes a 5-byte prefix, a magic byte 0 and the 4-byte id, followed by the encoded value. Optionally, the id goes in a record header instead.
  3. The consumer's deserializer reads the id, fetches that schema from the registry once and caches it, and decodes the value.
  4. When a producer registers a new version, the registry checks it against the subject's compatibility rule, BACKWARD by default, and rejects changes that would break readers.
Schema formats supported by Confluent Schema Registry
FormatSerializerEncodingBest for
AvroKafkaAvroSerializerCompact binary, no field namesThe usual default in Kafka, strong evolution rules
JSON SchemaKafkaJsonSchemaSerializerPlain JSON textTeams already on JSON, readable payloads
ProtobufKafkaProtobufSerializerCompact binary with field numbersOrganisations already using Protobuf and gRPC

The programs use Confluent's 8.4 serializers with a mock:// registry URL. The serializers then use MockSchemaRegistry, an in-memory registry inside the JVM, instead of calling a server; everything else, from the wire format to subject names, is the same code path. One difference matters: the mock registry does not enforce compatibility when a schema is registered, while a real registry does, so the compatibility checks on the schema evolution page call the check explicitly. The broker program starts a single-node Kafka 4.2 broker inside the JVM; a real cluster has 3 or more brokers. The REST calls at the end were not run, because no registry server runs here.

The wire format, byte by byte

An order with three fields is small enough to read in hex. The program serializes it with KafkaAvroSerializer, takes the bytes apart, compares them with the same order as JSON, then asks the registry what was registered:

Java
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaMetadata;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
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.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 WireFormat {

    static final String ORDER_SCHEMA = """
            {"type": "record", "name": "Order", "namespace": "shop",
             "fields": [
               {"name": "id",       "type": "string"},
               {"name": "customer", "type": "string"},
               {"name": "cents",    "type": "long"}
             ]}""";

    public static void main(String[] args) throws Exception {
        quietLogs();
        // "mock://" gives an in-memory registry shared by everything in this JVM using the scope
        Map<String, String> config = Map.of("schema.registry.url", "mock://shop");
        Schema schema = new Schema.Parser().parse(ORDER_SCHEMA);
        GenericRecord order = new GenericData.Record(schema);
        order.put("id", "o-1001");
        order.put("customer", "ann");
        order.put("cents", 4599L);

        try (var serializer = new KafkaAvroSerializer();
             var deserializer = new KafkaAvroDeserializer()) {
            serializer.configure(config, false); // false: this is a value serializer
            deserializer.configure(config, false);
            byte[] bytes = serializer.serialize("orders", order);

            System.out.println("serialized: " + bytes.length + " bytes");
            System.out.println("  hex: " + HexFormat.ofDelimiter(" ").formatHex(bytes));
            ByteBuffer buf = ByteBuffer.wrap(bytes);
            System.out.println("  byte 0, magic byte: " + buf.get());
            System.out.println("  bytes 1-4, schema id: " + buf.getInt());
            System.out.println("  bytes 5-" + (bytes.length - 1) + ": Avro binary, "
                    + buf.remaining() + " bytes, no field names");

            String json = "{\"id\":\"o-1001\",\"customer\":\"ann\",\"cents\":4599}";
            System.out.println("the same order as JSON: "
                    + json.getBytes(StandardCharsets.UTF_8).length + " bytes");

            SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope("shop");
            System.out.println("subjects: " + registry.getAllSubjects());
            SchemaMetadata latest = registry.getLatestSchemaMetadata("orders-value");
            System.out.println("orders-value: version " + latest.getVersion()
                    + ", id " + latest.getId());

            Object back = deserializer.deserialize("orders", bytes);
            System.out.println("deserialized: " + back.getClass().getSimpleName() + " " + back);
        }
    }

    static void quietLogs() {
        // 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);
    }
}
Output
serialized: 18 bytes
  hex: 00 00 00 00 01 0c 6f 2d 31 30 30 31 06 61 6e 6e ee 47
  byte 0, magic byte: 0
  bytes 1-4, schema id: 1
  bytes 5-17: Avro binary, 13 bytes, no field names
the same order as JSON: 45 bytes
subjects: [orders-value]
orders-value: version 1, id 1
deserialized: Record {"id": "o-1001", "customer": "ann", "cents": 4599}
  • The value is 18 bytes. The first, 00, is the magic byte that marks the Confluent format.
  • Bytes 1 to 4, 00 00 00 01, are the schema id 1 as a big-endian integer.
  • The remaining 13 bytes are the Avro binary encoding. 0c is the length 6 of "o-1001" in Avro's zigzag variable-length encoding, followed by its characters; 06 and "ann" are the customer; ee 47 is 4599, also zigzag encoded. No field names are stored: the reader needs the schema to know what the bytes are.
  • The same order as JSON takes 45 bytes, because every record repeats the field names.
  • Serializing registered the schema under orders-value, the topic name plus "-value", as version 1 with id 1.
  • The deserializer found id 1 in the prefix, fetched the schema and returned a GenericData.Record.

The schema id is global to the registry, not per subject: the same schema registered under two subjects gets the same id. A consumer that receives a record with an id its registry does not know fails with an error, so producers and consumers must use the same registry.

Producing and consuming Avro on a broker

In an application, the serializers are configured as producer and consumer properties, with schema.registry.url passed through. The program sends one order with the classic id prefix and one with the id in a header, then reads both with a single consumer:

Java
import ch.qos.logback.classic.Level;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.serializers.schema.id.HeaderSchemaIdSerializer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.consumer.ConsumerConfig;
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.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
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 AvroOnBroker {

    static final Schema ORDER = new Schema.Parser().parse("""
            {"type": "record", "name": "Order", "namespace": "shop",
             "fields": [{"name": "id", "type": "string"}, {"name": "cents", "type": "long"}]}""");

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();

        // producer 1: the schema id goes in front of the value, the classic format
        try (var producer = new KafkaProducer<String, Object>(producerProps(servers, Map.of()))) {
            producer.send(new ProducerRecord<>("orders", "o-1", order("o-1", 4599))).get();
        }
        // producer 2: the schema id goes in a record header, the value is plain Avro
        try (var producer = new KafkaProducer<String, Object>(producerProps(servers,
                Map.of("value.schema.id.serializer", HeaderSchemaIdSerializer.class.getName())))) {
            producer.send(new ProducerRecord<>("orders", "o-2", order("o-2", 1250))).get();
        }

        Properties c = new Properties();
        c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                KafkaAvroDeserializer.class.getName());
        c.put("schema.registry.url", "mock://shop");
        try (var consumer = new KafkaConsumer<String, Object>(c)) {
            TopicPartition tp = new TopicPartition("orders", 0);
            consumer.assign(List.of(tp));
            consumer.seekToBeginning(List.of(tp));
            int seen = 0;
            while (seen < 2) {
                for (ConsumerRecord<String, Object> r : consumer.poll(Duration.ofMillis(500))) {
                    seen++;
                    GenericRecord value = (GenericRecord) r.value();
                    System.out.println(r.key() + ": " + value + ", cents field is a "
                            + value.get("cents").getClass().getSimpleName());
                    System.out.println("  value size " + r.serializedValueSize() + " bytes");
                    for (Header h : r.headers()) {
                        // byte 0 is a format version, the other 16 a random schema GUID
                        System.out.println("  header " + h.key() + ": " + h.value().length
                                + " bytes, first byte " + h.value()[0]);
                    }
                }
            }
        }
        broker.destroy();
    }

    static GenericRecord order(String id, long cents) {
        GenericRecord r = new GenericData.Record(ORDER);
        r.put("id", id);
        r.put("cents", cents);
        return r;
    }

    static Properties producerProps(String servers, Map<String, String> extra) {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName());
        p.put("schema.registry.url", "mock://shop"); // a real registry: "http://registry:8081"
        p.putAll(extra);
        return p;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // 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);
        }
    }
}
Output
o-1: {"id": "o-1", "cents": 4599}, cents field is a Long
  value size 11 bytes
o-2: {"id": "o-2", "cents": 1250}, cents field is a Long
  value size 6 bytes
  header __value_schema_id: 17 bytes, first byte 1
  • Both values came back as GenericRecord, and the long field arrived as a Java Long. Strings arrive as Avro's Utf8 type unless the schema says otherwise, which is why code calls toString() on them.
  • The first value is 11 bytes: the 5-byte prefix and 6 bytes of Avro.
  • With value.schema.id.serializer set to HeaderSchemaIdSerializer, the second value is 6 bytes of plain Avro, and the id travels in a __value_schema_id header of 17 bytes: a version byte, 1, and a 16-byte GUID that identifies the schema.
  • One consumer read both, because the default value.schema.id.deserializer, DualSchemaIdDeserializer, accepts an id in either place.

Header ids keep the payload a valid Avro, JSON or Protobuf document that tools without Schema Registry support can read. Older consumers that expect the prefix cannot read such records, so switch producers only after every consumer runs a client version that understands headers. In production, also set specific.avro.reader=true on the consumer when you use classes generated from .avsc files by the Avro Maven or Gradle plugin; the deserializer then returns those classes instead of GenericRecord.

Subject naming strategies

The subject decides which schemas are compared with each other. Two event types, an order and a refund, are sent to the same payments topic under each of the three built-in strategies, and the program lists the resulting subjects:

Java
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.serializers.subject.RecordNameStrategy;
import io.confluent.kafka.serializers.subject.TopicNameStrategy;
import io.confluent.kafka.serializers.subject.TopicRecordNameStrategy;
import java.util.HashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.common.errors.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SubjectStrategies {

    static final Schema ORDER = new Schema.Parser().parse("""
            {"type": "record", "name": "OrderPlaced", "namespace": "shop",
             "fields": [{"name": "id", "type": "string"}]}""");
    static final Schema REFUND = new Schema.Parser().parse("""
            {"type": "record", "name": "RefundIssued", "namespace": "shop",
             "fields": [{"name": "id", "type": "string"}, {"name": "cents", "type": "long"}]}""");

    public static void main(String[] args) throws Exception {
        quietLogs();
        Class<?>[] strategies = {TopicNameStrategy.class, RecordNameStrategy.class,
                TopicRecordNameStrategy.class};
        for (Class<?> strategy : strategies) {
            String scope = strategy.getSimpleName();
            Map<String, Object> config = new HashMap<>();
            config.put("schema.registry.url", "mock://" + scope);
            config.put("value.subject.name.strategy", strategy.getName());
            System.out.println(scope + ": two event types to topic payments");
            try (var serializer = new KafkaAvroSerializer()) {
                serializer.configure(config, false);
                for (GenericRecord event : new GenericRecord[] {record(ORDER), record(REFUND)}) {
                    try {
                        serializer.serialize("payments", event);
                        System.out.println("  " + event.getSchema().getName() + ": registered");
                    } catch (SerializationException e) {
                        System.out.println("  " + event.getSchema().getName() + ": REJECTED, "
                                + e.getCause().getMessage().split(";")[0]);
                    }
                }
            }
            SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope(scope);
            for (String subject : registry.getAllSubjects().stream().sorted().toList()) {
                System.out.println("  subject " + subject + ", versions "
                        + registry.getAllVersions(subject));
            }
        }

        // producers in production often must not register schemas themselves
        Map<String, Object> strict = new HashMap<>();
        strict.put("schema.registry.url", "mock://strict");
        strict.put("auto.register.schemas", false);
        try (var serializer = new KafkaAvroSerializer()) {
            serializer.configure(strict, false);
            serializer.serialize("orders", record(ORDER));
        } catch (SerializationException e) {
            System.out.println("auto.register.schemas=false, schema not registered: "
                    + e.getCause().getClass().getSimpleName());
        }
    }

    static GenericRecord record(Schema schema) {
        GenericRecord r = new GenericData.Record(schema);
        r.put("id", "x-1");
        if (schema.getField("cents") != null) {
            r.put("cents", 500L);
        }
        return r;
    }

    static void quietLogs() {
        // 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);
    }
}
Output
TopicNameStrategy: two event types to topic payments
  OrderPlaced: registered
  RefundIssued: registered
  subject payments-value, versions [1, 2]
RecordNameStrategy: two event types to topic payments
  OrderPlaced: registered
  RefundIssued: registered
  subject shop.OrderPlaced, versions [1]
  subject shop.RefundIssued, versions [1]
TopicRecordNameStrategy: two event types to topic payments
  OrderPlaced: registered
  RefundIssued: registered
  subject payments-shop.OrderPlaced, versions [1]
  subject payments-shop.RefundIssued, versions [1]
auto.register.schemas=false, schema not registered: RestClientException
  • TopicNameStrategy, the default, put both event types in payments-value, as versions 1 and 2. A real registry would have checked the refund against the order as a new version of the same schema and, under BACKWARD, rejected it. The mock accepted it, as noted above. This strategy suits one event type per topic.
  • RecordNameStrategy created one subject per record name, shop.OrderPlaced and shop.RefundIssued, whatever the topic. Each type evolves on its own, but the same record name used in two topics shares one history.
  • TopicRecordNameStrategy combined both, payments-shop.OrderPlaced and payments-shop.RefundIssued: several types per topic, each with its own history per topic.
  • With auto.register.schemas=false, serializing a schema that was never registered failed with RestClientException, the registry's "not found" error. That is what you want in production: schemas are registered by a build pipeline, and a producer cannot invent a new version at run time.

Two related settings are useful with auto.register.schemas=false. use.latest.version=true makes the serializer use the subject's latest schema instead of looking up the exact schema of the object. latest.compatibility.strict, true by default, then checks that the object's schema is compatible with that latest version.

JSON Schema from Java classes

With JSON Schema, the serializer can generate the schema from a Java class. A Shipment record with two strings and an int shows what it generates, and whether it rejects a missing id:

Java
import ch.qos.logback.classic.Level;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.testutil.MockSchemaRegistry;
import io.confluent.kafka.serializers.json.KafkaJsonSchemaDeserializer;
import io.confluent.kafka.serializers.json.KafkaJsonSchemaSerializer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import org.apache.kafka.common.errors.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonSchemaRecords {

    public record Shipment(String id, String city, int parcels) {
    }

    public static void main(String[] args) throws Exception {
        quietLogs();
        Map<String, Object> config = Map.of(
                "schema.registry.url", "mock://shipping",
                "json.fail.invalid.schema", true, // validate every value against its schema
                "json.value.type", Shipment.class.getName());
        try (var serializer = new KafkaJsonSchemaSerializer<Shipment>();
             var deserializer = new KafkaJsonSchemaDeserializer<Shipment>()) {
            serializer.configure(config, false);
            deserializer.configure(config, false);

            byte[] bytes = serializer.serialize("shipments", new Shipment("s-1", "Leeds", 3));
            System.out.println("serialized: " + bytes.length + " bytes, prefix "
                    + Arrays.toString(Arrays.copyOf(bytes, 5)));
            System.out.println("payload: "
                    + new String(bytes, 5, bytes.length - 5, StandardCharsets.UTF_8));

            SchemaRegistryClient registry = MockSchemaRegistry.getClientForScope("shipping");
            System.out.println("registered schema for shipments-value:");
            System.out.println("  " + registry.getLatestSchemaMetadata("shipments-value")
                    .getSchema());

            Shipment back = deserializer.deserialize("shipments", bytes);
            System.out.println("deserialized: " + back);

            try {
                serializer.serialize("shipments", new Shipment(null, "York", 1));
                System.out.println("null id accepted");
            } catch (SerializationException e) {
                System.out.println("null id: " + e.getMessage());
            }
        }
    }

    static void quietLogs() {
        // 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);
    }
}
Output
serialized: 44 bytes, prefix [0, 0, 0, 0, 1]
payload: {"id":"s-1","city":"Leeds","parcels":3}
registered schema for shipments-value:
  {"$schema":"http://json-schema.org/draft-07/schema#","title":"Shipment","type":"object","additionalProperties":false,"properties":{"id":{"oneOf":[{"type":"null","title":"Not included"},{"type":"string"}]},"city":{"oneOf":[{"type":"null","title":"Not included"},{"type":"string"}]},"parcels":{"type":"integer"}},"required":["parcels"]}
deserialized: Shipment[id=s-1, city=Leeds, parcels=3]
null id accepted
  • The value has the same 5-byte prefix, followed by plain JSON text: 44 bytes in all.
  • The generated schema is draft-07. It sets additionalProperties to false, so a reader rejects unknown fields; this closed content model affects how the schema may evolve.
  • Each String became "null or string", because a Java reference can be null. Only parcels, a primitive int, is required.
  • That is why the shipment with a null id was accepted, although json.fail.invalid.schema validates every value: the generated schema allows it.

Generated schemas describe Java's type system, not your business rules. For a contract that other teams rely on, write the schema by hand, mark required fields, and register it from the build; annotations such as Jackson's @JsonProperty(required = true) also influence the generator.

Working with a real registry

A real Schema Registry is a separate service with a REST API on port 8081 by default, storing its schemas in the Kafka topic _schemas. These calls come from Confluent's documentation and were not run here, because no registry server is available in this environment:

Shell
# list subjects
curl http://localhost:8081/subjects

# register a schema version under a subject
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"schema": "{\"type\": \"string\"}"}' \
  http://localhost:8081/subjects/Kafka-value/versions

# fetch a schema by its global id
curl http://localhost:8081/schemas/ids/1

# test a schema against the latest version, without registering it
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"schema": "{\"type\": \"string\"}"}' \
  http://localhost:8081/compatibility/subjects/Kafka-value/versions/latest

# change the global compatibility level
curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"compatibility": "NONE"}' http://localhost:8081/config

In client configuration, only the URL changes from the programs above, plus credentials when the registry is secured, for example basic.auth.credentials.source=USER_INFO and basic.auth.user.info. Clients cache schemas by id, so a running consumer keeps working through a short registry outage as long as no new schema ids appear.

Mistakes that break consumers

  • Plain deserializers on registry data: a StringDeserializer on an Avro topic returns garbage starting with the 5 prefix bytes. Every consumer of the topic must use the matching deserializer.
  • Different registries per environment, shared topics: ids are only meaningful in the registry that issued them. Mirroring a topic to another cluster needs the schemas mirrored too.
  • Auto-registration in production: any producer build can register a new version. Disable it and register from CI, where a failed compatibility check stops the release.
  • Several event types under TopicNameStrategy: the second type is checked as a new version of the first and is rejected, or forces NONE compatibility. Use a record-based strategy or one topic per type.
  • Keys with schemas: an Avro key is hashed as its serialized bytes. Changing the key schema, even compatibly, can change the bytes and send the same logical key to another partition. Keep keys as simple strings or numbers.

Choosing a format and a strategy

Situations and what to use
SituationUse
A new Kafka platform with many teamsAvro with Schema Registry, BACKWARD compatibility, schemas registered from CI
Existing JSON producers that must stay readableJSON Schema with hand-written schemas
An organisation standardised on ProtobufProtobuf with Schema Registry
One event type per topicTopicNameStrategy, the default
Several event types in one topic, for ordering per keyTopicRecordNameStrategy
Consumers or tools that must read payloads without the registry prefixSchema ids in headers, once all consumers support them
Two Spring services owned by one teamJSON without a registry can be enough; see Kafka serialization

How schemas may change over time, and which change breaks which consumer, is the subject of schema evolution and compatibility. Serializers without a registry are covered on Kafka serialization, and the producer settings they plug into on Kafka producer.