Consumer-driven contract testing with PactNet for HTTP and messages, the Pact Broker and can-i-deploy, comparison with end-to-end tests, and concrete backward compatibility rules for JSON APIs and events.
Use consumer-driven contract tests: each consumer writes a test that records the requests it makes and only the fields it relies on, producing a pact file (PactNet 5.x, Pact specification v4). The provider's pipeline replays every consumer's pact against the real service, and the Pact Broker's can-i-deploy blocks a release that would break a consumer in that environment. Unlike end-to-end tests, they run in seconds per service without deploying everything. Pair them with compatibility rules: additive changes only (new optional fields, new endpoints), tolerant readers that ignore unknown fields, and a new version plus a deprecation period for anything breaking. The trade-off: contract tests catch shape and semantics you encode, not every behaviour, so keep a few journey-level smoke tests.
"The root problem is that the provider can't see who depends on which field. Consumer-driven contract testing fixes that: each consumer writes a test against a Pact mock server that says 'when I call
GET /orders/42I expect a 200 with anid, astatusand atotalthat's a number'. Running that test produces a pact file, which is published to a Pact Broker. The provider's pipeline then pulls every consumer's pact and replays the requests against the real provider, using provider states like 'order 42 exists' to set up data. If the provider removestotal, its own build fails before it reaches any environment. Andcan-i-deployasks the broker whether this version has verified contracts with every consumer currently in production.For example, at [company] we had [N] consumers of an orders API, and end-to-end tests in a shared test environment took [40 minutes] and failed for unrelated reasons about a third of the time. I introduced PactNet on the [two most critical] consumers first. Within [a quarter], the provider caught [a renamed field] in its own PR, and we cut the shared end-to-end suite down to [a handful of] journey smoke tests.
Contracts only help if you also follow compatibility rules. Additive changes are safe: new optional fields, new endpoints. Removing, renaming, changing a type or meaning, or making an optional field required is breaking, and needs a new version running alongside the old one until consumers have moved. On the consumer side I insist on tolerant readers that ignore unknown fields and unknown enum values. Messages get the same treatment, with even more care, because old messages sit in queues and get replayed. The mistake I see is versioning by policy but never knowing who uses what; contracts give you the facts."
| Consumer-driven contract tests | End-to-end tests | |
|---|---|---|
| What runs | One service + a mock or its pact | All services deployed together |
| Speed | Seconds to minutes | Tens of minutes |
| Flakiness | Low | High (data, timing, other teams' bugs) |
| What they catch | Shape and agreed behaviour of each interaction | Whole journeys, configuration, wiring |
| Who breaks the build | The provider, in its own pipeline | Whoever runs the shared suite |
| Scales with services | Linearly | Badly |
| Change | Safe? | Notes |
|---|---|---|
| Add optional response field | Yes | Consumers must ignore unknown fields |
| Add optional request field | Yes | Provider defaults it |
| Add endpoint | Yes | |
| Add enum value | Only with tolerant consumers | Otherwise deserialisation or switch statements fail |
| Remove or rename field | No | New version, deprecate old with Deprecation/Sunset headers |
| Change type or format (int → string, date format) | No | |
| Make optional request field required | No | |
| Change meaning of a field | No, and the worst kind | Contract test may still pass; document and version |
| Rule | Why |
|---|---|
Version in the message (type name or schemaVersion) |
Consumers can branch or upcast |
| Add fields, don't remove, during an overlap | Old messages are still in queues and DLQs |
| Producers publish both versions, or consumers accept both, during migration | Independent deployment |
| Use Pact message pacts or a schema registry with compatibility checks | Automated gate |
After adding contract tests for the [orders] API's [six] consumers, provider PRs that would have broken a consumer were caught in ~4 minutes of CI instead of in the shared test environment days later, and the shared end-to-end suite went from [45] tests and ~40 minutes to [8] smoke tests and ~6 minutes.
Checks whether the candidate can keep independently deployed services compatible with tooling and rules, not hope.
Green flags
Red flags
A provider has N consumers, each using a subset of its fields. Without contracts, the provider either never changes anything (fear) or breaks someone (surprise). End-to-end tests try to catch this by deploying everything, which gets slower and flakier with every service.
Consumer CI Pact Broker Provider CI
----------- ----------- -----------
unit test vs Pact mock server
-> pact file (JSON) ---------> stores pact for
(consumer, version, branch)
| webhook / fetch
+--------------------> replay each interaction
against the real provider
(provider states set data)
<---- verification result --- pass/fail per pact
can-i-deploy --to-environment production ? (both sides ask before releasing)
record-deployment after release
Key ideas:
Match.Type, Match.Regex, Match.MinType say "a number", not "exactly 42.50", so tests aren't brittle.As of late 2026 the current major version is PactNet 5 (5.0.0 released October 2024, 5.0.1 in March 2025). Version 5 replaced Newtonsoft.Json with System.Text.Json and added Pact specification v4 support; it wraps the Rust Pact core, so it runs on Windows, Linux and macOS. It supports HTTP interactions and message interactions (for queues and events).
For asynchronous messages, the consumer test describes the message it can handle and calls its real handler with it; the provider verification asks the provider to produce that message (through a function that builds it with the real serialiser) and compares. This catches the classic break: a producer renames a property in an event and every consumer silently gets null.
Alternatives: Avro, Protobuf or JSON Schema with a schema registry (Confluent Schema Registry, Azure Event Hubs schema registry) set to BACKWARD or FULL compatibility, which rejects incompatible schemas at publish time.
System.Text.Json ignores unknown properties by default (don't turn on JsonUnmappedMemberHandling.Disallow for external contracts).default in switches.Asp.Versioning.Http) for breaking HTTP changes; deprecation via Deprecation and Sunset headers.Contract tests check the interactions the consumer wrote down. They don't test performance, auth configuration, network wiring or full journeys. Keep a thin layer of smoke tests in a deployed environment.
HttpClient and look at the generated pact JSON.WebApplicationFactory hosting the real API on a local port and a provider-state middleware.pact-broker can-i-deploy.Consumer test with PactNet 5: the consumer states what it needs, and the test produces a pact file.
namespace Billing.ContractTests;
using System.Net;
using PactNet;
using PactNet.Matchers;
using Xunit;
public sealed class OrdersApiConsumerTests
{
private readonly IPactBuilderV4 _pact = Pact.V4("billing-api", "orders-api", new PactConfig
{
PactDir = Path.Combine("..", "..", "..", "pacts")
}).WithHttpInteractions();
[Fact]
public async Task Gets_an_order_with_the_fields_billing_uses()
{
_pact.UponReceiving("a request for an existing order")
.Given("order 42 exists")
.WithRequest(HttpMethod.Get, "/orders/42")
.WillRespond()
.WithStatus(HttpStatusCode.OK)
.WithJsonBody(new
{
// Only what billing reads. Matchers: type, not exact values.
id = Match.Integer(42),
status = Match.Regex("Completed", "^(Pending|Completed|Cancelled)$"),
total = Match.Decimal(129.95m)
});
await _pact.VerifyAsync(async ctx =>
{
var client = new OrdersClient(new HttpClient { BaseAddress = ctx.MockServerUri });
var order = await client.GetAsync(42, CancellationToken.None);
Assert.Equal(129.95m, order!.Total);
});
}
}
public sealed record OrderDto(int Id, string Status, decimal Total);
public sealed class OrdersClient(HttpClient http)
{
public Task<OrderDto?> GetAsync(int id, CancellationToken ct) =>
http.GetFromJsonAsync<OrderDto>($"/orders/{id}", ct);
}
// Provider verification: replays every consumer's pact from the broker against the real API.
using PactNet.Verifier;
[Fact]
public void Orders_api_honours_its_consumers_contracts()
{
// The API is started on a real port (e.g. a Kestrel host built from Program), with a
// /provider-states endpoint that seeds data for states like "order 42 exists".
using var verifier = new PactVerifier("orders-api");
verifier.WithHttpEndpoint(new Uri("http://localhost:5199"))
.WithPactBrokerSource(new Uri("https://pact-broker.internal"), o => o
.ConsumerVersionSelectors(new ConsumerVersionSelector { DeployedOrReleased = true },
new ConsumerVersionSelector { MainBranch = true })
.PublishResults(Environment.GetEnvironmentVariable("GIT_SHA")!))
.WithProviderStateUrl(new Uri("http://localhost:5199/provider-states"))
.Verify();
}
# Gate the release on verified contracts with everything already in production.
pact-broker can-i-deploy --pacticipant orders-api --version "$GIT_SHA" --to-environment production
Match.Type, Match.Regex, Match.Integer.can-i-deploy in both pipelines and record-deployment afterwards.System.Text.Json ignores unknown properties by default, but setting JsonUnmappedMemberHandling.Disallow or failing on unknown enum values makes a new optional field or enum value a breaking change. Instead: tolerant readers; map unknown enum values to a fallback.Contract testing is as much a communication tool as a testing tool: the broker shows the provider exactly which consumers use which fields, so deprecations become data-driven. The cost is real: provider states need maintenance, and teams need a broker and pipeline integration. Introduce it on the most-changed, most-consumed interfaces first rather than everywhere.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Consumer-driven contracts (Pact) | Several teams, known consumers, HTTP or messages | Broker, provider states, discipline | Public APIs with unknown consumers |
| Provider-driven (OpenAPI diff, schema checks) | Public or many unknown consumers | Doesn't know actual usage | When you need to know who breaks |
| Schema registry compatibility | Kafka/Event Hubs with Avro/Protobuf | Registry ops | Ad-hoc JSON over HTTP |
| End-to-end tests | A few critical journeys | Slow, flaky, shared environments | As the main safety net |
Measure: breaking changes caught in CI vs found in test or production, and time spent on shared end-to-end suites.
A consumer-driven contract test checks one consumer-provider pair in isolation. The consumer's tests run against a Pact mock and record what it actually uses; the provider replays those expectations against its real code (dependencies stubbed) in its own CI. Because the provider must keep passing every consumer's contract, it can evolve and version its API without silently breaking anyone, which preserves team autonomy.
An end-to-end test deploys many services together and drives a real user journey. It catches wiring, configuration and infrastructure problems contract tests can't, but it needs a shared environment, runs for minutes, fails for unrelated reasons and slows every deployment pipeline that waits on it.
So: a contract test for every consumer-provider pair as the main safety net, and only a handful of end-to-end smoke tests for the few journeys that make money. The trade-off is fast, precise feedback versus realistic but slow, flaky coverage.
A contract is the only surface others may depend on: a module's public interface, an HTTP or gRPC API, or an event schema. I choose synchronous calls when the caller needs an answer to continue, and asynchronous messages when it doesn't, because messages decouple availability and absorb load spikes.
The provider owns the contract but designs it from consumer needs; for events, the publisher owns the schema. To change safely I use consumer-driven contract tests (Pact): each consumer records what it relies on, and the provider's pipeline verifies those expectations before deploying.
Versioning rule: additive changes by default, tolerant readers, and an explicit new version with a deprecation window only for breaking changes.
The trade-off: sync is simpler but couples availability; async is resilient but harder to trace and reason about.
Make changes additive where possible, so one schema serves both. When a breaking change is unavoidable, give the event a version (in the type name or a schemaVersion field), have consumers accept both (or upcast old to new on read) before producers switch, and keep old-version support until no old messages remain in queues, dead-letter queues or replayable logs. A schema registry with BACKWARD or FULL compatibility can enforce this at publish time.
How to tell it (STAR)
**S:** At [company], an [orders] API release renamed one field, and billing quietly produced invoices with zero totals for [a few hours]. **T:** I was asked to fix the data and make sure a provider change couldn't silently break consumers again. **A:** We hotfixed the field back and re-ran invoicing. Then I introduced PactNet: billing and the other consumers wrote tests for just the fields they use, the orders pipeline verified every pact from a broker, and can-i-deploy gated releases. **R:** In the next [quarter] the provider caught [three] breaking changes in its own PRs, and we cut the nightly end-to-end suite from [~40 minutes] to [~6].
Last updated 23 Nov 2026.