TestingVol. 11 · Part XI
0 / 0

Shelves / Testing

TS·117

Contract Testing

Verifying that services agree on their interfaces without running them all together: the integration problem in distributed systems, consumer-driven contracts with Pact (consumer tests, pact files, provider verification, provider states, the broker and can-i-deploy), provider-driven and bi-directional contracts with OpenAPI, schema compatibility for events (Avro, Protobuf, JSON Schema with a schema registry), backward, forward and full compatibility rules, breaking-change detection (buf, oasdiff), and versioning and evolution strategies.

21 topics · ~16 min read · 30-question quiz
Updated Suggest a correction

Start here: two services agreeing without meeting

The kitchen display shows orders it fetches from the orders API. Two teams own the two services, and each deploys on its own schedule. How does the orders team know a change won't break the kitchen screen, without running both systems together in a shared test environment? A contract test answers that: the consumer writes down exactly what it needs, and the provider checks, in its own pipeline, that it still provides it.

Step 1: the consumer records what it needs

The kitchen display's test talks to a Pact mock provider and describes the interaction it relies on:

Python
(pact.upon_receiving("a request for order 101")
     .given("order 101 exists")
     .with_request("GET", "/orders/101")
     .will_respond_with(200)
     .with_body({"id": match.int(101),
                 "status": match.regex("cooking", regex="placed|cooking|ready|delivered"),
                 "items": match.each_like({"name": match.str("Dal Tadka")}),
                 "total_paise": match.int(25200)}))
Text
1 passed in 0.07s   →   pacts/kitchen-display-orders-api.json

The matchers say what matters: id must be an integer (not exactly 101), status one of four values, items a list of objects with a string name. The test passes only if the consumer's real client code handled that response, and it leaves behind a pact file, the contract.

Step 2: the provider verifies it

The orders team replays the pact against their real service. Three versions:

Text
v1 (current):                         VERIFIED
v2 (renamed total_paise → total{…}):  FAILED
    $ -> Actual map is missing the following keys: total_paise
v3 (added "eta_minutes": 25):         VERIFIED

Renaming a field the kitchen display reads would have broken it in production; the contract test caught it in the orders team's own build, with a diff showing exactly which key went missing. Adding a new field was fine, because the consumer didn't ask about it. v1 also returned two items where the pact's example had one, and still verified: each_like means "a list of things shaped like this", not "this exact list".

Why not just test them together?

An end-to-end environment with every service deployed at the right versions is slow, shared and often broken by someone else's change. Contract tests split the check into two fast, independent halves, each run by the team that owns the code. The provider state ("order 101 exists") tells the provider what data to set up before replaying each interaction.

How deep to go in contract testing

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain what a contract test is and why distributed systems need them
L2 Write a consumer Pact test and run provider verification with provider states
L3 Explain matchers, Postel's law, bi-directional and schema-based contracts, and message pacts
L4 Diagnose verification failures and decide whether a change is breaking, and for whom
L5 Design a contract workflow: a broker, can-i-deploy gates, versioning and environments
L6 Run contract testing as an organisation-wide practice for API evolution

The problem contract tests solve

In a system of many services, how do you know that a change to the orders API won't break the checkout front end, the invoicing service and a partner integration?

  • Unit tests with mocks verify each side against its own assumptions about the other side. Both can pass while the services disagree (the provider renamed total to amount).
  • End-to-end tests across all services catch disagreements but are slow, flaky, need every service deployed at compatible versions, and give late, vague feedback ("checkout journey failed").

Contract tests check the agreement between a consumer and a provider directly, with each side tested independently and quickly:

consumer testscode → Pact mockrecords interactions pact brokerpacts · results · envs provider verifyprovider statesreplay vs real API ① ② ③ ④ can-i-deploy?compatible with what's in prod? ① publish pact② fetch pacts③ results
Consumer-driven contract testing with Pact. The consumer's tests run against a Pact mock provider, which records the interactions the consumer relies on into a pact file. The pact is published to a broker. The provider's build fetches the pacts of all its consumers and replays them against the real provider, setting up provider states first. Results go back to the broker, which answers 'can I deploy this version?' for either side.

Contract tests are not functional tests of the provider: they verify that the shape and semantics the consumer depends on are honoured, not every business rule.

Consumer-driven contracts

In consumer-driven contract testing (CDCT), each consumer declares what it needs from a provider, and the provider verifies it satisfies all its consumers. Benefits: providers learn exactly which fields and endpoints are used (and can safely remove unused ones); breaking changes are caught in the provider's CI before deployment.

Pact is the most widely used tool (implementations for JVM, JavaScript/TypeScript, Go, Python, Rust, .NET, Ruby, PHP, Swift; HTTP and asynchronous message interactions; plugins for gRPC/Protobuf). Spring Cloud Contract is a JVM alternative (contracts defined by the provider in Groovy/YAML, generating tests and stubs).

Consumer side

The consumer's test describes an interaction (given a provider state, upon receiving a request, the provider responds with…) and exercises the consumer's real client code against Pact's mock server. Use matchers so the contract specifies types and formats, not exact example values:

// TypeScript consumer test (Pact JS V4 API)
import { PactV4, MatchersV3 } from "@pact-foundation/pact";
const { like, eachLike, regex } = MatchersV3;

const provider = new PactV4({ consumer: "checkout-web", provider: "orders-api" });

test("fetches an order", async () => {
  await provider
    .addInteraction()
    .given("order o-123 exists")
    .uponReceiving("a request for order o-123")
    .withRequest("GET", "/orders/o-123", (b) => b.headers({ Accept: "application/json" }))
    .willRespondWith(200, (b) =>
      b.jsonBody({
        id: like("o-123"),
        status: regex("PLACED|PAID|SHIPPED", "PLACED"),
        totalCents: like(4999),
        items: eachLike({ sku: like("book-1"), qty: like(1) }),
      }))
    .executeTest(async (mock) => {
      const order = await new OrdersClient(mock.url).get("o-123");   // real client code
      expect(order.totalCents).toBe(4999);
    });
});
// Generates pacts/checkout-web-orders-api.json

Good consumer contracts:

  • Include only what the consumer actually uses (Postel's law: be conservative in what you send, liberal in what you accept; consumers should ignore unknown fields).
  • Use type matchers rather than exact values, so the provider can return different data.
  • Cover important variations: not found (404), validation errors, empty lists.
  • Don't encode provider business rules ("a gold customer gets 10% off"); test those in the provider's own tests.

Provider side

The provider's CI fetches all consumer pacts (for the relevant branches/environments) from the broker and replays each request against the real provider (running locally with its real code, test database, stubbed downstreams), comparing actual responses to the contract:

Java
// Provider verification (Pact JVM with Spring Boot)
@Provider("orders-api")
@PactBroker   // url and auth from config; consumer version selectors pick main/deployed pacts
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrdersApiPactVerificationTest {
    @LocalServerPort int port;
    @Autowired OrderRepository orders;

    @BeforeEach
    void target(PactVerificationContext ctx) { ctx.setTarget(new HttpTestTarget("localhost", port)); }

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void verify(PactVerificationContext ctx) { ctx.verifyInteraction(); }

    @State("order o-123 exists")                 // provider state: arrange data for the interaction
    void orderExists() { orders.save(Order.placed("o-123", 4999)); }
}

Provider states let consumers describe preconditions ("order o-123 exists", "user has no orders"); the provider implements a setup hook for each state name.

The broker and can-i-deploy

A Pact Broker (open source) or PactFlow (hosted) stores pacts and verification results, tagged with application versions (Git SHAs), branches and environments (records of what's deployed where). This enables:

  • Webhooks: when a consumer publishes a changed pact, trigger the provider's verification build.
  • can-i-deploy: before deploying version X of a service to production, ask whether it has been verified compatible with the versions of its consumers/providers currently in production:
Shell
pact-broker can-i-deploy --pacticipant orders-api --version "$GIT_SHA" --to-environment production
# then after deploying:
pact-broker record-deployment --pacticipant orders-api --version "$GIT_SHA" --environment production
  • Pending pacts and WIP pacts: new consumer expectations don't break the provider's build until the provider has verified them once, so consumers can't block provider teams.

Provider-driven and bi-directional contracts

Consumer-driven contracts need cooperation from both teams. Alternatives:

  • Provider-driven contracts: the provider publishes a specification (OpenAPI, AsyncAPI, Protobuf, GraphQL schema) as the contract, verified against the implementation (schema-validated tests, Schemathesis/Dredd to fuzz and check the API against its spec). Consumers generate clients from it. Works well for public APIs with unknown consumers.
  • Bi-directional contract testing (PactFlow): the provider uploads its OpenAPI spec plus evidence it's verified; consumers upload pacts (or mocks generated from their tests); the broker statically compares consumer expectations against the provider spec. Less setup, slightly weaker guarantees (the spec might not match the implementation exactly unless the provider verifies it).

Schema compatibility

Compatibility directions

For APIs and especially events (where producers and consumers deploy independently and old messages persist in topics), you need precise compatibility rules:

Type Definition Lets you…
Backward compatible New readers can read data written by old writers Upgrade consumers first
Forward compatible Old readers can read data written by new writers Upgrade producers first
Full Both Upgrade in any order
Transitive variants Compatibility holds with all previous versions, not just the last one Replay old data from long-retention topics
producer v1 message v1 consumer v2 backward: new reader, old data → upgrade consumers first producer v2 message v2 consumer v1 forward: old reader, new data → upgrade producers first safe: add optional field with default · breaking: rename, retype
Backward and forward compatibility for a message schema evolving from v1 to v2. Backward compatibility means a consumer upgraded to v2 can still read v1 messages, so consumers can be deployed first; forward compatibility means a consumer still on v1 can read v2 messages, so producers can be deployed first. Adding an optional field with a default is safe in both directions.

Rules by format

Change JSON (tolerant readers) Avro Protobuf
Add optional field Safe if consumers ignore unknown fields Safe with a default Safe (new field number)
Remove field Breaks consumers that read it Safe only if it had a default (for backward) Safe if number/name are reserved and consumers tolerate absence
Rename field Breaking Use aliases Wire-safe (numbers matter, not names) but breaks JSON mapping and generated code
Change type Breaking Only allowed promotions (int → long) Only compatible wire types; generally avoid
Add enum value Old consumers may fail on unknown values Breaking for old readers unless a default enum symbol is set Unknown values preserved as numbers; code must handle them
Make optional → required Breaking Breaking required doesn't exist in proto3 for this reason

Protobuf rules of thumb: never reuse or change field numbers, reserved removed numbers and names, add new fields rather than changing old ones. Avro needs the writer's schema to read data (schema registry provides it by ID in each message).

Schema registries and automated checks

  • Schema registries (Confluent Schema Registry, Apicurio, AWS Glue Schema Registry, Redpanda's built-in registry) store versions of each subject's schema and reject incompatible registrations according to the configured mode (BACKWARD, FORWARD, FULL, *_TRANSITIVE). Run the compatibility check in CI (mvn schema-registry:test-compatibility, registry REST API) before merging.
  • Protobuf: buf breaking --against '.git#branch=main' detects wire- and source-breaking changes; buf lint enforces style.
  • OpenAPI: oasdiff breaking base.yaml revision.yaml (or openapi-diff) flags removed endpoints, new required parameters, narrowed types.
  • GraphQL: schema checks against real client operations (GraphOS/Hive/Inigo schema checks, graphql-inspector), so a field is only "breaking" if someone actually queries it.
  • AsyncAPI describes event-driven APIs (channels, messages) like OpenAPI does for HTTP.
Shell
# Fail the PR if the protobuf change is breaking relative to main
buf breaking --against '.git#branch=main'

# Fail the PR on breaking OpenAPI changes
oasdiff breaking --fail-on ERR api/openapi.main.yaml api/openapi.yaml

Versioning and evolution strategies

When a breaking change is unavoidable:

  1. Expand and contract (parallel change): add the new field/endpoint alongside the old one; migrate consumers (tracked via contracts and usage metrics); remove the old one only when nobody uses it. The same pattern applies to database schemas (Vol. 4).
  2. Versioned endpoints or media types (/v2/orders, Accept: application/vnd.acme.order.v2+json) for public APIs, with deprecation headers (Deprecation, Sunset RFC 8594) and timelines.
  3. New topics/event types for incompatible event changes (order-placed.v2), with producers dual-writing during migration.
  4. Tolerant readers: consumers ignore unknown fields and handle unknown enum values gracefully, which makes many changes non-breaking in practice.

Contract tests tell you who a change breaks; usage telemetry (which clients call which fields) tells you when it's safe to remove something.

Lab: a consumer-driven contract, end to end

pact-python 4.2.0 (the Rust-based Pact core, specification V4) and two small Python services on the lab machine. The consumer is the kitchen display's client; the provider is a stub orders API with three versions. Pact Broker is not used here (the pact file is passed through the file system), which is the one part of a real workflow the lab leaves out.

Experiment 1: the consumer test

Python
def get_order(base, order_id):
    with urllib.request.urlopen(f"{base}/orders/{order_id}") as r:
        d = json.load(r)
    return {"id": d["id"], "status": d["status"],
            "items": [i["name"] for i in d["items"]], "total": d["total_paise"] / 100}
Text
1 passed in 0.07s
pacts/kitchen-display-orders-api.json:
  consumer kitchen-display, provider orders-api
  "a request for order 101", given "order 101 exists"
  request  GET /orders/101
  response body {"id": 101, "items": [{"name": "Dal Tadka"}], "status": "cooking", "total_paise": 25200}
  + matching rules (integer, regex placed|cooking|ready|delivered, each-like, string, integer)

Notice what the consumer doesn't ask for: the provider's other fields, headers it ignores, or the exact number of items. A good consumer contract is the minimum the client actually reads; asserting on more makes the provider unable to change anything.

Experiment 2: verifying three provider versions

Python
Verifier("orders-api", host="127.0.0.1") \
    .add_transport(url="http://127.0.0.1:8171") \
    .add_source("pacts") \
    .state_handler("http://127.0.0.1:8171/_pact/state", body=True) \
    .verify()
Text
v1  has status code 200 (OK), Content-Type (OK), has a matching body (OK)   → VERIFIED
v2  has a matching body (FAILED)
      $ -> Actual map is missing the following keys: total_paise
      - "total_paise": 25200
      + "total": {"amount": 25200, "currency": "INR"}                        → FAILED
v3  extra field eta_minutes                                                 → VERIFIED

Each verification took 6–7 ms. Before each interaction the verifier POSTs the provider state to the state-handler URL, and the provider seeds order 101. Two setup lessons from building this lab: the verifier must be told the same host as the transport (host="127.0.0.1", or it refuses with Host mismatch: 127.0.0.1 != localhost), and the provider subprocess must be stopped in a finally block, or a failed verification leaves it running and the test run never exits.

Experiment 3: shipping v2 safely

The v2 change is legitimate (money as an object with a currency), so how does it ship? Expand and contract:

  1. Provider adds total alongside total_paise (an additive change: verifies, deploys).
  2. Consumer switches to total.amount, and its new pact no longer mentions total_paise.
  3. Once every consumer's latest pact in production has stopped using total_paise, the provider removes it, and verification proves no one still depends on it.

With a Pact Broker, step 3 is automated: pact-broker can-i-deploy --pacticipant orders-api --version <sha> --to-environment production checks the provider version against every consumer version deployed there, and blocks the deploy if any verification is missing or failing.

Try it yourself

  1. Change the consumer's matcher for status to an exact value ("cooking"). Which harmless provider change now breaks verification?
  2. Add a second interaction, "order 999 does not exist" → 404, with its own provider state.
  3. Write a message pact for an order.placed event on a queue, so the kitchen consumer and the orders producer agree on the event's shape.
  4. Compare with a schema contract: generate an OpenAPI spec for the provider and run Schemathesis against it. What does each approach catch that the other misses?

Revision sheet: contract testing

Key ideas

  • Problem: independently deployed services must agree on interfaces; shared E2E environments are slow and brittle.
  • Consumer-driven contracts (Pact): consumer tests against a mock provider produce a pact; the provider verifies it against the real service with provider states.
  • Matchers capture shape and type, not incidental values; consumers ask for the minimum they use.
  • Postel's law: be liberal in what you accept (ignore unknown fields); additive changes are safe.
  • Broker workflow: publish pacts with versions and branches; record deployments; can-i-deploy gates releases; webhooks trigger provider verification when a pact changes.
  • Variants: message pacts for events; bi-directional contracts (provider's OpenAPI vs consumer pacts); schema-first contracts with OpenAPI/AsyncAPI/protobuf plus breaking-change checks (buf breaking, oasdiff).
  • Evolution: expand and contract; version only when you must.

Numbers to remember

  • Lab: consumer test 0.07 s; each provider verification 6–7 ms.
  • Lab: rename of one field → FAILED with a key-level diff; added field → VERIFIED.

Pitfalls

  • Consumers asserting on every field and exact values, freezing the provider.
  • Using contract tests as functional tests of provider business logic.
  • Provider verification not run on every provider change (or not gating deploys).
  • Pacts not versioned by consumer branch and environment.
  • Strict deserialisers that reject unknown fields, making additive changes breaking.

Glossary

  • Pact: the contract file of interactions.
  • Mock provider: Pact's stand-in the consumer test calls.
  • Provider state: named setup the provider performs before an interaction.
  • Pact Broker / PactFlow: service storing pacts and verification results.
  • can-i-deploy: check that a version is compatible with what's deployed in an environment.