Schemas and evolution (Avro, Schema Registry)

Senior Differentiator 3 min

On this page

The question

Why use a schema registry with Kafka?

30-second answer

Kafka stores bytes and checks nothing, while producers and consumers are deployed by different teams at different times. A schema registry stores every version of each topic's schema, in Avro, Protobuf or JSON Schema, and rejects a new version that breaks the compatibility rule. Records carry only a small schema ID, so they stay compact, and consumers fetch the writer's schema to decode them. Contract breaks fail in continuous integration (CI), not in production.

Understand it

Compatible or breaking under BACKWARD

Build

The subject orders-value uses BACKWARD compatibility: consumers on the new schema must read every old record. Give each change its verdict.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
  5. Empty
  6. Empty
View as text

The schema Order version 1, with id as a string, total as an int and currency as a string, above six proposed changes, each with an empty slot for its verdict. The subject orders-value uses BACKWARD compatibility: consumers on the new schema must read every old record. Give each change its verdict.

Add coupon, optional, default null: Compatible: old records get the default. Add channel, required, no default: Breaking: old records have no channel. Remove currency: Compatible: the new reader ignores it. Rename total to amount: Breaking: old data has no amount field. Change total from int to long: Compatible: an int widens to a long. Change id from string to int: Breaking: a string cannot become an int.

Three changes pass and three are rejected by the registry. Adding a field with a default is safe both ways; renames and type changes break readers.

The schema Order version 1, with id as a string, total as an int and currency as a string, above six proposed changes, each with an empty slot for its verdict. The subject orders-value uses BACKWARD compatibility: consumers on the new schema must read every old record. Give each change its verdict.

Add coupon, optional, default null: Compatible: old records get the default. Add channel, required, no default: Breaking: old records have no channel. Remove currency: Compatible: the new reader ignores it. Rename total to amount: Breaking: old data has no amount field. Change total from int to long: Compatible: an int widens to a long. Change id from string to int: Breaking: a string cannot become an int.

Three changes pass and three are rejected by the registry. Adding a field with a default is safe both ways; renames and type changes break readers.

Takeaway: A schema registry checks every new version against the old ones. Under BACKWARD, the default, the new schema must read old data: fields can be added only with a default, and removed freely.

Which side upgrades first, by compatibility modeUnder BACKWARD compatibility, the new schema reads old data, so consumers upgrade first. Under FORWARD, old schemas read new data, so producers upgrade first. Under FULL, both hold, so either side can go first. The TRANSITIVE variants check against every earlier version, not only the latest.BACKWARD, thedefault:new reads oldUpgradeconsumers firstFORWARD:old reads newUpgradeproducers firstFULL: bothAny order
Which side upgrades first, by compatibility modeUnder BACKWARD compatibility, the new schema reads old data, so consumers upgrade first. Under FORWARD, old schemas read new data, so producers upgrade first. Under FULL, both hold, so either side can go first. The TRANSITIVE variants check against every earlier version, not only the latest.BACKWARD, thedefault:new reads oldUpgradeconsumers firstFORWARD:old reads newUpgradeproducers firstFULL: bothAny order
Which side upgrades first, by compatibility mode

In code

Schema v1 = SchemaBuilder.record("Order").namespace("com.shop").fields()
    .requiredString("id")
    .requiredInt("total")
    .requiredString("currency")
    .endRecord();

Schema v2 = SchemaBuilder.record("Order").namespace("com.shop").fields()
    .requiredString("id")
    .requiredInt("total")
    .requiredString("currency")
    .optionalString("coupon")             // ["null", "string"], default null: old records read as null
    .endRecord();

// The registry's question under BACKWARD: can v2 read what v1 wrote?
var result = SchemaCompatibility.checkReaderWriterCompatibility(v2, v1);
assert result.getType() == SchemaCompatibilityType.COMPATIBLE;
Order v1 and v2 with Avro's SchemaBuilder
spring.kafka.producer.value-serializer=io.confluent.kafka.serializers.KafkaAvroSerializer
spring.kafka.consumer.value-deserializer=io.confluent.kafka.serializers.KafkaAvroDeserializer
spring.kafka.properties.schema.registry.url=http://schema-registry:8081
# Register schemas from CI, not from a producer at runtime
spring.kafka.producer.properties.auto.register.schemas=false
spring.kafka.producer.properties.use.latest.version=true
# Deserialize into the generated Order class, not a GenericRecord
spring.kafka.consumer.properties.specific.avro.reader=true
Producer and consumer with the Avro serializers and a schema registry
curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"compatibility": "BACKWARD"}' http://localhost:8081/config/orders-value

curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data @order-v2-request.json \
  http://localhost:8081/compatibility/subjects/orders-value/versions/latest
# {"is_compatible":false}   the change would break consumers: fix it before merging
Set the rule for a subject, and test a new schema before registering it
// No default: a consumer on v2 cannot fill channel for records written with v1
 Wrong .name("channel").type().stringType().noDefault()

// A default: records written with v1 read as channel = "web"
 Right .name("channel").type().stringType().stringDefault("web")
A new required field breaks every reader of old records
What travels in a record, and where the schema livesThe producer's serializer looks up the ID of its schema in the registry, 7, and caches it. Each record holds a magic byte, the schema ID and the Avro bytes, not the schema. The consumer's deserializer fetches schema 7 once, caches it, and decodes the record with it, resolved against its own reader schema.ConsumerKafkaSchema registryProducerdecode, then resolveto its reader schemaID of my schema?7magic byte, ID 7, Avro bytesthe same bytesschema 7?schema 7, then cached
What travels in a record, and where the schema livesThe producer's serializer looks up the ID of its schema in the registry, 7, and caches it. Each record holds a magic byte, the schema ID and the Avro bytes, not the schema. The consumer's deserializer fetches schema 7 once, caches it, and decodes the record with it, resolved against its own reader schema.ConsumerKafkaSchema registryProducerdecode, then resolveto its reader schemaID of my schema?7magic byte, ID 7, Avro bytesthe same bytesschema 7?schema 7, then cached
What travels in a record, and where the schema lives

Solve it

Add a field to OrderPlaced without breaking twelve consumers

OrderPlaced is an Avro record on orders, read by twelve services owned by six teams. Marketing needs a new channel field, web or app. The subject uses BACKWARD compatibility. Design the change and the rollout so that no consumer fails, whatever order the teams deploy in.

  1. Ask both questions. BACKWARD asks whether new readers can read old records; old readers meeting new records is FORWARD. Twelve teams will not deploy at once, so the change should be safe both ways.
  2. Pick a change that is. Adding a field with a default is backward compatible, since old records get the default, and forward compatible, since old readers skip a field they do not know. A required field fails BACKWARD.
  3. Choose the default deliberately. null with an optional type says “unknown”, which is honest for old orders; "web" would claim something nobody recorded.
  4. Let the registry decide, in CI. Test the new schema against the subject in the build, and register it from the pipeline, with auto.register.schemas=false on producers.
  5. Check. In a test, read a record written with v1 using v2 and the reverse; both decode, and channel is null for the old one.
Schema v2 = SchemaBuilder.record("OrderPlaced").namespace("com.shop").fields()
    .requiredString("orderId")
    .requiredLong("totalCents")
    .optionalString("channel")                      // null for every record written before
    .endRecord();

@Test
void v2IsCompatibleBothWays() {
    assertThat(checkReaderWriterCompatibility(v2, v1).getType()).isEqualTo(COMPATIBLE);   // backward
    assertThat(checkReaderWriterCompatibility(v1, v2).getType()).isEqualTo(COMPATIBLE);   // forward
}
v2 adds an optional channel, checked both ways in a unit test

How to answer

  • Schemas are grouped by subject, by default the topic name plus -key or -value.
  • The serializer prefixes each record with a magic byte and a 4-byte schema ID.
  • Clients cache schemas, so the registry is not called per record.

Common mistakes

  • Sending free-form JSON and calling the topic a contract. Nothing stops a producer from breaking consumers.
  • Registering schemas automatically from producers in production, which bypasses review.

Follow-up questions

What is the difference between backward and forward compatibility?

Backward compatible means consumers on the new schema can read data written with the old one, so you upgrade consumers first; it is the registry's default. Forward compatible means consumers on the old schema can read data written with the new one, so producers can upgrade first. Full means both. The transitive variants check against every earlier version, not just the latest, which matters when old data is replayed.

  • Adding a field with a default is safe both ways.
  • Removing a field is backward compatible but breaks old readers that need it, unless it had a default.
  • Renaming a field breaks both, unless the new schema declares the old name as an alias.

See it in the infographic: Compatible or breaking under BACKWARD

Check yourself

1. A subject uses BACKWARD compatibility. Which change does the schema registry reject?
Show answers
  • Adding a required field with no default: Correct. A new reader cannot fill that field for old records.
  • Adding an optional field with default null: Incorrect. Old records simply read the default.
  • Removing a field: Incorrect. The new reader ignores the field in old records, so BACKWARD allows it.