📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you design and evolve integration event contracts between .NET services? Explain schema versioning, the CloudEvents envelope, who owns a contract, and why a shared NuGet library of event classes used by every service causes coupling.

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.

Mid-Level Theory Intermediate architecture cloudevents contracts integration-events messaging schema-versioning

🎯 Key points

  • The publisher owns the contract; consumers depend on it like a public API
  • Within a version: add optional (nullable or defaulted) fields only; never add a required field, rename, remove, retype or change meaning
  • Required vs optional: a field consumers must have can't be introduced mid-version (old messages in queues lack it); making a required field optional is a two-step change with consumers updated first
  • Tolerant reader: System.Text.Json ignores unknown JSON properties by default; consumer DTOs keep only needed fields, nullable or defaulted, and avoid C# required members for fields that may be absent
  • Breaking change = new event type or version (order-placed.v2), publish both during migration, deprecate with a date
  • CloudEvents envelope: id, source, type, specversion, time, dataschema; maps to Service Bus message id and application properties
  • Per-publisher contract packages (or JSON Schema) instead of one shared events library that couples release cycles
  • Verify with schema compatibility checks or consumer-driven contract tests (Pact) in CI

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, time and optionally dataschema and subject. On Azure Service Bus I map those to the message id and application properties, so subscriptions can filter on type, consumers dedup on id, 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.Events NuGet 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 classification

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

Contract distribution options

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate treats integration events as owned, versioned public contracts and understands the coupling risks of shared libraries.

Green flags

  • Publisher ownership and tolerant readers
  • Clear safe vs breaking change rules; side-by-side versions with deprecation
  • Knows the CloudEvents attributes and how they map to Service Bus
  • Explains why a shared events library couples services
  • Mentions CI compatibility checks or consumer-driven contracts

Red flags

  • "Just update the shared package and redeploy everyone"
  • Versioning by editing classes in place
  • Publishing domain entities as events

📚 Learn in depth

1. Contracts are owned, not shared

+--------------------+   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.

2. Compatibility directions, and required vs optional fields

  • Backward compatible: new consumers can read old messages (important: queues and dead-letter queues hold old messages for days).
  • Forward compatible: old consumers can read new messages (tolerant reader).

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:

  1. Announce it; mark the property obsolete in the contracts package.
  2. Consumers change their DTO to nullable and handle the missing case; verify with contract tests.
  3. Only after every subscription's consumers are updated (track by subscription and consumer version), the publisher stops populating it.
  4. Remove it in the next major version.

System.Text.Json specifics for tolerant readers:

  • Unknown JSON properties are ignored by default, so old consumers survive added fields. Don't turn on JsonUnmappedMemberHandling.Disallow in consumers.
  • Missing JSON properties leave the C# property at its default, unless it is a C# 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.

3. CloudEvents on Azure Service Bus

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.

4. Versioning strategies

  1. Additive optional changes inside a version (default).
  2. New type name with version suffix for breaking changes; publish both from the outbox during migration.
  3. Upcasting at the consumer when the consumer wants one internal model for v1 and v2.
  4. Deprecation: announce, track which subscriptions still consume v1 (Service Bus metrics per subscription), remove after the date.

5. Guarding contracts in CI

  • Generate JSON Schema from contract records and diff against the last published schema; fail on breaking changes (new required fields, removals, type changes).
  • Consumer-driven contracts (Pact supports message pacts): consumers publish expectations, the publisher's build verifies them.
  • Keep sample messages per version as test fixtures; consumers deserialise them in unit tests.
  • Document with AsyncAPI for discoverability.

6. What goes in the payload

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).

Try it yourself

  1. Write OrderPlacedV1 as a record, serialise a sample, add an optional field, and confirm an old consumer still deserialises the new message.
  2. Add a required property to a consumer DTO and deserialise an old message: watch it throw, then make it nullable.
  3. Rename a field and watch the consumer silently get null; then add a schema-diff check that fails the build.
  4. Publish a CloudEvent to the Service Bus emulator in binary mode and create a subscription SQL filter on the type property.
  5. Set up a Pact message contract between a publisher and consumer project.

💻 Code

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;
    }
}

⚠ Common mistakes

  • Mistake: One shared events NuGet package for all services. Why it is wrong: couples release cycles, forces lockstep upgrades and attracts shared domain code. Instead: per-publisher contracts packages or JSON Schema.
  • Mistake: Renaming or retyping a field in place. Why it is wrong: old messages still sit in queues and old consumers break or silently read null. Instead: additive optional changes only; breaking changes become a new versioned type.
  • Mistake: Adding a new required field to an existing version. Why it is wrong: messages already queued, and any still produced by older publisher instances during a rolling deploy, don't have it. Instead: add it as optional, or introduce a new version.
  • Mistake: Strict deserialisation on consumers (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.
  • Mistake: Publishing domain classes or EF entities as events. Why it is wrong: internal refactors become breaking changes and data leaks. Instead: dedicated contract records.
  • Mistake: Removing v1 as soon as v2 ships. Why it is wrong: consumers on v1 and backlog messages break. Instead: publish both, track v1 consumers, deprecate with a date.
  • Mistake: Changing the meaning or unit of a field (cents to dollars, local time to UTC) without changing its name or version. Why it is wrong: the structure is unchanged, so deserialisation succeeds and no test catches it, but every consumer now computes wrong values: invoices 100 times too large, or reports shifted by ten hours. Instead: a new field with an explicit name (TotalMinorUnits) or a new version, documented in the schema.
  • Mistake: No compatibility checks in CI. Why it is wrong: breaking changes are found in production. Instead: schema diffing or consumer-driven contract tests.
  • Mistake: Stuffing PII into events "in case". Why it is wrong: copies personal information to every consumer, widening breach impact under the NDB scheme. Instead: minimum necessary data; ids and lookups for the rest.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says contracts must not expose domain types. Why: Checks they separate internal domain events from published contracts.
    How to answer

    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.

    • Domain events are dispatched inside the unit of work (just before or as part of SaveChanges), so their side effects commit or roll back together.
    • Integration events must only leave after the commit. You write them to an outbox table in the same transaction, and a relay publishes them to Azure Service Bus.

    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.

  2. When: Candidate compares event contracts to public APIs. Why: Checks they apply the same versioning discipline as HTTP APIs.
    How to answer

    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.

🛠 Real-world problems: how you handle them

A field rename in a shared events package breaks consumers reading backlog
Situation
A [retail] estate of [14] .NET services referenced one shared `Company.Events` package. The Ordering team renamed `Amount` to `Total` on `OrderPlaced` and bumped the package.
Signals
Billing started creating invoices for [$0]; Service Bus dead-letter counts rose on the warehouse subscription; [9] teams were asked to redeploy the same weekend; consumers that hadn't upgraded deserialised null.
Investigation
Compared message bodies in the dead-letter queue with consumer DTOs; checked which services referenced which package version in the dependency graph; correlated the first [$0] invoice with the Ordering deployment in Application Insights release annotations.
Resolution
Immediate: Ordering restored `Amount` and kept populating both `Amount` and `Total` with the same value, so old and new consumers both worked; DLQ messages were resubmitted once consumers could read them; Billing re-processed affected orders from the outbox history. Then, to make compatibility hold in practice: froze the v1 schema (both fields kept, `Total` documented as the preferred one), added a schema-diff gate to Ordering's pipeline that fails on removals, renames and new required fields, gave consumers sample v1 messages as test fixtures, and tracked each subscription's consumer version until all had moved to `Total` before planning `Amount`'s removal in v2 with a [90-day] notice. Longer term: split the shared package into per-publisher contract packages and adopted CloudEvents type names.
Prevention
Schema-diff check in each publisher's CI; sample message fixtures per version in consumer tests; an event catalogue documented in AsyncAPI; a deprecation policy of [90] days with tracked consumers.

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.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me