Software Testing

Expert path · lesson 14 of 21

ExpertAutomation5 min readPublished November 12, 2026

Contract testing for microservices

With dozens of services deployed independently, end-to-end environments become slow, fragile and always out of date. Contract testing checks every consumer–provider pair in isolation and tells you, before deployment, whether a change is safe to release.

On this page

Key takeaways

  • A contract captures what a consumer actually needs from a provider: requests, responses and message shapes. Each side is tested independently against it, with no shared environment.
  • In consumer-driven contract testing (for example with Pact), consumers' tests generate the contract; providers verify it in their own pipelines. A broker stores contracts and verification results per version and environment.
  • The payoff is the deployment question: "can I deploy this version to production?", answered from the verification matrix, not from a slow end-to-end run.

Where this picks up

The test pyramid in practice introduced consumer-driven contracts in four steps. This article is about running them across many teams and services: what to put in contracts, how to version them and how to make deployment decisions from them.

Why end-to-end environments don't scale

With 40 services owned by 12 teams:

  • A shared end-to-end environment is almost never running the exact combination of versions that will reach production.
  • Failures are hard to attribute: whose change broke it?
  • Tests are slow and flaky, so teams wait, retry and eventually ignore them.

Contract testing replaces most of that with pairwise, versioned checks that run in each team's normal pipeline.

The moving parts

PartRole
Consumer testRuns the consumer's real client code against a mock provider that records the interactions the consumer expects
Contract (pact file)The recorded interactions: requests, minimal expected responses, matchers
BrokerStores contracts and verification results, tagged by version, branch and environment
Provider verificationReplays every interaction against the real provider, with the required data set up via provider states
can-i-deployQueries the broker: is this version compatible with every version currently deployed in the target environment?
WebhooksWhen a consumer publishes a changed contract, trigger the provider's verification automatically

What a good contract contains

// Consumer test (Pact JS, simplified)
provider
  .given("product 42 exists")                        // provider state
  .uponReceiving("a request for product 42")
  .withRequest({ method: "GET", path: "/products/42" })
  .willRespondWith({
    status: 200,
    body: {
      id: integer(42),                               // matchers: type, not exact value
      name: string("Coffee"),
      price: decimal(32.0),
    },
  });

Guidelines:

  • Only what the consumer uses. If the consumer reads id, name and price, the contract shouldn't mention the other 30 fields. That leaves the provider free to change them.
  • Match by type and shape, not exact values, unless the value matters, like an enum or a status code.
  • Use provider states for preconditions ("product 42 exists", "user is suspended"), so the provider can set up data deterministically.
  • Include important error cases: 404 for a missing product, 422 for invalid input, if the consumer handles them.

Versioning and deployment safety

  1. Publish contracts and verification results with the exact version (for example, the git commit) and the branch.
  2. Record deployments: tell the broker which version is in which environment when you deploy.
  3. Gate deployment with can-i-deploy: before deploying, ask whether this version is verified against everything deployed in that environment.
  4. Protect providers from new expectations: features like pending contracts let a new consumer expectation fail verification without blocking the provider's existing build, until the provider implements it.
  5. Verify against the right consumer versions: typically the main branch and every version deployed in production.

Variants

  • Bi-directional contract testing: the provider publishes its API specification (for example OpenAPI), and the broker checks consumer contracts against it, without the provider replaying interactions. It's quicker to adopt for existing APIs, but weaker: it trusts the specification matches the implementation.
  • Message contracts: the same idea for events on queues and topics. The consumer states which message shapes it can process; the producer verifies it can produce them.
  • Schema-based checks: for gRPC/Protobuf or Avro, schema-compatibility tools in the pipeline catch breaking changes, such as removed or renumbered fields.
Real-world exampleFrom a four-hour staging run to a deployment matrix

A company with about 30 services ran a nightly end-to-end suite in a shared staging environment. It took around four hours, failed most nights for environment reasons and blocked releases twice a week.

They introduced consumer-driven contracts for the ten most critical integrations first: checkout, payments, pricing, inventory and identity. Each provider verified contracts in its own pipeline, triggered by webhooks when a consumer's contract changed. Deployment jobs ran can-i-deploy before every production release.

Within a quarter, most integration failures were caught in pull requests, attributed to the right team immediately. The end-to-end suite was cut to a short smoke run of critical journeys.

Lesson: contract tests didn't remove the need to test the whole system. They removed the need to test every integration through the whole system.

Do

Keep contracts minimal: only fields and behaviours the consumer actually uses, matched by type, with provider states for setup.

Don't

Copy full production responses into contracts as exact values. Every harmless provider change will break them, and teams will stop trusting the tests.

Check yourself

A provider team wants to rename the field `price` to `amount`. Three consumers read `price`. How do contract tests and can-i-deploy help them do this safely?

Show answer

The provider's verification will fail against the three consumers' contracts, so the breaking change is caught before deployment. The safe path is expand and contract: add amount alongside price, get consumers to switch and publish new contracts, and use can-i-deploy to confirm that no deployed consumer version still needs price. Only then remove it.