Data Mesh: Streaming Data Products, Schemas, Event Contracts, and AsyncAPI for Reliable Architectures
Learn how to design, validate, and evolve Streaming Data Products in a Data Mesh using event contracts, JSON Schema, Apache Avro, Schema Registry, and AsyncAPI 3.0 without breaking consumer domains.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
When a Valid Broker Event Breaks Three Consumer Domains
On a Thursday afternoon, the Sales domain at CommerceFlow deploys a minor update to its order microservice to support multi-currency promotions. The team modifies the translator publishing to the sales.order-events topic of the sales-order-events streaming product: the total_amount field, previously emitted as a decimal number (149.90), is now serialized as a nested object {"amount": "149.90", "scale": 2}, and the status CONFIRMED changes to ORDER_CONFIRMED to follow a new internal naming convention. Furthermore, because promotional discounts are now subtracted before emitting the event, total_amount silently shifts from representing the gross amount to the net amount while keeping the exact same attribute name.
From Apache Kafka's perspective, nothing goes wrong: the broker accepts the bytes, preserves partition ordering by order_id, and delivers every record within milliseconds. Yet within ten minutes, three simultaneous incidents erupt across downstream domains:
Payments suffers deserialization exceptions when trying to cast total_amount into a Decimal inside its real-time reconciliation engine (paid-sales-live).
Inventory processes messages without throwing technical errors, but silently ignores every confirmation because its filter checks for event_type == "OrderConfirmed" while the producer started emitting "OrderConfirmedV2" unannounced.
Finance ingests a hotfix that temporarily restores the numeric type, but miscalculates tax liabilities because the accounting meaning of total_amount changed from gross to net while keeping the same field name and data type.
The failure was neither in the streaming infrastructure nor in Change Data Capture (CDC), but in the absence of a formal cross-domain boundary: publishing bytes to a topic is not the same as offering a reliable Streaming Data Product. For an event stream to be consumable as a product, the owning domain must establish explicit event contracts, typed schemas with verifiable compatibility rules, and an asynchronous interface specification documenting how to connect, what guarantees to expect, and how to evolve without breaking consumers.
Six Distinct Concepts Often Confused in Event-Driven Architectures
When teams design asynchronous integrations, they frequently treat terms operating at different architectural layers as synonyms. Distinguishing them precisely prevents assuming that a single tool solves responsibilities outside its scope:
Concept
What It Really Is
What Problem It Solves
What It Does NOT Solve Alone
Technical Event / Internal Change
Raw record of a local state mutation (e.g., a database binlog row or an internal persistence event).
Capturing mutations inside the source database or microservice.
Does not express stable business language or hide internal storage details.
Integration Event (Domain Event)
Immutable business fact deliberately published for other domains (OrderConfirmed).
Communicating what happened in the domain with stable meaning for external consumers.
Does not define by itself how bytes are encoded or validated in a pipeline.
Serialized Message
Physical byte representation (UTF-8 JSON, Avro binary, or Protobuf) along with transport headers and key.
Transmitting the event across the network and storing it in broker partitions.
Does not document semantic rules or ownership if the content changes.
Data Schema
Formal definition of payload structure, data types, syntactic constraints, and default values (JSON Schema, Avro, Protobuf).
Validating that a message matches an expected structure and enabling safe serialization/deserialization.
Does not describe topics, servers, protocols, owners, SLAs, or accounting meaning changes.
Async Interface Specification (AsyncAPI)
Machine-readable standard document describing servers, channels, operations (send/receive), headers, and schema references.
Discovering how to connect to the stream, which messages travel on each channel, and generating docs or client code.
Does not store historical schema versions at runtime, nor create Kafka topics or permissions.
Event Contract
Comprehensive data product agreement: unites interface (AsyncAPI), schemas (Avro/JSON Schema), semantic invariants, security classification, owner, evolution policy, and operational expectations.
Guaranteeing autonomy between producer and consumer domains through rules verifiable in CI/CD.
Does not replace producer unit tests or runtime observability.
Anatomy of a Domain Event and Producer Responsibilities
At CommerceFlow, the Sales domain owns the sales-order-events Streaming Data Product. It publishes three integration event types on the logical channel sales.order-events: OrderCreated, OrderConfirmed, and OrderCancelled.
A common mistake is mixing business attributes with transport details or envelope auditing in a single flat structure. A clean architecture separates three layers:
Transport Metadata (Kafka Record Headers / Key / Offset): belongs to the broker and messaging protocol. Includes the partitioning key (record_key = "ORD-90412"), assigned partition, offset, broker ingestion timestamp, and technical headers like traceparent for distributed tracing.
Event Envelope Metadata: uniquely identifies the published fact regardless of transport. If the event moves from Kafka to Amazon S3 or another message bus, this metadata travels with it:
event_id: globally unique identifier (UUIDv4 or UUIDv7) used by consumers to guarantee idempotency.
event_type: explicit name of the domain fact (OrderConfirmed).
event_version vs. schema_version: semantic version of the event or the schema revision used to emit it.
occurred_at: exact instant when the fact happened in the domain (Event Time in UTC ISO 8601 format), distinct from when the broker received it.
producer: identifier of the emitting component or product (urn:commerceflow:sales:sales-order-events).
Business Payload (data): contains the domain facts (order_id, customer_id, total_amount, currency, confirmed_at, items_count).
Three Versions You Must Never Confuse
When evolving a real-time data product, three version numbers coexist with different lifecycles:
Streaming Data Product Version (product_version, e.g., 2.1.0): encompasses the entire product in the catalog (available channels, retention policies, SLOs, and supported event set).
Major Event Type Version (event_type / channel, e.g., OrderConfirmed v1 vs. v2): changes only when business meaning or structure breaks incompatibly and requires parallel event coexistence.
Schema Revision (schema_version / schema_id in Schema Registry, e.g., revision 1, 2, 3): every compatible adjustment (such as adding an optional discount_code field) increments the schema revision in the registry without changing the event type or breaking the product.
Architectural Note: Topic naming conventions (sales.order-events.v1 vs. sales.orders), partition key strategies, and whether to embed version numbers in channel names are architectural decisions made by each organization, not universal standards. What matters in a Data Mesh is declaring that decision at the platform level and applying it consistently across domains.
The Comprehensive Contract for the sales-order-events Streaming Data Product
Before writing a serialization schema or an AsyncAPI file, the Sales domain defines the data product contract. This manifest connects federated governance, catalog metadata, data classification, and semantic guarantees:
# contracts/sales-order-events.contract.yamlapiVersion:datamesh.commerceflow.io/v1kind:StreamingDataContractmetadata:id:urn:commerceflow:sales:contract:sales-order-eventsproductVersion:1.2.0domain:salesownerTeam:sales-platform-team@commerceflow.examplestatus:activechannel:logicalName:sales.order-eventstopicName:sales.order-events.v1partitionKey:order_idorderingGuarantee:per-partition-by-order-iddeliverySemantics:at-least-onceevents:-eventType:OrderCreateddescription:Emittedwhenabuyerplacesanorderpendingpayment.schemaSubject:sales.order-events.v1-OrderCreatedcompatibilityPolicy:BACKWARD_TRANSITIVE-eventType:OrderConfirmeddescription:Emittedwhentheorderiscommerciallyconfirmedwithitsfinalgrossamount.schemaSubject:sales.order-events.v1-OrderConfirmedcompatibilityPolicy:FULL_TRANSITIVE-eventType:OrderCancelleddescription:Emittedwhentheorderiscancelledpriortofulfillment.schemaSubject:sales.order-events.v1-OrderCancelledcompatibilityPolicy:BACKWARD_TRANSITIVEsemanticInvariants:-field:data.total_amountrule:>
Always represents the confirmed GROSS order amount (taxes included, promotional
discounts already applied to list price), expressed in the currency indicated by
data.currency with two exact decimal places. Must never be <= 0 in OrderConfirmed.
-field:occurred_atrule:>
UTC timestamp of the transactional commit in the Sales domain. Must never use
the connector publication time or broker ingestion time.
securityAndPrivacy:dataClassification:INTERNAL_CONFIDENTIALpiiFields:-path:data.customer_idclassification:PSEUDONYMIZED_IDENTIFIERpolicy:MaskortokenizeforanalyticalconsumersoutsideSales,Payments,andFinance.accessControl:producersAllowed:-principal:arn:aws:iam::111122223333:role/sales-outbox-publisherconsumersSubscribed:-domain:paymentsproductOrService:paid-sales-liveprincipal:arn:aws:iam::111122223333:role/payments-stream-consumer-domain:inventoryproductOrService:stock-reservation-workerprincipal:arn:aws:iam::111122223333:role/inventory-stream-consumerdeprecationPolicy:noticePeriodDays:60dualPublishingRequired:true
Notice what this contract provides beyond a bare schema file: it declares who owns the stream, which consumers depend on it (direct input for data lineage), which fields hold sensitive data, which key guarantees per-order sequencing, and above all, the semantic invariant of total_amount.
Schema Definition and Serialization Formats: JSON Schema, Apache Avro, and Protocol Buffers
A contract must translate into executable schemas that validate each event's structure. However, JSON Schema, Apache Avro, and Protocol Buffers (Protobuf) do not perform the exact same job:
JSON Schema is a declarative vocabulary for validating JSON documents. The message travels as human-readable UTF-8 JSON text; the schema is not used to pack the bytes, but to verify that the document obeys types, formats, regular expressions, and required properties.
Apache Avro is both a schema definition language and a compact binary serialization format. Field names are not repeated inside every binary message; therefore, to deserialize an Avro message, the consumer must know both the exact schema used to write it (writer schema) and the schema it expects to read (reader schema).
Protocol Buffers (Protobuf) is an interface definition language (.proto) and a binary serialization mechanism based on numeric field tags. Instead of identifying attributes by name on the wire, Protobuf encodes the tag number (1, 2, 3) alongside the wire type.
Let's examine how the same OrderConfirmed event is modeled across all three formats and the technical implications of each choice.
1. JSON Schema for OrderConfirmed
{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://schemas.commerceflow.example/sales/order-confirmed-v1.schema.json","title":"OrderConfirmedEvent","description":"Schema for the OrderConfirmed event in the sales-order-events product","type":"object","additionalProperties":false,"required":["event_id","event_type","schema_version","occurred_at","data"],"properties":{"event_id":{"type":"string","format":"uuid","description":"Globally unique event identifier for idempotency."},"event_type":{"type":"string","const":"OrderConfirmed"},"schema_version":{"type":"integer","minimum":1},"occurred_at":{"type":"string","format":"date-time","description":"ISO 8601 UTC timestamp of the business fact in the Sales domain."},"data":{"type":"object","additionalProperties":false,"required":["order_id","customer_id","total_amount","currency"],"properties":{"order_id":{"type":"string","pattern":"^ORD-[0-9]{5,10}$"},"customer_id":{"type":"string","pattern":"^CUST-[0-9]{4,10}$"},"total_amount":{"type":"number","exclusiveMinimum":0,"multipleOf":0.01,"description":"Confirmed gross amount in the specified currency."},"currency":{"type":"string","enum":["USD","EUR","MXN","COP","CLP"]},"sales_channel":{"type":"string","enum":["WEB","MOBILE_APP","PARTNER_API"],"default":"WEB"}}}}}
Key strength: Immediately readable and expressive for validation constraints (pattern, exclusiveMinimum, additionalProperties: false).
Evolution caveat: Setting "additionalProperties": false catches producer typos, but if a producer adds a new field in a later revision and a consumer validates against the older closed schema, validation will fail (breaking forward compatibility).
2. Equivalent Apache Avro Schema (.avsc)
{"type":"record","name":"OrderConfirmedEvent","namespace":"io.commerceflow.sales.events","doc":"Event emitted by the Sales domain when an order is confirmed.","fields":[{"name":"event_id","type":"string","doc":"Event UUID for deduplication."},{"name":"event_type","type":{"type":"enum","name":"OrderConfirmedType","symbols":["OrderConfirmed"]}},{"name":"schema_version","type":"int","default":1},{"name":"occurred_at","type":{"type":"long","logicalType":"timestamp-millis"},"doc":"UTC epoch in milliseconds when the order was confirmed."},{"name":"order_id","type":"string"},{"name":"customer_id","type":"string"},{"name":"total_amount_cents","type":"long","doc":"Confirmed gross amount in cents to avoid floating-point precision loss."},{"name":"currency","type":"string"},{"name":"sales_channel","type":["null","string"],"default":null,"doc":"Optional sales channel; union with null and default null for compatible evolution."}]}
Fundamental differences between Avro and JSON Schema:
Writer vs. Reader Resolution: Avro resolves differences between the schema used to write the binary payload and the consumer's reader schema at deserialization time.
Explicit Unions for Nullability: In Avro, an optional field is not simply omitted from a required list; it is modeled as a union ["null", "string"], and the first branch of the union must match the type of "default": null.
Mandatory Defaults for Compatibility: If you add a field in revision v2 without "default", a consumer upgraded to v2 will not know what value to assign when reading older events written with v1 (breaking backward compatibility).
3. Protocol Buffers (.proto) for Comparison
syntax = "proto3";
package commerceflow.sales.v1;
// Representation of OrderConfirmed using immutable numeric field tags.
message OrderConfirmedEvent {
string event_id = 1;
string event_type = 2;
int32 schema_version = 3;
int64 occurred_at_epoch_ms = 4;
string order_id = 5;
string customer_id = 6;
int64 total_amount_cents = 7;
string currency = 8;
string sales_channel = 9;
// When removing a field in the future, reserve both its tag number and name
// so no developer accidentally reuses the tag for another attribute.
reserved 10;
reserved "legacy_promo_flag";
}
Why the difference matters: In Protobuf, wire identity is not the name total_amount_cents, but the tag = 7. Renaming the field in .proto does not alter binary encoding (though it affects generated code or JSON mapping), whereas reusing tag 7 with a different type silently corrupts deserialization.
Schema Registry and Compatibility Policies
A Schema Registry (such as Confluent Schema Registry, Apicurio Registry, or AWS Glue Schema Registry) is a centralized service provided by the Self-Serve Data Platform where domains register and version their schemas under a logical identifier called a Subject (for instance, sales.order-events.v1-OrderConfirmed).
How Producers, Consumers, and the Registry Interact
[Sales CI/CD Pipeline]
|
| 1. Checks compatibility (POST /compatibility/subjects/.../versions)
| 2. If approved, registers new version and receives schema_id = 42
v
+---------------------------------------------------+
| SCHEMA REGISTRY |
| Subject: sales.order-events.v1-OrderConfirmed |
| v1 (id: 38) -> v2 (id: 42, FULL_TRANSITIVE) |
+---------------------------------------------------+
^ ^
| 3. Fetches/caches schema_id = 42 | 5. Reads schema_id = 42 from message
| | prefix and fetches writer schema
[Sales Producer] ========================> [Payments Consumer]
4. Publishes to Kafka:
[Magic Byte + ID 42 + Binary Payload]
The workflow operates in five clear steps:
Pre-deployment Check in CI/CD: Before deploying producer code, the pipeline submits the proposed schema to the Schema Registry to verify that it satisfies the subject's compatibility policy.
Registration and Immutable ID: If compatible, the registry stores the new version and assigns an immutable global schema_id.
Producer Serialization: The producer does not embed the full schema text inside every Kafka event; it queries its local cache (backed by the Schema Registry) and prepends a compact header containing the schema_id (e.g., 5 bytes: 1 magic byte + 4-byte ID) to the serialized payload.
Lightweight Kafka Transport: The broker stores the compact message.
Consumer Deserialization: When Payments reads the message, it extracts the schema_id, retrieves the writer schema from the registry (via local cache), and projects the record into its own reader schema.
Critical Boundary to Remember: A Schema Registry is neither a complete governance engine nor a business rule validator. The registry checks structural and type compatibility across schema revisions, but it cannot prevent a producer from emitting a negative total_amount_cents, changing the accounting meaning of an amount, or misinterpreting a currency code. Nor does it guarantee which code version is running in production containers if a team deploys an outdated consumer outside the validated workflow.
Compatibility Policies: Backward, Forward, Full, and Transitivity
Compatibility is always defined by the relationship between the writer schema and the reader schema, and dictates the required upgrade order for producers and consumers:
Policy
What It Guarantees
Mandatory Deployment Order
Transitive Variants (_TRANSITIVE)
BACKWARD
Consumers upgraded to the new schema (vN) can read messages written with the immediately preceding schema (vN-1). Essential for replaying historical events in Kafka or S3.
Upgrade all consumers first, then upgrade the producer.
BACKWARD_TRANSITIVE requires the consumer on vN to read all prior versions (v1, v2, ..., vN-1), not just the latest.
FORWARD
Consumers still running the older schema (vN-1) can continue reading messages produced with the new schema (vN).
Upgrade the producer first, and consumers can migrate gradually afterward.
FORWARD_TRANSITIVE requires every older consumer (v1...vN-1) to read messages produced with vN.
FULL
Combines both guarantees: new consumers read old data and old consumers read new data.
Independent deployments: producers and consumers can upgrade in any order.
FULL_TRANSITIVE enforces bidirectional compatibility across the entire version history of the subject.
In a Data Mesh where multiple domains consume the same topic on independent release schedules and may rewind offsets to reprocess historical events, FULL_TRANSITIVE (or at minimum BACKWARD_TRANSITIVE when consumer rollouts are coordinated) is the safest policy for core events like OrderConfirmed.
Schema Change Matrix and Real Impact
Simply memorizing "adding a field is compatible" is insufficient. Compatibility depends on the format, default values, and closure rules:
Proposed Schema Change
In Avro (with default on affected field)
In JSON Schema
Technical Impact and Explanation
Add an optional field with default
FULL compatible (BACKWARD + FORWARD).
Compatible if additionalProperties is true. FORWARD Incompatible if the old reader has additionalProperties: false.
In Avro, the new reader uses default when reading old messages, and the old reader ignores the unknown field when reading new messages.
Add a required field (no default)
BACKWARD Incompatible (is FORWARD).
BACKWARD Incompatible.
A consumer upgraded to the new schema will fail when reprocessing historical topic events that lack that attribute.
Remove a field that had a default
FULL compatible.
Compatible if it was optional.
The old reader falls back to its default value when the new producer stops sending the field.
Remove a required field (no default)
FORWARD Incompatible (is BACKWARD).
FORWARD Incompatible.
Existing consumers expecting that field will fail as soon as the producer stops emitting it.
Rename a field
Incompatible (unless explicit aliases are declared in Avro).
Incompatible.
To the serializer, renaming is equivalent to deleting the original field and adding an unrelated new one.
Change a field's data type (e.g., string to int, or number to object)
Incompatible (except native promotions like int -> long in Avro).
Incompatible.
Directly breaks deserialization in existing consumers.
Add a symbol to an enum
BACKWARD compatible, FORWARD Incompatible (unless an enum default is defined in Avro 1.9+).
BACKWARD compatible, FORWARD Incompatible.
If the producer emits an enum symbol missing from the older consumer's closed list, the consumer rejects the message.
Change business meaning while keeping field name and type
Schema Registry marks it technically compatible, but it is a severe semantic breaking change.
Technically valid, semantically incompatible.
Changing total_amount from gross to net or from cents to whole units corrupts financial calculations without raising parse errors.
Asynchronous Interface Specification with AsyncAPI 3.0
While Avro or JSON Schema describes the internal structure of a message, AsyncAPI describes the streaming product interface: which servers host it, which channels exist, which operations are exposed, and which messages and headers flow through each channel.
Important Note on Versions: In AsyncAPI 3.0, channels (channels) are decoupled from operations (operations). Unlike AsyncAPI 2.x (which placed publish and subscribe directly inside the channel with often confusing semantics), AsyncAPI 3.0 uses action: send or action: receive inside the operations block and explicitly references the target channel and messages. Also remember that AsyncAPI is a descriptive specification: it does not create Kafka topics, manage IAM permissions, or replace Schema Registry at runtime.
Below is the AsyncAPI 3.0.0 specification for the sales-order-events product, documenting its three events (OrderCreated, OrderConfirmed, and OrderCancelled) and detailing the OrderConfirmed structure:
asyncapi:3.0.0id:'urn:commerceflow:sales:streaming-product:sales-order-events'info:title:CommerceFlowSalesOrderEventsStreamingDataProductversion:1.2.0description:>
Official integration event stream of the Sales domain. Publishes the lifecycle
of created, confirmed, and cancelled orders for cross-domain consumption.
contact:name:SalesPlatformTeamemail:sales-platform-team@commerceflow.exampletags:-name:data-mesh-name:domain-salesservers:productionKafka:host:'msk-prod.commerceflow.internal:9098'protocol:kafka-securedescription:ProductionAmazonMSKclusterwithIAMauthentication.channels:salesOrderEventsChannel:address:sales.order-events.v1description:>
Channel partitioned by order_id. Guarantees strict event ordering
within the lifecycle of the same order.
bindings:kafka:topic:sales.order-events.v1partitions:12replicas:3messages:orderCreatedMessage:$ref:'#/components/messages/OrderCreated'orderConfirmedMessage:$ref:'#/components/messages/OrderConfirmed'orderCancelledMessage:$ref:'#/components/messages/OrderCancelled'operations:publishOrderLifecycleEvents:action:sendchannel:$ref:'#/channels/salesOrderEventsChannel'summary:TheSalesdomainemitsorderlifecycleevents.messages:-$ref:'#/channels/salesOrderEventsChannel/messages/orderCreatedMessage'-$ref:'#/channels/salesOrderEventsChannel/messages/orderConfirmedMessage'-$ref:'#/channels/salesOrderEventsChannel/messages/orderCancelledMessage'consumeOrderConfirmedEvents:action:receivechannel:$ref:'#/channels/salesOrderEventsChannel'summary:Consumerdomains(Payments,Inventory)receiveorderconfirmations.messages:-$ref:'#/channels/salesOrderEventsChannel/messages/orderConfirmedMessage'components:messages:OrderCreated:name:OrderCreatedtitle:OrderCreatedcontentType:application/jsonsummary:Emittedwhenanorderpendingpaymentisregistered.payload:type:objectrequired: [event_id, event_type, schema_version, occurred_at, data]
properties:event_id:type:stringformat:uuidevent_type:type:stringconst:OrderCreatedschema_version:type:integerminimum:1occurred_at:type:stringformat:date-timedata:type:objectrequired: [order_id, customer_id, currency]
properties:order_id:type:stringcustomer_id:type:stringcurrency:type:stringOrderConfirmed:name:OrderConfirmedtitle:CommerciallyConfirmedOrdercontentType:application/jsonsummary:Emittedwhentheorderisconfirmedwithitsfinalgrossamount.headers:type:objectrequired: [ce_id, ce_type, ce_source, partition_key]
properties:ce_id:type:stringdescription:Mirrorofevent_idinKafkaheadersforfastfiltering.ce_type:type:stringconst:OrderConfirmedce_source:type:stringconst:urn:commerceflow:sales:sales-order-eventspartition_key:type:stringdescription:Mandatorypartitioningkeyequaltodata.order_id.payload:$ref:'#/components/schemas/OrderConfirmedPayload'OrderCancelled:name:OrderCancelledtitle:OrderCancelledcontentType:application/jsonsummary:Emittedwhenanorderisvoidedpriortoshipment.payload:type:objectrequired: [event_id, event_type, schema_version, occurred_at, data]
properties:event_id:type:stringformat:uuidevent_type:type:stringconst:OrderCancelledschema_version:type:integerminimum:1occurred_at:type:stringformat:date-timedata:type:objectrequired: [order_id, cancellation_reason]
properties:order_id:type:stringcancellation_reason:type:stringschemas:OrderConfirmedPayload:type:objectadditionalProperties:falserequired:-event_id-event_type-schema_version-occurred_at-dataproperties:event_id:type:stringformat:uuidevent_type:type:stringconst:OrderConfirmedschema_version:type:integerminimum:1occurred_at:type:stringformat:date-timedata:type:objectadditionalProperties:falserequired:-order_id-customer_id-total_amount-currencyproperties:order_id:type:stringpattern:'^ORD-[0-9]{5,10}$'customer_id:type:stringpattern:'^CUST-[0-9]{4,10}$'total_amount:type:numberexclusiveMinimum:0currency:type:stringenum: [USD, EUR, MXN, COP, CLP]
sales_channel:type:stringenum: [WEB, MOBILE_APP, PARTNER_API]
default:WEB
Practical Implementation in Python: Contract Validation and Compatibility Checker
So that the contract does not remain a passive document, the Sales domain pipeline executes automated checks before allowing any schema or event publisher change.
The following Python script is self-contained and verifiable. It uses the Python standard library along with jsonschema (pip install jsonschema) to accomplish three tasks:
Validate valid and invalid OrderConfirmed events against the JSON Schema (Draft202012Validator with format checking enabled).
Programmatically evaluate whether a new Avro-style schema revision breaks or respects BACKWARD, FORWARD, and FULL compatibility.
Verify semantic contract invariants (such as matching the Kafka partition key against data.order_id).
# file: verify_event_contracts.py# Requirements: Python 3.10+ and jsonschema library (`pip install jsonschema`)from __future__ import annotations
from dataclasses import dataclass
from typing importAnyfrom jsonschema import Draft202012Validator, FormatChecker
# 1. OrderConfirmed JSON Schema definition (v1)
ORDER_CONFIRMED_JSON_SCHEMA: dict[str, Any] = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"additionalProperties": False,
"required": ["event_id", "event_type", "schema_version", "occurred_at", "data"],
"properties": {
"event_id": {"type": "string", "format": "uuid"},
"event_type": {"type": "string", "const": "OrderConfirmed"},
"schema_version": {"type": "integer", "minimum": 1},
"occurred_at": {"type": "string", "format": "date-time"},
"data": {
"type": "object",
"additionalProperties": False,
"required": ["order_id", "customer_id", "total_amount", "currency"],
"properties": {
"order_id": {"type": "string", "pattern": r"^ORD-[0-9]{5,10}$"},
"customer_id": {"type": "string", "pattern": r"^CUST-[0-9]{4,10}$"},
"total_amount": {"type": "number", "exclusiveMinimum": 0},
"currency": {"type": "string", "enum": ["USD", "EUR", "MXN", "COP", "CLP"]},
"sales_channel": {
"type": "string",
"enum": ["WEB", "MOBILE_APP", "PARTNER_API"],
"default": "WEB",
},
},
},
},
}
@dataclass(frozen=True)classContractValidationResult:
is_valid: bool
errors: list[str]
defvalidate_order_confirmed_message(
kafka_key: str,
headers: dict[str, str],
payload: dict[str, Any],
schema: dict[str, Any] = ORDER_CONFIRMED_JSON_SCHEMA,
) -> ContractValidationResult:
"""
Validates both the JSON Schema and the envelope/transport contract rules.
"""
validator = Draft202012Validator(schema, format_checker=FormatChecker())
validation_errors: list[str] = [
f"Path '{'.'.join(str(p) for p in err.absolute_path) or'<root>'}': {err.message}"for err insorted(validator.iter_errors(payload), key=lambda e: str(e.path))
]
# Contract Rule 1: Kafka partition key MUST match data.order_id
order_id = payload.get("data", {}).get("order_id")
if order_id and kafka_key != order_id:
validation_errors.append(
f"Partitioning violation: kafka_key ('{kafka_key}') != data.order_id ('{order_id}')."
)
# Contract Rule 2: Header ce_id must mirror event_id for traceability
event_id = payload.get("event_id")
if event_id and headers.get("ce_id") != event_id:
validation_errors.append(
f"Header violation: headers.ce_id ('{headers.get('ce_id')}') != event_id ('{event_id}')."
)
return ContractValidationResult(
is_valid=len(validation_errors) == 0,
errors=validation_errors,
)
# 2. Educational Avro Record Compatibility Evaluatordefcheck_avro_record_compatibility(
old_schema: dict[str, Any],
new_schema: dict[str, Any],
policy: str = "FULL",
) -> list[str]:
"""
Evaluates core BACKWARD, FORWARD, or FULL compatibility rules
between two versions of an Avro record schema.
"""
old_fields = {f["name"]: f for f in old_schema.get("fields", [])}
new_fields = {f["name"]: f for f in new_schema.get("fields", [])}
issues: list[str] = []
check_backward = policy in ("BACKWARD", "FULL")
check_forward = policy in ("FORWARD", "FULL")
# Rule A: Fields added in the new schemafor name, field_def in new_fields.items():
if name notin old_fields:
if check_backward and"default"notin field_def:
issues.append(
f"[BACKWARD INCOMPATIBLE] New field '{name}' defines no 'default'. ""Readers using the new schema will fail when reading historical events."
)
# Rule B: Fields removed in the new schemafor name, field_def in old_fields.items():
if name notin new_fields:
if check_forward and"default"notin field_def:
issues.append(
f"[FORWARD INCOMPATIBLE] Removed field '{name}' had no 'default' in the previous schema. ""Older readers will fail once the producer stops sending it."
)
# Rule C: Fields present in both schemas that changed typefor name inset(old_fields).intersection(new_fields):
old_type = old_fields[name]["type"]
new_type = new_fields[name]["type"]
if old_type != new_type:
# Allow only int -> long promotion in backward directionifnot (policy == "BACKWARD"and old_type == "int"and new_type == "long"):
issues.append(
f"[TYPE INCOMPATIBLE] Field '{name}' changed type from '{old_type}' to '{new_type}'."
)
return issues
if __name__ == "__main__":
# Case 1: Valid OrderConfirmed event
valid_event = {
"event_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"event_type": "OrderConfirmed",
"schema_version": 1,
"occurred_at": "2026-11-07T19:45:00Z",
"data": {
"order_id": "ORD-90412",
"customer_id": "CUST-5510",
"total_amount": 149.90,
"currency": "USD",
"sales_channel": "WEB",
},
}
res_ok = validate_order_confirmed_message(
kafka_key="ORD-90412",
headers={"ce_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479"},
payload=valid_event,
)
assert res_ok.is_valid, f"Expected valid event, but got errors: {res_ok.errors}"# Case 2: Invalid event (total_amount as object, disallowed currency, and wrong Kafka key)
invalid_event = {
"event_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"event_type": "OrderConfirmed",
"schema_version": 1,
"occurred_at": "2026-11-07T19:45:00Z",
"data": {
"order_id": "ORD-90412",
"customer_id": "CUST-5510",
"total_amount": {"amount": "149.90", "scale": 2},
"currency": "ARS",
},
}
res_bad = validate_order_confirmed_message(
kafka_key="CUST-5510", # Error: partitioned by customer_id instead of order_id
headers={"ce_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479"},
payload=invalid_event,
)
assertnot res_bad.is_valid
assertlen(res_bad.errors) == 3# total_amount type, currency enum, and partition key# Case 3: Verify Avro FULL compatible vs. incompatible evolution
avro_v1 = {
"type": "record",
"name": "OrderConfirmedEvent",
"fields": [
{"name": "order_id", "type": "string"},
{"name": "total_amount_cents", "type": "long"},
],
}
# Compatible evolution: adds discount_code with null union and default None
avro_v2_compatible = {
"type": "record",
"name": "OrderConfirmedEvent",
"fields": [
{"name": "order_id", "type": "string"},
{"name": "total_amount_cents", "type": "long"},
{"name": "discount_code", "type": ["null", "string"], "default": None},
],
}
assert check_avro_record_compatibility(avro_v1, avro_v2_compatible, policy="FULL") == []
# Incompatible evolution: adds required tax_jurisdiction without default
avro_v2_breaking = {
"type": "record",
"name": "OrderConfirmedEvent",
"fields": [
{"name": "order_id", "type": "string"},
{"name": "total_amount_cents", "type": "long"},
{"name": "tax_jurisdiction", "type": "string"},
],
}
breaking_issues = check_avro_record_compatibility(avro_v1, avro_v2_breaking, policy="FULL")
assertlen(breaking_issues) == 1assert"BACKWARD INCOMPATIBLE"in breaking_issues[0]
print("All contract and compatibility validations passed successfully.")
CI/CD Workflow, Federated Governance, and Controlled Evolution Strategy
In a mature Data Mesh, no developer registers schemas manually in production. The contract lifecycle is automated inside the producer domain's CI/CD pipeline and connected with the Data Catalog and Data Lineage:
# .github/workflows/streaming-contract-ci.yml (Illustrative for the Sales domain)name:ValidateandPublishStreamingEventContracton:pull_request:paths:-'contracts/**'-'schemas/**'-'asyncapi/**'jobs:contract-governance:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-name:1.ValidateAsyncAPI3.0syntaxrun:npx--yes@asyncapi/clivalidateasyncapi/sales-order-events.asyncapi.yaml-name:2.RuncontracttestsandGoldenPayloadsrun:|
pip install jsonschema pytest
python verify_event_contracts.py
-name:3.CheckFULL_TRANSITIVEcompatibilityagainstSchemaRegistryrun:|
curl --fail -X POST \
-H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data @schemas/avro/order-confirmed-payload.json \
"$SCHEMA_REGISTRY_URL/compatibility/subjects/sales.order-events.v1-OrderConfirmed/versions?verbose=true"
-name:4.Verifyfederatedgovernancepolicies(PII,Owner,Semantics)run:pythonscripts/check_federated_policies.pycontracts/sales-order-events.contract.yaml
What to Do When a Breaking Change Is Unavoidable
If a tax regulation or a major redesign in the Sales domain requires an incompatible structure that cannot be expressed by adding optional fields:
Impact Analysis via Lineage: Before modifying the schema, the team inspects the catalog and lineage graph to identify subscribed consumers (Payments with paid-sales-live and Inventory with stock-reservation-worker).
Version Coexistence (Dual Publishing or Additive Enrichment):
Option A (Within the same event, preferred for scoped changes): Keep total_amount intact with its original meaning and add the new optional attribute net_amount_breakdown with a default value. Mark total_amount as @deprecated in the schema documentation and open the deprecation window (60 days).
Option B (New event type or new major channel): Simultaneously publish OrderConfirmed (v1) and OrderConfirmedV2 (or publish to sales.order-events.v2) from the same Outbox translator.
Progressive Consumer Migration: Each consumer domain updates its reader on its own release cadence, verifying via contract tests that it parses the new structure.
Verified Sunset: Only after broker and registry metrics confirm zero reads on the deprecated event or version throughout the agreed notice period is the old emission retired.
Three Real-World Architectural Decision Scenarios
Scenario 1: High-Volume E-Commerce with Multiple Independent Consumers (CommerceFlow)
Context: The sales-order-events stream emits 2,500 events per second and is consumed by Payments (Java/Flink), Inventory (Go), and the analytical Lakehouse (Python/Spark).
Decision: Use Apache Avro with Schema Registry under a FULL_TRANSITIVE policy, document the public interface in AsyncAPI 3.0, and enforce golden payload validation in CI/CD.
Why: Binary encoding drastically reduces Kafka bandwidth and storage costs; Avro's writer/reader resolution allows teams across three programming languages to deploy without coordinating maintenance windows.
Scenario 2: B2B Integration with External Logistics Partners and Frequent Human Inspection
Context: The Fulfillment domain exposes a shipment-status-events stream with low volume (15 events per minute) consumed by external carriers who debug integrations manually.
Decision: Use JSON messages validated with JSON Schema at the publishing gateway and documented in AsyncAPI 3.0, allowing additional properties on readers (additionalProperties: true on consumers, false in producer tests).
Why: At 15 events per minute, binary byte savings are negligible compared to enabling external partner teams to inspect plain-text payloads without installing Avro deserializers or requiring direct network access to an internal Schema Registry.
Scenario 3: When a Simpler Alternative Is Enough
Context: An internal service within the Catalog domain sends a local event to a single worker owned by the exact same team to regenerate product image thumbnails when a photo is uploaded. No other domain consumes or will consume that topic.
Decision:Do not build a Streaming Data Product, maintain a formal AsyncAPI specification, or manage a cross-domain contract. A shared typed class or schema inside the team's monorepo and a simple internal queue are sufficient.
Why: Applying the full ceremony of federated contracts, public catalogs, and 60-day deprecation windows to a private queue inside a single Bounded Context adds operational friction without contributing value to the data mesh.
AI Prompts for Designing and Auditing Event Contracts
Prompt 1: Detect Structural and Semantic Compatibility Breaks Before a Pull Request
Act as a Data Architect specializing in Streaming Data Mesh.
I will share the current version (v1) and proposed version (v2) of an event schema, along with the semantic contract of the Streaming Data Product.
Context:
- Producer domain: Sales (product: sales-order-events)
- Active consumers: Payments (real-time financial reconciliation) and Inventory (stock reservation)
- Schema format: [Apache Avro / JSON Schema]
- Target Schema Registry policy: FULL_TRANSITIVE
[PASTE V1 SCHEMA AND SEMANTIC CONTRACT HERE]
[PASTE PROPOSED V2 SCHEMA HERE]
Task:
1. Evaluate whether the change from v1 to v2 is BACKWARD, FORWARD, and FULL compatible according to the exact rules of the specified format.
2. Identify any semantic breaking risks (changes in units, currency, rounding, time zone, or business meaning) even if data types remain identical.
3. Propose a non-disruptive evolution alternative (additive or dual-publishing) ready to implement.
What a human must verify: Confirm that the AI does not assume JSON Schema handles "default" values the same way Apache Avro does during deserialization, and verify with business stakeholders whether the accounting meaning of every numeric attribute remains unchanged.
Prompt 2: Generate an AsyncAPI 3.0 Specification and Test Cases from a Domain Contract
Act as a Platform Engineer in a Data Mesh architecture.
From the following event contract of the Payments domain (`PaymentCaptured`), generate:
1. A valid AsyncAPI 3.0.0 specification (strictly using channels and operations with action: send/receive, without mixing 2.x syntax such as publish/subscribe inside channels).
2. Three test JSON payloads (one valid and two invalid that violate business or format constraints) to integrate into our pytest + jsonschema suite.
Event constraints:
- Logical channel: payments.transaction-events.v1
- Partition key: order_id
- Required envelope fields: event_id (uuid), event_type ("PaymentCaptured"), schema_version (int >= 1), occurred_at (UTC date-time).
- Business fields in data: payment_id (PAT: ^PAY-[0-9]{6}$), order_id (PAT: ^ORD-[0-9]{5,10}$), captured_amount_cents (int > 0), currency (USD, EUR, MXN), payment_method (CARD, TRANSFER, WALLET).
What a human must verify: Run @asyncapi/cli validate on the generated YAML to confirm no AsyncAPI 2.x keywords were mixed in, and check that the regular expressions match the real identifiers emitted by the domain in production.
Practical Application Exercises
Exercise 1: Diagnosing Avro Schema Evolution
The Sales domain wants to evolve the Avro schema of OrderConfirmedEvent by introducing two simultaneous changes in version v2:
It adds the field loyalty_points_earned of type "int" without a "default" attribute.
It removes the field sales_channel, which in v1 was defined as {"name": "sales_channel", "type": ["null", "string"], "default": null}.
If the subject in Schema Registry is configured with FULL_TRANSITIVE, which of the two changes will be rejected, why, and how should you fix it?
Exercise 2: Auditing a Change "Invisible" to Schema Registry
To standardize units across CommerceFlow, a Sales developer modifies the Outbox translator for OrderConfirmed: the total_amount_cents field (long in Avro) changes from expressing cents (14990 for USD 149.90) to expressing rounded whole currency units (150), without touching the .avsc file.
Explain:
What will Schema Registry respond during the CI/CD pipeline check?
What will happen in the derived product paid-sales-live owned by Payments?
Which contract artifact and automated test should have blocked this change before reaching production?
Exercise 3: Designing a Zero-Downtime Migration
Currently, OrderCancelled includes "cancellation_reason": "string" containing free-form text. The Sales team needs to replace it with a structured object "cancellation_detail": {"code": "PAYMENT_TIMEOUT", "initiated_by": "SYSTEM"} and remove the free-form string. Design a concrete step-by-step evolution plan that avoids breaking the three consumer domains reading this event in real time.
Reasoned Solutions
Solution to Exercise 1
Diagnosis: Change (2)—removing sales_channel—is FULL compatible because in v1 it already had "default": null; when an older consumer (v1) reads a new message (v2) lacking that field, Avro populates sales_channel with null. Conversely, change (1)—adding loyalty_points_earned without "default"—will be rejected as BACKWARD incompatible. If a consumer upgraded to v2 reads a historical event from the topic written with v1, the binary record lacks the field and Avro will not know what integer to assign.
Fix: Define an explicit default value in v2:
{"name":"loyalty_points_earned","type":"int","default":0,"doc":"Loyalty points earned by the order; 0 for orders without an active program or prior to v2."}
Solution to Exercise 2
Schema Registry Response: It will approve the check without warning (is_compatible: true), because the data type remains long and the field name did not change.
Impact on paid-sales-live (Payments): The reconciliation engine will divide 150 by 100 assuming the value is still in cents, interpreting a USD 1.50 sale instead of USD 149.90 and triggering false payment discrepancy alerts across 100% of orders.
Blocking Mechanism: The semanticInvariants section of the contract (sales-order-events.contract.yaml) paired with a Golden Payload contract test in the producer's CI pipeline (which takes a known test order of 149.90 USD in the database/Outbox and asserts assert emitted_event["total_amount_cents"] == 14990).
Solution to Exercise 3
To prevent any consumer downtime, apply the Expand and Contract pattern:
Phase 1 — Additive Expansion (v2 FULL compatible): Keep "cancellation_reason": "string" intact and add the new "cancellation_detail" field as optional with a default of null in the schema. Update the Sales producer to populate both fields simultaneously on every emitted event.
Phase 2 — Communication and Deprecation: Mark cancellation_reason as deprecated in the contract and AsyncAPI 3.0 specification, notifying all three consumer domains with the sunset date per policy (noticePeriodDays: 60).
Phase 3 — Consumer Migration: Each of the three domains updates its consumer to read cancellation_detail and stop referencing cancellation_reason.
Phase 4 — Controlled Contraction: Once verified that all three consumers rely exclusively on cancellation_detail, either assign "default": "" to cancellation_reason before omitting it, or transition to a new major event version when compacting topic history.
Criteria for Applying What You Learned and Summary
Apply formal event contracts, Schema Registry, and AsyncAPI when:
An event stream crosses domain boundaries and is consumed by teams with independent deployment lifecycles.
Consumers replay topic history or materialize analytical and operational views that demand structural and semantic stability.
You need the organization's catalog to discover both batch and real-time data products under unified ownership and governance rules.
Avoid this overhead when a topic or queue is strictly private within a single microservice or Bounded Context and both producer and consumer deploy together as a single unit.
With event contracts, versioned schemas, and AsyncAPI, a Kafka stream stops being a fragile byte pipe and becomes a predictable product interface. Once contract structure and evolution are secured at design and CI/CD time, the next challenge is protecting stream behavior at runtime: measuring consumer lag, isolating poison pill messages (Dead Letter Queues), guaranteeing safe reprocessing, and operating streaming observability in production.
A comprehensive hands-on capstone project to design, build, and verify an end-to-end Data Mesh architecture on AWS using S3, Parquet, Glue, Athena, Lake Formation, Terraform, YAML contracts, and Python validations.
Learn how to connect governed Data Products in a Data Mesh with Machine Learning systems, Feature Stores, MLOps, and generative AI RAG architectures while preventing data leakage, semantic errors, and permission breaches.
A practical and strategic guide to planning enterprise Data Mesh adoption: maturity assessment, pilot selection, team topologies, FinOps cost modeling, real outcome KPIs, and criteria to avoid over-engineering.