Lab 4 of 8 · Schemas and Schema Registry
Enforce an order schema
Run Schema Registry, send Avro-encoded orders, and prove that the registry rejects a breaking change and accepts a safe one.
- Time
- 75 minutes
- Cost
- Free. Schema Registry is free to use under the Confluent Community License.
What you learn
When many services share a topic, one bad message can break every consumer. You define an Avro schema, register it in Schema Registry, and let the registry reject changes that would break readers.
- Why events need a contract
- Avro schemas and serialising events from Python
- Schema Registry subjects and versions
- Backward compatibility: safe and unsafe schema changes
In the AI era: AI is good at drafting schemas from sample data. Review every field’s type and default yourself: a schema is a contract other teams depend on, and changing it later is hard.
Get set up
Commands use Homebrew in the Terminal app. Already have a tool? Skip it.
- A terminalOfficial install page ↗
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"Use the Terminal app. The command installs Homebrew, which the other macOS commands use.
- Multipass (a free Ubuntu server on your computer)Official install page ↗
brew install --cask multipassCheck it worked:
multipass version
Before you start
Start your server and activate
.venvin~/kafka-streaming-lab.
Step by step
1 Start Schema Registry
It stores schemas in a Kafka topic on your broker and serves them on port 8081.
--network hostlets it reach Kafka onlocalhost:9092.docker run -d --name schema-registry --restart unless-stopped --network host \ -e SCHEMA_REGISTRY_HOST_NAME=localhost \ -e SCHEMA_REGISTRY_LISTENERS=http://0.0.0.0:8081 \ -e SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS=PLAINTEXT://localhost:9092 \ confluentinc/cp-schema-registry:7.9.1 sleep 20 curl -s localhost:8081/subjectsYou should see:[]: the registry is running and has no schemas yet.2 Write the order schema
Create
schemas/order.avsc.{ "type": "record", "name": "Order", "namespace": "lab.orders", "fields": [ { "name": "order_id", "type": "int" }, { "name": "customer", "type": "string" }, { "name": "item", "type": "string" }, { "name": "qty", "type": "int" } ] }3 Write an Avro producer
The serializer registers the schema the first time and checks every order against it before sending. The last part tries an order with no
qty. Save it asavro_producer.py.from confluent_kafka import Producer from confluent_kafka.schema_registry import SchemaRegistryClient from confluent_kafka.schema_registry.avro import AvroSerializer from confluent_kafka.serialization import MessageField, SerializationContext, StringSerializer registry = SchemaRegistryClient({"url": "http://localhost:8081"}) with open("schemas/order.avsc") as schema_file: serialize_value = AvroSerializer(registry, schema_file.read()) serialize_key = StringSerializer("utf_8") producer = Producer({"bootstrap.servers": "localhost:9092", "partitioner": "murmur2_random"}) context = SerializationContext("orders-avro", MessageField.VALUE) order = {"order_id": 1, "customer": "alice", "item": "book", "qty": 1} producer.produce("orders-avro", key=serialize_key("alice"), value=serialize_value(order, context)) producer.flush(10) print("sent", order) try: serialize_value({"order_id": 2, "customer": "bob", "item": "pen"}, context) except Exception as error: print("rejected an order with no qty:", type(error).__name__)4 Run it and look at the registry
The schema is registered under the subject
orders-avro-value.python avro_producer.py curl -s localhost:8081/subjects curl -s localhost:8081/subjects/orders-avro-value/versions/latestYou should see:sent {...},rejected an order with no qty: ValueError, then["orders-avro-value"]and version 1 of your schema.5 Try a breaking change
Adding a required field breaks consumers that read old orders, so the registry’s default BACKWARD rule rejects it. This only checks; it does not register anything.
NEW='{"type":"record","name":"Order","namespace":"lab.orders","fields":[{"name":"order_id","type":"int"},{"name":"customer","type":"string"},{"name":"item","type":"string"},{"name":"qty","type":"int"},{"name":"coupon","type":"string"}]}' curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \ --data "$(jq -n --arg s "$NEW" '{schema: $s}')" \ localhost:8081/compatibility/subjects/orders-avro-value/versions/latestYou should see:{"is_compatible":false}.6 Make it a safe change
Give the new field a default. Old orders can then be read as if they had
coupon: "".NEW='{"type":"record","name":"Order","namespace":"lab.orders","fields":[{"name":"order_id","type":"int"},{"name":"customer","type":"string"},{"name":"item","type":"string"},{"name":"qty","type":"int"},{"name":"coupon","type":"string","default":""}]}' curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \ --data "$(jq -n --arg s "$NEW" '{schema: $s}')" \ localhost:8081/compatibility/subjects/orders-avro-value/versions/latestYou should see:{"is_compatible":true}.7 Write your schema rules and push
Create
notes/04-schemas.md, then commit.# Schemas - Subject and version: ... - Why adding a required field broke compatibility: ... - Why a default made it safe: ... - What the AI suggested for my schema, and what I changed: ...8 Commit and push
Save your work.
git add schemas avro_producer.py notes git commit -m "Add Avro order schema and compatibility checks" git push
You are done when
Schema Registry shows
orders-avro-valueversion 1.An order with a missing field was rejected before it was sent.
The registry rejected a breaking change and accepted the same change with a default.
We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.