1. Introduction
In the previous article Kafka (Part 1) – Introduction we have walked through Kafka’s basic concepts with a sample project to demonstrate topics, message keys, and consumer groups using Spring Cloud Stream.
Within this project, the producer and consumer interact via the “Order” message which contains two fields: id and customerId, and is serialized via JsonSerializer, this approach works well in the scope of our project but in real work there will be many potential scenarios we need to take into account:
- Backward/Forward Compatibility: one day the business asks us to add one more field to the “Order” information such as “customerName“, hence we need to ensure the new version of the Order schema can still read data written with older versions, and the older versions can also read data written with newer versions.
- Data Validation: in case the Order schema is complex, we may need a big effort to handle data validation to prevent corrupted or invalid data.
- Centralized Schema Management: if many services produce/consume Order messages, we will need a centralized repository for managing schemas, which simplifies schema distribution and version control instead of implementing the schema serialization/deserialization and data validation at each service.
Kafka Schema Registry is the solution we need to deal with the above scenario which is a centralized service that manages and enforces data schemas for messages in Apache Kafka. It ensures that data produced to and consumed from Kafka topics adheres to defined schemas, supporting formats like Avro, Protobuf, and JSON Schema (we will use Avro in this topic – the most popular format).

The Schema Registry enables schema evolution with compatibility checks, ensuring that new schema versions are compatible with existing ones, thus maintaining data integrity and preventing corruption. It facilitates efficient serialization and deserialization of messages, making it crucial for applications that require robust data validation and schema management.
2. Avro Schema and Confluent Schema Registry
An Avro schema is a blueprint that defines the structure of data in Apache Avro, a data serialization system. It specifies the fields, their types, and any nesting or complex structures within the data. Avro schemas are written in JSON format and are used for data validation, serialization, and deserialization in Avro-based systems.
In the previous article, we use Order POJO to store Order messages which can be converted to Avro schema as below. In this article, we use gradle-avro-plugin to convert the Order avro file back to Java class.
Order.java
public class Order implements Serializable {
private Integer id;
private Integer customerId;
}
order.avsc
{
"type": "record",
"name": "Order",
"namespace": "com.thoainguyen.kafka.schema",
"fields": [
{
"name": "id",
"type": "int"
},
{
"name": "customerId",
"type": "int"
}
]
}
Confluent Schema Registry developed by Confluent, is one such popular implementation of schema registry used widely with Kafka for managing schemas used in Apache Kafka-based data pipelines. It ensures data compatibility and consistency by storing and validating Avro schemas, enabling versioning and evolution of schemas over time via REST API. For example, we can register Order schema and then retrieve it with REST API calls.
- Register Order subject
curl --location --request POST 'http://localhost:8081/subjects/com.thoainguyen.kafka.schema.Order/versions' \
--header 'Content-Type: application/vnd.schemaregistry.v1+json' \
--data-raw '{
"schema": "{\"type\":\"record\",\"name\":\"Order\",\"namespace\":\"com.thoainguyen.kafka.schema\",\"fields\":[{\"name\":\"id\",\"type\":\"int\"},{\"name\":\"customerId\",\"type\":\"int\"}]}"
}'
- Retrieve Order subject
curl --location --request GET 'http://localhost:8081/subjects/com.thoainguyen.kafka.schema.Order/versions/latest'
3. Demonstration
We will apply Confulence Schema Registry to the Order Management system that we implemented in the Kafka (Part 1) topic containing three services: Checkout Service, Order Service, and Fulfillment Service.

3.1. Build up Conflunce Schema Registry
Add a schema-registry image to the docker-compose file and configure it to communicate with the kafka broker kafka:29092, we also need to expose its 8081 port which will be used by our application to interact with registered schema via REST API.
docker-compose.yml
...
schema-registry:
image: confluentinc/cp-schema-registry:latest
hostname: schema-registry
container_name: schema-registry
depends_on:
- kafka
ports:
- "8081:8081"
environment:
SCHEMA_REGISTRY_HOST_NAME: schema-registry
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'kafka:29092'
SCHEMA_REGISTRY_LISTENERS: http://0.0.0.0:8081
3.2. Define schema
In the previous article, we used customerId as the message key to ensure all events related to the same customer are processed sequentially by assigning them to the same partition, we also need to define a OrderKey schema to store this key beside the Order schema and register it to the Schema Registry:
curl --location --request POST 'http://localhost:8081/subjects/com.thoainguyen.kafka.schema.OrderKey?normalize=false&deleted=false' \
--header 'Content-Type: application/json' \
--data-raw '{"schema":"{\"type\":\"record\",\"name\":\"OrderKey\",\"namespace\":\"com.thoainguyen.kafka.schema\",\"fields\":[{\"name\":\"customerId\",\"type\":\"int\"}]}"}'
Now, we have two registered schemas, we can check them by calling the get subjects API of Confulence Schema Registry:
curl --location --request GET 'http://localhost:8081/subjects'
[
"com.thoainguyen.kafka.schema.Order",
"com.thoainguyen.kafka.schema.OrderKey"
]
3.3. Add needed dependencies to the client application
build.gradle
plugins {
....
id "com.github.davidmc24.gradle.plugin.avro" version "1.9.0" (1)
}
...
dependencies {
...
implementation 'io.confluent:kafka-avro-serializer:7.6.0' (2)
implementation 'org.apache.avro:avro:1.11.0' (3)
}
- A Gradle plugin to allow easy performing Java code generation for Apache Avro
- 3. Kafka Avro Serializer
3.4. Update consumer/producer serde
Our Spring application which is using Spring Cloud to streamline the communication with Kafka need to be updated to integrate with the Schema Registry.
application.yml
...
spring:
cloud:
function:
definition: consumeOrderCreated;consumeOrderProcessed
stream:
kafka:
binder:
brokers: localhost:9092
bindings:
# checkout service to produce orderCreated message
produceOrderCreated-out-0:
producer:
configuration:
key.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer (1)
value.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer (2)
key.subject.name.strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy (3)
value.subject.name.strategy: io.confluent.kafka.serializers.subject.RecordNameStrategy (4)
schema.registry.url: http://localhost:8081 (5)
specific.avro.reader: true (6)
auto.register.schemas: false (7)
....
bindings:
produceOrderCreated-out-0:
destination: orderCreatedTopic
content-type: application/*+avro (8)
producer:
use-native-encoding: true
....
...
- Change key serializer from StringSerializer to KafkaAvroSerializer
- Change value serializer from JsonSerializer to KafkaAvroSerializer
- Determines how to construct the subject name under which the key schema is registered with the Schema Registry for key. Here we use RecordNameStrategy to construct the subject name by namespace + record name.
- It means when publishing an Order message under com.thoainguyen.kafka.schema package, the subject name will be com.thoainguyen.kafka.schema.Order matched with our defined subjects.
- You can learn more about other strategies here
- Same as above but it is for value
- Define Schema Registry URL which is exposed from our Docker container in 3.1
- Tells Schema Registry that we will be using a specific Avro type (Order and OrderKey) otherwise Kafka will expect GenericRecord to be used on the topic
- Disable automatic schema registration, it is false by default which means client applications automatically register new schemas.
- If they produce new messages for a new topic, they will automatically try registering new schemas. This is convenient in development environments, but in production environments, it’s recommended that client applications do not automatically register new schemas
- Tells binding to accept Avro content-type
All consumers and producers now need to use the Order POJO generated from Avro schema instead of defining them in our source code using gradle-avro-plugin. Additionally, the producers will need to wrap the customerId message key to the OrderKey object.
package com.thoainguyen.producer;
import com.thoainguyen.kafka.schema.Order;
import com.thoainguyen.kafka.schema.OrderKey;
import lombok.AllArgsConstructor;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class Producer {
private final StreamBridge streamBridge;
public void produceOrderCreated(Order order) {
OrderKey key = new OrderKey();
key.setCustomerId(order.getCustomerId());
Message<Order> message = MessageBuilder.withPayload(order).setHeader(
KafkaHeaders.MESSAGE_KEY, key).build();
streamBridge.send("produceOrderCreated-out-0",message);
}
public void produceOrderProcessed(Order order) {
OrderKey key = new OrderKey();
key.setCustomerId(order.getCustomerId());
Message<Order> message = MessageBuilder.withPayload(order).setHeader(
KafkaHeaders.MESSAGE_KEY, key).build();
streamBridge.send("produceOrderProcessed-out-0",message);
}
}
3.4. Test
Let start the application and send a request to the create order REST API that we created in the previous article to trigger an Order process.
curl --location --request POST 'localhost:8082/app/order/14?customerId=100'
If you open our applications’s logs you will notice each message in the subscribed topic partitions is consumed by only one consumer successfully as the previous article which does not use Schema Registry.
But if we look at the Kafka UI, we can see the message key and value as a plain text because they were encoded into binary by the Scheme Registry.

4. Conclusion
The Schema Registry is vital for managing and validating data schemas in modern data architectures, especially with platforms like Apache Kafka. It ensures schema compatibility and consistency, enhancing data quality and governance. By enabling schema evolution, centralized management, and interoperability, it simplifies development and integration across systems. Incorporating a Schema Registry improves the reliability, maintainability, and scalability of data pipelines, making it indispensable for handling complex data ecosystems effectively. The source code of this demo project can be found on GitHub.