Why channel contracts matter
In any organisation that runs core business flows over Kafka — payments, orders, policy administration, logistics — Kafka is not a message queue; it is the connective tissue between services. In a payments estate, for example, it links the payment initiation service, the fraud engine, the liquidity manager, the settlement adapter, and the regulatory reporting feed. Each of these services is owned by a different squad, deployed on its own release cycle, and written by engineers who joined the organisation at different times and may never have met each other.
The implicit contract problem surfaces quietly: a fraud engine update changes the field name from transactionAmount to txnAmt in the Kafka message it publishes. The fraud squad tests against their own consumer. The payment enrichment service, which reads from the same topic, does not find out until its deserialization starts silently nulling amounts in production. By then, hundreds of payments have been risk-scored against a null amount and passed.
Avro Schema Registry with compatibility modes catches schema incompatibility. It does not catch: channel renaming, partition-key semantic changes, header field removal, encoding changes from Avro to Protobuf, or the addition of a new mandatory semantic field that is technically backward-compatible but logically breaks downstream logic. AsyncAPI contracts catch all of these — because they document the intent of the channel, not just the wire format.
AsyncAPI and Confluent Schema Registry solve different problems. Schema Registry enforces wire-format compatibility on every produce and consume. AsyncAPI documents the channel’s semantic contract: which service owns it, what the message means, how it is partitioned, what data-protection classification the payload carries, and what downstream consumers can expect from the event ordering. Use both.
AsyncAPI 3.0 structure
AsyncAPI 3.0 introduced a cleaner separation between channels (the broker-side entity) and operations (the application-side send/receive intent). This separation is particularly useful for Kafka: the same channel can be both produced to and consumed from, and the spec makes clear which services own which operations.
The key change in 3.0 from 2.x: operations no longer live inside channels. A channels block entry is purely the broker entity — the Kafka topic — with its bindings, message types, and metadata. An operations block entry declares what an application does with that channel: sends to it, receives from it, or both. This model maps cleanly onto a service ownership model: the Payment Service sends to payments.initiated.v2, while the Fraud Engine and the Settlement Adapter each independently receive from it — and the spec makes all of this explicit in one place.
Defining payment channels
A complete AsyncAPI spec for the payment-initiated event channel. This is the full spec that lives in source control alongside the code — not a generated artefact, not a documentation afterthought, but the primary contract reviewed and approved before a producer or consumer is written.
asyncapi: '3.0.0'
info:
title: Payment Initiated Channel
version: '2.0.0'
description: >
Published by the Payment Initiation Service when a pacs.008 credit transfer
instruction has been validated, persisted, and assigned an internal payment ID.
Consumed by: fraud-engine, liquidity-manager, notification-service, audit-feed.
contact:
name: Payments Domain Squad
url: https://wiki.example.internal/payments/channel-contracts
x-channel-owner: payment-initiation-squad # custom extension
x-data-classification: restricted # custom extension
x-regulatory-scope: payment-lifecycle # custom extension
servers:
production:
host: kafka.example.internal:9093
protocol: kafka-secure
security:
- $ref: '#/components/securitySchemes/mTLS'
channels:
paymentInitiated:
address: payments.initiated.v2
description: >
Append-only topic. Log-compaction disabled. Retention: 90 days.
Partition key: paymentId (UUID). Partitions: 12.
messages:
PaymentInitiatedMessage:
$ref: '#/components/messages/PaymentInitiatedMessage'
bindings:
kafka:
topic: payments.initiated.v2
partitions: 12
replicas: 3
topicConfiguration:
retention.ms: 7776000000 # 90 days
cleanup.policy: delete
min.insync.replicas: 2
operations:
publishPaymentInitiated:
action: send
channel:
$ref: '#/channels/paymentInitiated'
summary: Payment initiation service publishes after pacs.008 validation
bindings:
kafka:
# Kafka operation binding: clientId is a schema, not a plain string; producers have no groupId
clientId: { type: string, enum: [payment-initiation-svc] }
components:
messages:
PaymentInitiatedMessage:
name: PaymentInitiated
title: Payment Initiated
contentType: avro/binary # wire format; the payload below is described in AsyncAPI Schema
headers:
type: object
properties:
correlationId:
type: string
description: ISO 20022 EndToEndId, carries across all downstream events
traceId:
type: string
description: OpenTelemetry W3C TraceContext trace-id
schemaVersion:
type: string
enum: ["2.0"]
payload:
$ref: '#/components/schemas/PaymentInitiatedPayload'
schemas:
PaymentInitiatedPayload:
type: object
required: [paymentId, endToEndId, debtorIban, creditorIban, amount, currency]
properties:
paymentId:
type: string
format: uuid
description: Internal UUID, partition key
endToEndId:
type: string
maxLength: 35
description: ISO 20022 EndToEndId, set by originator, idempotency key
debtorIban:
type: string
x-personal-data: personal-financial
creditorIban:
type: string
x-personal-data: personal-financial
amount:
type: string
description: Decimal as string (Avro logicalType decimal, precision 18 scale 2)
currency:
type: string
enum: ["USD", "EUR", "GBP", "CHF"]
initiatedAt:
type: string
format: date-time
description: Server-set timestamp, not client-supplied
securitySchemes:
mTLS:
type: X509
description: mTLS with internal CA; certificate CN must match client-id pattern
Two things worth calling out explicitly. First, the custom extensions (x-channel-owner, x-data-classification, x-regulatory-scope, x-personal-data) are not decoration — they feed the governance pipeline. A CI gate validates that every channel spec has x-data-classification set to a recognised value and that every field carrying personal data has x-personal-data annotated. Second, the Kafka bindings in the channel include topicConfiguration: this means the spec doubles as the source of truth for topic creation via Terraform or the Kafka Admin API, preventing topic configuration drift between environments.
Schema Registry alignment
AsyncAPI defines the contract; Confluent Schema Registry enforces the wire-format compatibility rule at produce and consume time. These two tools work at different layers and need to be kept consistent — which means the Avro schema in Schema Registry must be the canonical source for the payload definition referenced in the AsyncAPI spec, not a copy.
The practical approach: the .avsc Avro schema file lives in Git next to the AsyncAPI spec. In AsyncAPI 3.0 a message payload can point at it directly with a Multi Format Schema Object — payload: { schemaFormat: 'application/vnd.apache.avro;version=1.9.0', schema: { $ref: './payment-initiated-v2.avsc' } }; the example above describes the payload in AsyncAPI Schema instead, so the personal-data annotations can be checked in CI, and keeps the two in step with a CI comparison. CI runs schema-registry-maven-plugin to check compatibility against the registered schema in Schema Registry before merging any PR that modifies the schema. On merge to main, CI registers the new schema version and publishes the updated Maven artefact. Services pull the versioned artefact — they do not embed schema definitions in their own source.
BACKWARD compatibility lets new consumers read old messages. FORWARD compatibility lets old consumers read new messages. FULL gives both. FULL_TRANSITIVE extends FULL to every historical version, not just the immediately prior one. For a payment topic that may have consumers still running a version from six months ago, FULL_TRANSITIVE is the only mode that guarantees no consumer breaks regardless of when they last updated their schema artefact.
Data-protection classification metadata
Data-protection laws — the EU GDPR, Saudi Arabia’s PDPL, California’s CCPA/CPRA and their equivalents elsewhere — require that personal data processing be documented, purpose-limited, and access-controlled. A Kafka topic carrying account numbers, customer names, or national ID references is a personal data processing activity — not just a technical message bus. The AsyncAPI spec is the place to document this, and the custom extensions that do so need to be enforced in CI, not treated as optional annotations.
A tiered classification scheme maps cleanly onto the categories most data-protection laws use, and onto Kafka access control:
| x-data-classification | Typical legal category | Example channels | Kafka ACL pattern |
|---|---|---|---|
public | Non-personal | currency rates, product catalogue | Any authenticated service |
internal | Organisation data | service health events, audit log entries (aggregated) | Service certificate in payments org |
restricted | Personal data | payments.initiated, account-updates | Explicit allowlist of consumer groups, mTLS required |
sensitive | Special-category or high-risk personal data | fraud-flags, health-claim events, credit-score events | Separate Kafka cluster, dual-key encryption at rest |
The CI enforcement script checks every AsyncAPI spec for the presence of x-data-classification at the info level, and validates that every schema property whose name matches a personal-data pattern (.*Iban.*, .*NationalId.*, .*FullName.*, .*PhoneNumber.*) has an x-personal-data annotation. Unannotated personal data fields fail the build.
#!/usr/bin/env bash
set -euo pipefail
SPEC_FILE="$1"
# Require top-level data-protection classification
DATA_CLASS=$(yq '.info["x-data-classification"]' "$SPEC_FILE")
if [[ "$DATA_CLASS" == "null" || -z "$DATA_CLASS" ]]; then
echo "ERROR: $SPEC_FILE missing info.x-data-classification" >&2
exit 1
fi
# Find schema properties matching personal-data patterns
PERSONAL_FIELDS=$(yq '.components.schemas[].properties | keys | .[]' "$SPEC_FILE" \
| grep -iE 'iban|nationalid|fullname|phonenumber|email|address' || true)
for field in $PERSONAL_FIELDS; do
ANNOTATION=$(yq ".components.schemas[].properties[\"$field\"][\"x-personal-data\"]" "$SPEC_FILE")
if [[ "$ANNOTATION" == "null" || -z "$ANNOTATION" ]]; then
echo "ERROR: field '$field' looks like personal data but has no x-personal-data annotation" >&2
exit 1
fi
done
echo "Personal-data annotation check passed: $SPEC_FILE (class=$DATA_CLASS)"
Code generation
The asyncapi-generator CLI with the @asyncapi/java-spring-cloud-stream-template template generates Spring Cloud Stream @Bean configurations, message POJOs, and channel binding interfaces from the AsyncAPI spec. The generated code is published as a Maven artefact and versioned alongside the spec — services depend on the artefact, not on the spec file itself.
stage('Generate Channel Bindings') {
steps {
sh """
asyncapi generate fromTemplate payments-initiated.asyncapi.yaml \
@asyncapi/java-spring-cloud-stream-template \
--param javaPackage=com.example.events.payments \
--param artifactId=payments-channel-bindings \
--param springCloudStreamVersion=4.1.3 \
--output target/generated-sources/channels
"""
}
}
stage('Publish to Maven') {
when { branch 'main' }
steps {
sh """
mvn deploy -f target/generated-sources/channels/pom.xml \
-DaltDeploymentRepository=nexus::default::https://nexus.example.internal/repository/maven-releases/ \
-Drevision=${SPEC_VERSION}.${BUILD_NUMBER}
"""
}
}
The generated Spring Cloud Stream binding for a consumer looks like:
// Generated by asyncapi-generator. Do not edit manually.
@Component
public class FraudEngineChannelConsumer
implements Consumer<Message<PaymentInitiatedPayload>> {
/**
* Bound to: payments.initiated.v2
* Consumer group: fraud-engine
* Channel contract: payments-initiated.asyncapi.yaml v2.0.0
*/
@Override
public void accept(Message<PaymentInitiatedPayload> message) {
// Implement your fraud check logic here
// payload is already deserialized via Confluent Avro deserializer
PaymentInitiatedPayload payload = message.getPayload();
// headers are accessible via message.getHeaders()
String correlationId = (String) message.getHeaders().get("correlationId");
}
}
The asyncapi-generator template produces the binding interface and the POJO — the shape and wiring. The business logic (the actual fraud check, the settlement instruction) stays in handwritten code that implements the generated interface. Keep the generated layer thin: binding, deserialization, header extraction. The moment you add business logic to generated code, you will regret the next time the spec version increments and you re-run the generator.
Channel versioning strategy
Channel versioning is not schema versioning. A schema version increment is a wire-format change handled by Schema Registry compatibility rules. A channel version increment is a semantic change to the contract: a new partition key, a changed retention policy, a redefined meaning for an existing field, a change in the set of consumers or producers, or a data-protection reclassification.
-
Encode the major version in the topic name
Topic names are permanent in a running Kafka cluster without migration. Use
payments.initiated.v2, notpayments.initiated. When a breaking channel change is needed, createpayments.initiated.v3, migrate consumers, and deprecate v2 with a 90-day sunset window. Never rename or repurpose an existing topic. -
Patch versions are schema-only
A schema change that passes FULL_TRANSITIVE compatibility gets a patch version increment in the AsyncAPI spec (e.g.
2.0.0→2.0.1). A new optional field, a description update, anx-personal-dataannotation added — these are patch changes. No topic rename, no consumer re-registration required. -
Minor versions add operations, not channels
Adding a new consuming service to the AsyncAPI spec (a new
operationsentry) is a minor version change (2.0.0→2.1.0). The channel itself is unchanged; the contract is updated to document the new consumer. This triggers a Maven artefact publish but no Kafka configuration change. -
Major versions always create a new topic
Any change to the partition key, retention policy, cleanup.policy, or number of partitions is a major version change and requires a new topic. Run old and new topics in parallel: the producer writes to both, consumers migrate at their own pace, the old topic is sealed (no new produces) after all consumer groups have committed their final offsets, and deleted after the retention period.
-
Sunset deprecated channels with a formal process
Add a
x-deprecated-atandx-sunset-dateextension to the channel entry in the AsyncAPI spec when deprecation begins. CI alerts on consumer services still registering against a deprecated channel in their Spring config. The channel contract owner owns the migration — not the consumers.
CI enforcement
An AsyncAPI spec checked into Git without CI enforcement is a documentation file. CI enforcement is what makes it a contract. Three gates are required on every PR that modifies a channel spec:
name: AsyncAPI Contract Validation
on:
pull_request:
paths: ['channels/**/*.asyncapi.yaml', 'schemas/**/*.avsc']
jobs:
validate:
runs-on: self-hosted # air-gapped internal runner
strategy:
matrix:
spec: [channels/payments/payments-initiated.asyncapi.yaml]
steps:
- uses: actions/checkout@v4
# Gate 1: AsyncAPI spec structural validity
- name: Validate AsyncAPI spec
run: asyncapi validate "${{ matrix.spec }}"
# Gate 2: personal-data annotation completeness
- name: Personal-data annotation check
run: bash ci/validate-privacy-annotations.sh "${{ matrix.spec }}"
# Gate 3: Avro compatibility against Schema Registry
# (subjects and schema paths are configured in the pom's plugin section)
- name: Schema compatibility check
run: mvn -B schema-registry:test-compatibility -Dschema.registry.url=https://schema-registry.internal:8082
A fourth gate runs only on the main branch after merge: channel topic configuration reconciliation. A Kafka Admin API script reads the existing topic configuration from the broker and compares it to the bindings.kafka.topicConfiguration block in the AsyncAPI spec. Any drift — a manually applied retention change, a partition count that does not match — fails the post-merge check and opens a Jira ticket in the channel-governance backlog automatically. The spec is always the source of truth; the broker is the materialisation.
AsyncAPI spec PRs that change a schema field but do not update the Avro .avsc file in the same commit are a red flag: the spec is drifting away from the actual wire format. Require that schema changes always update both the .avsc and the AsyncAPI spec in one atomic PR. A spec that references a Schema Registry subject but describes a different schema than what is registered is worse than no spec at all — it actively misleads consumers.
Channel ownership & governance
Channel governance answers three questions that matter for any organisation running dozens of Kafka topics across several integration domains: who can create a new channel, who can modify an existing one, and who is accountable when a consumer breaks.
Channel ownership rules for a typical enterprise integration programme:
- One squad owns each channel, identified by
x-channel-ownerin the spec. The owning squad is responsible for the channel contract, the data-protection annotations, and the consumer migration when the channel changes. Consumers do not own channels they consume. - New channels require architecture sign-off. A squad cannot create a new Kafka topic by pushing YAML — every new channel spec requires a PR reviewed by the integration architecture group. This prevents topic sprawl: the architecture team can reject a proposed channel if the same event is already published on an existing topic under a different name.
- Restricted and sensitive channels require Data Protection Officer review on every PR that changes the data classification or adds a new consumer. The DPO sign-off is a CODEOWNERS requirement, not optional.
AsyncAPI vs alternatives
| Approach | Catches semantic breaks | Code generation | Privacy metadata | CI integration | Tooling maturity |
|---|---|---|---|---|---|
| AsyncAPI 3.0 | Yes (full channel contract) | Yes (Spring Cloud Stream) | Custom extensions, CI-enforced | Strong (asyncapi-cli) | Growing; 3.0 tools less mature than 2.x |
| Schema Registry only | Wire-format only | No | No | Strong (maven plugin) | Mature, production-proven |
| OpenAPI callbacks | No (REST-centric) | Yes (OpenAPI generator) | Extension pattern | Strong | Mature, but conceptually wrong for Kafka |
| Informal wiki docs | No | No | No | None | N/A |
| Protobuf + Buf | Partial (wire format + naming) | Yes (multi-language) | Custom options | Strong (buf CLI) | Mature for gRPC; Kafka integration via Buf Schema Registry |
The decision: use AsyncAPI 3.0 + Schema Registry together. AsyncAPI is the contract document; Schema Registry is the enforcement mechanism. Do not choose between them. If the team is not ready for the overhead of full AsyncAPI governance on all channels, start with the highest-risk domain channels — payments, customer data, the topics with the most personal-data exposure — and expand coverage as the tooling becomes familiar.
Anti-patterns
Some frameworks auto-generate AsyncAPI specs by scanning @KafkaListener annotations. The result describes what the code does — not what the channel contract intends. Generated specs drift the moment a developer refactors the listener class. Write the spec first. The spec is the authority; the code is the implementation. If your tools cannot produce a spec from code that matches the intent you want to express, the answer is to write the spec manually, not to accept a weaker spec.
A single all-channels.asyncapi.yaml file covering dozens of topics is unmanageable: every PR touches the same file, CODEOWNERS cannot be applied per-channel, and the file becomes a merge conflict magnet. One spec per channel, stored in a channels/ directory with a CODEOWNERS file mapping each channel spec to its owning squad. The CI pipeline validates all specs on each PR but only requires sign-off from the owners of the specific channels changed.
x- extensions as optional decorationCustom extensions are only useful if CI enforces them. An x-data-classification that developers add only when they remember, or an x-channel-owner that nobody updates when a squad reorganisation happens, provides false confidence. Every x- extension that matters for governance must be checked in CI, with a build failure if it is absent or set to an unrecognised value. If you cannot enforce it in CI, remove it from the spec — misleading metadata is worse than no metadata.