What is consumer-driven contract testing with Pact?

Most teams that adopt Pact are not chasing better test coverage. They want to stop relying on a shared integration environment, where every service must be deployed and healthy before anyone can learn whether a change breaks a neighbor. Pact contract testing for microservices replaces that slow, flaky gate with a check that runs in each service's own pipeline.

A consumer-driven contract is a recording of the interactions a consumer actually depends on. For each interaction, the consumer's test captures the request it sends (method, path, query, headers, body shape) and the minimal response it expects back. That response includes only the fields the consumer reads, not every field the provider returns. Pact writes these interactions to a contract file, called a pact. The provider is then verified by replaying each recorded request against a real running instance of the provider and checking that the responses satisfy the expectations.

The "consumer-driven" part matters because the contract describes real usage, not the full API surface. Suppose a provider exposes forty fields and three consumers together read six of them. The contracts constrain only those six. The provider team can rename, remove or restructure the other thirty-four without coordinating with anyone. If a change would break a consumer, verification fails in the provider's build, before deployment, and names the specific consumer and interaction affected.

Each side tests in isolation. The consumer tests against a Pact mock server, and the provider tests against recorded requests. Neither needs the other running.

How does Pact work end to end?

The loop has six steps, and each one passes data to the next.

  1. The consumer test generates a pact file. When the consumer's tests run against the Pact mock server, every interaction they exercise is written to a JSON pact file. The file describes requests the consumer actually sends and the response fields it actually reads.
  2. The consumer publishes the pact to the Pact Broker. The publish step records the consumer version as the git SHA and also records the branch. The SHA ties a contract to an exact build. The branch lets the provider choose which consumer lines to verify against, such as main or whatever is currently deployed.
  3. The provider verifies the pact and publishes the results. Provider CI fetches the relevant pacts and replays each request against a running instance of the provider. It then reports pass or fail back to the broker under its own SHA.
  4. The broker builds a compatibility matrix. From these results it records which consumer versions have been verified against which provider versions.
  5. can-i-deploy checks the matrix before release. This command asks whether a specific version is compatible with everything currently running in a target environment. It answers that question with a yes or no that a pipeline can act on.
  6. The deployment is recorded back to the broker. After a successful deploy, the pipeline tells the broker which version now runs in which environment. Without this step, can-i-deploy checks compatibility against stale data.

Webhooks close the gap between the two teams. When a consumer publishes a pact whose content has changed, the broker can trigger a provider CI build that verifies just that pact. The consumer then gets a result in minutes and does not have to wait for the provider's next unrelated commit.

Writing the tests is the smaller part of the work. Most of the engineering effort goes into this broker workflow: consistent versioning, branch conventions, reliable deployment recording, and pipeline gates.

+--------------------+                         +--------------------+
|    CONSUMER CI     |                         |    PROVIDER CI     |
| 1. tests run vs    |                         | 3. fetch pacts,    |
|    mock server     |                         |    replay against  |
|    -> pact (JSON)  |                         |    running app     |
+--------------------+                         +--------------------+
     |                                            ^             |
     | 2. publish pact               webhook:     |             | results
     |    (git SHA + branch)         pact changed |             | (prov SHA)
     v                                            |             v
+---------------------------------------------------------------------+
|                          PACT BROKER                                |
| stores pacts + results, keyed by version SHA, branch and environment|
|  4. builds COMPATIBILITY MATRIX: consumer vN x provider vM -> ok?   |
|  (most of the setup effort lives here)                              |
+---------------------------------------------------------------------+
          ^                   |                     ^
          | 5. can-i-deploy?  | yes / no            | 6. record deployment
          | (version, env)    v                     | (version -> env)
+---------------------------------------------------------------------+
|                 DEPLOY PIPELINE (consumer or provider)              |
|      ask broker -> deploy only on yes -> record what now runs       |
+---------------------------------------------------------------------+

The Pact loop: consumer pacts and provider results flow into the broker's compatibility matrix, which can-i-deploy queries before release and recorded deployments keep current. A webhook triggers provider verification when a changed pact is published.

How do you write a Pact consumer test?

A consumer test has three steps. First, register the interactions you expect with Pact's mock provider: for a given request (method, path, query, headers, body), the mock should return a given response. Second, point your real API client at the mock's URL and call it the way production code does. Third, when the test passes, Pact writes the recorded interactions to a pact file, a JSON document that becomes the contract.

Drive the real client, not raw HTTP

Make the call through the same client class your service ships. If the test sends its own hand-built HTTP request, it only proves that the test author can format a request. Using the real client means the contract covers the code that actually runs: how paths are built, how query parameters are encoded, which headers are set, and how JSON is serialized and deserialized. A typo in a path template or a field the client parses as the wrong type then fails the consumer build. Without this, the same bug would reach production even though the contract looked correct.

Match structure, not incidental values

Use matchers so the contract checks shape and meaning instead of literal sample data:

  • Type matching checks that id is a number or createdAt is a string. It does not care which number or string.
  • Regex matching constrains format, such as an ISO-8601 timestamp or a UUID.
  • Array-like matching checks that a list holds at least one element of a given shape.

Avoid over-specification

Assert only the fields your consumer actually reads. Two common mistakes cause trouble. Pinning exact IDs or timestamps makes verification fail on harmless provider changes. Including fields the consumer ignores locks the provider into data no one depends on. Both produce false failures, and teams that see enough false failures stop trusting the gate and start working around it.

import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import { OrderClient } from '../src/orderClient'; // the same client class production code uses

const { like, integer, regex, eachLike } = MatchersV3;

const provider = new PactV3({ consumer: 'checkout-web', provider: 'order-service' });

describe('OrderClient', () => {
  it('lists open orders for a customer', () => {
    // Step 1: register the interaction we expect the provider to honour
    provider
      .given('customer 42 has open orders')
      .uponReceiving('a request for open orders for a customer')
      .withRequest({
        method: 'GET',
        path: '/customers/42/orders',
        query: { status: 'open' },
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': regex(/application\/json.*/, 'application/json') },
        // At least one order of this shape; only fields the client actually reads.
        body: eachLike({
          id: integer(1001),                // any integer, not this specific ID
          status: like('open'),             // any string
          createdAt: regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, '2026-01-15T09:30:00Z'),
        }),
      });

    // Step 2: drive the real client against the mock, so path building,
    // query encoding, headers and JSON parsing are all exercised
    return provider.executeTest(async (mockServer) => {
      const client = new OrderClient(mockServer.url);
      const orders = await client.listOpenOrders(42);
      expect(orders[0].id).toBe(1001);
      expect(typeof orders[0].createdAt).toBe('string');
    });
    // Step 3: on success, Pact writes the pact file (./pacts by default)
  });
});

A Pact JS consumer test that registers an interaction with type, regex and array-like matchers, exercises the shipped OrderClient against the mock provider, and produces a pact file on success.

How do you verify a provider and design provider states?

Provider verification turns the contract into a test against the real service. The verifier starts with your provider running locally or in CI, reads each interaction from the pact, sends the recorded request to the provider, and compares the actual response with the expected one using the matching rules the consumer wrote. In CI, the verifier should fetch pacts from the Pact Broker rather than from files. Consumer version selectors tell it which pacts to check, such as those from the consumer's main branch and from versions currently deployed. When the run finishes, publish the results tagged with the provider's version and branch. The broker can only answer deployment questions if those results reach it.

Provider states as named preconditions

Interactions often depend on data, as in "user 42 exists" or "order 7 is cancelled". The consumer names that precondition as a provider state, and the provider registers a handler for each name. A good handler sets up exactly one fact, close to the data layer. It can swap in a stubbed repository that returns a fixed user, or it can insert a single row into a database used only by that test run.

Handlers are the most common place verification goes wrong. When a team points every state at a shared, fully seeded database, runs start to depend on the order interactions execute in, leftover data, and downstream services. Verification then slows to the pace of an integration suite and inherits that suite's flakiness. Keep each handler isolated, fast, and repeatable on every run.

import { Verifier } from '@pact-foundation/pact';
import type { Server } from 'http';
import { app } from '../src/app';
import { userRepo } from '../src/repositories/userRepo';

// Keep the real lookup so each state handler starts from a clean slate
const realFindById = userRepo.findById;

describe('user-service pact verification', () => {
  let server: Server;
  beforeAll((done) => { server = app.listen(8081, done); });
  afterAll((done) => { server.close(done); });

  it('honours consumer contracts from the broker', () => {
    return new Verifier({
      provider: 'user-service',
      providerBaseUrl: '',
      // Fetch pacts from the broker, not local files
      pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,
      pactBrokerToken: process.env.PACT_BROKER_TOKEN,
      // Check the consumer's main branch plus anything deployed or released
      consumerVersionSelectors: [{ mainBranch: true }, { deployedOrReleased: true }],
      // Publish only from CI so the broker can answer can-i-deploy
      publishVerificationResult: process.env.CI === 'true',
      providerVersion: process.env.GIT_SHA,
      providerVersionBranch: process.env.GIT_BRANCH,
      // One handler per named precondition; each sets up exactly one fact
      // at the repository layer instead of seeding a shared database
      stateHandlers: {
        'user 42 exists': async () => {
          userRepo.findById = async (id: number) => (id === 42 ? { id: 42, name: 'Ada' } : realFindById(id));
        },
        'no users exist': async () => {
          userRepo.findById = async () => null;
        },
      },
    }).verifyProvider();
  });
});

A pact-js provider verification that fetches pacts from the Pact Broker with consumer version selectors, publishes results tagged with the provider version and branch, and uses small state handlers that stub the repository layer rather than seeding a shared database.

How do you use the Pact Broker and can-i-deploy as a deployment gate?

Every pacticipant publishes under one version: the git commit SHA of the build that produced it. Consumers publish pacts with that SHA and their branch name. Providers publish verification results the same way. Never use a semantic version or a build number that can be reused. If two different builds share a version, the broker cannot tell which code a result belongs to, and its matrix of verified pairs stops reflecting reality.

Before deploying to any environment, the pipeline asks can-i-deploy whether this SHA is compatible with everything currently recorded in that target environment. If the answer is yes, deploy. Then immediately run record-deployment (or record-release for things like mobile apps, where several versions coexist). Skipping that last step is the most common way the gate quietly breaks. The broker still believes the old version is in production, so later checks pass against code that isn't running. Missing branch metadata causes a related failure: provider verification can't select pacts from the consumer's main branch, and new contracts go untested.

Configure a webhook that triggers a provider verification build whenever a pact with changed content is published. Without it, a consumer's pipeline stalls until the provider happens to build again.

Treat the broker as production infrastructure. Give it an owning team, backups, and monitoring. Decide in advance what happens during an outage. One option is to block deploys. The other is to allow them only through an explicit, logged override. Don't let each team improvise under pressure.

#!/usr/bin/env bash
# Consumer pipeline: publish, gate, deploy, record. Assumes the pact-broker CLI
# (pact_broker-client) is installed. It reads PACT_BROKER_BASE_URL and
# PACT_BROKER_TOKEN from the environment, e.g.
set -euo pipefail

APP="order-web"
VERSION="$(git rev-parse HEAD)"            # one immutable version per build: the commit SHA
BRANCH="$(git rev-parse --abbrev-ref HEAD)" # lets providers select pacts from main
ENV="${TARGET_ENV:-production}"

# Publish pacts tagged with SHA and branch. Without --branch, provider
# verification cannot pick up this consumer's main-branch contracts.
pact-broker publish ./pacts --consumer-app-version "$VERSION" --branch "$BRANCH"

# Outage policy decided in advance: block, unless an explicit, logged override is set.
if ! curl -fsS "$PACT_BROKER_BASE_URL/diagnostic/status/heartbeat" > /dev/null; then
  if [[ "${PACT_GATE_OVERRIDE:-}" == "approved" ]]; then
    echo "WARN: broker unreachable; deploying $APP@$VERSION to $ENV under override by ${GITLAB_USER_LOGIN:-unknown}" | tee -a deploy-audit.log
  else
    echo "Broker unreachable; deploy blocked (set PACT_GATE_OVERRIDE=approved to override)" >&2
    exit 1
  fi
else
  # Is this SHA compatible with what the broker records as running in $ENV?
  # Retry while the webhook-triggered provider verification is still in progress.
  pact-broker can-i-deploy --pacticipant "$APP" --version "$VERSION" \
    --to-environment "$ENV" --retry-while-unknown 12 --retry-interval 10
fi

./deploy.sh "$ENV" "$VERSION"   # placeholder for your real deploy step

# Record what is actually running now. Skipping this leaves the broker
# believing the old version is deployed, and later checks become meaningless.
# (Use record-release instead for apps where several versions coexist.)
# Note: after an override deploy, run this once the broker is reachable again.
pact-broker record-deployment --pacticipant "$APP" --version "$VERSION" --environment "$ENV"

A consumer CI script that publishes pacts under the commit SHA and branch, gates the deploy with can-i-deploy, applies a predefined block-or-logged-override policy when the broker is down, and records the deployment afterwards.

Who should adopt Pact, and when should you avoid it?

Where Pact pays off

Pact works best when your organization owns both sides of an internal HTTP or messaging interface. Contracts only work if the consumer team can publish expectations and the provider team agrees to verify them in CI. It also needs several services that deploy independently. With only two or three services released together, a shared integration suite is cheaper. The clearest sign that you need it is a shared staging environment that has become a queue: teams wait for a slot, then debug failures caused by someone else's half-deployed change.

A rollout that builds trust

Start with one consumer-provider pair that carries real traffic and breaks often enough to matter. Run provider verification on every build, but keep it non-blocking at first. Use that period to find flaky provider states and over-specified matchers. Make can-i-deploy blocking only once verification results have been reliable for long enough that a red result means a real incompatibility. If you gate too early, teams learn to reach for the override.

When to avoid it

  • Public APIs with unknown consumers. No one can write contracts on behalf of consumers you can't see. Schema-based and versioning approaches fit better.
  • One team adopting it alone. A consumer publishing pacts that no provider verifies produces documentation, not safety.
  • Very few services. The broker, CI wiring and state handlers cost more than they save.
  • Complex streaming protocols. Message pacts describe individual messages. They fit poorly when correctness depends on ordering, backpressure or long-lived sessions.

Asynchronous message pacts also need a different testing style. Instead of replaying requests against a running provider, you test the code that produces a message and the handler that consumes it.

What are the alternatives to Pact, and how do costs compare?

Pact is one of several ways to catch interface breaks before production. The approaches differ in who defines the contract and whether real code on both sides is checked against it.

Approach Who defines the interface What it catches Main cost
Consumer-driven contracts (Pact) Consumers, verified by the provider Breaking changes to fields and interactions consumers actually use Provider states, broker upkeep, cross-team coordination
Shared end-to-end environment Nobody explicitly Integration failures and some cross-service logic Slow, flaky runs and contention for the environment
Provider-side schema validation (e.g. OpenAPI checks) Provider Provider drifting from its own spec No view of which parts of the spec consumers rely on
Consumer-only mocks Consumer Nothing on the provider side Mocks drift silently from the real provider

In the test pyramid, contract tests sit between unit and end-to-end tests. They replace most cross-service integration tests whose only job is interface compatibility. They do not cover business rules that span services, performance, semantics (a field is present but its meaning changed), or infrastructure such as DNS, TLS and network policy. Keep a thin layer of smoke or end-to-end tests for those.

Illustrative estimate (assumed numbers, not a benchmark).

Net hours saved per month = (flaky E2E runs avoided × hours per investigation) + (blocked releases avoided × hours per coordinated release) − (contract maintenance hours + broker ownership hours)

Assume 20 runs avoided at 1.5 h each (30 h), 4 releases avoided at 3 h each (12 h), 16 h of maintenance and 4 h of broker work. The result is 30 + 12 − 20 = 22 hours saved per month. If maintenance outweighs the savings, the interface may be changing too quickly for contracts to pay off yet.

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.