What is consumer-driven contract testing, and what is it not?
A Pact file on its own does not protect you. If contracts are generated in CI but nothing checks them before a deploy, you have documentation, not a safety net. The value comes from storing contracts and verification results in a Pact Broker and refusing to ship when can-i-deploy says no.
A consumer-driven contract records the HTTP requests a consumer actually sends and the parts of each response it actually reads. The consumer writes it as a side effect of its own unit tests. If the orders service calls GET /customers/42 and reads only id and email, the contract contains that request and those two fields. It says nothing about the other thirty fields the customer service returns.
That narrow scope sets the limits of what a contract covers:
- It is not a full API schema. The provider stays free to add fields, rename unused ones, or restructure anything no consumer depends on. An OpenAPI document describes what the provider offers. A contract describes what one consumer needs.
- It is not a functional test of provider logic. Verification checks that a response has the right shape for a given provider state. It does not check that a discount was calculated correctly.
- It does not replace end-to-end tests. Checkout, login, and other critical flows still need a small set of tests that run through the real deployed system.
Teams adopt contract testing because it moves the "you broke my integration" discovery earlier. Without it, that failure tends to surface in shared staging or in production. With contracts in place, it shows up as a failed CI check on the provider's pull request.
Who should use it?
Pact with a can-i-deploy gate suits organizations that run several internally owned services talking over HTTP and that deploy those services independently. The typical signs that it will help:
- Multiple teams own services that call each other. One team's change can break another team's client, and the break is usually found by the team that didn't cause it.
- Services deploy on their own schedules. If every service always ships together as one release, a shared integration test run may already cover you. Contract testing earns its keep when consumer and provider versions in production differ from each other.
- A shared staging environment is a bottleneck. Teams queue for it, it is often broken by someone else's change, and failures there take cross-team effort to diagnose.
- Both sides will participate. Consumer teams must write and publish pacts, and provider teams must run verification and treat a failure as blocking.
Within those organizations, the roles split cleanly. Consumer developers write the contract tests alongside their HTTP client code. Provider developers maintain state handlers and keep verification green. Whoever owns the CI/CD pipelines wires in publishing, verification, can-i-deploy and record-deployment, and someone has to own the broker itself: tokens, backups and retention.
It is a poor fit for teams that publish APIs to unknown external consumers, for a single team adopting it without its providers, or for systems that already rely on a schema registry with enforced compatibility rules. The last section covers those cases in more detail.
How does it work?
In short: the consumer's tests record what it needs from the provider, the provider proves it still delivers that, and the deploy pipeline refuses to ship any version whose counterparts in the target environment haven't been proven compatible.
Concretely, the consumer's unit tests run its real HTTP client against a Pact mock server. Each interaction (a provider state, a request and the expected response, expressed with matchers) is written to a pact file. CI publishes that file to the Pact Broker under the consumer's commit SHA. The provider's CI pulls the relevant pacts from the broker, sets up each provider state, replays each request against a running instance of the real provider and publishes pass or fail back to the broker under the provider's commit SHA. The broker now holds a matrix of which consumer and provider versions are known to work together. Before any deploy, can-i-deploy queries that matrix for the target environment, and after a successful deploy record-deployment updates the broker's record of what is running there.
The next section walks through each step of that loop, and the sections after it show the consumer test, provider verification and deploy gate in code.
How does the Pact loop work from consumer to provider to deploy gate?
The loop has four steps, and each one leaves a record in the Pact Broker.
- Consumer test produces a pact. The consumer's unit tests run against a Pact mock server rather than the real provider. Each request the consumer makes, along with the response it expects, is written to a pact file, a JSON document that describes exactly what this consumer relies on.
- The pact is published. CI uploads the file to the broker, using the git commit SHA as the consumer version and attaching the branch name.
- The provider verifies it. The provider's CI fetches the relevant pacts, replays each request against a running instance of the real service, and checks the responses. The pass or fail result is published back to the broker under the provider's own commit SHA and branch.
- The deploy is gated. Before deploying,
can-i-deployasks the broker whether this version has a successful verification against every version already running in the target environment. After the deploy succeeds, a deployment record tells the broker which version now runs there.
Commit SHAs are used as versions because they are unique and immutable. That lets the broker build a matrix of exact consumer and provider pairs that are known to work together. Semantic versions or "latest" labels can't do this, because they get reused and drift away from the code they originally described.
The provider usually changes less often than its consumers. To avoid waiting for the provider's next build, you configure a broker webhook that fires when a consumer publishes a pact whose content has changed. The webhook triggers a provider build that verifies only that pact, so the consumer gets an answer within minutes.
CONSUMER CI PACT BROKER PROVIDER CI
+------------------+ +-----------------------+ +------------------+
| 1. Consumer unit | | Pacts by consumer SHA | | 3. Fetch pacts, |
| tests vs Pact | | + branch webhook: |---->| replay vs |
| mock server | | | | real service |
+--------+---------+ | Verification results | +--------+---------+
| pact file | by provider SHA | | results
v | |<-------------+
+------------------+ | Matrix of verified |
| 2. Publish pact | | consumer x provider |
| version = SHA |---->| SHA pairs |
| branch = name | | |
+------------------+ | Deployment records |
| per environment |
+-----+-----------+-----+
can-i-deploy? | ^ deployment
v | record
+-----------------------+
| 4. can-i-deploy gate |
| then deploy, then |
| record deployment |
+-----------------------+
The Pact loop: consumer pacts and provider results are stored under commit SHAs, a webhook triggers verification of changed pacts, and can-i-deploy checks the matrix before each deploy is recorded.
How do you write a Pact consumer test with matchers?
A consumer test is a unit test of your real HTTP client. You start the Pact mock server and declare one interaction per behaviour: a provider state ("order 42 exists"), the request, and the expected response. Then you point your actual client code at the mock server's URL and call it. If the client sends a request the mock doesn't expect, the test fails. If it passes, Pact writes the interactions to a pact file, and that file is what you publish.
The response body is where contracts go wrong. An over-specified contract has three common problems:
- Literal values. It asserts
"status": "SHIPPED"and"total": 129.99. - Ignored fields. It copies every field from a captured response, including ones the client never reads.
- Provider business rules. It asserts that a discounted order always has
total < subtotal.
Each of these makes provider verification depend on fixture data and internal logic that the consumer doesn't rely on. The provider then can't rename an unused field, change seed data, or adjust pricing without breaking a build that should have passed. After a few false failures, teams start marking verification as non-blocking, and the gate stops catching anything.
A well-scoped contract includes only the fields your client deserializes. It uses a type matcher (like) for values whose shape matters but whose content doesn't. It uses an array matcher (eachLike) for collections and a regex matcher for constrained formats such as ISO-8601 timestamps or a fixed set of status codes. Business rules belong in the provider's own tests.
import path from 'path';
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import { OrderClient } from '../src/orderClient'; // the real client under test
const { like, eachLike, regex } = MatchersV3;
const provider = new PactV3({
consumer: 'checkout-web',
provider: 'order-service',
dir: path.resolve(process.cwd(), 'pacts'), // pact file written here on success
});
// Over-specified (avoid): body: { id: 42, status: 'SHIPPED', total: 129.99,
// subtotal: 149.99, warehouseCode: 'EU-3', ... } plus asserting total < subtotal.
describe('OrderClient', () => {
it('fetches an order by id', () => {
provider
.given('order 42 exists')
.uponReceiving('a request for order 42')
.withRequest({ method: 'GET', path: '/orders/42' })
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
// Only the fields OrderClient deserializes; values match by type/format.
body: {
id: like(42),
status: regex('^(PENDING|SHIPPED|CANCELLED)$', 'SHIPPED'),
placedAt: regex('^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$', '2024-05-01T10:15:00Z'),
lines: eachLike({ sku: like('SKU-1001'), quantity: like(1) }),
},
});
return provider.executeTest(async (mockServer) => {
// Real client code pointed at the mock server's URL.
const order = await new OrderClient(mockServer.url).getOrder(42);
expect(order.status).toBe('SHIPPED');
expect(order.lines[0].sku).toBe('SKU-1001');
});
});
});
A pact-js consumer test that runs the real OrderClient against the Pact mock server, using type, array and regex matchers for only the fields the client reads, with the over-specified alternative noted in a comment for contrast.
How does provider verification work with provider states and deployed-version selectors?
On the provider side, verification runs as an ordinary test job. The Pact verifier starts or connects to a running instance of the provider, asks the broker which pacts it should verify, and replays each recorded request against that instance. It then compares the real response to the consumer's expectations, using the matchers rather than exact values. The provider never calls the consumer. The pact file is the only thing it needs.
Provider states
Many interactions declare a provider state, such as "order 42 exists". Before replaying that interaction, the verifier calls a state handler that puts the provider into the matching condition. Keep these handlers thin. Seed rows through a test-only setup endpoint or repository call, and stub downstream services the provider depends on so verification doesn't need the rest of the system running. Thin handlers keep the run fast and deterministic.
Watch how the handlers grow over time. Each new consumer adds states, and the handlers can turn into a second fixture system with its own builders, ordering assumptions and drift from production data shapes. If a handler needs more than a few lines, the interaction is probably testing business logic instead of the contract.
Selecting consumer versions
Verifying only the latest pact misses the case that matters most. Configure consumer version selectors to verify the consumers' main branch and every version currently deployed or released in each environment. That second set is what catches a provider change that would break a consumer already running in production.
Finally, publish the verification results back to the broker, tagged with the provider's version and branch. The deploy gate depends on those results.
import { Verifier } from '@pact-foundation/pact';
// Local test-only helpers. Not shipped in the production build.
import { seedOrder, resetDb } from './test-support/db';
import { stubInventoryService } from './test-support/stubs';
// Assumes the provider is already running locally with downstream calls
// pointed at stubs, so verification doesn't need the rest of the system.
const verifier = new Verifier({
provider: 'order-service',
providerBaseUrl: '',
pactBrokerUrl: '',
pactBrokerToken: process.env.PACT_BROKER_TOKEN,
// Verify every consumer's main branch AND whatever is deployed or released
// in any environment. The second selector catches breaking production consumers.
consumerVersionSelectors: [{ mainBranch: true }, { deployedOrReleased: true }],
// Thin handlers: reset, seed one row through a test-only path, stub a dependency.
stateHandlers: {
'order 42 exists': async () => {
await resetDb();
await seedOrder({ id: 42, status: 'PLACED' });
},
'inventory is unavailable': async () => {
stubInventoryService({ status: 503 });
},
},
// Publish results from CI only, so the can-i-deploy gate can use them.
publishVerificationResult: process.env.CI === 'true',
providerVersion: process.env.GIT_COMMIT,
providerVersionBranch: process.env.GIT_BRANCH,
});
verifier.verifyProvider().catch(() => process.exit(1));
A pact-js provider verification that fetches pacts for consumers' main branches and their deployed or released versions, uses thin state handlers, and publishes results to the broker tagged with the provider's version and branch.
How do you gate deployments with can-i-deploy and record deployments?
Before deploying, each pipeline runs can-i-deploy with its pacticipant name, the version being shipped, and the target environment. The broker checks whether that version has a successful verification against every integrated version currently recorded in that environment. If any pairing is missing or failed, the command exits non-zero and the job stops.
After a successful deploy, run record-deployment for the same version and environment. The broker learns what is in production only from these calls. If you skip them, it keeps an outdated view of production. can-i-deploy then checks against versions that are no longer running, and provider verification with deployed-version selectors tests the wrong consumers. The gate still passes, but it no longer protects you.
Webhook-driven feedback
Suppose a consumer adds a field it needs and publishes a new pact on its branch. A broker webhook for "contract requiring verification published" triggers the provider's verification build against that specific pact. Meanwhile, the consumer's can-i-deploy waits, using its retry options, for the result. If the provider doesn't return the field yet, verification fails and the consumer cannot deploy. The failure appears before merge, so the team doesn't discover it in staging. The consumer either waits for the provider to ship the field or treats it as optional.
Expand and contract
For an intentional breaking change, the provider first adds the new field alongside the old one and deploys. Consumers then migrate to the new field and publish updated pacts. Once every deployed consumer version has its deployment recorded, a provider build that drops the old field passes can-i-deploy only when no consumer in the environment still depends on it. At that point the provider can remove the old field safely.
#!/usr/bin/env bash
set -euo pipefail
export PACT_BROKER_BASE_URL=""
export PACT_BROKER_TOKEN="${PACT_BROKER_TOKEN:?set in CI secrets}"
PACTICIPANT="checkout-web"
VERSION="${GIT_COMMIT:?}" # same version used when the pact was published
ENVIRONMENT="production"
pact-broker can-i-deploy \
--pacticipant "$PACTICIPANT" \
--version "$VERSION" \
--to-environment "$ENVIRONMENT" \
--retry-while-unknown 30 \
--retry-interval 10
./deploy.sh "$ENVIRONMENT" "$VERSION"
pact-broker record-deployment \
--pacticipant "$PACTICIPANT" \
--version "$VERSION" \
--environment "$ENVIRONMENT"
A CI deploy script that blocks on can-i-deploy, retrying while a webhook-triggered provider verification is pending, and records the deployment only after a successful deploy so the broker's view of production stays accurate.
Reference CI pipeline layout for consumers and providers
Each service runs its own pipeline, and the broker connects them. Version every artifact with the git commit SHA so that a pact, a verification result and a deployment all point to the same build.
| Pipeline | Step | Failure means | What to do |
|---|---|---|---|
| Consumer | Run tests, generate pact | Consumer code disagrees with its own expectations | Fix the code or the interaction; nothing has left the build yet |
| Consumer | Publish pact | Broker unreachable or token rejected | Check credentials; republish under the same SHA |
| Consumer | can-i-deploy |
Provider hasn't verified this pact, or verification failed | Wait for the webhook-triggered verification, or coordinate the change with the provider team |
| Both | Deploy | Ordinary deploy failure | Roll back as usual; don't record anything |
| Both | Record deployment | Broker's view of the environment is stale | Rerun this step. Otherwise later checks run against the wrong versions |
| Provider | Verify pacts (main branch plus deployed and released selectors) | Provider breaks a consumer, or a provider state is missing | Fix the provider or the state setup; never edit the consumer's pact |
| Provider | Publish results | can-i-deploy has no evidence to evaluate |
Publish only from CI, never from laptops |
| Provider | can-i-deploy |
A deployed consumer still depends on behaviour you changed | Keep the old behaviour until that consumer ships |
Running the broker involves three decisions. First, authentication: CI needs a write token, while developers usually need read-only access. Second, data retention: pacts and results for branches that will never ship pile up, so prune them on a schedule. Third, behaviour during a broker outage, which is a policy choice to make in advance. Either can-i-deploy fails closed and deploys stop, or the pipeline offers a documented manual override. If you allow the override, log it and audit it afterwards.
How can it save engineering time?
The time savings come from where and when integration breaks are found, not from writing fewer tests.
- Failures land with the team that caused them. A provider change that breaks a consumer fails the provider's own verification job, on the provider's pull request. The provider developer sees which consumer, which interaction and which field, while the change is still fresh. Without the gate, the consumer team typically finds the break in staging and has to work out whose change caused it.
- Diagnosis is shorter. A failed verification names the interaction and the mismatched field. A failed end-to-end test in staging often just reports a timeout or a 500 several hops away from the real cause.
- Less waiting on shared environments. Because compatibility is checked per pair of versions, teams don't need a fully assembled staging environment to learn whether their change is safe to deploy. Staging can be reserved for the small set of end-to-end journeys.
- Fewer coordinated releases.
can-i-deployanswers "is this version compatible with what is running?" directly, so teams can deploy independently instead of scheduling joint releases or manually checking with other teams before shipping. - Safer removal of old fields. The broker shows which deployed consumers still depend on a field, so providers can delete it with evidence instead of leaving it in place indefinitely or announcing a deprecation and hoping.
To judge whether the effort pays back for your organization, put your own numbers into a simple comparison. The following is an illustrative estimate, not a measured result, and every input is assumed:
- Assumed: a team sees 3 integration breaks per month that are currently first found in shared staging.
- Assumed: each one costs 2 engineers about 3 hours to triage, identify the responsible change, fix and redeploy, so roughly 6 engineer-hours per break, or 18 engineer-hours per month.
- Assumed: with contracts and the gate in place, 2 of those 3 breaks are caught on the pull request and fixed by the author in about 1 hour each, while the third involves behaviour contracts don't cover and still reaches staging.
- Illustrative result: about 2 + 6 = 8 engineer-hours per month instead of 18, a saving of about 10 engineer-hours per month before ongoing costs.
Against that, subtract the ongoing cost: maintaining consumer tests and provider state handlers, broker operation, and the occasional false failure from an over-specified contract. If your assumed inputs give a small or negative difference, for example because integration breaks are rare or the services rarely change, the setup may not be worth it yet. The estimate also leaves out harder-to-count gains such as fewer production incidents and less time spent waiting for staging.
When should you avoid Pact, and what are the alternatives?
Pact pays off when services communicate over request/response HTTP, your organization controls both sides, and both consumer and provider teams have agreed to run their half of the loop. If any of those conditions is missing, the cost grows faster than the benefit.
Skip it for public APIs, because you cannot collect contracts from consumers you don't know. Skip it when only one team is adopting it, because a contract that no provider verifies protects nothing. For message-based systems, Pact can model message contracts, but the extra setup may not pay off if a schema registry with compatibility rules already covers you.
Know the limits before you rely on it:
- Only tested interactions are protected. A field that no consumer test exercises can still break.
- Shape, not behavior. Contract tests do not catch a wrong calculation or a slow endpoint.
- Broker data drives
can-i-deploy. A manual deploy that skipsrecord-deployment, or version numbers that don't map to commits, makes the answer wrong.
| Approach | Catches | Misses | Best fit |
|---|---|---|---|
| Consumer-driven contracts (Pact) | Breaks in fields consumers actually use | Untested paths, semantics | Internal HTTP, both teams engaged |
| Schema compatibility checks | Structural breaks across the whole schema | Which fields consumers rely on | Event streams, protobuf/Avro |
| Provider-driven schema contracts | Deviation from a published spec | Real consumer usage | Public or many-consumer APIs |
| End-to-end tests | Wiring, semantics, real flows | Fast feedback; flaky at scale | A few critical journeys |
The costs are real: cross-team coordination, running and backing up the broker, and keeping provider states in step with the data model. What you get back is less time spent queuing for a shared integration environment and failures that surface in a pull request instead of in staging. Keep a small set of end-to-end tests for flows such as login and checkout. Those tests cover the semantics and wiring that contracts don't check.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to pact contract testing microservices, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.