Learn Apache Kafka Β· 6/12

Schema Management with Confluent Schema Registry

6 min read

πŸ‘‹ Introduction

Welcome to the Schema Management module. In previous sections, we treated Kafka messages as opaque byte arrays. We sent strings, integers, or raw JSON, trusting that the consumer knew how to interpret them.

In a production environment, "trust" is not an engineering strategy.

As systems scale, producers and consumers evolve independently. If a producer changes the data format (e.g., renaming a field from userId to user_id) without informing the consumer, the consumer application will likely crash. This is known as a poison pillβ€”a message that breaks the consumer.

This guide explores Confluent Schema Registry, a standalone server process that sits outside your Kafka brokers. It enforces data governance, ensuring that the data entered into the topic adheres to a specific structure (schema).


1. The Data Contract: Why Stream Processing Needs Schemas πŸ“œ

Definition

A Schema is a structural definition of data. It defines field names, data types (string, int, boolean), and rules (nullable, default values).
A Data Contract is the agreement between producers and consumers that the data flowing through the system will adhere to a specific schema.

The Problem: The "Wild West" of Serialization

Without a schema registry, Kafka is agnostic to your data types. It takes bytes and stores bytes.

  1. Implicit Coupling: The consumer must "guess" or hardcode the structure of the data it receives.
  2. Fragility: If a developer adds a field to the producer but forgets to update the consumer, deserialization errors occur.
  3. Data Quality: There is no validation. You could accidentally send a string "hello" into a field meant for a timestamp.

The Solution: Explicit Governance

Confluent Schema Registry solves this by acting as a central authority.

  • Producer Validation: Before sending a message, the Producer talks to the Registry. "does this data match the registered schema?"
  • Consumer Clarity: The Consumer asks the Registry, "How do I read this message?"
  • Central Storage: Schemas are stored in the Registry, not pasted into every source code file.

2. Data Formats: Avro, Protobuf, and JSON Serialization πŸ“¦

While you can use raw JSON with Kafka, it is inefficient and lacks strict type safety. The industry standard involves binary serialization formats.

Apache Avro ( The Industry Standard)

Avro is a binary serialization format. It relies on a schema (defined in JSON) to interpret binary data.

  • Pros: extremely compact (field names are not sent with every message, only values), rich ecosystem, excellent splitability.
  • Cons: Not human-readable without tools.

Example Avro Schema (User.avsc):

json
{
  "type": "record",
  "namespace": "com.freecodecamp.kafka",
  "name": "User",
  "fields": [
    { "name": "id", "type": "int" },
    { "name": "username", "type": "string" },
    { "name": "signup_ts", "type": "long" }
  ]
}

Protocol Buffers (Protobuf)

Developed by Google.

  • Pros: Highly optimized, strongly typed, code generation is excellent for many languages.
  • Cons: Historically less integrated with Hadoop ecosystems than Avro (though this gap is closing).

JSON Schema

  • Pros: Human readable, widely understood.
  • Cons: Verbose. You send field names {"id": 1} repeatedly, wasting bandwidth.

🧠 Interesting Fact

In high-throughput systems, switching from text-based JSON to binary Avro can reduce network bandwidth and storage usage by 30% to 50%. When you are processing petabytes of data, this change alone can save millions of dollars in infrastructure costs.


3. Schema Registry Setup and Client Integration βš™οΈ

We will set up a local Schema Registry using Docker. This is the standard way to run the Confluent stack locally.

Step 1: The Infrastructure (Docker Compose)

Create a docker-compose.yml. You need a Zookeeper, a Kafka Broker, and the Schema Registry.

yaml
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181

  broker:
    image: confluentinc/cp-kafka:7.5.0
    depends_on: [zookeeper]
    ports: [ "9092:9092" ]
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

  schema-registry:
    image: confluentinc/cp-schema-registry:7.5.0
    depends_on: [broker]
    ports: [ "8081:8081" ]
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'broker:29092'

Run docker-compose up -d. The Registry is now listening on port 8081.

Step 2: Client Integration (Java)

To use the Registry, we replace the standard String serializer with KafkaAvroSerializer.

Dependencies (Maven):
You need the Confluent serializer libraries.

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

Producer Configuration:

java
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

// 1. Point to Schema Registry
props.put("schema.registry.url", "http://localhost:8081");

// 2. Use the Avro Serializer for the value
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);

KafkaProducer<String, User> producer = new KafkaProducer<>(props);

// When you send this, the Serializer automatically registers the schema
// and sends the ID with the message.
User user = new User(1, "Camper", System.currentTimeMillis());
producer.send(new ProducerRecord<>("users", user.getUsername(), user));

The Wire Protocol (What actually travels over the network)

When KafkaAvroSerializer sends data, it modifies the payload. It does not just send the Avro bytes. It sends:

Byte Index Description
0 Magic Byte (Always 0, indicates this is a Confluent serialization)
1-4 Schema ID (4-byte integer referencing the ID in Registry)
5+ Data (The actual Avro serialized binary)

This allows the Consumer to read bytes 1-4, look up the schema ID in its local cache (or fetch from Registry), and then deserialize the rest of the data.


4. Schema Evolution: Upgrading Data Models Safely 🧬

Data models change. Business requirements evolve. You might need to add a "email" field to the User object. This is called Schema Evolution.

The Schema Registry enforces Compatibility Types to ensure changes don't break consumers.

Backward Compatibility (Default)

Definition: A new schema is backward compatible if it can be used to read data written with the previous schema.

  • Use Case: You update the Consumer first, then the Producer.
  • Rule: If you add a field, it must have a default value.
  • Why? The Consumer (using the new schema) reads an old message (missing the new field). It uses the default value to fill in the gap.

Example Change:

json
// Old
{ "name": "username", "type": "string" }

// New (Valid Backward Compatible)
{ "name": "username", "type": "string" },
{ "name": "email", "type": "string", "default": "[email protected]" }

Forward Compatibility

Definition: Data written with a new schema can be read by a consumer using the old schema.

  • Use Case: You update the Producer first.
  • Rule: You can add fields, but you cannot delete required fields. The old consumer simply ignores the new fields it doesn't recognize.

Full Compatibility

Definition: Backward + Forward. Old consumers can read new data, and new consumers can read old data.

  • Use Case: Maximum safety during rolling upgrades of complex microservices.

πŸ§ͺ Industry Practice

In production, you should set the compatibility level to BACKWARD or FULL. You can verify compatibility via the CLI before deploying code:

bash
# Check if a new schema is compatible with the latest version in the registry
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  --data '{"schema": "{\"type\": \"string\"}"}' \
  http://localhost:8081/compatibility/subjects/my-topic-value/versions/latest

πŸ“ Summary

  1. Contracts: Don't guess your data structure. Define it.
  2. Registry: Use Confluent Schema Registry as the source of truth.
  3. Formats: Use Avro or Protobuf for performance; avoid raw JSON in high-throughput topics.
  4. Evolution: Always provide default values for new fields to maintain Backward Compatibility.

πŸ“š Further Reading & References

Challenge

You are responsible for managing the Avro schema for a UserProfile entity in a Kafka-based system. The system's schema compatibility is set to BACKWARD.

Part 1: Initial Schema

Define the initial Avro schema for a UserProfile. The schema should be a record with the following details:

  • A namespace of com.example.users.
  • A name of UserProfile.
  • Three fields:
    1. userId: a universally unique identifier, which should be of type string.
    2. username: the user's chosen name, also a string.
    3. signupTimestamp: the Unix epoch timestamp (milliseconds) of when the user signed up, which should be of type long.

Part 2: Schema Evolution

Business requirements have changed. You need to evolve the schema.

  • Add a new field to store the user's email address, called email. This field is optional.
  • The signupTimestamp field is no longer needed and should be removed.

Modify the schema from Part 1 to reflect these changes while ensuring it remains BACKWARD compatible. Place your final evolved schema in the designated section.

Expected result

The output should be a single JSON object containing two keys: "Part 1: Initial UserProfile Schema" and "Part 2: Backward Compatible Evolved Schema".

For Part 1, the value should be a valid Avro schema object with:

  • namespace set to "com.example.users".
  • name set to "UserProfile".
  • The fields array should contain three objects, one for userId (type: "string"), one for username (type: "string"), and one for signupTimestamp (type: "long").

For Part 2, the value should be the evolved Avro schema:

  • It should retain the userId and username fields from the original schema.
  • The signupTimestamp field should be removed.
  • A new field email must be added. To maintain BACKWARD compatibility when adding a new field, it must have a default value. The type should be a union that includes "null", and the default value should be null. For example: {"name": "email", "type": ["null", "string"], "default": null}.
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.