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

📚 Interview question

How do you stop one service from breaking another when it changes its API or its messages? Explain consumer-driven contract testing with Pact (PactNet), how it differs from end-to-end tests, and the backward compatibility rules you follow for HTTP APIs and message schemas.

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.

Senior Theory Advanced api-versioning backward-compatibility contract-testing distributed-systems microservices pact

🎯 Key points

  • Consumer-driven contracts: each consumer records the requests it makes and the fields it relies on
  • PactNet 5 (5.0.0 October 2024, 5.0.1 March 2025; System.Text.Json, Pact spec v4): consumer tests run against a mock server and produce a pact file
  • Provider verification replays every consumer's pact against the real provider, with provider states for test data
  • Pact Broker / PactFlow in CI/CD: webhooks trigger provider verification, can-i-deploy gates releases, record-deployment tracks environments
  • Contract tests are fast and per-service; end-to-end tests are slow, flaky and need every service deployed
  • Safe changes: add optional fields, add endpoints, add enum values only if consumers tolerate unknowns
  • Breaking changes: remove or rename fields, change types or meaning, make optional required; need a new version and a deprecation period
  • Tolerant reader on the consumer side (System.Text.Json ignores unknown properties by default); for messages, version the schema and support old and new during the overlap

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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/42 I expect a 200 with an id, a status and a total that'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 removes total, its own build fails before it reaches any environment. And can-i-deploy asks 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."


Contract tests vs end-to-end tests

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

Compatibility rules (HTTP JSON)

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

Messages

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can keep independently deployed services compatible with tooling and rules, not hope.

Green flags

  • Explains consumer-driven contracts, provider verification and provider states
  • Mentions the broker and can-i-deploy as a deployment gate
  • Gives concrete safe vs breaking change rules, including enums and meaning changes
  • Treats messages with extra care (queued and replayed old versions)

Red flags

  • Relies only on end-to-end tests in a shared environment
  • Pacts that copy the whole response
  • "We just version the API every time something changes"

📚 Learn in depth

1. The problem contract tests solve

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.

2. The Pact flow

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:

  • Consumer-driven: the consumer specifies only what it uses, so the provider is free to change everything else.
  • Matchers: Match.Type, Match.Regex, Match.MinType say "a number", not "exactly 42.50", so tests aren't brittle.
  • Provider states: named setups ("order 42 exists") the provider implements, typically through a test-only endpoint or middleware.
  • can-i-deploy: the broker knows which versions are in which environment and which pairs verified; deployment is gated on that matrix.

3. PactNet today

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

4. Message contracts

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.

5. Compatibility in practice

  • Tolerant reader: deserialise only what you use; System.Text.Json ignores unknown properties by default (don't turn on JsonUnmappedMemberHandling.Disallow for external contracts).
  • Enums: deserialise unknown values safely (string enums with a fallback, or keep as string), and handle default in switches.
  • Parallel change (expand, migrate, contract): add the new field, have consumers move, then remove the old one after usage drops to zero, which the broker or telemetry can tell you.
  • Versioning: URL or header versions (Asp.Versioning.Http) for breaking HTTP changes; deprecation via Deprecation and Sunset headers.

6. Limits

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.

Try it yourself

  1. Write a PactNet consumer test for a typed HttpClient and look at the generated pact JSON.
  2. Write the provider verification with WebApplicationFactory hosting the real API on a local port and a provider-state middleware.
  3. Rename a response field in the provider and watch verification fail.
  4. Run a Pact Broker in Docker, publish both sides, and try pact-broker can-i-deploy.
  5. Add an unknown enum value to a response and check your consumer still deserialises it.

💻 Code

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

⚠ Common mistakes

  • Mistake: Writing the consumer pact with every field the provider returns. Why it is wrong: the provider can't change anything without failing verification. Instead: only the fields the consumer actually uses.
  • Mistake: Exact-value assertions instead of matchers. Why it is wrong: tests break on test data, not on contract changes. Instead: Match.Type, Match.Regex, Match.Integer.
  • Mistake: Treating contract tests as functional tests of the provider. Why it is wrong: pacts become huge and brittle. Instead: contracts check the interaction shape and key semantics; provider logic has its own tests.
  • Mistake: Publishing pacts by hand or without a broker, and never gating deployment. Why it is wrong: breaks are found after release, and nobody knows which consumer versions are in which environment. Instead: publish from CI to a Pact Broker or PactFlow, trigger provider verification by webhook, run can-i-deploy in both pipelines and record-deployment afterwards.
  • Mistake: Turning on strict deserialisation for external contracts. Why it is wrong: 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.
  • Mistake: Renaming a field in an event because "all consumers are ours". Why it is wrong: old messages remain in queues and dead-letter queues, and replays use old shapes. Instead: add the new field, migrate consumers, remove the old one later.
  • Mistake: Changing a field's meaning (e.g. total now includes GST). Why it is wrong: contract tests still pass and data silently goes wrong. Instead: new field or new version, documented.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares contract tests with integration or end-to-end tests Why: Checks they can place each test type in a strategy.
    How to answer

    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.

  2. When: Candidate mentions who owns a contract or sync vs async Why: Checks contract ownership and versioning at the architecture level.
    How to answer

    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.

  3. When: Candidate mentions message contracts Why: Checks they handle queued and replayed messages, not just live HTTP calls.
    How to answer

    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.

🛠 Real-world problems: how you handle them

A renamed field broke billing after an orders release
Situation
An [orders] API with [six] consuming services; releases [several times a day]. A shared end-to-end suite ran nightly in a test environment.
Signals
After an orders release, billing's invoice totals showed $0.00 for new orders; no errors, because `System.Text.Json` left the renamed `total` property at its default; the nightly end-to-end run had been red for days for unrelated reasons, so nobody noticed.
Investigation
Compared orders API responses before and after the release; traced the change to a PR that renamed `total` to `grandTotal`; checked which consumers read `total` by searching repos, which took a day and missed one.
Resolution
Immediate: restored `total` alongside `grandTotal` in a hotfix and re-ran the invoice job for affected orders. Real fix: PactNet consumer tests in billing and the other consumers, provider verification in the orders pipeline, and `can-i-deploy` as a release gate.
Prevention
Pact Broker with webhooks to trigger provider verification on new pacts; compatibility rules in the API guidelines (additive only, deprecation with `Sunset` headers); review checklist item for renames and meaning changes.

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

↩ Usually asked after

More in Microservices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me