Lesson 23 of 28Quality and safety
Contract Tests and Architecture Tests
Replace slow cross-service end-to-end suites with consumer-driven contracts, schema checks and tests that enforce your architecture's rules.
It is Thursday afternoon. The billing team renames amount_cents to a nested amount object, every billing test passes, and they deploy. Ten minutes later the checkout page shows "NaN" for every invoice, because the checkout team read that field and nobody told them. The company has an end-to-end suite that would have caught it, but it takes 50 minutes, needs eight services running in a shared staging environment, and fails randomly so often that people re-run it until it goes green. This lesson is about the tests that catch that bug in seconds, inside each team's own pipeline: contract tests between services, and architecture tests that stop your own codebase drifting away from its design.
Why cross-service end-to-end tests do not scale
In Testing Strategy you met the pyramid and a contract test for a fake repository. Between services the problem gets harder. To run an end-to-end (E2E) test across services you need every service deployed, at the right versions, with matching test data, in one environment. That has four costs that grow with the number of services:
- Slow. Each test crosses several network hops and databases. Suites of 30 to 60 minutes are normal.
- Flaky. Any one service being redeployed, out of data, or slow makes a test fail for reasons that have nothing to do with your change.
- Late. You find the break after merging, often in a shared staging environment, where it blocks everyone else too.
- Wrong versions. Staging runs whatever was deployed last. Production may be running something else. A green run proves that these versions work together, not that your version works with what is live.
The last point is the one people miss. The real question before a deploy is: "Is the version I am about to ship compatible with the versions of its neighbours that are in production right now?" An E2E suite in staging answers a different question.
A contract test splits the problem in half. Instead of running both sides together, you write down the agreement between them (the contract) and test each side against that agreement on its own. Each half is a fast, deterministic test that runs in one team's CI.
Consumer-driven contracts with Pact
Pact is the most widely used tool for this. The idea is consumer-driven: the consumer (the side that calls the API) writes down exactly what it sends and exactly what it needs back. Not the whole response, only the fields it reads. The provider then proves it still satisfies every consumer's needs.
The consumer side is a unit test against a mock server that Pact runs for you. Here is the checkout web app's test of its billing client, using pact-js:
import { PactV3, MatchersV3 } from "@pact-foundation/pact";
import { getInvoice } from "./billing-client";
const { like, integer, string } = MatchersV3;
const provider = new PactV3({ consumer: "checkout-web", provider: "billing-api" });
it("reads an invoice", () => {
provider
.given("invoice 42 exists")
.uponReceiving("a request for invoice 42")
.withRequest({ method: "GET", path: "/invoices/42" })
.willRespondWith({
status: 200,
headers: { "Content-Type": "application/json" },
body: like({ id: 42, amount_cents: integer(1999), currency: string("GBP") }),
});
return provider.executeTest(async (mockServer) => {
const invoice = await getInvoice(mockServer.url, 42);
expect(invoice.amountCents).toBe(1999);
});
});Three things happen. Your real client code runs against the mock, so the test proves your client sends that request and can parse that response. The matchers (like, integer, string) say "any value of this type", so the contract is about shape, not about the literal 1999. And when the test passes, Pact writes a pact file: a JSON document of every interaction.
{
"consumer": { "name": "checkout-web" },
"provider": { "name": "billing-api" },
"interactions": [
{
"description": "a request for invoice 42",
"providerStates": [{ "name": "invoice 42 exists" }],
"request": { "method": "GET", "path": "/invoices/42" },
"response": {
"status": 200,
"body": { "id": 42, "amount_cents": 1999, "currency": "GBP" },
"matchingRules": { "body": { "$.amount_cents": { "matchers": [{ "match": "integer" }] } } }
}
}
],
"metadata": { "pactSpecification": { "version": "3.0.0" } }
}Read it field by field. providerStates names a setup the provider must arrange before replaying the request ("invoice 42 exists"). request is replayed verbatim against the real provider. response.body is the example, and matchingRules says how strictly to compare it. Newer Pact versions write specification V4, which wraps each interaction with a type such as synchronous HTTP or asynchronous message, but the ideas are the same.
On the provider side, billing's CI starts the real API (with a test database) and runs a verifier. The verifier fetches every pact that names billing-api, sets up each provider state through a hook you write, replays each request, and checks each response against the rules.
import { Verifier } from "@pact-foundation/pact";
it("honours its consumers' contracts", () =>
new Verifier({
provider: "billing-api",
providerBaseUrl: "http://localhost:8000",
pactBrokerUrl: process.env.PACT_BROKER_URL,
providerVersion: process.env.GIT_SHA,
publishVerificationResult: true,
stateHandlers: {
"invoice 42 exists": async () => { await seedInvoice({ id: 42, amountCents: 1999 }); },
},
}).verifyProvider());The key property: the provider is free to change anything no consumer relies on. If billing adds a pdf_url field, or removes one nobody reads, every pact still passes. Contracts make change safe and make the safe changes obvious. Here is the whole loop in miniature, so you can see why.
Press Run (⌘ Enter) to see what happens.What does this print?
contract_fields = {"id": int, "amount_cents": int, "currency": str}
def billing_v3():
# pdf_url removed, new field "status" added
return {"id": 42, "amount_cents": 1999, "currency": "GBP", "status": "paid"}
body = billing_v3()
missing = [f for f in contract_fields if f not in body]
print(len(missing), "status" in contract_fields)The broker and can-i-deploy
Pact files have to travel from consumer CI to provider CI. Emailing JSON does not scale, so teams run a Pact Broker (open source, or the hosted PactFlow). The broker stores every pact and every verification result, tagged with the git SHA of each side, and knows which versions are deployed to which environment. That turns "is it safe to deploy?" into a query.
The consumer's unit tests pass and produce a pact. CI publishes it, tagged with the consumer's git SHA and branch.
pact-broker can-i-deploy --pacticipant checkout-web --version "$GIT_SHA" --to-environment productionpact-broker record-deployment --pacticipant checkout-web --version "$GIT_SHA" --environment productionBoth sides run can-i-deploy. The consumer asks before shipping code that relies on a new field. The provider asks before shipping a change that might break a live consumer. This is what replaces the shared staging gate: compatibility is checked against what is actually in production, per version, in seconds.
Put the consumer-driven contract workflow in order, for a consumer that starts reading a new field.
- Tap the steps below in the right order.
Schema-first contracts
Consumer-driven contracts work best when you know your consumers and they can run Pact. Often you do not, or the contract already exists as a schema. Then the schema is the contract, and you test both sides against it.
- OpenAPI for HTTP. You met Schemathesis in Testing with Real Databases: it reads your FastAPI app's
/openapi.json, generates thousands of requests, and checks responses match. On top of that, run a breaking-change diff of the schema in CI (tools such asoasdiffcompare two OpenAPI files and flag removed fields, new required parameters, and narrowed types). Consumers generate their client from the same file, so their compiler catches drift. - Protobuf for gRPC.
buf breaking --against '.git#branch=main'compares your.protofiles with main and fails on wire-breaking changes, such as reusing a field number or changing a field's type. Protobuf's rules are strict and well defined, which makes this check cheap and reliable. - Events. Messages on Kafka or a queue need contracts too, and they are easier to break because nobody gets an error response. Describe each topic with AsyncAPI or a JSON Schema (or Avro or Protobuf), store it in a schema registry, and set a compatibility mode. Backward compatible means new consumers can read old messages; forward means old consumers can read new messages. The registry rejects a producer that tries to register an incompatible schema. Pact also supports message pacts for asynchronous interactions.
Bi-directional (or provider-driven) contracts combine the two. The provider publishes its OpenAPI file plus evidence that it was tested against it (say, a Schemathesis run). Consumers publish pacts, or mocks generated from their own tests. The broker checks that every consumer expectation is a valid subset of the provider's schema, without replaying requests. This fits public or widely shared APIs, where the provider cannot run every consumer's verification, and teams that already have good schema tests. It is weaker than replaying requests: the schema says a field is an integer, but only a real replay proves the provider actually returns it in the state the consumer cares about.
Match each situation to the contract approach that fits best.
Architecture tests: your design as executable rules
Contracts protect the line between services. Inside one codebase, a different kind of drift happens. Layered Architecture taught "dependencies point inward". Six months later a deadline arrives, someone imports HTTPException into the domain to save ten minutes, and review does not spot it. A year later the domain cannot be tested without FastAPI, and nobody remembers deciding that.
An architecture test turns the rule into a check that fails CI. These are a kind of fitness function: an automated, objective measure of one architectural property. In Python the standard tool is import-linter:
[importlinter]
root_package = app
include_external_packages = True
[importlinter:contract:layers]
name = API calls services, services call domain
type = layers
layers =
app.api
app.services
app.domain
[importlinter:contract:pure-domain]
name = The domain does not know about frameworks
type = forbidden
source_modules =
app.domain
forbidden_modules =
fastapi
sqlalchemyRun lint-imports in CI, next to ruff and mypy. The layers contract means a higher layer may import a lower one but never the reverse. The forbidden contract bans specific imports. In TypeScript, dependency-cruiser does the same with rules such as "nothing in src/domain may import from src/ui", and eslint-plugin-boundaries enforces feature boundaries in React apps. On the JVM, ArchUnit writes these rules as ordinary unit tests, and the pattern is often called "ArchUnit-style" in other languages.
The mechanism is simple enough to build yourself. This version parses imports with ast and applies two rules: the domain stays pure, and services talk to adapters only through ports.
Press Run (⌘ Enter) to see what happens.Two habits make architecture tests stick. First, add them to a legacy codebase with the existing violations listed as known exceptions (import-linter supports ignore_imports), then shrink the list over time. A rule that fails on day one gets deleted. Second, keep the rules few and meaningful: layer direction, no framework in the domain, no cycles between modules, and no reaching into another module's internals. Other fitness functions follow the same pattern: a budget on bundle size, a maximum p95 latency in a load test, or "no new endpoint without an auth dependency".
Test data and environments
Contracts and architecture tests shrink the need for shared environments, but each service still needs realistic integration tests of its own. Two tools carry most of the weight.
Testcontainers starts real dependencies (Postgres, Kafka, Redis, LocalStack for AWS) in throwaway Docker containers from inside the test run, then deletes them. Each test run gets a clean, real database at the same version as production, with no shared state between developers or CI jobs. It has libraries for Python, Java, Go, Node and .NET.
Ephemeral preview environments spin up a full copy of a service (often the whole app, for a frontend) per pull request, seeded with synthetic data, and tear it down on merge. They are excellent for manual review and a handful of smoke tests. They are not a replacement for contracts: a preview environment still pairs your branch with whatever versions of neighbours it was given.
For test data, prefer factories that build exactly the rows a test needs over a shared seed dump that every test depends on. Shared fixtures are the main source of "it passes alone and fails in the suite".
Where each test lives
Put together, each service owns a fast suite that it can run alone, and only a thin layer of tests ever needs more than one service.
Each service keeps its own pyramid: many unit tests, integration tests at its seams, and architecture tests in the same CI job.
- contract test
- A test of one side of an integration against a written agreement, so each side can be verified alone.
- consumer-driven contract
- A contract written by the caller, listing only the requests it sends and the response fields it relies on.
- provider state
- A named setup, such as 'invoice 42 exists', that the provider arranges before a pact interaction is replayed.
- can-i-deploy
- A Pact Broker check that a version has been verified against the versions of its neighbours deployed to an environment.
- schema registry
- A store of event schemas that rejects new versions which break the configured compatibility mode.
- architecture test
- An automated check, such as an import rule, that fails the build when code breaks the intended structure.
- fitness function
- Any objective, automated measure of an architectural property, run continuously like a test.