My account

Contracts Between Services

A contract is everything two services agree on: the data shape, the meaning of each field, and the rules. Choose how strict it is on purpose. Send only the data consumers need, not the whole object. And let consumers write down what they use, so the provider's pipeline knows before release when a change will break someone.

Not reviewedWritten with AI helpReading time: 11 minOnline shop exampleStrict and loose contractsConsumer-driven contract tests

Author: bezzad

Contents

The problem: “We only removed an unused field”

The Customer team cleans up their API. They remove the field “middleName”, because “nobody uses it”. All their tests pass. They release on Friday.

On Saturday the Invoice service crashes. It printed the middle name on invoices. Nobody in the Customer team knew.

The Customer team did not do anything strange. The problem is that nobody wrote down who uses what.

What is a contract?

A contract is everything two services agree on. It is more than the field names:

  1. Shape. Which fields, which types, which are required.
  2. Meaning. “total” includes tax or not? Which currency? Which time zone?
  3. Rules. Error codes, limits, how fast it answers, if a message can arrive twice.
  4. Change policy. How the provider announces changes and how long old versions live.

A contract is the “small public contract” of the coupling lesson: the only knowledge that should cross the border between two far parts.

How strict should it be?

StrictLooseTyped clientgenerated from a schemaPublished schemachecked on every messageTolerant readerreads only what it needsFree key-value mapanything goes+ errors found at build time− every change ripples to consumers+ provider can add and change freely− errors found later, at runtime
Strict contracts catch errors early but make every change ripple. Loose contracts allow change but catch errors late.
  • Strict. A schema (for example OpenAPI, JSON Schema, Protobuf or Avro) with types and required fields. Tools generate typed clients and check every message. You see errors at build time. But every change in the schema reaches all consumers.
  • Loose. The consumer reads plain JSON and takes only the fields it needs. It ignores unknown fields. The provider can add fields freely. But a missing field is found only at runtime.

There is no single right answer:

  • Inside one team, or for a stable, important contract like payments: lean strict.
  • Between many teams that change at different speeds: lean loose on the reading side (a “tolerant reader”), and add contract tests (below) to catch real breaks.

Send only what is needed

Customer serviceEmail serviceWhole Customer messageemailfirstNamelastNamebirthDatephoneaddressesloyaltyLevelcreditLimittaxIdnotes… and 4 moreUses 2 fields, but breaks when any of the 14 changes
The Email service needs two fields but receives fourteen. Now it can break when any of them changes.

Sending the whole object “because it is easy” creates stamp coupling: the consumer is tied to a big data shape it does not need.

  1. Every change in any of the fields is a possible break.
  2. More data goes over the network on every call.
  3. Private data (birth date, tax id) is copied to places that should not have it.

Better: design the message for its consumers. For example, an event for the order flow:

// Made for consumers: only what they need, with clear meaning.
public sealed record OrderPlaced(
    Guid OrderId,
    Guid CustomerId,
    decimal TotalWithTax,
    string Currency,          // ISO code, for example "EUR"
    DateTimeOffset PlacedAt);

And a consumer that reads only its fields. The System.Text.Json serializer ignores unknown fields by default, so the provider can add new fields without breaking it:

// The Email service reads only what it uses.
public sealed record OrderPlacedForEmail(Guid OrderId, Guid CustomerId);

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var msg = JsonSerializer.Deserialize<OrderPlacedForEmail>(json, options);

Consumer-driven contracts

How does the provider know who uses which field? Let the consumers write it down, as tests.

Shippingneeds: id, addressEmailneeds: id, emailInvoicesneeds: id, totalContract storeone file per consumerOrder servicepipeline checksevery contractA broken contractstops the release
Each consumer publishes what it needs. The provider's pipeline checks all of them and stops a release that would break one.
  1. The consumer writes its expectations. The Shipping team writes: “I ask for one order by its id, and I need its id and address.” This is a small test in the Shipping code.
  2. The expectations become a contract file. It is shared in one place, for example a contract broker or a shared repository.
  3. The provider checks all contracts. The Order service pipeline replays each consumer’s requests against the real service and checks the answers.
  4. A broken contract stops the release. If the Order team removes “address”, the pipeline fails before production, and it says which consumer needs it.

Tools like Pact work this way. The benefit is big: the provider can change anything that no consumer uses, with confidence.

Changing a contract safely

When a real change is needed, change in small, safe steps. The lesson on schema evolution shows these in detail:

  1. Add, do not change. Add the new field next to the old one.
  2. Move the consumers to the new field, one by one. Contract tests show who is left.
  3. Remove the old field only when no contract uses it.

For a big break, publish a new version (for example /v2) and keep the old one for an agreed time.

Common mistakes

Mistake Result The right way
No written contract “Unused” fields that someone uses. A schema, plus consumer contract tests.
Sending the whole object Stamp coupling and data leaks. Messages designed for their consumers.
Strict reading of every field Any new field breaks consumers. Tolerant reader: ignore unknown fields.
Meaning not written “total” with or without tax? Document units, currency and time zone.
Breaking change in one step Friday release, Saturday outage. Add, move consumers, then remove.

Summary in six lines

  1. A contract is shape, meaning, rules and a change policy.
  2. Strict contracts catch errors early; loose ones allow change but fail later.
  3. Send only the fields consumers need; the whole object creates stamp coupling.
  4. A tolerant reader ignores unknown fields, so the provider can add freely.
  5. Consumer-driven contract tests tell the provider who uses what, before release.
  6. Change in steps: add, move consumers, then remove.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.