00:00

Kafka Schema Registry and Serialization

Last updated:

Schema Registry keeps producers and consumers of a Kafka topic in agreement about the structure of the data. Kafka itself only stores bytes; it never checks what is inside a record. Schema Registry stores versioned schemas, gives each one an ID, and rejects schema changes that would break existing consumers.

This tutorial explains why serialization needs a contract, how the Avro serializer and Schema Registry work together on the wire, what subjects and compatibility modes mean, and how to use Avro with plain Java and Spring Boot. It also covers the settings you should change before going to production.

1. What Is Schema Registry?

Schema Registry is a separate service with a REST API that stores schemas for Kafka data. Producers register the schema they write with, consumers look it up when they read, and the registry enforces rules about how a schema may change over time. It supports Avro, Protobuf and JSON Schema.

Apache Kafka vs Confluent: Schema Registry is not part of Apache Kafka. The most widely used implementation is developed by Confluent and is licensed separately from Apache Kafka; it runs alongside any Kafka cluster, including the open-source one. Apicurio Registry is an open-source alternative with a compatible API mode. The concepts on this page apply to both; the code uses Confluent’s serializers.

The registry stores its schemas in a compacted Kafka topic (_schemas by default), so it needs no database of its own, and several registry instances can run behind a load balancer for availability.

2. Why Kafka Needs a Schema Contract

In Kafka, the producer and the consumer never talk to each other. They share only the topic. If the order service renames amount to totalAmount in its JSON, every consumer that reads amount breaks at run time, possibly days later, and the bad records stay in the topic until retention removes them.

Without a schema registryWith a schema registry
Structure lives only in code and documentationEvery version of the structure is stored and numbered
Breaking changes are found in production, by consumersBreaking changes are rejected when the producer tries to register them
Each JSON record repeats every field nameBinary formats send only values plus a 5-byte header
Consumers guess types (is amount a string or a number?)Types, defaults and optional fields are defined precisely

3. Serialization Formats Compared

FormatEncodingSchemaTypical use
Plain JSON (for example Spring’s JacksonJsonSerializer)Text, field names in every recordNone enforcedSimple systems with few consumers that are deployed together
JSON SchemaTextJSON Schema in the registryTeams that want JSON on the wire but validated structure
AvroCompact binaryAvro schema (JSON) in the registryThe most common choice for Kafka data pipelines; excellent evolution rules
ProtobufCompact binary.proto definition in the registryOrganisations already using Protobuf for gRPC

Kafka’s own serializers (StringSerializer, ByteArraySerializer and so on) turn objects into bytes but know nothing about schemas. The registry-aware serializers add the schema lookup and the wire format described next.

4. How It Works on the Wire

Schema Registry serialization flowThe producer's Avro serializer registers or looks up the schema for subject orders-value in Schema Registry and receives schema ID 42, which it caches. It writes a record to the orders topic whose value starts with magic byte 0 and the 4-byte schema ID 42, followed by the Avro-encoded data. The consumer's deserializer reads the ID, fetches schema 42 from the registry once and caches it, then decodes the data. Schema Registry stores its schemas in the compacted _schemas topic. ProducerKafkaAvroSerializer ConsumerKafkaAvroDeserializer Schema Registrysubject orders-value → v3 = id 42stored in topic _schemas topic "orders"[0][00 00 00 2A][Avro bytes] 1. register / look up 2. id 42 (cached) 3. write 4. read 5. fetch schema 42 once
Records carry only a schema ID; the full schema is fetched once per ID and cached by each client.
  1. Before sending the first record of a type, the serializer asks the registry for the ID of its schema under the record’s subject. With the default settings it registers the schema if it is new; the registry runs the compatibility check at this point.
  2. The returned ID is cached in the producer, so later records need no registry call.
  3. Each record value is written as a magic byte (0), the 4-byte schema ID, then the encoded data.
  4. The consumer’s deserializer reads the ID, downloads that schema the first time it sees the ID, caches it and decodes the record.

Because clients cache schemas by ID, a short registry outage does not stop producers and consumers that already know their schemas; it only blocks new schemas and new clients.

5. Subjects and Naming Strategies

A subject is the name under which versions of a schema are stored and checked for compatibility. The serializer derives it with a naming strategy:

StrategySubject for the value of topic ordersWhen to use
TopicNameStrategy (default)orders-value (and orders-key for keys)One event type per topic; the usual and simplest choice
RecordNameStrategyThe record’s full name, for example com.javabytechie.OrderPlacedSeveral event types in one topic, with the same type used across topics
TopicRecordNameStrategyorders-com.javabytechie.OrderPlacedSeveral event types in one topic, evolved independently per topic

Keeping several event types in one topic is the standard way to preserve their order for the same key, for example OrderPlaced and OrderCancelled for one order. See message ordering for why that matters.

6. Compatibility Modes and Schema Evolution

Each subject has a compatibility mode. When a new schema version is registered, the registry checks it against the previous version (or all previous versions for the _TRANSITIVE modes) and rejects it if the check fails. The default mode is BACKWARD.

ModeGuaranteeAllowed changes (Avro)Upgrade first
BACKWARD (default)Consumers using the new schema can read data written with the previous oneRemove fields; add fields that have defaultsConsumers
FORWARDConsumers using the previous schema can read data written with the new oneAdd fields; remove fields that have defaultsProducers
FULLBoth of the aboveAdd or remove only fields that have defaultsEither, in any order
*_TRANSITIVESame, but against all earlier versionsAs aboveAs above
NONENo checksAnythingEveryone at once, or use a new topic

In practice, give every new field a default value. That one habit keeps most changes compatible in every mode. Renaming a field or changing its type is a breaking change; the usual approach is to add the new field, migrate consumers, and remove the old field later, or to publish to a new topic.

Why transitive matters: a consumer replaying old data from the start of a topic may meet records written with version 1 while it uses version 5. BACKWARD only proves that v5 reads v4; BACKWARD_TRANSITIVE proves that v5 reads every earlier version. Use transitive modes for topics that are replayed or retained for a long time.

7. Example: Avro Producer and Consumer in Java

Add a Schema Registry container next to the broker from the Kafka Docker setup:

docker-compose.yml (additional service)
  schema-registry:
    image: confluentinc/cp-schema-registry:8.4.1
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_LISTENERS: http://0.0.0.0:8081
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: PLAINTEXT://broker:19092
    depends_on:
      broker:
        condition: service_healthy

The Confluent serializers are published in Confluent’s Maven repository, not Maven Central:

pom.xml (excerpt)
<repositories>
  <repository>
    <id>confluent</id>
    <url>https://packages.confluent.io/maven/</url>
  </repository>
</repositories>

<dependency>
  <groupId>io.confluent</groupId>
  <artifactId>kafka-avro-serializer</artifactId>
  <version>8.4.1</version>
</dependency>

The schema of an order event, with a defaulted optional field:

src/main/resources/avro/order-placed.avsc
{
  "type": "record",
  "name": "OrderPlaced",
  "namespace": "com.javabytechie.orders",
  "fields": [
    { "name": "orderId",    "type": "string" },
    { "name": "customerId", "type": "string" },
    { "name": "amount",     "type": { "type": "bytes", "logicalType": "decimal", "precision": 12, "scale": 2 } },
    { "name": "couponCode", "type": ["null", "string"], "default": null }
  ]
}

A producer that uses GenericRecord, so no code generation is needed for this example:

AvroOrderProducer.java
package com.javabytechie.kafka;

import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.Properties;
import org.apache.avro.Conversions;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
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.serialization.StringSerializer;

public class AvroOrderProducer {

    public static void main(String[] args) throws Exception {
        Schema schema;
        try (InputStream in = AvroOrderProducer.class.getResourceAsStream("/avro/order-placed.avsc")) {
            schema = new Schema.Parser().parse(in);
        }

        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
        props.put("schema.registry.url", "http://localhost:8081");

        Schema amountSchema = schema.getField("amount").schema();
        ByteBuffer amount = new Conversions.DecimalConversion().toBytes(
                new BigDecimal("249.90"), amountSchema, LogicalTypes.decimal(12, 2));

        GenericRecord order = new GenericData.Record(schema);
        order.put("orderId", "ord-1001");
        order.put("customerId", "cus-77");
        order.put("amount", amount);
        order.put("couponCode", null);

        try (var producer = new KafkaProducer<String, GenericRecord>(props)) {
            producer.send(new ProducerRecord<>("orders", "ord-1001", order), (meta, ex) -> {
                if (ex != null) ex.printStackTrace();
                else System.out.printf("Sent to %s-%d@%d%n", meta.topic(), meta.partition(), meta.offset());
            });
        }
    }
}

After the first run, the registry contains the subject orders-value with version 1. You can inspect it with the REST API:

Terminal
curl -s http://localhost:8081/subjects
# ["orders-value"]

curl -s http://localhost:8081/subjects/orders-value/versions/latest
# {"subject":"orders-value","version":1,"id":1,"schema":"{\"type\":\"record\", ...}"}

A consumer only needs the deserializer and the registry URL. Without further settings it returns GenericRecord values; set specific.avro.reader=true to get generated classes instead.

8. Using Schema Registry with Spring Boot

In a Spring Boot application you normally generate Java classes from the .avsc files at build time with the avro-maven-plugin (schema goal, with its sourceDirectory pointing at the folder that holds the .avsc files), and configure the Confluent serializers through Spring Boot properties. Properties under spring.kafka.properties are passed to producers, consumers and admin clients alike:

application.yml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    properties:
      schema.registry.url: http://localhost:8081
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
    consumer:
      group-id: billing-service
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
      properties:
        specific.avro.reader: true
BillingListener.java
package com.javabytechie.billing;

import com.javabytechie.orders.OrderPlaced;   // generated from order-placed.avsc
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class BillingListener {

    @KafkaListener(topics = "orders")
    public void onOrder(OrderPlaced order) {
        // fields are typed; couponCode is null when the producer did not set it
        System.out.printf("Invoice for %s, coupon=%s%n", order.getOrderId(), order.getCouponCode());
    }
}

Spring for Apache Kafka has no Schema Registry of its own; it simply uses whatever Serializer and Deserializer you configure. To handle a record that cannot be deserialized, for example because its schema ID is unknown, wrap the Avro deserializer in Spring’s ErrorHandlingDeserializer as described in Kafka error handling.

9. Production Configuration

SettingDefaultRecommendation
auto.register.schemas (serializer)trueSet to false in production and register schemas from the CI pipeline, so a service cannot publish a schema that nobody reviewed
use.latest.version (serializer)falseSet to true together with auto.register.schemas=false to serialize with the latest registered version
Subject compatibilityBACKWARDUse a transitive mode for long-retained or replayed topics; set it per subject with PUT /config/{subject}
value.subject.name.strategyTopicNameStrategyChange only when a topic carries several event types

Before deploying a schema change, test it against the registry with the compatibility endpoint, for example from a CI job:

Terminal
curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data @new-schema-request.json \
  http://localhost:8081/compatibility/subjects/orders-value/versions/latest
# {"is_compatible":true}

10. Common Mistakes

  • Adding a field without a default. Under the default BACKWARD mode the new schema cannot read old records, so registration fails, or with NONE the consumers fail later.
  • Leaving auto-registration on in production. A developer’s local change can register a new schema version in the shared registry.
  • Mixing serializers on one topic. A record written as plain JSON has no magic byte and schema ID, so the Avro deserializer fails on it, and it blocks the partition unless errors are handled.
  • Treating the registry as optional infrastructure. New producers and consumers cannot start without it; run at least two instances in production.
  • Forgetting the key. If keys are Avro too, the orders-key subject evolves separately; changing the key schema also changes partitioning.

11. Best Practices

  • Treat schemas as code: keep .avsc or .proto files in a shared repository, review changes, and register them from CI.
  • Default every optional field and avoid renames; deprecate and remove fields over several releases.
  • Pick one format per organisation where possible; Avro is the most common choice for Kafka.
  • Use simple string keys (such as an order ID) unless you have a reason to put structured data in the key.
  • Plan upgrades by mode: with BACKWARD, deploy consumers before producers.

12. Summary

Kafka stores bytes, so the structure of events must be agreed elsewhere. Schema Registry stores versioned schemas per subject, hands out schema IDs that travel in a 5-byte header with every record, and blocks incompatible changes before they reach consumers. Use Avro or Protobuf with registry-aware serializers, keep the default BACKWARD mode (or its transitive form for replayed topics), give new fields defaults, and register schemas from CI rather than from running services.

14. References