Integration event contracts in a .NET service landscape: publisher ownership, backward- and forward-compatible schema changes, versioned event types, the CloudEvents envelope and Azure Service Bus mapping, schema registries and contract tests, and the coupling caused by a shared events library.
An integration event is a public API owned by the publisher. Within a version I only make backward-compatible changes: add optional (nullable or defaulted) fields. I never add a required field mid-version (messages already in queues won't have it), and never rename, remove or retype. Consumers are tolerant readers: they ignore unknown fields and default missing optional ones. A breaking change becomes a new event type (orders.order-placed.v2), published alongside v1 until consumers move, then deprecated with a date.
I wrap events in a CloudEvents envelope (id, source, type, time, dataschema). Each publisher ships its own contracts package or JSON Schema; one shared events library for every service forces lockstep upgrades.
The trade-off: discipline and some duplication in exchange for independent deployments.
"I treat an integration event exactly like a public HTTP API, and the publisher owns it. If the Ordering service publishes
OrderPlaced, Ordering decides its shape, documents it, and promises not to break it. Consumers code against it as tolerant readers: System.Text.Json ignores unknown properties by default, and consumers default anything optional. That gives me the rule for changes. Within a version I can add optional fields; I can't rename, remove, change a type or change the meaning of a field. If I need any of those, it's a new event type,orders.order-placed.v2, and I publish both v1 and v2 from the outbox until every consumer has moved, with a deprecation date agreed in advance.For the envelope I like CloudEvents, the CNCF spec: every message carries
id,source,type,specversion,timeand optionallydataschemaandsubject. On Azure Service Bus I map those to the message id and application properties, so subscriptions can filter ontype, consumers dedup onid, and traces correlate. The payload itself stays small: ids, facts consumers need, an aggregate version for ordering.The thing I push back on is the shared
Company.EventsNuGet package that every service references. It looks tidy, but now a change to one event means a new package version, every service has to upgrade to get unrelated changes, and teams start putting helper code and domain types in it. You've rebuilt a distributed monolith through a package. Instead each publisher publishes its own contracts package or JSON Schema, consumers can even copy the DTO they need, and compatibility is checked in CI with schema diffing or consumer-driven contract tests.The mistake I see is versioning by editing the class and hoping. Contracts need the same rigour as APIs, because a broken consumer at 2 am doesn't care that it was 'only an event'."
| Change | Safe within a version? | Why |
|---|---|---|
| Add an optional field | Yes | Tolerant readers ignore it; old producers omit it |
| Add a required field | No | Old messages in queues lack it |
| Rename a field | No | Old consumers see null |
| Change a type (int to string) | No | Deserialisation fails |
| Remove a field | No | Consumers relying on it break |
| Change meaning (cents to dollars) | No | Silent data corruption |
| Add a new event type | Yes | Consumers subscribe when ready |
| Option | Coupling | Fits when |
|---|---|---|
| One shared events library for all services | High: lockstep upgrades | Never, beyond a single team's modules |
| Per-publisher contracts package | Low: consumers pin versions | .NET-only estate, several teams |
| JSON Schema / AsyncAPI document | Lowest: language-neutral | Mixed languages, external consumers |
| Consumers copy the DTO | None at build time | Few fields used; CI contract tests guard drift |
An estate of 14 services shared one Events package. A single field rename forced 9 services to redeploy in one weekend and still broke two consumers reading from backlog queues. After moving to per-publisher contracts with additive-only rules and a v2 side-by-side policy, the next 30 contract changes shipped with zero consumer incidents.
Checks that the candidate treats integration events as owned, versioned public contracts and understands the coupling risks of shared libraries.
Green flags
Red flags
+--------------------+ publishes +---------------------------+
| Ordering service |-------------->| Topic: orders |
| owns: | | type=orders.order-placed.v1
| Ordering.Contracts| | type=orders.order-placed.v2 (migration)
+--------------------+ +-------------+-------------+
|
+-----------------------------+-------------+
v v v
Warehouse (v1) Billing (v2) Analytics (JSON Schema)
Dependency direction matters: consumers depend on the publisher's contract, never the reverse. A consumer that needs a new field asks the publisher, like any API change request.
How each kind of field change plays out:
| Change | Old consumer, new message | New consumer, old message | Verdict |
|---|---|---|---|
| Add optional field (nullable or with a default) | Ignores it | Sees null/default | Safe |
| Add required field | Ignores it | Missing: fails or wrong default | New version |
| Make a required field optional (publisher may omit it) | Expects it, gets null | Fine | Two-step: update consumers first, then stop sending |
| Make an optional field required | Fine | Old messages lack it | New version |
| Remove a field | Gets null | Fine | Deprecate, then new version |
The safe way to retire or relax a required field:
System.Text.Json specifics for tolerant readers:
JsonUnmappedMemberHandling.Disallow in consumers.required member or marked [JsonRequired], in which case deserialisation throws (System.Text.Json has honoured required since .NET 8). So consumer DTOs should keep only the fields they need, make anything that might be absent nullable or defaulted, and reserve required for fields guaranteed in every version they accept.CloudEvents attribute Service Bus mapping
--------------------- -------------------
id MessageId (also used by duplicate detection)
type ApplicationProperties["cloudEvents:type"] / Subject
source ApplicationProperties["cloudEvents:source"]
time ApplicationProperties["cloudEvents:time"]
dataschema ApplicationProperties["cloudEvents:dataschema"]
datacontenttype ContentType = application/json
data Body
The Azure.Messaging.CloudEvent type in Azure.Core supports structured mode (whole envelope as JSON body); Event Grid supports CloudEvents natively. Binary mode (attributes as properties, payload as body) lets Service Bus SQL filters route on type without parsing the body.
Ids, the facts consumers need, occurredAt, an aggregate version. Not the whole entity, not internal enums whose values might change, not PII that consumers don't need (Privacy Act APP 3 and APP 11: collect and keep only what's necessary).
OrderPlacedV1 as a record, serialise a sample, add an optional field, and confirm an old consumer still deserialises the new message.required property to a consumer DTO and deserialise an old message: watch it throw, then make it nullable.A publisher-owned contract, a CloudEvents envelope in binary mode on Service Bus, and a tolerant consumer.
// Ordering.Contracts: a small package owned by the Ordering team. Records only, no domain types.
namespace Ordering.Contracts;
public static class EventTypes
{
public const string OrderPlacedV1 = "au.example.orders.order-placed.v1";
public const string OrderPlacedV2 = "au.example.orders.order-placed.v2";
}
public sealed record OrderPlacedV1(Guid OrderId, Guid CustomerId, decimal Total, long Version)
{
public string? Channel { get; init; } // added later: optional, so v1 stays compatible
}
// Breaking change (money as minor units + currency) -> new type, published alongside v1 during migration.
public sealed record OrderPlacedV2(Guid OrderId, Guid CustomerId, long TotalMinorUnits, string Currency, long Version);
namespace Ordering.Infrastructure;
using System.Text.Json;
using Azure.Messaging.ServiceBus;
public static class CloudEventMessage
{
// Binary mode: CloudEvents attributes as properties, payload as body, so subscriptions can filter on type.
public static ServiceBusMessage Create<T>(Guid id, string type, T data, DateTimeOffset time) => new(JsonSerializer.SerializeToUtf8Bytes(data))
{
MessageId = id.ToString(),
ContentType = "application/json",
Subject = type,
ApplicationProperties =
{
["cloudEvents:specversion"] = "1.0",
["cloudEvents:id"] = id.ToString(),
["cloudEvents:type"] = type,
["cloudEvents:source"] = "/services/ordering",
["cloudEvents:time"] = time.ToString("O")
}
};
}
namespace Warehouse.Consumers;
using System.Text.Json;
using Azure.Messaging.ServiceBus;
// The consumer keeps its own copy of just the fields it needs: a tolerant reader.
internal sealed record OrderPlaced(Guid OrderId, long Version);
public sealed class OrderPlacedConsumer
{
public Task HandleAsync(ServiceBusReceivedMessage message, CancellationToken ct)
{
var type = (string)message.ApplicationProperties["cloudEvents:type"];
if (type is not ("au.example.orders.order-placed.v1" or "au.example.orders.order-placed.v2"))
return Task.CompletedTask; // not ours to handle; subscription filters normally prevent this
// Unknown properties are ignored by default; don't enable JsonUnmappedMemberHandling.Disallow here.
var evt = JsonSerializer.Deserialize<OrderPlaced>(message.Body, JsonSerializerOptions.Web)!;
// ... dedup on message.MessageId (inbox), then create the pick list
return Task.CompletedTask;
}
}
JsonUnmappedMemberHandling.Disallow, required members for fields that may be absent). Why it is wrong: any added or relaxed field breaks them. Instead: tolerant readers with nullable or defaulted properties.TotalMinorUnits) or a new version, documented in the schema.I think of contracts in terms of who pays for change. With a shared library, every service pays for every change. With publisher-owned, versioned contracts, the publisher pays a little more (publishing v1 and v2 for a while), and everyone else pays only when they choose to. That trade is almost always worth it once more than one team is involved.
Inside a modular monolith owned by one team, I'm more relaxed: a contracts project per module, referenced by others, is fine, because one build deploys everything. The rules tighten as the deployment and team boundaries separate.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Contracts project per module, same solution | Modular monolith, one deployable | Low | Separate deployables |
| Per-publisher NuGet contracts | .NET services, several teams | Package publishing, version pinning | Mixed languages |
| JSON Schema / AsyncAPI + codegen | Polyglot or external consumers | Tooling | Tiny estates |
| Consumer-driven contract tests | Many consumers per event | Pact setup, broker | One consumer you own |
I'd measure consumer incidents caused by contract changes, the number of services that must redeploy per change, and how long v1 lingers after v2 ships.
A domain event records something meaningful that happened inside one bounded context, such as OrderPlaced. It is raised by an aggregate, handled in-process by other parts of the same model, and uses domain types freely. An integration event is a published contract for other services or modules: serialised, versioned and owned by the publisher.
SaveChanges), so their side effects commit or roll back together.The trade-off: domain events give you strong consistency in one context; integration events give you decoupling at the cost of eventual consistency and at-least-once delivery.
I add Asp.Versioning 10.x (Asp.Versioning.Http for Minimal APIs, plus Asp.Versioning.Mvc.ApiExplorer and Asp.Versioning.OpenApi), declare a versioned API with route groups per version, and let API Explorer group endpoints into v1 and v2 so the built-in OpenAPI support emits one document per version.
For deprecation I mark 1.0 as deprecated, so api-deprecated-versions is reported, and send the Deprecation header (RFC 9745, @epoch-seconds) and Sunset header (RFC 8594, HTTP-date) with a Link to the migration guide.
Both versions call the same handler; only the request and response DTOs and their mapping differ. The trade-off: every extra version is more mapping code and tests, so I keep the version count low and measure v1 traffic to know when to remove it.
How to tell it (STAR)
**S:** At [company], a field rename in our shared events package caused Billing to raise [$0] invoices and [9] teams to scramble a weekend redeploy. **T:** As [senior engineer on the platform team], I was asked to stop this from recurring. **A:** I had Ordering publish both the old and new field the same day so every consumer worked again, then proposed per-publisher contract packages with additive-only rules and versioned types in [an ADR], and added a schema-diff gate to publisher pipelines. Some teams preferred keeping the shared package for convenience, so I ran a [two-week] pilot with two services to show the effort. **R:** Over the next [30] contract changes we had zero consumer incidents, and no change required more than one service to deploy.
Last updated 23 Nov 2026.