5 minute read

A Kafka record is durable long after the application that created it has changed. That makes the value format a cross-team interface, not an implementation detail. Apache Avro gives events a compact binary representation and a schema that defines each field, while a schema registry gives every deployed process a common place to resolve writer and reader schemas.

This article is dated to Avro and Kafka practices used in 2017. Amazon MSK came later and does not bundle a schema registry. Today a common deployment uses AWS Glue Schema Registry or a self-managed/partner Registry service with MSK.

The contract includes more than field types

An effective event contract specifies:

  • a namespace, record name, and subject;
  • required fields and their semantic units;
  • field defaults for old readers or writers;
  • partition key and event identity;
  • nullability and permitted enum values;
  • a compatibility policy;
  • owner, deprecation date, and rollback procedure.

Here is an order-created schema:

{
  "type": "record",
  "name": "OrderCreated",
  "namespace": "com.example.orders",
  "fields": [
    {"name": "event_id", "type": "string"},
    {"name": "order_id", "type": "string"},
    {"name": "occurred_at", "type": {
      "type": "long",
      "logicalType": "timestamp-millis"
    }},
    {"name": "currency", "type": "string", "default": "USD"},
    {"name": "total_cents", "type": "long"},
    {"name": "coupon_code", "type": ["null", "string"], "default": null}
  ]
}

The defaults are important. Under backward compatibility, a new reader can resolve records written with an older schema only when newly added fields have defaults. A nullable union alone does not guarantee resolution. Changing order_id from string to long, changing a record name, renaming a field without an alias, or reusing an enum label with different meaning is a breaking change.

Evolution rules

Choose compatibility based on deployment direction:

Mode Registration test Best fit
BACKWARD New readers can read old records Consumers deploy before or during producer rollout
FORWARD Old readers can read new records Producers deploy before lagging consumers
FULL Both directions pass Independent producer and consumer release trains
NONE No check Temporary migration only, with explicit approval

Use per-subject compatibility rather than assuming one policy is right for all domains. FULL is conservative but can make type corrections and field replacement difficult. Version a topic when a breaking logical change is required. Avoid using NONE merely to remove a rollout blocker.

Adding discount_cents with a default is a safe backward-compatible step:

{"name": "discount_cents", "type": "long", "default": 0}

An old reader may ignore the new field. A new reader can calculate its expected default for older records. To move from postal_code string to a structured address, add the new structure first, dual-write it, migrate consumers, and remove the old field in a later major topic version.

Registry in the data path

Schema registry request path with producers, compatibility checks, MSK records, consumers, and a quarantine stream

A producer normally serializes a datum and prefixes or associates it with a schema identifier. A consumer uses that identifier to retrieve the writer schema, then applies its reader schema. Cache schemas with the registry client, but retain clear behavior when the cache misses.

The registry is in the serialization path, so design it as a service:

  • deploy it across multiple Availability Zones;
  • use IAM or mTLS from clients;
  • monitor availability, authorization failures, cache misses, and latency;
  • restrict schema update permission separately from read permission;
  • retain registry snapshots and audit schema changes;
  • test that producers cannot reach Kafka while bypassing registration.

In a Python producer with a Glue-compatible serializer, the exact adapter depends on the schema registry implementation. The essential behavior is:

from uuid import uuid4
from myapp.registry import AvroSerializer
from confluent_kafka import Producer

serializer = AvroSerializer(
    registry_name="orders",
    subject="orders.events-value",
    schema_file="schemas/order-created-v2.avsc",
)

value = {
    "event_id": str(uuid4()),
    "order_id": "ORD-1042",
    "occurred_at": 1503262800000,
    "currency": "USD",
    "total_cents": 12900,
    "coupon_code": None,
    "discount_cents": 500,
}

producer = Producer({"bootstrap.servers": "BROKER_LIST"})
producer.produce(
    "orders.events",
    key="ORD-1042".encode(),
    value=serializer.serialize(value),
    on_delivery=lambda err, msg: record_delivery(err, msg),
)
producer.flush()

In Java, generated Avro classes make contract changes visible at compile time:

OrderCreated event = OrderCreated.newBuilder()
    .setEventId(UUID.randomUUID().toString())
    .setOrderId("ORD-1042")
    .setOccurredAt(Instant.ofEpochMilli(1503262800000L))
    .setCurrency("USD")
    .setTotalCents(12900L)
    .setCouponCode(null)
    .build();

serializer = factory.createSerializer(OrderCreated.class);
producer.send(new ProducerRecord<>(
    "orders.events", event.getOrderId().toString(),
    serializer.serialize(event)));

Use the serializer supplied by the selected registry. The logical rules do not change, but wire framing and registry APIs do.

Reject, quarantine, and repair

There are four distinct bad-record classes:

  1. malformed transport bytes or an unknown schema identifier;
  2. a known schema with data that violates its contract;
  3. semantic corruption, such as a negative amount in a valid long field;
  4. an unavailable or unauthorized registry.

Do not treat all four as poison data. For classes 1 and 2, publish the original bytes and metadata to a quarantine topic without trying to deserialize them, increment a bounded retry counter, and page if the rate exceeds baseline. For class 3, route to a domain validation dead-letter stream. For class 4, consumers should retry only from the last committed offset and preserve the partition assignment until a clear recovery timeout.

A useful quarantine envelope is:

{
  "source_topic": "orders.events",
  "partition": 8,
  "offset": 1849201,
  "schema_id": "unknown",
  "error_class": "SchemaNotFound",
  "event_id": null,
  "first_seen_at": "2017-08-20T12:05:11Z",
  "retry_count": 0
}

If the registry is temporarily unavailable, a warm client cache can continue reading previously used schemas. Do not let that become a false availability guarantee: a newly introduced schema has no cache entry. Consumers must surface failures, retain offsets, and avoid publishing partial transformations.

Release and rollback

Treat schema registration as a deployment step:

  1. lint names, defaults, logical types, and field documentation;
  2. run the registry’s compatibility check in CI against the target subject;
  3. deploy reader changes behind a feature flag;
  4. register the schema to staging, then production;
  5. deploy compatible producers with canary traffic;
  6. compare old and new schema version rates;
  7. roll traffic back or continue rollout.

Rollback removes the new producer binary, not the schema record in the registry. Consumers may still encounter the new version in Kafka during replay. Therefore, “rolling back” a schema release is safe only if all possible readers remain compatible with every record already produced. A registry should be treated as append-only. Correct an accidentally registered but unused schema by disabling the affected deployment; do not assume deletion restores reality.

Measurable controls

Alert on:

  • schema registration error or denied update;
  • unknown schema IDs above zero for a newly deployed consumer;
  • deserialization failures above 0.01 percent or any abrupt step change;
  • registry p99 read latency above 200 ms;
  • cache miss rate that rises after normal warm-up;
  • a schema version with traffic but no approved owner or deprecation plan.

Compatibility prevents many structural failures, but not incorrect business meaning. Pair schema checks with golden Avro fixtures, consumer contract tests, and canary events. The schema is a transport contract; the event’s semantics still need tests and observability.