API Contract Testing and k6 Load Testing in One Pipeline

How I pair a consumer-driven contract check with a k6 load test so a breaking API change or a capacity regression is caught before release, not after.

Two failures, one shape

A contract break and a capacity regression look nothing alike to a user, but they are the same kind of failure to a release process: a change that was fine in isolation and is not fine in combination.

The API team changed a field type. The field was optional in every test fixture, so nothing caught it — and the first consumer to read it crashed in production. Separately, a caching change took the service from three hundred to eleven hundred requests per second, and the p95 latency went from 40ms to 2.4s under the same load.

Both were caught after release in this case. This article is about the pipeline that catches them before.

  • Contract breaks hide behind optional fields and untested default values
  • Capacity regressions hide behind load the staging environment never sees
  • Both are cheap to catch in CI and expensive to catch in production

The contract half: check the producer against what consumers actually use

The mistake in most contract testing setups is testing the API against a document of what the API is supposed to be. That document is always slightly wrong, and it is wrong in the direction that hides breakage.

A consumer-driven contract records what each consumer actually depends on, and verifies the provider against those records. The consumer defines the contract, the provider is tested against it, and the provider publishes the contract it has agreed to.

The hard part is not the tooling, it is the discipline of not adding a field to the contract because "it might be useful". Every contract line is a promise to maintain, and a contract that promises everything promises nothing.

import { test, expect } from '@playwright/experimental-ct'; import { pact } from '@pact-foundation/pact'; import { orderService } from './order-service'; // The consumer states what it depends on. Not what the API could // offer — what this client actually reads. pact.given('an order with a pending payment') .uponReceiving('a GET request for /orders/42') .willRespondWith({ status: 200, headers: { 'Content-Type': 'application/json' }, body: { id: pact.integer(42), status: 'PENDING', // The consumer reads this field. It is the whole reason // this contract exists — if the type changes, this test fails // in the provider's build, not in production. total: pact.decimal(129.95), currency: 'USD', }, }); test('the order page renders a pending order', async ({ page }) => { await page.goto('/orders/42'); await expect(page.getByTestId('order-total')).toHaveText('$129.95'); }); 
  • The contract is written from the consumer's side, so it captures real usage rather than aspiration
  • Only the fields the consumer actually reads belong in the contract
  • A provider change that breaks a contract fails the provider's pipeline, not the consumer's
  • Contracts are versioned — a breaking change is a new version, never an in-place edit

The load half: k6 measures what staging cannot

Staging has the wrong shape for a load test. It is smaller than production, its data volume is a fraction, and its dependencies are stubs or lower environments. A test that passes against staging tells you the code path works, not that it holds.

k6 is useful here because the test script is plain JavaScript, it runs fast, and the thresholds are declarative — you write down the number that matters and the test fails when the number is missed.

The most important decision is what the thresholds actually are. Latency percentiles beat averages, and the p95 at a stated concurrency is a contract you can hold a release to.

import http from 'k6/http'; import { check, sleep } from 'k6'; export const options = { scenarios: { steady: { executor: 'ramping-vus', startVUs: 0, stages: [ { duration: '30s', target: 50 }, { duration: '1m', target: 50 }, { duration: '30s', target: 0 }, ], }, }, thresholds: { // A threshold is a contract the release is held to. p95, not // the average — an average hides the tail that hurts users. 'http_req_duration{scenario:steady}': ['p(95)<400'], 'http_req_failed{scenario:steady}': ['rate<0.01'], // The throughput the service has to sustain, asserted explicitly // so a silent capacity drop cannot pass. 'http_reqs': ['count>20000'], }, }; const BASE = __ENV.BASE_URL; export default function () { const res = http.get(`${BASE}/api/orders/42`, { headers: { Authorization: `Bearer ${__ENV.TOKEN}` }, }); check(res, { 'status is 200': (r) => r.status === 200, 'body has total': (r) => r.body.includes('total'), }); sleep(1); } 
  • Write the threshold before you write the test — a threshold chosen after seeing the result is not a threshold
  • p95, not average: the average hides exactly the tail that hurts
  • Assert the request count, so a run that quietly did nothing cannot pass
  • Run against an environment shaped like production, or the numbers are fiction

Running both without making the pipeline unbearable

A load test in every pull request is a way to guarantee your pipeline gets ignored. The load test is slow, it is sensitive to noisy neighbours on shared runners, and its failure mode is often environmental rather than a real regression.

So it runs on a schedule and on the release branch, not on every push. The contract check runs on every pull request, because it is fast and deterministic — a contract break is a real break and should be caught at the moment the change is proposed.

The division of labour is the whole design. Fast deterministic checks gate every merge; slow environment-sensitive checks gate the release. Splitting by that line is what keeps both of them credible.

name: contract-and-load on: pull_request: branches: [main] schedule: - cron: '0 3 * * 1-5' workflow_dispatch: jobs: contract: # Fast and deterministic — runs on every PR.  runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - run: npm ci - run: npm run test:contract load: # Slow and environment-sensitive — runs on a schedule and on  # demand, never on every push.  if: github.event_name != 'pull_request' needs: contract runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@v4 - run: npm ci - run: k6 run --summary-export=load-summary.json load/api.js - uses: actions/upload-artifact@v4 with: name: k6-summary path: load-summary.json 

Reading the results honestly

Both tools will lie to you if you let them. The contract test passes against a provider that has not deployed the change yet. The load test passes against an environment with a warm cache or a quiet neighbour.

The guard against the first is ordering: the contract verification must run against the branch under test, and a green contract check means nothing if it ran against production. The guard against the second is repeating — a load number that only holds once is a measurement of the noise.

And both need a human to be willing to read the output when it fails in a new way. A gate that produces a number is easy to trust blindly; the failure modes worth catching are often the ones that show up as a threshold that was crossed for the wrong reason.

  • A contract check must run against the branch under test, never against production
  • A load number that holds once is a measurement of the noise — repeat it
  • Keep the raw summary as a build artifact so a failure can be compared against the previous run
  • If a threshold is routinely flaky, the threshold is wrong; fix it or delete it

The takeaway

Contract testing and load testing look like separate disciplines and are bought for separate reasons, but they defend against the same failure: a change that is fine alone and broken in company. The contract check defends the shape of the interface; the load check defends its behaviour under pressure.

The pipeline shape that makes both work is unglamorous: run the fast deterministic one everywhere, run the slow sensitive one on a schedule and on the release branch, and keep the thresholds written down before the numbers are known.

Key takeaways

  • Test the provider against what consumers actually read, not against a spec that hides breakage.
  • A contract line is a maintenance promise — a contract that promises everything promises nothing.
  • p95 beats the average; the average hides exactly the tail that hurts users.
  • Assert the request count, so a load run that did nothing cannot pass.
  • Split by determinism: fast checks gate every merge, slow checks gate the release.
  • A green contract check against production proves nothing — run it against the branch.