Consumer-driven contracts: where they sit in the test pyramid
Consumer-driven contracts catch mismatches between services without a running environment. The consumer describes the minimum it needs from the provider, and the provider verifies in its own CI that its code meets it. This checks the shape of communication, not business logic, so e2e and functional tests remain. It fits known consumers and a frequently changing API; for public APIs OpenAPI is used.
API · Contract testing in practice
Frontend and backend are green on their own but fail together on staging. Where do you catch it earlier?
The backend team renamed the fullName field to name, its tests are green. The frontend team changed nothing, its tests are green too, because they run on a mock with the old shape. The connection breaks on staging or in production, when a user sees an empty name in the profile. The lesson explains why such bugs live at the seam between services, how consumer-driven contracts catch them and where this kind of test sits in the pyramid.
How it works and why it is designed so
The classic answers have weak spots. e2e tests are slow, flaky and need an environment with all dependencies running. Integration tests against a real provider break on foreign data and an unavailable service. Mocks in the consumer's unit tests drift from the real API over time, and everything is green until production falls.
Contract testing closes this gap. In the consumer-driven contracts (CDC) approach the consumer describes in its own test the minimum it needs from the provider: a request and the shape of the response. That description is stored as a contract, and the provider checks in its own CI that the real code honours it. No test needs both services at once, so everything is fast and deterministic. The consumer's mock and the provider's verification rest on the same document, so they cannot drift apart.
Contracts in the test pyramid
Figure 1. Contract tests sit between unit and e2e and do not replace them.
Worked example: a renamed field, two ways
The consumer reads the fullName field from the GET /users/7 response. The contract records this as the consumer's requirement:
This is a simplified fragment: a real pact file carries metadata and matchers (details in the next lessons). When the provider renames the field and opens a PR, its CI replays this request against the new code. The response holds name, not fullName, so the verification is red and the report shows the consumer and the field. Compare where the same bug is found without a contract:
Where a renamed field is found
e2e on staging
Finds it, but late
All services are needed together. The failure shows after the merge, and the cause is not obvious: data, network or a renamed field.
A contract in CI
Finds it in the PR
The provider verifies the consumer's pact without running its neighbours. A red PR says which field of which consumer is broken.
Figure 2. The difference is not that e2e is bad but in the moment the signal appears.
Limits and alternatives
Contract tests check the shape of communication, not business logic. They do not replace:
the provider's functional tests: a contract says that status is a string, not that an order is paid correctly;
a small number of e2e tests on critical paths: they check configuration, network, authorisation and real data;
an OpenAPI schema and a breaking-change check where there are many unknown consumers (a public API): CDC needs the consumer to publish its expectations.
When CDC fits. The teams know each other and work in one company (microservices, a BFF and a frontend, a mobile client and a backend), the API changes often, and e2e has become the bottleneck of a release. When it does not: one monolith, one team on both sides or unknown consumers.
The business result is easy to measure: fewer incidents caused by API changes, independent service releases without an "alignment meeting" and a shorter pipeline, where e2e stays a small set on critical paths.
Common mistakes
Treating a contract as a replacement for e2e: configuration, network and authorisation stay unchecked.
Introducing CDC inside one monolith with one team: overhead with no gain.
Describing business rules in the contract: it turns into a duplicate of functional tests.
Check yourself
Why does a consumer's contract test not need a running provider?
Answer
In the test the consumer works with a mock provider that replays the contract, while the provider separately verifies the same contract against real code in its own CI. The two sides are linked by the contract file, not by a live connection.
A public API has hundreds of unknown consumers. Is CDC suitable as the main approach?
Answer
No: CDC requires every consumer to publish its expectations. Here the provider's OpenAPI schema, a breaking-change check between versions and a versioning policy work.
Related lessons: “Pact end to end: consumer test, Broker, can-i-deploy”, “Consumer-driven contracts and breaking changes”, “OpenAPI as a source of tests”.
In an interview.Junior: Contract tests check that a consumer and a provider understand the request and response format the same way, without a running environment. The consumer writes the contract, the provider verifies it. Middle/Senior: I understand the place in the pyramid: it is the shape of communication, not business logic, so e2e and the provider's functional tests stay. I judge fit: known consumers, frequent API changes, e2e as the bottleneck. For public APIs I take OpenAPI and a breaking-change check.
Pact end to end: consumer test, Broker, can-i-deploy
The Pact cycle: a consumer test against a mock provider, publishing the pact to the Broker, provider verification on real code, and a check before deploy. It is can-i-deploy that turns Pact into release protection: without it a red verification blocks nothing. The version is a git SHA, the branch is passed separately, and the environment is recorded with record-deployment. Provider states must be independent.
API · Contract testing in practice
The pact files exist, yet nothing blocks a deploy. Which step of the cycle is missing?
A team set up Pact: the consumer generates contracts, the provider verifies them, the Broker stores the results. A month later the provider ships a release that breaks the consumer and still reaches production: the verification was red, but nobody asked the Broker before the deploy. The lesson goes through the whole cycle and shows which step turns Pact from "extra tests" into protection of a release.
How it works and why it is designed so
The consumer test. The client code (not the UI!) calls a mock provider that Pact starts locally. The test describes an interaction: a state (given), a request and the expected response. After the test passes, a pact file (JSON) is generated.
Publishing. The consumer's CI publishes the pact to the Pact Broker (or PactFlow) with a version, usually the git SHA, and a branch.
Provider verification. The provider runs a Verifier that takes pacts from the Broker, replays every request against a really running provider (with its dependencies stubbed) and compares the response. The result is published back with the provider version.
The deploy decision. Before a release either side asks the Broker whether this version is verified against what is currently in that environment. After the deploy the fact is recorded.
The Pact cycle from a test to a release
Figure 1. Without the last step Pact is just extra tests: can-i-deploy is what blocks a dangerous release.
Worked example: what to add to the pipeline
Three commands close the cycle. The first publishes the consumer's contracts, the second asks the Broker before a release, the third records that the version is now in production:
# 1. the consumer publishes the pact
pact-broker publish ./pacts --consumer-app-version $GIT_SHA --branch $BRANCH
# 2. before a release: is this version verified against what is in production
pact-broker can-i-deploy --pacticipant web-app --version $GIT_SHA --to-environment production
# 3. after the deploy: record the fact
pact-broker record-deployment --pacticipant web-app --version $GIT_SHA --environment production
can-i-deploy looks in the matrix "consumer version × the provider version currently in this environment" for a successful verification. If there is none, the command returns a non-zero code and the deploy step does not start. If this line is missing from the pipeline, a field renamed by the provider reaches production even though the verification was red.
On the provider side the verification is set up like this:
Provider states. An interaction says "when order 42 exists, GET /orders/42 returns…". During verification the provider must bring the system into that state through stateHandlers: create test data or set up stubs. The states should be independent and repeatable.
Versions, branches, environments. The modern model: a pacticipant version = git SHA, the branch is passed separately (--branch), and "what is in production now" is tracked by environments (record-deployment, for libraries and mobile apps record-release). Tags, which used to play this role, are no longer recommended by the Pact documentation for new setups.
Selectors. The verification chooses pacts through consumerVersionSelectors: usually mainBranch, matchingBranch and deployedOrReleased. Without deployedOrReleased the provider does not check what really runs in production.
Pending pacts and WIP. A new pact from a consumer branch that the provider does not yet satisfy should not break the provider's build: with enablePending: true its verification does not block until it has passed at least once. includeWipPactsSince pulls in such "work in progress" pacts automatically.
Webhooks. So as not to wait for the provider's next build, the Broker has a webhook for the contract_requiring_verification_published event: a new or changed agreement triggers verification in the provider's CI, and the result returns to the Broker.
Common mistakes
No can-i-deploy before a deploy: the contracts exist, the protection does not.
Not calling record-deployment: the Broker does not know what is in production, and the matrix compares against the wrong version.
Writing the consumer test through the UI instead of the client layer: the test is slow and brittle.
States that depend on data from another test: the verification is unstable.
Check yourself
The provider verification is red but the release still went through. What exactly is missing in the pipeline?
Answer
The can-i-deploy step before the deploy (and its non-zero exit code that stops the pipeline). Without it the verification result stays information in the Broker, not a release gate.
Why does the provider need enablePending when a consumer's new pact is not yet satisfied?
Answer
So that a new, not yet supported pact from a consumer branch does not break the provider's build until it has passed at least once. Otherwise any new consumer requirement would stop another team.
Related lessons: “Consumer-driven contracts: where they sit in the test pyramid”, “Pact JS/TS: an example, matchers and what not to put in a contract”, “Bi-directional, schema-based and message contracts; adopting it in a team”.
In an interview.Junior: The consumer creates a pact in a test, it is published to the Broker, the provider verifies it against real code, and before a release can-i-deploy is checked. Middle/Senior: I stress that without can-i-deploy Pact is just extra tests. I take the version as the git SHA, pass branches separately and record environments through record-deployment. For the provider I set up selectors, pending pacts and a webhook, and I keep provider states independent.
Pact JS/TS: an example, matchers and what not to put in a contract
A Pact contract describes the response shape through matchers, not exact values: like checks the type, eachLike an array, regex a string against a pattern. The consumer test runs real client code, and the contract holds only fields the client reads and only errors it handles. Business logic stays out of the contract: otherwise verification fails without a real break, and the team stops trusting Pact.
API · Contract testing in practice
A Pact test fails every time the provider changes a value. What is wrong with the contract?
The provider refreshed its test data and the verification is red: the contract records "total": 150 and now it is 175. There is no real breakage, the API works as before. After the third such case the provider team starts ignoring Pact. This loss of trust is a heavier consequence than a missed bug. The lesson shows how to write a consumer test that tells "shape" from "value" and what is better left out of a contract.
How it works and why it is designed so
An example consumer test in Pact JS (the @pact-foundation/pact package, the PactV3 API; for new tests the Pact JS docs recommend PactV4, exported as Pact, with the same idea):
The provider state: before verification the provider brings the system to "order 42 exists".
like(42): the type (a number) is checked, not the value 42.
eachLike: an array of at least one element of this shape.
The real client code hits the mock server: the test checks that the client parses the response.
Matchers. An example value in a contract does not mean "must be exactly this". like(x) checks the type, eachLike(template) an array with at least one element of that shape, regex(pattern, example) a string by a pattern, and there are also integer, datetime, uuid. Without matchers Pact compares values literally, and the provider fails on every data change.
The consumer test must run the real client code (the HTTP client, parsing), not check the mock itself. The goal is simple: if the client expects a field, it is in the contract; if the client does not read it, it is not.
Worked example: from a brittle contract to a thin one
One contract in two versions
Too tight
Exact values and extra fields
total: 150, every field of the response, the order of elements. The provider fails on every data change and the team stops trusting the tests.
Sufficient
The type and shape of what the client reads
total: like(150) and only the fields the client really uses. A change in data does not break verification, a change in shape does.
Figure 1. A brittle contract breaks with no real breakage and costs trust in the tests.
The diagnosis is simple: in the verification report the difference concerns a value (150 versus 175) with the type unchanged. The fix: replace the literal with a matcher and remove the fields the client code does not read. After that the verification fails only where the client would really break: a field disappeared or changed type.
What NOT to put in a contract
Business logic and exact values. The contract says "total is a number", not "total = 150 for this cart". Logic is checked by the provider's functional tests.
Fields the consumer does not use. Extra fields tie the provider down for no gain and get in the way of its refactoring.
All error codes "just in case". Only those the client really handles (404, 409, 422 with an error body).
UI details. A test through the browser instead of the client layer makes the contract slow and brittle.
A useful rule: "write the contract as an acceptance test of the consumer's need", not as a copy of the provider's response.
Common mistakes
Literals instead of matchers: verification fails on data changes.
The test checks the mock, not the client: the contract is "green" while a client that parses the response wrongly is not caught.
Copying the provider's whole response as the contract: extra fields and exact values.
Check yourself
The contract has status: regex('NEW|PAID|SHIPPED', 'NEW'). The provider added a CANCELLED status. Will the verification fail?
Answer
Only if the real response during verification contains CANCELLED: then the value does not match the pattern. That is the right signal if the client cannot handle the status, so before adding a new value you check who reads it.
Why must the consumer test call the real client code rather than just send a request to the mock?
Answer
The contract should reflect what the client really reads. If the test does not go through the client code, the contract holds what the author "thinks is needed", and nobody checks how the client parses the response.
Related lessons: “Pact end to end: consumer test, Broker, can-i-deploy”, “Schema validation in code: ajv and zod”, “Consumer-driven contracts: where they sit in the test pyramid”.
In an interview.Junior: In the contract I describe the request and the shape of the response through matchers: like for a type, eachLike for an array. I do not fix exact values. Middle/Senior: The consumer test goes through the real client code, and the contract holds only the fields the client reads and only the errors it handles. Business logic stays with the provider's functional tests. That keeps the team's trust: a red Pact means a real breakage.
Bi-directional, schema-based and message contracts; adopting it in a team
Beyond classic Pact there are bi-directional contracts (a PactFlow feature), schema-based checks and message pacts for queues. Bi-directional compares the provider's OpenAPI with the consumer's pact statically: cheaper, but a weaker guarantee, as no real request is made. A message pact checks the message shape, not the transport. Adoption starts with one critical integration, through to can-i-deploy.
API · Contract testing in practice
Contract testing: start with the whole system or with one integration?
Classic CDC works well when consumers are known and ready to write contracts. And what if the provider already has OpenAPI, the team is not ready to set up provider states, the interaction goes through a message queue, or there are simply too many consumers? The lesson goes through the options next to Pact: bi-directional contracts, a schema-first approach, fuzzing from OpenAPI and message pacts, and ends with advice on introducing it in a team.
How it works and why it is designed so
Bi-directional contract testing (a PactFlow feature from SmartBear; Pact OSS does not have it) removes the need for provider states and verification of every pact. The provider publishes its OpenAPI specification together with the results of its own tests ("the specification really matches the code"), the consumer publishes a pact with its expectations (they can be generated from mocking tools such as Mock Service Worker or Cypress), and PactFlow statically compares them for compatibility. Plus: a low entry barrier, the provider does not have to maintain states. Minus: a weaker guarantee. The correctness of the specification depends on what confirms it, and the comparison does not make a real request.
Consumer-driven or bi-directional: two legitimate options
Consumer-driven (Pact)
A stronger guarantee
A real request against the provider's real code with states. More work: states, verification in the provider's CI.
Bi-directional
A lower entry barrier
A static comparison of the provider's OpenAPI with the consumer's pact. No states needed, but the guarantee is weaker: a spec is only as true as its tests.
Figure 1. The choice depends on how much effort the team is ready to put into states and verification.
Other approaches alongside
Provider-driven (schema-based). When there are many consumers or they are unknown, the provider's OpenAPI is the basis: a specification linter, a breaking-change check between versions (for example oasdiff) and client generation. This complements CDC rather than competing with it.
Schema-based fuzzing. Tools such as Schemathesis read OpenAPI and generate hundreds of requests (boundary values, missing fields, wrong types), checking that responses match the schema and the server does not return 500. The name of the address flag depends on the major version of the tool, so read the documentation of the installed one. This finds mismatches between the specification and reality, but does not check what a specific consumer needs.
Asynchronous interactions. For queues and events (Kafka, SQS, RabbitMQ) Pact has message pacts: the contract describes the shape of a message. The consumer checks that its handler accepts such a payload; the producer proves in verification that its code generates a message of that shape. The transport does not take part, so the configuration of topics and the broker is checked separately.
Worked example: how to adopt it without getting stuck
A typical failed start: a team decides to describe all twenty integrations with contracts, writes three dozen pacts in a month, none of them sits in a blocking pipeline, and nobody trusts the results. The working order is the opposite: one critical integration, the full cycle up to can-i-deploy, and only then the next one.
The order of adoption
Figure 2. A full cycle on one pair beats half a cycle on twenty.
The QA role: helping to write "thin" contracts, watching that states are independent and showing the value through metrics: breaking changes caught, a smaller e2e set, time from PR to release.
Typical traps
An over-specified contract: exact values, extra fields, the order of elements. The provider fails with no real breakage and the team stops trusting the tests.
Shared fixtures and dependent provider states: the state "an order exists" leans on data from another test and verification is unstable.
Verification against the wrong version: the provider's main is checked, although another version runs in production. Cured by selectors and can-i-deploy --to-environment.
A contract without can-i-deploy: the pacts exist but nobody blocks a deploy.
Verification against the provider's real dependencies: that is an integration test again. Dependencies need stubbing.
Check yourself
A team has the provider's OpenAPI and no wish to maintain provider states. Which approach do you consider first and at what cost?
Answer
Bi-directional: PactFlow compares the provider's spec with the consumer's pact statically. The cost: a weaker guarantee, because the comparison makes no real request and the spec is only as true as the provider's tests confirm.
Why does a message pact not prove that a Kafka topic is configured correctly?
Answer
The contract describes only the shape of a message: the consumer checks the handler, the producer checks the generation. The transport takes no part, so topics, permissions and broker settings are checked by other tests.
Related lessons: “Consumer-driven contracts and breaking changes”, “Swagger/OpenAPI in testing”, “Pact end to end: consumer test, Broker, can-i-deploy”.
In an interview.Junior: Besides Pact there are bi-directional contracts with OpenAPI, schema fuzzing and message pacts for queues. It is better to adopt it from one integration. Middle/Senior: I choose by guarantee and cost: CDC gives a real verification with states, bi-directional is cheaper but static, a schema with oasdiff suits unknown consumers. I start with one critical link and take it to can-i-deploy, and show success with metrics: breaking changes caught and fewer e2e tests.