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
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.
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
Retry storm: the slow dependency gets 4.0 times its normal load
Three questions. No score is saved anywhere — this is just you against the material.
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.
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.
At the intermediate level you write both.
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.
At the advanced level the tests decide deployments.
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.
At the master level contracts and resilience are organisation-wide practice.
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.
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.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.
{
"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.
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.
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.
Introduce contract and resilience testing for an orders API used by six internal consumers, two of which are batch jobs that run monthly.
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?
Say 400 requests a second, three dependencies, six consumers on different release schedules, and a 30-minute pipeline budget.
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.
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.