Hello! In our last lesson, we successfully set up a local Kafka environment with a broker, schema registry, and a UI using Docker Compose. We now have the fundamental infrastructure for building event-driven features.
This lesson focuses on the next critical step: designing the contract for our events. We'll explore why data contracts are essential in distributed systems and then design our very first event schema for the user-registered event using Apache Avro. This schema will act as a guarantee between the service that creates the event (the producer) and any service that listens to it (the consumer).
Why Do We Need an Event Schema?
In our current monolith, all code lives in one place. If you change a data model, the compiler or your IDE often helps you find all the places that need updating. In a distributed system, this safety net disappears.
Imagine our Auth Service sends a UserRegistered event. A separate Notification Service listens for this event to send a welcome email.
- Producer (
Auth Service) sends:{"user_id": "...", "email_address": "..."} - Consumer (
Notification Service) expects:{"userId": "...", "email": "..."}
The consumer will fail to parse the message because the field names don't match. This is a runtime error that can be hard to detect and debug. An event schema solves this by creating a formal, machine-readable contract that both the producer and consumer must adhere to.
MERN-to-Spring Mapping: From Conventions to Contracts
In the MERN world, you might handle this by sharing TypeScript interfaces between services or using a validation library like Zod to define and enforce a shape at the application level. This works, but it's a convention your application code must follow.
Apache Avro combined with a Schema Registry elevates this concept. The schema becomes a first-class citizen enforced by the infrastructure. A producer literally cannot publish a message that violates the schema, and a consumer knows exactly what structure to expect. This provides a much stronger guarantee, especially in a polyglot microservices environment where services might be written in different languages.
To understand this problem and the role of schemas, watch the first few minutes of this video.
Spring Boot | Kafka Schema Registry & Avro with Practical Example and Implementation | #JavaTechie
This video from Java Techie clearly explains the problem that schemas solve in a Kafka ecosystem, particularly when data formats change over time.
Watch from the beginning until 05:28. Pay close attention to the scenario described: what happens when the producer changes the data format? The video then introduces Avro and the Schema Registry as the solution.
Choosing Our Schema Format: Apache Avro
There are several formats for defining schemas, including JSON Schema and Google's Protocol Buffers (Protobuf). For our project, we'll use Apache Avro, which is a de facto standard in the Kafka world.
Here's why Avro is a great fit:
- Rich Data Structures: It supports complex data types.
- Compact Binary Format: Avro serializes data into a very small binary format, which is efficient for network transfer and storage, unlike verbose JSON.
- Schema Evolution: This is Avro's superpower. It has clear rules for how schemas can evolve (e.g., adding or removing fields) while maintaining compatibility between producers and consumers.
- Strongly Typed: When used with Java, Avro schemas can be used to generate Java classes, giving you compile-time type safety.

Designing the UserRegisteredEvent Schema
Let's design the schema for the event that our Auth Service will emit when a new user registers. A good event schema should contain all the information a consumer would need to react to that event, without needing to call back to the originating service.
For a UserRegisteredEvent, a consumer (like a Notification Service or an Analytics Service) would likely need:
- The unique ID of the user.
- The user's email address.
- The timestamp of when the registration occurred.
We'll define this structure in an Avro Schema file, which has an .avsc extension and uses a JSON-like format.
The Avro Schema (.avsc) Definition
Here is the Avro schema for our UserRegisteredEvent.
{
"type": "record",
"namespace": "com.example.blog.events",
"name": "UserRegisteredEvent",
"fields": [
{ "name": "userId", "type": "string" },
{ "name": "email", "type": "string" },
{ "name": "registeredAt", "type": "long", "logicalType": "timestamp-millis" }
]
}
Let's break down this definition:
"type": "record": Defines the schema as a record type, which is like a class or an object."namespace": "com.example.blog.events": This is similar to a package name in Java or a module scope in JavaScript. It prevents naming conflicts. When we generate Java code from this, the classes will be in thecom.example.blog.eventspackage."name": "UserRegisteredEvent": The name of our record, which will become the class name."fields": An array defining the properties of the record.- Each field has a
nameand atype. - We use standard types like
stringandlong. "logicalType": "timestamp-millis"is an Avro annotation that tells tools thelongvalue represents a timestamp in milliseconds since the Unix epoch. This is a language-agnostic and efficient way to handle time.
- Each field has a
The Role of the Schema Registry and Schema Evolution
So, we have a schema file. How do our services actually use it? This is where the Schema Registry comes in.

This process makes the system incredibly robust. If you want to change the event, you don't just change the producer's code. You evolve the schema.
For example, what if we want to add a username to our UserRegisteredEvent? We can't just add the field, as that would break older consumers. Instead, we define it as an optional field with a default value.
Updated UserRegisteredEvent.avsc (v2):
{
"type": "record",
"namespace": "com.example.blog.events",
"name": "UserRegisteredEvent",
"fields": [
{ "name": "userId", "type": "string" },
{ "name": "email", "type": "string" },
{ "name": "username", "type": ["null", "string"], "default": null },
{ "name": "registeredAt", "type": "long", "logicalType": "timestamp-millis" }
]
}
"type": ["null", "string"]"defines a union type, meaning the field can be eithernullor astring."default": nullprovides a default value.
This change is backward compatible. A new producer can send events with the username, and an old consumer that doesn't know about username will simply ignore it. When the Schema Registry receives this new schema, it will store it as version 2 of the UserRegisteredEvent schema.
The following article is a fantastic deep dive into schema-driven development and best practices.
Schema-Driven Messaging with Avro: A Practical Guide for Engineers
The article 'Schema-Driven Messaging with Avro' provides a practical guide on why schemas are critical, how Avro works, and how to manage schema evolution. It reinforces the concepts we've discussed with clear examples.
Please read the following sections: 'Why Schemas Matter', 'What Avro Brings to the Table', 'Baseline Architecture', 'Initial Schema (v1)', 'Creating an Avro Schema File', 'Why You Should Not Generate Schemas from Code', 'How Schema Versions Are Managed', and 'Updated Schema (v2)'. These sections provide a solid foundation in the principles of schema-first design.
Your Task: Create the Event Schema File
Now it's time to apply what you've learned. Your task is to create the Avro schema file for our UserRegisteredEvent.
-
Create the Directory: In the root of your Spring Boot project, create the following directory structure:
src/main/avro. This is the conventional location for Avro schema files in a Maven project. -
Create the Schema File: Inside the
avrodirectory, create a new file namedUserRegisteredEvent.avsc. -
Add the Schema Content: Copy the following JSON content into your
UserRegisteredEvent.avscfile. We will start with the simpler, initial version of the schema.{ "type": "record", "namespace": "com.example.blog.events", "name": "UserRegisteredEvent", "fields": [ { "name": "userId", "type": "string" }, { "name": "email", "type": "string" }, { "name": "registeredAt", "type": "long", "logicalType": "timestamp-millis" } ] }
Runtime Observation & Debugging Task
Let's interact with the Schema Registry we set up in the last lesson to see it in action. We can manually register our new schema using a curl command.
-
Make sure your Docker Compose stack (Kafka, Schema Registry) is running.
-
Open a terminal and execute the following
curlcommand. This command sends your schema to the registry's REST API.- The subject name
user-registered-events-valueis a convention. Kafka topics often have a schema for their key and their value. We are defining the schema for thevalueof messages in a futureuser-registered-eventstopic.
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \ --data '{ "schema": "{\\"type\\":\\"record\\",\\"name\\":\\"UserRegisteredEvent\\",\\"namespace\\":\\"com.example.blog.events\\",\\"fields\\":[{\\"name\\":\\"userId\\",\\"type\\":\\"string\\"},{\\"name\\":\\"email\\",\\"type\\":\\"string\\"},{\\"name\\":\\"registeredAt\\",\\"type\\":\\"long\\",\\"logicalType\\":\\"timestamp-millis\\"}]}" }' \ http://localhost:8081/subjects/user-registered-events-value/versionsNote: The schema string is escaped for the JSON payload.
- The subject name
-
Observe the Output: The Schema Registry should respond with a JSON object containing a unique ID for this schema, like
{"id":1}. This confirms your schema has been successfully registered as version 1 for this subject. -
Verify: You can now fetch the schema you just registered by its ID:
curl http://localhost:8081/schemas/ids/1This should return the schema you just posted.
This exercise gives you a direct, hands-on feel for the Schema Registry's role as a database for your data contracts.
Conclusion
In this lesson, you've learned one of the most important concepts in building robust, event-driven systems: schema-based data contracts.
Key Takeaways:
- Event schemas act as a formal contract between producers and consumers, preventing data compatibility issues in a distributed architecture.
- Apache Avro is a powerful tool for defining schemas, offering a compact binary format and excellent support for schema evolution.
- The Schema Registry is the central authority that stores, versions, and validates these schemas at runtime.
- Schema evolution, when done correctly with rules like backward compatibility, allows services to be updated independently without breaking the system.
Preview of the Next Lesson:
Now that we have designed our event's contract, the next step is to put it to use. In the next lesson, you will implement a Kafka producer in the Auth service to publish an event upon successful user registration. We will configure our project to automatically generate Java classes from our .avsc file and use Spring Kafka to send a strongly-typed UserRegisteredEvent to our Kafka topic.