Services

Resources

Company

Print-style illustration on mustard: a consumer service and a provider service fit together like puzzle pieces, with a stamped contract above the joint and a dashed verification loop running between them
Print-style illustration on mustard: a consumer service and a provider service fit together like puzzle pieces, with a stamped contract above the joint and a dashed verification loop running between them

Contract Testing with Pact: A Practical Guide for Java Microservices

Contract Testing with Pact: A Practical Guide for Java Microservices

Print-style illustration on mustard: a consumer service and a provider service fit together like puzzle pieces, with a stamped contract above the joint and a dashed verification loop running between them

Contract Testing with Pact: A Practical Guide for Java Microservices

Print-style illustration on mustard: a consumer service and a provider service fit together like puzzle pieces, with a stamped contract above the joint and a dashed verification loop running between them

Contract Testing with Pact: A Practical Guide for Java Microservices

On a recent client project, we were working on a set of Java services owned by different teams. Each service had decent unit tests and its own build pipeline, and integration was tested in a shared staging environment. Most of the bugs that hurt us didn’t live inside any one service. They lived in the calls between them.

Here’s a simplified version of what kept happening. An orders service calls a users service to get a customer’s name and email before confirming an order. The users team renames email to emailAddress. Their unit tests pass, since they were updated for the new field. The orders tests pass too, because they run against a stub someone wrote months ago that still returns email. Both get deployed, and order confirmations start going out with no recipient.

Staging can catch this, but only after both changes are merged and deployed together, and only if someone happens to exercise that path. When it does fail, it’s not always obvious whose change broke it. We wanted that failure to show up in the users team’s own build, on the commit that caused it.

Contract testing gave us that, and we used Pact to do it. This post walks through how it works and how we set it up with Java and Spring Boot.

What contract testing checks

A contract is the list of requests a consumer makes and the responses it expects back. Contract testing checks that both sides agree on that list, without running them together.

Take the example above. orders is the consumer and users is the provider. The contract between them says roughly this: when orders sends GET /users/42, users replies with 200 and a JSON body that has a numeric id, a string name and a string email. This is what orders relies on.

Contract testing checks the two halves of that separately. On the orders side, it checks that the client really sends that request and can handle that response. On the users side, it checks that the real service really returns it. When the users team renames email to emailAddress, the second check fails, in their build.

Pact is consumer-driven. The consumer’s tests produce the contract, and the provider has to prove it can honour it. This also means the provider is only held to what consumers actually use. If nobody reads a field, the provider can change or drop it.

It also differs from schema-based checks such as validating against an OpenAPI spec. The Pact docs call it contract by example: a contract is a list of concrete request/response pairs, not a description of every possible shape (Pact docs). A schema tells you the provider could return email. A pact tells you a named consumer depends on it.

Approach

What it proves

Where it fails

Unit tests with hand-written mocks

Each service works against its own idea of the other

Mocks drift silently from reality

End-to-end tests in a shared environment

The whole system works, once deployed together

Slow, flaky, late feedback, unclear ownership

Schema validation (OpenAPI)

Provider matches its published spec

Doesn’t prove consumers call it correctly

Consumer-driven contracts (Pact)

Provider satisfies what each consumer actually uses

Needs both teams to adopt it

How Pact works

Pact splits one integration test into two halves that run in different pipelines. The pact file is the only thing that crosses between them.

Pact flow: in consumer CI, the consumer test calls the Pact mock server, which records a pact file that is published to the Pact Broker. In provider CI, the verifier fetches pacts, replays each request against the real users service and publishes results back. can-i-deploy queries the Broker: yes deploys and records the deployment, no blocks the release.
  1. Consumer test. The consumer’s test starts a Pact mock server and declares an interaction: “given user 42 exists, GET /users/42 returns 200 with a name and email”. The real consumer client code then calls the mock.

  2. Pact file. If the client behaves as declared, Pact writes the interactions to a JSON file named after the consumer–provider pair. If the client sends something unexpected, the test fails here, on the consumer side.

  3. Publish. CI publishes the pact to a Pact Broker, tagged with the consumer’s version and branch.

  4. Provider verification. The provider’s CI fetches every pact that applies to it, starts the real service, and replays each recorded request. The actual response is compared with the expected one.

  5. Provider states. The given ... part of each interaction maps to a setup hook on the provider. That hook seeds the data the interaction needs, so verification doesn’t depend on a shared test database.

  6. Results. Verification results go back to the Broker. The Broker now knows which consumer versions are compatible with which provider versions.

The key property: neither side needs the other running. The consumer tests against a mock that is guaranteed to match the contract. The provider is checked against the same contract, so the mock can’t drift.

A minimal example: orders consumes users

The examples below use Pact JVM with JUnit 5 and Spring Boot.

The two services

The users service exposes one endpoint, GET /users/{id}. It returns the user as JSON, or 404 if there’s no such user.

// users service (provider)
@RestController
@RequestMapping("/users")
class UserController {

  private final UserRepository users;

  UserController(UserRepository users) {
    this.users = users;
  }

  @GetMapping("/{id}")
  ResponseEntity<User> getUser(@PathVariable Long id) {
    return users.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}

A response looks like this:

{ "id": 42, "name": "Asha", "email": "asha@example.com" }

On the other side, orders has a small client for that endpoint.

// orders service (consumer)
public record User(long id, String name, String email) {}

public class UsersClient {

  private final RestClient http;

  public UsersClient(String baseUrl) {
    this.http = RestClient.create(baseUrl);
  }

  public User getUser(long id) {
    return http.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
  }
}

The tests below are written against these two classes. The consumer test exercises UsersClient; the provider test runs the real UserController.

Consumer side: write the contract

The test describes the interaction, then runs the real HTTP client against the mock server Pact starts.

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "users")
class UsersClientPactTest {

  @Pact(consumer = "orders")
  V4Pact userExists(PactDslWithProvider builder) {
    return builder
      .given("user 42 exists")
      .uponReceiving("a request for user 42")
        .path("/users/42")
        .method("GET")
      .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body(newJsonBody(body -> {
          body.integerType("id", 42);
          body.stringType("name", "Asha");
          body.stringType("email", "asha@example.com");
        }).build())
      .toPact(V4Pact.class);
  }

  @Test
  void fetchesUserById(MockServer mockServer) {
    UsersClient client = new UsersClient(mockServer.getUrl());
    User user = client.getUser(42);
    assertThat(user.email()).isEqualTo("asha@example.com");
  }
}

Two details matter here.

  • Matchers, not literals. integerType and stringType match on type. The provider can return any user with a string email, not exactly asha@example.com. Exact values make contracts brittle and couple the consumer to the provider’s test data.

  • Only what you use. The consumer declares id, name and email because that is what orders reads. If users also returns phone, it stays out of the contract, and the users team can change it freely.

A passing run writes orders-users.json under build/pacts (Gradle) or target/pacts (Maven). CI then publishes it with the consumer’s git SHA and branch:

pact-broker publish ./build/pacts \
  --consumer-app-version "$GIT_SHA" \
  --branch "$GIT_BRANCH"

Provider side: verify the contract

The users provider test boots the Spring Boot app on a random port and replays every pact the Broker holds for it.

@Provider("users")
@PactBroker
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UsersProviderPactTest {

  @LocalServerPort
  int port;

  @Autowired
  UserRepository users;

  @PactBrokerConsumerVersionSelectors
  static SelectorBuilder consumerVersionSelectors() {
    return new SelectorBuilder()
      .mainBranch()
      .deployedOrReleased();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void verifyPact(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @State("user 42 exists")
  void user42Exists() {
    users.save(new User(42L, "Asha", "asha@example.com"));
  }
}

The Broker URL, token and provider version come from system properties set in CI: pactbroker.url, pactbroker.auth.token, pact.provider.version, pact.provider.branch and pact.verifier.publishResults=true.

@PactBrokerConsumerVersionSelectors decides which pacts to verify. Here it picks the consumer’s main branch plus whatever versions are currently deployed. That second selector is what stops a provider change from breaking a consumer version already running in production.

Each @State method is where a given("user 42 exists") string lands. It seeds only what its interaction needs, so verification doesn’t depend on a shared test database.

Back to the renamed field

Now replay the opening story. The users team renames email to emailAddress and pushes. Their unit tests pass. Provider verification does not: the replayed GET /users/42 response no longer has an email field, and the failure names the consumer (orders), the interaction (a request for user 42) and the missing path in the body.

The break surfaces in the users pipeline, on the commit that caused it, before anything is deployed. The users team now knows exactly who to talk to.

Gating releases with can-i-deploy

A green verification proves compatibility with some consumer version. It doesn’t prove the version you are about to ship is compatible with what is already in production. That is the job of can-i-deploy.

The Broker keeps a matrix: every consumer version, every provider version, and whether they were verified against each other. can-i-deploy looks up the row for your version against whatever is currently recorded in the target environment.

# before deploying
pact-broker can-i-deploy \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --to-environment production

# after a successful deploy
pact-broker record-deployment \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --environment

can-i-deploy exits 0 when the deploy is safe and 1 when it isn’t, so it drops into any CI system as a plain gate. record-deployment is the half teams forget. Without it, the Broker doesn’t know what is in production, and every can-i-deploy check is answered against stale data.

A working pipeline for each service ends up looking like this:

  1. Run unit and Pact tests. Consumers publish pacts; providers verify and publish results.

  2. Run can-i-deploy --to-environment <env>.

  3. Deploy.

  4. Run record-deployment --environment <env>.

Repeat steps 2 to 4 per environment. Each service deploys on its own schedule, and the Broker is the single place that says whether a given combination is safe.

Conclusion

The renamed-field bug from the opening wasn’t a testing failure in either service. It was a missing test for the agreement between them. Pact makes that agreement an artifact: written by the consumer, verified by the provider, and checked again before every deploy.

  • Consumer tests generate the contract from real client code, so the mock can’t drift.

  • Provider verification replays that contract against the real service, on the commit that would break it.

  • can-i-deploy plus record-deployment turns compatibility into a release gate.

  • Use matchers, declare only what you read, and agree on who owns verification failures.

Start small. Pick one consumer–provider pair that has broken before, add a single interaction, and wire can-i-deploy into one environment. Once the first real break gets caught in CI instead of production, the case for rolling it out makes itself.

On a recent client project, we were working on a set of Java services owned by different teams. Each service had decent unit tests and its own build pipeline, and integration was tested in a shared staging environment. Most of the bugs that hurt us didn’t live inside any one service. They lived in the calls between them.

Here’s a simplified version of what kept happening. An orders service calls a users service to get a customer’s name and email before confirming an order. The users team renames email to emailAddress. Their unit tests pass, since they were updated for the new field. The orders tests pass too, because they run against a stub someone wrote months ago that still returns email. Both get deployed, and order confirmations start going out with no recipient.

Staging can catch this, but only after both changes are merged and deployed together, and only if someone happens to exercise that path. When it does fail, it’s not always obvious whose change broke it. We wanted that failure to show up in the users team’s own build, on the commit that caused it.

Contract testing gave us that, and we used Pact to do it. This post walks through how it works and how we set it up with Java and Spring Boot.

What contract testing checks

A contract is the list of requests a consumer makes and the responses it expects back. Contract testing checks that both sides agree on that list, without running them together.

Take the example above. orders is the consumer and users is the provider. The contract between them says roughly this: when orders sends GET /users/42, users replies with 200 and a JSON body that has a numeric id, a string name and a string email. This is what orders relies on.

Contract testing checks the two halves of that separately. On the orders side, it checks that the client really sends that request and can handle that response. On the users side, it checks that the real service really returns it. When the users team renames email to emailAddress, the second check fails, in their build.

Pact is consumer-driven. The consumer’s tests produce the contract, and the provider has to prove it can honour it. This also means the provider is only held to what consumers actually use. If nobody reads a field, the provider can change or drop it.

It also differs from schema-based checks such as validating against an OpenAPI spec. The Pact docs call it contract by example: a contract is a list of concrete request/response pairs, not a description of every possible shape (Pact docs). A schema tells you the provider could return email. A pact tells you a named consumer depends on it.

Approach

What it proves

Where it fails

Unit tests with hand-written mocks

Each service works against its own idea of the other

Mocks drift silently from reality

End-to-end tests in a shared environment

The whole system works, once deployed together

Slow, flaky, late feedback, unclear ownership

Schema validation (OpenAPI)

Provider matches its published spec

Doesn’t prove consumers call it correctly

Consumer-driven contracts (Pact)

Provider satisfies what each consumer actually uses

Needs both teams to adopt it

How Pact works

Pact splits one integration test into two halves that run in different pipelines. The pact file is the only thing that crosses between them.

Pact flow: in consumer CI, the consumer test calls the Pact mock server, which records a pact file that is published to the Pact Broker. In provider CI, the verifier fetches pacts, replays each request against the real users service and publishes results back. can-i-deploy queries the Broker: yes deploys and records the deployment, no blocks the release.
  1. Consumer test. The consumer’s test starts a Pact mock server and declares an interaction: “given user 42 exists, GET /users/42 returns 200 with a name and email”. The real consumer client code then calls the mock.

  2. Pact file. If the client behaves as declared, Pact writes the interactions to a JSON file named after the consumer–provider pair. If the client sends something unexpected, the test fails here, on the consumer side.

  3. Publish. CI publishes the pact to a Pact Broker, tagged with the consumer’s version and branch.

  4. Provider verification. The provider’s CI fetches every pact that applies to it, starts the real service, and replays each recorded request. The actual response is compared with the expected one.

  5. Provider states. The given ... part of each interaction maps to a setup hook on the provider. That hook seeds the data the interaction needs, so verification doesn’t depend on a shared test database.

  6. Results. Verification results go back to the Broker. The Broker now knows which consumer versions are compatible with which provider versions.

The key property: neither side needs the other running. The consumer tests against a mock that is guaranteed to match the contract. The provider is checked against the same contract, so the mock can’t drift.

A minimal example: orders consumes users

The examples below use Pact JVM with JUnit 5 and Spring Boot.

The two services

The users service exposes one endpoint, GET /users/{id}. It returns the user as JSON, or 404 if there’s no such user.

// users service (provider)
@RestController
@RequestMapping("/users")
class UserController {

  private final UserRepository users;

  UserController(UserRepository users) {
    this.users = users;
  }

  @GetMapping("/{id}")
  ResponseEntity<User> getUser(@PathVariable Long id) {
    return users.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}

A response looks like this:

{ "id": 42, "name": "Asha", "email": "asha@example.com" }

On the other side, orders has a small client for that endpoint.

// orders service (consumer)
public record User(long id, String name, String email) {}

public class UsersClient {

  private final RestClient http;

  public UsersClient(String baseUrl) {
    this.http = RestClient.create(baseUrl);
  }

  public User getUser(long id) {
    return http.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
  }
}

The tests below are written against these two classes. The consumer test exercises UsersClient; the provider test runs the real UserController.

Consumer side: write the contract

The test describes the interaction, then runs the real HTTP client against the mock server Pact starts.

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "users")
class UsersClientPactTest {

  @Pact(consumer = "orders")
  V4Pact userExists(PactDslWithProvider builder) {
    return builder
      .given("user 42 exists")
      .uponReceiving("a request for user 42")
        .path("/users/42")
        .method("GET")
      .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body(newJsonBody(body -> {
          body.integerType("id", 42);
          body.stringType("name", "Asha");
          body.stringType("email", "asha@example.com");
        }).build())
      .toPact(V4Pact.class);
  }

  @Test
  void fetchesUserById(MockServer mockServer) {
    UsersClient client = new UsersClient(mockServer.getUrl());
    User user = client.getUser(42);
    assertThat(user.email()).isEqualTo("asha@example.com");
  }
}

Two details matter here.

  • Matchers, not literals. integerType and stringType match on type. The provider can return any user with a string email, not exactly asha@example.com. Exact values make contracts brittle and couple the consumer to the provider’s test data.

  • Only what you use. The consumer declares id, name and email because that is what orders reads. If users also returns phone, it stays out of the contract, and the users team can change it freely.

A passing run writes orders-users.json under build/pacts (Gradle) or target/pacts (Maven). CI then publishes it with the consumer’s git SHA and branch:

pact-broker publish ./build/pacts \
  --consumer-app-version "$GIT_SHA" \
  --branch "$GIT_BRANCH"

Provider side: verify the contract

The users provider test boots the Spring Boot app on a random port and replays every pact the Broker holds for it.

@Provider("users")
@PactBroker
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UsersProviderPactTest {

  @LocalServerPort
  int port;

  @Autowired
  UserRepository users;

  @PactBrokerConsumerVersionSelectors
  static SelectorBuilder consumerVersionSelectors() {
    return new SelectorBuilder()
      .mainBranch()
      .deployedOrReleased();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void verifyPact(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @State("user 42 exists")
  void user42Exists() {
    users.save(new User(42L, "Asha", "asha@example.com"));
  }
}

The Broker URL, token and provider version come from system properties set in CI: pactbroker.url, pactbroker.auth.token, pact.provider.version, pact.provider.branch and pact.verifier.publishResults=true.

@PactBrokerConsumerVersionSelectors decides which pacts to verify. Here it picks the consumer’s main branch plus whatever versions are currently deployed. That second selector is what stops a provider change from breaking a consumer version already running in production.

Each @State method is where a given("user 42 exists") string lands. It seeds only what its interaction needs, so verification doesn’t depend on a shared test database.

Back to the renamed field

Now replay the opening story. The users team renames email to emailAddress and pushes. Their unit tests pass. Provider verification does not: the replayed GET /users/42 response no longer has an email field, and the failure names the consumer (orders), the interaction (a request for user 42) and the missing path in the body.

The break surfaces in the users pipeline, on the commit that caused it, before anything is deployed. The users team now knows exactly who to talk to.

Gating releases with can-i-deploy

A green verification proves compatibility with some consumer version. It doesn’t prove the version you are about to ship is compatible with what is already in production. That is the job of can-i-deploy.

The Broker keeps a matrix: every consumer version, every provider version, and whether they were verified against each other. can-i-deploy looks up the row for your version against whatever is currently recorded in the target environment.

# before deploying
pact-broker can-i-deploy \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --to-environment production

# after a successful deploy
pact-broker record-deployment \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --environment

can-i-deploy exits 0 when the deploy is safe and 1 when it isn’t, so it drops into any CI system as a plain gate. record-deployment is the half teams forget. Without it, the Broker doesn’t know what is in production, and every can-i-deploy check is answered against stale data.

A working pipeline for each service ends up looking like this:

  1. Run unit and Pact tests. Consumers publish pacts; providers verify and publish results.

  2. Run can-i-deploy --to-environment <env>.

  3. Deploy.

  4. Run record-deployment --environment <env>.

Repeat steps 2 to 4 per environment. Each service deploys on its own schedule, and the Broker is the single place that says whether a given combination is safe.

Conclusion

The renamed-field bug from the opening wasn’t a testing failure in either service. It was a missing test for the agreement between them. Pact makes that agreement an artifact: written by the consumer, verified by the provider, and checked again before every deploy.

  • Consumer tests generate the contract from real client code, so the mock can’t drift.

  • Provider verification replays that contract against the real service, on the commit that would break it.

  • can-i-deploy plus record-deployment turns compatibility into a release gate.

  • Use matchers, declare only what you read, and agree on who owns verification failures.

Start small. Pick one consumer–provider pair that has broken before, add a single interaction, and wire can-i-deploy into one environment. Once the first real break gets caught in CI instead of production, the case for rolling it out makes itself.

On a recent client project, we were working on a set of Java services owned by different teams. Each service had decent unit tests and its own build pipeline, and integration was tested in a shared staging environment. Most of the bugs that hurt us didn’t live inside any one service. They lived in the calls between them.

Here’s a simplified version of what kept happening. An orders service calls a users service to get a customer’s name and email before confirming an order. The users team renames email to emailAddress. Their unit tests pass, since they were updated for the new field. The orders tests pass too, because they run against a stub someone wrote months ago that still returns email. Both get deployed, and order confirmations start going out with no recipient.

Staging can catch this, but only after both changes are merged and deployed together, and only if someone happens to exercise that path. When it does fail, it’s not always obvious whose change broke it. We wanted that failure to show up in the users team’s own build, on the commit that caused it.

Contract testing gave us that, and we used Pact to do it. This post walks through how it works and how we set it up with Java and Spring Boot.

What contract testing checks

A contract is the list of requests a consumer makes and the responses it expects back. Contract testing checks that both sides agree on that list, without running them together.

Take the example above. orders is the consumer and users is the provider. The contract between them says roughly this: when orders sends GET /users/42, users replies with 200 and a JSON body that has a numeric id, a string name and a string email. This is what orders relies on.

Contract testing checks the two halves of that separately. On the orders side, it checks that the client really sends that request and can handle that response. On the users side, it checks that the real service really returns it. When the users team renames email to emailAddress, the second check fails, in their build.

Pact is consumer-driven. The consumer’s tests produce the contract, and the provider has to prove it can honour it. This also means the provider is only held to what consumers actually use. If nobody reads a field, the provider can change or drop it.

It also differs from schema-based checks such as validating against an OpenAPI spec. The Pact docs call it contract by example: a contract is a list of concrete request/response pairs, not a description of every possible shape (Pact docs). A schema tells you the provider could return email. A pact tells you a named consumer depends on it.

Approach

What it proves

Where it fails

Unit tests with hand-written mocks

Each service works against its own idea of the other

Mocks drift silently from reality

End-to-end tests in a shared environment

The whole system works, once deployed together

Slow, flaky, late feedback, unclear ownership

Schema validation (OpenAPI)

Provider matches its published spec

Doesn’t prove consumers call it correctly

Consumer-driven contracts (Pact)

Provider satisfies what each consumer actually uses

Needs both teams to adopt it

How Pact works

Pact splits one integration test into two halves that run in different pipelines. The pact file is the only thing that crosses between them.

Pact flow: in consumer CI, the consumer test calls the Pact mock server, which records a pact file that is published to the Pact Broker. In provider CI, the verifier fetches pacts, replays each request against the real users service and publishes results back. can-i-deploy queries the Broker: yes deploys and records the deployment, no blocks the release.
  1. Consumer test. The consumer’s test starts a Pact mock server and declares an interaction: “given user 42 exists, GET /users/42 returns 200 with a name and email”. The real consumer client code then calls the mock.

  2. Pact file. If the client behaves as declared, Pact writes the interactions to a JSON file named after the consumer–provider pair. If the client sends something unexpected, the test fails here, on the consumer side.

  3. Publish. CI publishes the pact to a Pact Broker, tagged with the consumer’s version and branch.

  4. Provider verification. The provider’s CI fetches every pact that applies to it, starts the real service, and replays each recorded request. The actual response is compared with the expected one.

  5. Provider states. The given ... part of each interaction maps to a setup hook on the provider. That hook seeds the data the interaction needs, so verification doesn’t depend on a shared test database.

  6. Results. Verification results go back to the Broker. The Broker now knows which consumer versions are compatible with which provider versions.

The key property: neither side needs the other running. The consumer tests against a mock that is guaranteed to match the contract. The provider is checked against the same contract, so the mock can’t drift.

A minimal example: orders consumes users

The examples below use Pact JVM with JUnit 5 and Spring Boot.

The two services

The users service exposes one endpoint, GET /users/{id}. It returns the user as JSON, or 404 if there’s no such user.

// users service (provider)
@RestController
@RequestMapping("/users")
class UserController {

  private final UserRepository users;

  UserController(UserRepository users) {
    this.users = users;
  }

  @GetMapping("/{id}")
  ResponseEntity<User> getUser(@PathVariable Long id) {
    return users.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}

A response looks like this:

{ "id": 42, "name": "Asha", "email": "asha@example.com" }

On the other side, orders has a small client for that endpoint.

// orders service (consumer)
public record User(long id, String name, String email) {}

public class UsersClient {

  private final RestClient http;

  public UsersClient(String baseUrl) {
    this.http = RestClient.create(baseUrl);
  }

  public User getUser(long id) {
    return http.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
  }
}

The tests below are written against these two classes. The consumer test exercises UsersClient; the provider test runs the real UserController.

Consumer side: write the contract

The test describes the interaction, then runs the real HTTP client against the mock server Pact starts.

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "users")
class UsersClientPactTest {

  @Pact(consumer = "orders")
  V4Pact userExists(PactDslWithProvider builder) {
    return builder
      .given("user 42 exists")
      .uponReceiving("a request for user 42")
        .path("/users/42")
        .method("GET")
      .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body(newJsonBody(body -> {
          body.integerType("id", 42);
          body.stringType("name", "Asha");
          body.stringType("email", "asha@example.com");
        }).build())
      .toPact(V4Pact.class);
  }

  @Test
  void fetchesUserById(MockServer mockServer) {
    UsersClient client = new UsersClient(mockServer.getUrl());
    User user = client.getUser(42);
    assertThat(user.email()).isEqualTo("asha@example.com");
  }
}

Two details matter here.

  • Matchers, not literals. integerType and stringType match on type. The provider can return any user with a string email, not exactly asha@example.com. Exact values make contracts brittle and couple the consumer to the provider’s test data.

  • Only what you use. The consumer declares id, name and email because that is what orders reads. If users also returns phone, it stays out of the contract, and the users team can change it freely.

A passing run writes orders-users.json under build/pacts (Gradle) or target/pacts (Maven). CI then publishes it with the consumer’s git SHA and branch:

pact-broker publish ./build/pacts \
  --consumer-app-version "$GIT_SHA" \
  --branch "$GIT_BRANCH"

Provider side: verify the contract

The users provider test boots the Spring Boot app on a random port and replays every pact the Broker holds for it.

@Provider("users")
@PactBroker
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UsersProviderPactTest {

  @LocalServerPort
  int port;

  @Autowired
  UserRepository users;

  @PactBrokerConsumerVersionSelectors
  static SelectorBuilder consumerVersionSelectors() {
    return new SelectorBuilder()
      .mainBranch()
      .deployedOrReleased();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void verifyPact(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @State("user 42 exists")
  void user42Exists() {
    users.save(new User(42L, "Asha", "asha@example.com"));
  }
}

The Broker URL, token and provider version come from system properties set in CI: pactbroker.url, pactbroker.auth.token, pact.provider.version, pact.provider.branch and pact.verifier.publishResults=true.

@PactBrokerConsumerVersionSelectors decides which pacts to verify. Here it picks the consumer’s main branch plus whatever versions are currently deployed. That second selector is what stops a provider change from breaking a consumer version already running in production.

Each @State method is where a given("user 42 exists") string lands. It seeds only what its interaction needs, so verification doesn’t depend on a shared test database.

Back to the renamed field

Now replay the opening story. The users team renames email to emailAddress and pushes. Their unit tests pass. Provider verification does not: the replayed GET /users/42 response no longer has an email field, and the failure names the consumer (orders), the interaction (a request for user 42) and the missing path in the body.

The break surfaces in the users pipeline, on the commit that caused it, before anything is deployed. The users team now knows exactly who to talk to.

Gating releases with can-i-deploy

A green verification proves compatibility with some consumer version. It doesn’t prove the version you are about to ship is compatible with what is already in production. That is the job of can-i-deploy.

The Broker keeps a matrix: every consumer version, every provider version, and whether they were verified against each other. can-i-deploy looks up the row for your version against whatever is currently recorded in the target environment.

# before deploying
pact-broker can-i-deploy \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --to-environment production

# after a successful deploy
pact-broker record-deployment \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --environment

can-i-deploy exits 0 when the deploy is safe and 1 when it isn’t, so it drops into any CI system as a plain gate. record-deployment is the half teams forget. Without it, the Broker doesn’t know what is in production, and every can-i-deploy check is answered against stale data.

A working pipeline for each service ends up looking like this:

  1. Run unit and Pact tests. Consumers publish pacts; providers verify and publish results.

  2. Run can-i-deploy --to-environment <env>.

  3. Deploy.

  4. Run record-deployment --environment <env>.

Repeat steps 2 to 4 per environment. Each service deploys on its own schedule, and the Broker is the single place that says whether a given combination is safe.

Conclusion

The renamed-field bug from the opening wasn’t a testing failure in either service. It was a missing test for the agreement between them. Pact makes that agreement an artifact: written by the consumer, verified by the provider, and checked again before every deploy.

  • Consumer tests generate the contract from real client code, so the mock can’t drift.

  • Provider verification replays that contract against the real service, on the commit that would break it.

  • can-i-deploy plus record-deployment turns compatibility into a release gate.

  • Use matchers, declare only what you read, and agree on who owns verification failures.

Start small. Pick one consumer–provider pair that has broken before, add a single interaction, and wire can-i-deploy into one environment. Once the first real break gets caught in CI instead of production, the case for rolling it out makes itself.

On a recent client project, we were working on a set of Java services owned by different teams. Each service had decent unit tests and its own build pipeline, and integration was tested in a shared staging environment. Most of the bugs that hurt us didn’t live inside any one service. They lived in the calls between them.

Here’s a simplified version of what kept happening. An orders service calls a users service to get a customer’s name and email before confirming an order. The users team renames email to emailAddress. Their unit tests pass, since they were updated for the new field. The orders tests pass too, because they run against a stub someone wrote months ago that still returns email. Both get deployed, and order confirmations start going out with no recipient.

Staging can catch this, but only after both changes are merged and deployed together, and only if someone happens to exercise that path. When it does fail, it’s not always obvious whose change broke it. We wanted that failure to show up in the users team’s own build, on the commit that caused it.

Contract testing gave us that, and we used Pact to do it. This post walks through how it works and how we set it up with Java and Spring Boot.

What contract testing checks

A contract is the list of requests a consumer makes and the responses it expects back. Contract testing checks that both sides agree on that list, without running them together.

Take the example above. orders is the consumer and users is the provider. The contract between them says roughly this: when orders sends GET /users/42, users replies with 200 and a JSON body that has a numeric id, a string name and a string email. This is what orders relies on.

Contract testing checks the two halves of that separately. On the orders side, it checks that the client really sends that request and can handle that response. On the users side, it checks that the real service really returns it. When the users team renames email to emailAddress, the second check fails, in their build.

Pact is consumer-driven. The consumer’s tests produce the contract, and the provider has to prove it can honour it. This also means the provider is only held to what consumers actually use. If nobody reads a field, the provider can change or drop it.

It also differs from schema-based checks such as validating against an OpenAPI spec. The Pact docs call it contract by example: a contract is a list of concrete request/response pairs, not a description of every possible shape (Pact docs). A schema tells you the provider could return email. A pact tells you a named consumer depends on it.

Approach

What it proves

Where it fails

Unit tests with hand-written mocks

Each service works against its own idea of the other

Mocks drift silently from reality

End-to-end tests in a shared environment

The whole system works, once deployed together

Slow, flaky, late feedback, unclear ownership

Schema validation (OpenAPI)

Provider matches its published spec

Doesn’t prove consumers call it correctly

Consumer-driven contracts (Pact)

Provider satisfies what each consumer actually uses

Needs both teams to adopt it

How Pact works

Pact splits one integration test into two halves that run in different pipelines. The pact file is the only thing that crosses between them.

Pact flow: in consumer CI, the consumer test calls the Pact mock server, which records a pact file that is published to the Pact Broker. In provider CI, the verifier fetches pacts, replays each request against the real users service and publishes results back. can-i-deploy queries the Broker: yes deploys and records the deployment, no blocks the release.
  1. Consumer test. The consumer’s test starts a Pact mock server and declares an interaction: “given user 42 exists, GET /users/42 returns 200 with a name and email”. The real consumer client code then calls the mock.

  2. Pact file. If the client behaves as declared, Pact writes the interactions to a JSON file named after the consumer–provider pair. If the client sends something unexpected, the test fails here, on the consumer side.

  3. Publish. CI publishes the pact to a Pact Broker, tagged with the consumer’s version and branch.

  4. Provider verification. The provider’s CI fetches every pact that applies to it, starts the real service, and replays each recorded request. The actual response is compared with the expected one.

  5. Provider states. The given ... part of each interaction maps to a setup hook on the provider. That hook seeds the data the interaction needs, so verification doesn’t depend on a shared test database.

  6. Results. Verification results go back to the Broker. The Broker now knows which consumer versions are compatible with which provider versions.

The key property: neither side needs the other running. The consumer tests against a mock that is guaranteed to match the contract. The provider is checked against the same contract, so the mock can’t drift.

A minimal example: orders consumes users

The examples below use Pact JVM with JUnit 5 and Spring Boot.

The two services

The users service exposes one endpoint, GET /users/{id}. It returns the user as JSON, or 404 if there’s no such user.

// users service (provider)
@RestController
@RequestMapping("/users")
class UserController {

  private final UserRepository users;

  UserController(UserRepository users) {
    this.users = users;
  }

  @GetMapping("/{id}")
  ResponseEntity<User> getUser(@PathVariable Long id) {
    return users.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}

A response looks like this:

{ "id": 42, "name": "Asha", "email": "asha@example.com" }

On the other side, orders has a small client for that endpoint.

// orders service (consumer)
public record User(long id, String name, String email) {}

public class UsersClient {

  private final RestClient http;

  public UsersClient(String baseUrl) {
    this.http = RestClient.create(baseUrl);
  }

  public User getUser(long id) {
    return http.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
  }
}

The tests below are written against these two classes. The consumer test exercises UsersClient; the provider test runs the real UserController.

Consumer side: write the contract

The test describes the interaction, then runs the real HTTP client against the mock server Pact starts.

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "users")
class UsersClientPactTest {

  @Pact(consumer = "orders")
  V4Pact userExists(PactDslWithProvider builder) {
    return builder
      .given("user 42 exists")
      .uponReceiving("a request for user 42")
        .path("/users/42")
        .method("GET")
      .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body(newJsonBody(body -> {
          body.integerType("id", 42);
          body.stringType("name", "Asha");
          body.stringType("email", "asha@example.com");
        }).build())
      .toPact(V4Pact.class);
  }

  @Test
  void fetchesUserById(MockServer mockServer) {
    UsersClient client = new UsersClient(mockServer.getUrl());
    User user = client.getUser(42);
    assertThat(user.email()).isEqualTo("asha@example.com");
  }
}

Two details matter here.

  • Matchers, not literals. integerType and stringType match on type. The provider can return any user with a string email, not exactly asha@example.com. Exact values make contracts brittle and couple the consumer to the provider’s test data.

  • Only what you use. The consumer declares id, name and email because that is what orders reads. If users also returns phone, it stays out of the contract, and the users team can change it freely.

A passing run writes orders-users.json under build/pacts (Gradle) or target/pacts (Maven). CI then publishes it with the consumer’s git SHA and branch:

pact-broker publish ./build/pacts \
  --consumer-app-version "$GIT_SHA" \
  --branch "$GIT_BRANCH"

Provider side: verify the contract

The users provider test boots the Spring Boot app on a random port and replays every pact the Broker holds for it.

@Provider("users")
@PactBroker
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UsersProviderPactTest {

  @LocalServerPort
  int port;

  @Autowired
  UserRepository users;

  @PactBrokerConsumerVersionSelectors
  static SelectorBuilder consumerVersionSelectors() {
    return new SelectorBuilder()
      .mainBranch()
      .deployedOrReleased();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void verifyPact(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @State("user 42 exists")
  void user42Exists() {
    users.save(new User(42L, "Asha", "asha@example.com"));
  }
}

The Broker URL, token and provider version come from system properties set in CI: pactbroker.url, pactbroker.auth.token, pact.provider.version, pact.provider.branch and pact.verifier.publishResults=true.

@PactBrokerConsumerVersionSelectors decides which pacts to verify. Here it picks the consumer’s main branch plus whatever versions are currently deployed. That second selector is what stops a provider change from breaking a consumer version already running in production.

Each @State method is where a given("user 42 exists") string lands. It seeds only what its interaction needs, so verification doesn’t depend on a shared test database.

Back to the renamed field

Now replay the opening story. The users team renames email to emailAddress and pushes. Their unit tests pass. Provider verification does not: the replayed GET /users/42 response no longer has an email field, and the failure names the consumer (orders), the interaction (a request for user 42) and the missing path in the body.

The break surfaces in the users pipeline, on the commit that caused it, before anything is deployed. The users team now knows exactly who to talk to.

Gating releases with can-i-deploy

A green verification proves compatibility with some consumer version. It doesn’t prove the version you are about to ship is compatible with what is already in production. That is the job of can-i-deploy.

The Broker keeps a matrix: every consumer version, every provider version, and whether they were verified against each other. can-i-deploy looks up the row for your version against whatever is currently recorded in the target environment.

# before deploying
pact-broker can-i-deploy \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --to-environment production

# after a successful deploy
pact-broker record-deployment \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --environment

can-i-deploy exits 0 when the deploy is safe and 1 when it isn’t, so it drops into any CI system as a plain gate. record-deployment is the half teams forget. Without it, the Broker doesn’t know what is in production, and every can-i-deploy check is answered against stale data.

A working pipeline for each service ends up looking like this:

  1. Run unit and Pact tests. Consumers publish pacts; providers verify and publish results.

  2. Run can-i-deploy --to-environment <env>.

  3. Deploy.

  4. Run record-deployment --environment <env>.

Repeat steps 2 to 4 per environment. Each service deploys on its own schedule, and the Broker is the single place that says whether a given combination is safe.

Conclusion

The renamed-field bug from the opening wasn’t a testing failure in either service. It was a missing test for the agreement between them. Pact makes that agreement an artifact: written by the consumer, verified by the provider, and checked again before every deploy.

  • Consumer tests generate the contract from real client code, so the mock can’t drift.

  • Provider verification replays that contract against the real service, on the commit that would break it.

  • can-i-deploy plus record-deployment turns compatibility into a release gate.

  • Use matchers, declare only what you read, and agree on who owns verification failures.

Start small. Pick one consumer–provider pair that has broken before, add a single interaction, and wire can-i-deploy into one environment. Once the first real break gets caught in CI instead of production, the case for rolling it out makes itself.

On a recent client project, we were working on a set of Java services owned by different teams. Each service had decent unit tests and its own build pipeline, and integration was tested in a shared staging environment. Most of the bugs that hurt us didn’t live inside any one service. They lived in the calls between them.

Here’s a simplified version of what kept happening. An orders service calls a users service to get a customer’s name and email before confirming an order. The users team renames email to emailAddress. Their unit tests pass, since they were updated for the new field. The orders tests pass too, because they run against a stub someone wrote months ago that still returns email. Both get deployed, and order confirmations start going out with no recipient.

Staging can catch this, but only after both changes are merged and deployed together, and only if someone happens to exercise that path. When it does fail, it’s not always obvious whose change broke it. We wanted that failure to show up in the users team’s own build, on the commit that caused it.

Contract testing gave us that, and we used Pact to do it. This post walks through how it works and how we set it up with Java and Spring Boot.

What contract testing checks

A contract is the list of requests a consumer makes and the responses it expects back. Contract testing checks that both sides agree on that list, without running them together.

Take the example above. orders is the consumer and users is the provider. The contract between them says roughly this: when orders sends GET /users/42, users replies with 200 and a JSON body that has a numeric id, a string name and a string email. This is what orders relies on.

Contract testing checks the two halves of that separately. On the orders side, it checks that the client really sends that request and can handle that response. On the users side, it checks that the real service really returns it. When the users team renames email to emailAddress, the second check fails, in their build.

Pact is consumer-driven. The consumer’s tests produce the contract, and the provider has to prove it can honour it. This also means the provider is only held to what consumers actually use. If nobody reads a field, the provider can change or drop it.

It also differs from schema-based checks such as validating against an OpenAPI spec. The Pact docs call it contract by example: a contract is a list of concrete request/response pairs, not a description of every possible shape (Pact docs). A schema tells you the provider could return email. A pact tells you a named consumer depends on it.

Approach

What it proves

Where it fails

Unit tests with hand-written mocks

Each service works against its own idea of the other

Mocks drift silently from reality

End-to-end tests in a shared environment

The whole system works, once deployed together

Slow, flaky, late feedback, unclear ownership

Schema validation (OpenAPI)

Provider matches its published spec

Doesn’t prove consumers call it correctly

Consumer-driven contracts (Pact)

Provider satisfies what each consumer actually uses

Needs both teams to adopt it

How Pact works

Pact splits one integration test into two halves that run in different pipelines. The pact file is the only thing that crosses between them.

Pact flow: in consumer CI, the consumer test calls the Pact mock server, which records a pact file that is published to the Pact Broker. In provider CI, the verifier fetches pacts, replays each request against the real users service and publishes results back. can-i-deploy queries the Broker: yes deploys and records the deployment, no blocks the release.
  1. Consumer test. The consumer’s test starts a Pact mock server and declares an interaction: “given user 42 exists, GET /users/42 returns 200 with a name and email”. The real consumer client code then calls the mock.

  2. Pact file. If the client behaves as declared, Pact writes the interactions to a JSON file named after the consumer–provider pair. If the client sends something unexpected, the test fails here, on the consumer side.

  3. Publish. CI publishes the pact to a Pact Broker, tagged with the consumer’s version and branch.

  4. Provider verification. The provider’s CI fetches every pact that applies to it, starts the real service, and replays each recorded request. The actual response is compared with the expected one.

  5. Provider states. The given ... part of each interaction maps to a setup hook on the provider. That hook seeds the data the interaction needs, so verification doesn’t depend on a shared test database.

  6. Results. Verification results go back to the Broker. The Broker now knows which consumer versions are compatible with which provider versions.

The key property: neither side needs the other running. The consumer tests against a mock that is guaranteed to match the contract. The provider is checked against the same contract, so the mock can’t drift.

A minimal example: orders consumes users

The examples below use Pact JVM with JUnit 5 and Spring Boot.

The two services

The users service exposes one endpoint, GET /users/{id}. It returns the user as JSON, or 404 if there’s no such user.

// users service (provider)
@RestController
@RequestMapping("/users")
class UserController {

  private final UserRepository users;

  UserController(UserRepository users) {
    this.users = users;
  }

  @GetMapping("/{id}")
  ResponseEntity<User> getUser(@PathVariable Long id) {
    return users.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}

A response looks like this:

{ "id": 42, "name": "Asha", "email": "asha@example.com" }

On the other side, orders has a small client for that endpoint.

// orders service (consumer)
public record User(long id, String name, String email) {}

public class UsersClient {

  private final RestClient http;

  public UsersClient(String baseUrl) {
    this.http = RestClient.create(baseUrl);
  }

  public User getUser(long id) {
    return http.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
  }
}

The tests below are written against these two classes. The consumer test exercises UsersClient; the provider test runs the real UserController.

Consumer side: write the contract

The test describes the interaction, then runs the real HTTP client against the mock server Pact starts.

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "users")
class UsersClientPactTest {

  @Pact(consumer = "orders")
  V4Pact userExists(PactDslWithProvider builder) {
    return builder
      .given("user 42 exists")
      .uponReceiving("a request for user 42")
        .path("/users/42")
        .method("GET")
      .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body(newJsonBody(body -> {
          body.integerType("id", 42);
          body.stringType("name", "Asha");
          body.stringType("email", "asha@example.com");
        }).build())
      .toPact(V4Pact.class);
  }

  @Test
  void fetchesUserById(MockServer mockServer) {
    UsersClient client = new UsersClient(mockServer.getUrl());
    User user = client.getUser(42);
    assertThat(user.email()).isEqualTo("asha@example.com");
  }
}

Two details matter here.

  • Matchers, not literals. integerType and stringType match on type. The provider can return any user with a string email, not exactly asha@example.com. Exact values make contracts brittle and couple the consumer to the provider’s test data.

  • Only what you use. The consumer declares id, name and email because that is what orders reads. If users also returns phone, it stays out of the contract, and the users team can change it freely.

A passing run writes orders-users.json under build/pacts (Gradle) or target/pacts (Maven). CI then publishes it with the consumer’s git SHA and branch:

pact-broker publish ./build/pacts \
  --consumer-app-version "$GIT_SHA" \
  --branch "$GIT_BRANCH"

Provider side: verify the contract

The users provider test boots the Spring Boot app on a random port and replays every pact the Broker holds for it.

@Provider("users")
@PactBroker
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UsersProviderPactTest {

  @LocalServerPort
  int port;

  @Autowired
  UserRepository users;

  @PactBrokerConsumerVersionSelectors
  static SelectorBuilder consumerVersionSelectors() {
    return new SelectorBuilder()
      .mainBranch()
      .deployedOrReleased();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void verifyPact(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @State("user 42 exists")
  void user42Exists() {
    users.save(new User(42L, "Asha", "asha@example.com"));
  }
}

The Broker URL, token and provider version come from system properties set in CI: pactbroker.url, pactbroker.auth.token, pact.provider.version, pact.provider.branch and pact.verifier.publishResults=true.

@PactBrokerConsumerVersionSelectors decides which pacts to verify. Here it picks the consumer’s main branch plus whatever versions are currently deployed. That second selector is what stops a provider change from breaking a consumer version already running in production.

Each @State method is where a given("user 42 exists") string lands. It seeds only what its interaction needs, so verification doesn’t depend on a shared test database.

Back to the renamed field

Now replay the opening story. The users team renames email to emailAddress and pushes. Their unit tests pass. Provider verification does not: the replayed GET /users/42 response no longer has an email field, and the failure names the consumer (orders), the interaction (a request for user 42) and the missing path in the body.

The break surfaces in the users pipeline, on the commit that caused it, before anything is deployed. The users team now knows exactly who to talk to.

Gating releases with can-i-deploy

A green verification proves compatibility with some consumer version. It doesn’t prove the version you are about to ship is compatible with what is already in production. That is the job of can-i-deploy.

The Broker keeps a matrix: every consumer version, every provider version, and whether they were verified against each other. can-i-deploy looks up the row for your version against whatever is currently recorded in the target environment.

# before deploying
pact-broker can-i-deploy \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --to-environment production

# after a successful deploy
pact-broker record-deployment \
  --pacticipant orders \
  --version "$GIT_SHA" \
  --environment

can-i-deploy exits 0 when the deploy is safe and 1 when it isn’t, so it drops into any CI system as a plain gate. record-deployment is the half teams forget. Without it, the Broker doesn’t know what is in production, and every can-i-deploy check is answered against stale data.

A working pipeline for each service ends up looking like this:

  1. Run unit and Pact tests. Consumers publish pacts; providers verify and publish results.

  2. Run can-i-deploy --to-environment <env>.

  3. Deploy.

  4. Run record-deployment --environment <env>.

Repeat steps 2 to 4 per environment. Each service deploys on its own schedule, and the Broker is the single place that says whether a given combination is safe.

Conclusion

The renamed-field bug from the opening wasn’t a testing failure in either service. It was a missing test for the agreement between them. Pact makes that agreement an artifact: written by the consumer, verified by the provider, and checked again before every deploy.

  • Consumer tests generate the contract from real client code, so the mock can’t drift.

  • Provider verification replays that contract against the real service, on the commit that would break it.

  • can-i-deploy plus record-deployment turns compatibility into a release gate.

  • Use matchers, declare only what you read, and agree on who owns verification failures.

Start small. Pick one consumer–provider pair that has broken before, add a single interaction, and wire can-i-deploy into one environment. Once the first real break gets caught in CI instead of production, the case for rolling it out makes itself.

Share
Share
On this page

Continue reading.

Subscribe for more such content

Get the latest in software engineering best practices straight to your inbox. Subscribe now!

Subscribe for more such content

Get the latest in software engineering best practices straight to your inbox. Subscribe now!

Subscribe for more such content

Get the latest in software engineering best practices straight to your inbox. Subscribe now!