Platform Engineering · Lesson 65

Contract and Resilience Testing: Consumer-Driven Contracts, Fault Injection, and Retry Budgets

Unit tests prove a service does what its own team expects; they say nothing about what its callers expect, or about how it behaves when the things it calls go slow. Contract tests close the first gap: each consumer records the parts of an API it relies on, and the provider's pipeline refuses a change that breaks any of them. Resilience tests close the second: inject latency and errors into a dependency on purpose and check that timeouts, retries, and circuit breakers keep the failure small instead of multiplying it. This lesson follows one provider change through a pipeline with both, and shows a breaking rename that only contracts would catch and a retry storm that only fault injection would find.

Difficulty: Advanced · Know this first: Lesson 38, Lesson 37, Lesson 64

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits one provider change through the pipeline, in minutes. It is a worked example, not a measurement. The contract check is a small slice that protects every consumer; the canary is the slowest and most expensive place to find a problem.

Try it: how much do retries multiply load on a slow dependency?

Set the request rate, the client timeout, the retries, and an optional retry budget. When the dependency is slower than the timeout, every retry is another call to it.

If the dependency is slower than the timeout, calls = requests × (1 + retries), or requests + requests × budget with a retry budget

1,600calls/s to the dependency
4.0xnormal load
2.0 saverage wait per request

Retry storm: the slow dependency gets 4.0 times its normal load

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Contract and resilience testing grow in four levels: first what each test kind proves, then writing contracts and fault tests, then running them as deployment gates, and finally doing it across many teams.

Basic — Two questions unit tests cannot answer

At the basic level you can say what each test proves. A contract test proves a provider still gives each consumer what it relies on. A resilience test proves a service keeps a dependency's failure small. Neither replaces unit tests; both cover gaps unit tests cannot.

Terms: provider, consumer, contract, Pact Broker, can-i-deploy, fault injection, timeout, retry budget, circuit breaker, expand and contract.

Where it breaks: relying on end-to-end tests for compatibility; they are slow, flaky, and say "something broke" rather than "billing needs total_cents".

Try it: Basic

Which test tells you that your change breaks a specific consumer?

Now do it: Run contracts.py in Go deeper and add a contract for a third consumer that reads gift_wrap.

Intermediate — Write contracts and fault tests

At the intermediate level you write both.

  • Consumer side: tests against a mock provider that record the requests and the fields the consumer reads, published to a broker with the consumer's version.
  • Provider side: a verification step that replays the contracts against the real provider in CI, with provider states (fixtures) for each interaction.
  • Fault tests: Toxiproxy or a mesh fault rule adding latency and errors to one dependency while a small load runs, with assertions on the service's error rate, latency, and calls to the dependency.

Try it: Intermediate

A provider verification fails because a consumer's contract expects an order in state "shipped" that does not exist in the test data. What is missing?

Now do it: Write a Toxiproxy setup for one dependency of a service you know, with a 2-second latency toxic.

Advanced — Gates in the pipeline

At the advanced level the tests decide deployments.

  • can-i-deploy before every environment, recording what was deployed where so the broker knows which versions are live.
  • Webhooks: a consumer publishing a new contract triggers provider verification, so neither waits.
  • Fault scenarios as code: latency, error rates, and outages for each critical dependency, run on every release candidate, with thresholds on error rate and dependency load.
  • Retry hygiene: timeouts shorter than the caller's, retries only for idempotent calls, jittered backoff, a retry budget, and a circuit breaker.

Try it: Advanced

Your retry policy is 3 retries with backoff. What does a retry budget add?

Now do it: Use the simulator to find the retry budget that keeps the dependency under 1.5x load with 3 retries.

Master — Across many teams

At the master level contracts and resilience are organisation-wide practice.

  • Coverage: every internal API has contracts from its consumers; uncovered consumers are visible in the broker.
  • Deprecation: fields and endpoints are removed only when no live contract uses them, with dates published.
  • Game days: fault scenarios move from staging to production in controlled experiments, with steady-state hypotheses and abort criteria.
  • Platform: a shared broker, Toxiproxy or mesh fault tooling, and pipeline templates so teams adopt it by default.

Trade-off: contracts add work for consumers and a broker to run, and remove most end-to-end tests and breaking-change incidents. Fault tests add minutes to every release and find the failures that cost hours in production.

Try it: Master

You want to delete a deprecated field. How do you know it is safe?

Now do it: List the internal APIs your team provides and which consumers have contracts for them.

Go deeper

Both checks fit in a few lines. This script verifies three provider changes against two consumers' contracts and measures what retries do to a slow dependency, with and without a retry budget. Standard library only; python3 contracts.py.

Contracts, and a retry storm

# contracts.py - consumer-driven contract checks, and a fault-injection test of a client's retries
CONTRACTS = {  # what each consumer relies on in GET /orders/{id}: field -> type
    "billing": {"id": str, "total_cents": int, "currency": str},
    "mobile-app": {"id": str, "status": str, "eta_minutes": int},
}

def verify(response, contracts):
    """Provider-side verification: does the response still satisfy every consumer's contract?"""
    broken = []
    for consumer, fields in contracts.items():
        for name, kind in fields.items():
            if name not in response:
                broken.append(f"{consumer}: field '{name}' is missing")
            elif not isinstance(response[name], kind):
                broken.append(f"{consumer}: '{name}' is {type(response[name]).__name__}, expected {kind.__name__}")
    return broken

current = {"id": "o-17", "status": "shipped", "total_cents": 4599, "currency": "EUR", "eta_minutes": 35}
changes = {
    "add a field (gift_wrap)": dict(current, gift_wrap=False),
    "rename total_cents to amount": {k: v for k, v in current.items() if k != "total_cents"} | {"amount": 4599},
    "send eta_minutes as text": dict(current, eta_minutes="35"),
}
for name, response in changes.items():
    broken = verify(response, CONTRACTS)
    print(f"{name:<32} -> {'can deploy' if not broken else 'BLOCKED: ' + '; '.join(broken)}")

# Fault injection: the dependency slows to 2 s for a minute. How much load do the clients' retries add?
def calls_per_second(rps, timeout_s, retries, dependency_s, budget=None):
    if dependency_s <= timeout_s:
        return rps
    extra = rps * retries
    if budget is not None:
        extra = min(extra, rps * budget)            # a retry budget caps retries at a share of requests
    return rps + extra

rps = 400
for label, timeout_s, retries, budget in [("no timeout, no retries", 30.0, 0, None), ("timeout 0.5 s, 3 retries", 0.5, 3, None),
                                          ("timeout 0.5 s, 3 retries, 10% budget", 0.5, 3, 0.10)]:
    load = calls_per_second(rps, timeout_s, retries, 2.0, budget)
    print(f"{label:<38} -> {load:>6.0f} calls/s reach the slow dependency ({load / rps:.1f}x the normal load)")
$ python3 contracts.py
add a field (gift_wrap)          -> can deploy
rename total_cents to amount     -> BLOCKED: billing: field 'total_cents' is missing
send eta_minutes as text         -> BLOCKED: mobile-app: 'eta_minutes' is str, expected int
no timeout, no retries                 ->    400 calls/s reach the slow dependency (1.0x the normal load)
timeout 0.5 s, 3 retries               ->   1600 calls/s reach the slow dependency (4.0x the normal load)
timeout 0.5 s, 3 retries, 10% budget   ->    440 calls/s reach the slow dependency (1.1x the normal load)

Read it like this: the new field passes, the rename blocks on billing, and the type change blocks on the mobile app, each with the field named. Then a dependency slowed past the timeout gets four times its traffic with 3 retries, and about 1.1 times with a 10 percent budget.

A consumer contract, as Pact records it

{
  "consumer": {"name": "billing"},
  "provider": {"name": "orders"},
  "interactions": [{
    "description": "a shipped order",
    "providerState": "order o-17 exists and is shipped",
    "request": {"method": "GET", "path": "/orders/o-17"},
    "response": {"status": 200, "body": {"id": "o-17", "total_cents": 4599, "currency": "EUR"}}
  }],
  "metadata": {"pactSpecification": {"version": "2.0.0"}}
}

The file is a simplified Pact version 2 contract and parses as JSON; real Pact files usually add matching rules so values like the id can vary. The provider pipeline verifies it with its Pact verifier and asks the broker before deploying, for example pact-broker can-i-deploy --pacticipant orders --version $GIT_SHA --to-environment production. Check the flags against your broker CLI version.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A payments provider renamed a response field as part of a cleanup and updated every test in its own repository.

Timeline

  • Day 1The change passes CI and a canary; overall error rates do not move, because only one consumer reads the field and it calls rarely.
  • Day 3Month-end invoicing runs. Every invoice fails; the field it reads no longer exists.
  • Day 3Rolled back. Invoicing re-runs a day late.

What changed after

Consumers of the payments API publish contracts to a broker, and the provider's pipeline verifies them and runs can-i-deploy before each environment. Renames now go through expand and contract. The same review added fault tests after finding that the invoicing client retried three times with no budget.

If you remember nothing else

Design exercise

Introduce contract and resilience testing for an orders API used by six internal consumers, two of which are batch jobs that run monthly.

Clarifying questions to ask

Which consumers can publish contracts, and who owns them? Which fields does each read? Which dependencies does the orders API call, and with what timeouts and retries? Where can faults be injected safely? How will monthly jobs be represented before they run?

Rough sizing

Say 400 requests a second, three dependencies, six consumers on different release schedules, and a 30-minute pipeline budget.

Shape of the answer

A Pact Broker; consumer tests publishing contracts on every build; provider verification and can-i-deploy in the orders pipeline; webhooks to re-verify when contracts change; expand-and-contract for removals; Toxiproxy in staging with latency, error, and outage scenarios per dependency; assertions on error rate and dependency load; retry budgets and circuit breakers in the clients.

Trade-offs to name

Contracts add work to consumers and need a broker, and replace most cross-team end-to-end tests. Fault tests lengthen the pipeline by minutes and need realistic staging dependencies. Monthly jobs are easy to forget; their contracts must exist even though they rarely call.

Saved on this device, in this browser.
Next in this series · Lesson 66
Capacity Planning and Load Testing

I have watched a sale day go sideways in the first ten minutes. The traffic was not even that surprising. We had just planned for the average day instead of the peak hour, and the average day never shows up on sale day.

Go to Lesson 66 →

Or browse the full course from the Lessons index.