Consumer-Driven Contract Testing With Pact

Pact turns consumer needs into contracts that gate deployments.

Cover illustration for “Consumer-Driven Contract Testing With Pact”

Consumer-driven contract testing with Pact fills the gap between unit tests that run on their own and end-to-end tests that cost a lot to run. Its answer is to turn what consumers actually need into machine-readable contracts that providers verify against real code. With those results wired into deployment gates, a breaking API change becomes a failed pipeline before it can surprise the team downstream.

The integration-test gap that unit tests and E2E tests leave open

It is 2 a.m., and a downstream consumer breaks because a provider team renamed a field. All the provider’s tests were green. Its unit tests proved only that its code worked with mocked collaborators. The mock was a very agreeable witness.

End-to-end tests can expose that mismatch, but they require the services to run together in a shared environment. In a large organisation, a full run can take 30–60 minutes, with flaky tests and maintenance costs attached. Teams often get the results after the breaking change has merged. Contract testing checks the integration boundary instead, testing the consumer’s request and the provider’s response on their own, in their own pipelines, at unit-test speed.

What consumer-driven contracts mean, and how Pact's two-phase model works

With a provider-driven approach such as OpenAPI, the API owner defines the specification. With Pact, clients define what they need. A consumer describes a request and the response fields and types it actually reads, leaving the provider free to add fields or change unused parts of its response.

First, consumer tests run against a Pact mock server, which records the requests and the responses they expect. Then a provider verifier replays those requests against the real service and checks the responses against the recorded expectations. Neither service needs the other running during its tests. The shared artifact is the pact file, a JSON contract that makes the two phases independent.

Writing the consumer test: mock server, interactions, and the pact file it produces

For a Node.js consumer, setup starts with npm install @pact-foundation/pact --save-dev. Pact supports other languages too, so this choice does not bind the provider to JavaScript. The current JavaScript API uses PactV4 and MatchersV3. The consumer and provider names identify the contract relationship.

For a user-by-ID interaction, the test first declares that a user with the given ID exists through .given(). It describes the interaction with .uponReceiving(), defines the request through .withRequest(), and supplies the expected response through .willRespondWith(). The real consumer client then calls Pact’s mock server. Finally, the test asserts that the client handles the response correctly, rather than merely checking that the mock returns what the test told it to return.

Matchers are the most important habit to form. An exact expectation of “Jane Doe” forces that value into the agreement, while like() checks the type instead. Other matchers include eachLike() for array elements, regex() for string patterns, and integer() for integers. Only fields the client reads belong in the expectation. When the test passes, Pact writes JSON containing the interactions, matching rules, provider states, consumer and provider names, and metadata to the configured directory.

Provider states: the setup work that makes verification reproducible

The user-by-ID request needs a user to exist. That precondition is a provider state, and the consumer’s .given() string must map exactly to a handler in the provider’s verification setup. The provider owns that setup code. It must be reproducible and idempotent, so running it twice produces the same result.

That promise is hard to keep when tests share staging data. A state that depends on an external database or uncontrolled mutations can fail for reasons unrelated to compatibility. The practical approach is to use in-memory stubs or seed scripts scoped to the test run, avoiding complex mutations and external data dependencies. Well-defined states make the next step, provider verification, reliable.

Running provider verification: replaying the pact against real code

The provider imports Verifier from @pact-foundation/pact and configures it with a local pact file or broker location, the running provider service, and the state handlers. Before each recorded HTTP request, the verifier establishes its required state. It then sends the request to the real provider and checks the response against the pact’s matching rules.

If a field is renamed, a status code changes, or a required field is missing, the provider’s own CI can now fail before the change reaches a shared environment. The consumer does not need to be running. A provider with several consumers must satisfy their contracts together, and publishing verification results to a broker makes that compatibility information available beyond its pipeline.

The Pact Broker: storing contracts, tracking versions, and enabling deployment gating

The Pact Broker turns exchanged files into a compatibility record. It stores pacts, verification results, consumer and provider versions, environment assignments, and deployment metadata. Consumers publish contracts after their tests pass, and providers fetch them during CI. That history gives deployment decisions something firmer than “the last build looked fine”.

There are two legitimate ways to operate this layer. The self-hosted, open-source broker offers control with the work of running and maintaining it. PactFlow is a hosted option that teams pay for, with bi-directional contract testing, secrets management, and enterprise features added. Operational responsibility and needed features guide the choice.

The broker can also shorten the feedback loop. A webhook on publication of a new pact can trigger provider CI immediately. To keep that record useful, consumer and provider versions need branch or environment tags, and the broker needs to track their deployments correctly. The design also needs to keep the broker available, because verification and deployment checks that depend on it cannot run when it is down.

Gating deployments with can-i-deploy

Verification becomes deployment policy through can-i-deploy. The command asks whether a particular service version is compatible with the other services deployed to a target environment. A representative invocation is pact-broker can-i-deploy --pacticipant <service> --version <version> --to-environment <environment>. The pipeline uses its pass-or-fail result immediately before deployment, skipping the deploy and notifying the team when the check fails.

The broker needs accurate environment records to answer correctly. A successful verification against the wrong version does not establish compatibility with the version in the deployment environment. Without this gate, verification remains advisory. A warning light is useful, but it is not a brake.

Pending and Work In Progress pacts make adoption less disruptive. Pending pacts let a new, unverified consumer contract enter the process without immediately breaking the provider’s build. WIP pacts bring unverified contracts into provider verification with failures treated as informational. These features give new consumers an on-ramp without treating an unverified relationship as proven safe to deploy.

Extending contracts to async and event-driven systems with message pacts

Message pacts apply the same agreement to asynchronous payloads. For Kafka topics, SQS queues, and other async transports, the consumer describes the message body it expects, and the provider verifies the message shape it produces. The transport changes, but the division of responsibility does not. The process still relies on consumer expectations, provider verification, and the broker’s tracking of compatibility.

No live message broker is required during these tests. Sword Health uses Pact to validate event schemas so that event structures stay aligned across services as they scale. This extends the technique beyond HTTP without turning contract tests into a rehearsal of the entire messaging infrastructure.

What Pact catches, what it misses, and what that means for your test strategy

Pact gives its strongest guarantee for the interfaces that consumers actually use. If a response field they read is removed or renamed, verification fails, while removing a field they do not use correctly leaves the contract green. Verification also catches implementation drift because it runs the provider’s real code.

The blind spots follow from the same design. An edge-case input receives coverage only if a consumer test includes it. Unknown consumers cannot use these contracts to state what they depend on, and a response with the right structure can still contain the wrong business result. A number can have the right type and still be the wrong number.

Schema-based tools see a different slice of the problem. An OpenAPI diff can flag a field that was removed without knowing whether any consumer reads it, while conformance testing checks whether the code does what its specification says. Neither makes Pact redundant, and Pact does not replace them. Contracts should remain one layer with unit tests, provider functional tests, and targeted integration tests for critical flows.

Bi-directional contract testing as an alternative when full Pact adoption stalls

Bi-directional contract testing gives teams another way when they cannot take on the full Pact workflow together. The provider publishes an OpenAPI specification plus evidence that its implementation matches it, using Postman, Schemathesis, or another verification tool. The consumer publishes its usage as a pact or OpenAPI subset. PactFlow then checks statically whether the provider specification satisfies the consumer expectations.

The consumer contract is not replayed against provider code. PactFlow rates this approach more strongly for team decoupling and less strongly for guarantees, and reports more than 50% reduction in contract-test creation time among teams using it. Its AsyncAPI support also extends the workflow to asynchronous APIs.

This is a practical choice for teams whose adoption has stalled, organisations that are in transition, or provider teams that already keep an OpenAPI specification up to date and trust it. Schema-based testing alone is still the better fit for public APIs with unknown consumers. The goal is still to catch boundary failures cheaply, with a different balance of evidence and team independence.

Pitfalls that break Pact implementations in practice

A contract can be precise about the wrong things. Exact timestamps and generated IDs create brittle expectations, while copying the provider’s full response mistakes its current output for the consumer’s needs.

Versioning mistakes corrupt the deployment decision itself. When tags are missing or environment records are wrong, the broker cannot track the compatibility that a release depends on, even when each test run looks healthy.

Uncontrolled provider states make failures hard to interpret. Shared data and mutations without cleanup can turn verification into a test of what happened to be in the database that morning.

A green contract does not establish that the consumer can handle scenarios its tests never described, so success-only coverage leaves production failure modes undetected.

An unreliable broker disables the deployment gate, while a team that stops maintaining its half of the contract leaves the other side relying on stale expectations.

When Pact delivers the most value and when to reach for something else

Pact earns its upkeep when independent teams share internal providers and control both sides of their contracts. Its language support suits polyglot fleets, while message pacts cover event-schema compatibility across producers and consumers. Teams that need a hard consumer-driven deployment gate have an especially clear use for it.

Outside that setting, the choice should change. For anonymous public consumers, publish an OpenAPI specification and test against it. If a partner team will not adopt Pact, consider bi-directional testing to keep unverified contracts from becoming decorative documentation. For business-logic correctness, invest in the provider’s functional tests.

The UK Government Digital Service identified being positioned to replace expensive end-to-end tests with Pact where applicable as a benefit. That qualification is the useful part. Pact belongs where the painful gap is compatibility between services, and where the teams controlling both sides can turn that agreement into a release gate.

AllAboutAPIs Editors