QA Interview Hub · Knowledge base · Quizzes · Українська

System Design

Microservices and test strategy

A microservices testing strategy

In microservices, checks are split into layers, and e2e is kept for a few critical flows. Most checks sit in unit, integration and component tests, with contract tests between services. A stub in a component test only reflects an idea of the neighbour and goes stale, so a consumer-driven contract (Pact) is verified by the provider in its own CI. A breaking change is caught before deploy without a shared environment.

System design · Microservices

Thirty services, teams deploy daily. How many e2e tests can that release take?

In a monolith one e2e run really checks everything. In a system of 30 services where every team deploys on its own, a full e2e run per change gets slow and, worse, unstable: the test is red because another service is being deployed right now or its test database is in a strange state. The team stops trusting red. This lesson is about splitting checks into layers so every change gets fast and honest feedback, and where contracts fit in.

How it works and why

Each layer answers its own question. Unit: is the logic inside correct. Integration: does the code work correctly with its own database or queue. Component test: does one service work through its own API with a real database or queue (often in a container via Testcontainers) while neighbouring services are stubbed. Contract test: do two services understand the request and response format the same way. E2E: does a critical business flow work end to end. The higher the layer, the slower, costlier and more fragile the test, so there are few of them; the lower, the more.

Test layers in microservices

E2Ea few critical flowsContractformat between two servicesComponentone service, dependencies stubbedIntegrationservice + its database, queueUnitthe most, the fastest
Figure 1. The higher the layer, the fewer the tests.

A contract is needed because a stub in a component test only reflects the team's idea of the neighbour. If the neighbour changed a field, the stub does not know, the tests are green and production fails. The consumer-driven approach (Pact) closes this gap: the consumer (the calling service) describes which requests it makes and which response it expects, these expectations become the contract, and the provider (the service that serves the API) verifies in its own CI that it fulfils it. A breaking change is caught before the deploy and without a shared environment.

Example: a field was renamed

The Ledger Service decided to rename balance to available for clarity. Ledger's component tests are green because they are its own. The Transfer Service expects balance in the response.

// consumer (Transfer) expectation, shortened
{
  "request":  { "method": "GET", "path": "/accounts/42" },
  "response": { "status": 200, "body": { "id": "42", "balance": 1500 } }
}

Without contracts only e2e or production would find this. With a contract, provider verification in Ledger's CI fails at once: the response has no balance. The Ledger team sees what exactly breaks and for whom, and either restores the field or agrees on a migration: it returns both fields until the consumer is updated.

Limits and alternatives

  • A contract checks the shape (fields, types, statuses), not business logic: it will not prove that a transfer is calculated correctly.
  • The format of events in a queue is a contract too: Pact supports message pacts, and schemas (Avro, JSON Schema) in a schema registry give a similar guarantee.
  • An alternative without Pact: the provider publishes OpenAPI and the consumer validates its stub responses against the schema. Simpler, but it does not know which fields the consumer really uses.
  • A shared e2e environment stays for a few money flows: sign-up, top-up, transfer, withdrawal.

Common mistakes

  • Stubs written by hand from memory: they go stale and component tests lie in green. Generate the stub from the contract instead.
  • Hundreds of e2e tests "just in case": a 40-minute run, flaky, nobody investigates failures.
  • Backward compatibility is not planned: a new provider breaks old consumers because it removed a field instead of deprecating it first.

Check yourself

Ledger component tests are green but Transfer fails after the deploy. What is not covered and how to close it?

Answer

The format agreement between services is not covered: stubs know nothing about the change. Contract tests close it: the consumer publishes expectations and the provider verifies them in its own CI before the deploy.

Why not replace contract tests with more e2e?

Answer

E2E needs all services at once, is slow, unstable and does not say who broke it. A contract runs in one service's CI, is fast and immediately names the consumer-provider pair.

In an interview. Junior: In microservices the weight goes to unit, component and contract tests, and e2e stays for a few critical flows because running them across 30 services is slow and unstable. Middle/Senior: Stubs in component tests go stale, so I add consumer-driven contracts: the provider verifies them in its own CI and a breaking change is caught before the deploy without a shared environment. The event format in a queue is a contract too. Each team owns its service's tests, while standards and shared tooling are set by a dedicated role.

Task: how to test a transfer system with a queue

Testing a transfer system with a queue starts with risks, not a list of tools. The risks are double debit, a negative balance, a transfer without a final status and a duplicate request. Each risk is tied to the layer where it is cheapest to check, and the weight is on negative scenarios: a duplicate event, a consumer crash, parallel debits, the DLQ. E2E waits for the final status, not a sleep.

System design · Microservices

A transfer is stuck in PENDING and the client pressed Send again. How do you test that?

An interview task: a user creates a transfer through the API. The Transfer Service stores it with status PENDING and publishes an event to a queue. The Ledger Service debits and credits the funds and publishes an event, after which the status becomes COMPLETED. The Notification Service sends a push. The question: how to test it. What is assessed is not a list of tests but the order of reasoning: risks, layers, negative scenarios, metrics.

Risks first

Money must not be debited twice or lost. A balance must not go negative. Every transfer reaches a final status, COMPLETED or FAILED. A repeated client request does not create a second transfer. Each risk is then tied to the layer where it is cheapest to check.

The path of a transfer

Transfer APIPENDING record + eventQueueat-least-once: a duplicate is possibleLedgerdebit and creditEvent + Transferstatus COMPLETED / FAILED
Figure 1. Yellow marks where duplicates appear.

Test layers

  1. Unit: fee calculation, amount validation, status transitions.
  2. Component Transfer: API plus a real database, the queue a stub or a container. We check that the event is published in the right format.
  3. Component Ledger: feed an event to the queue and check the records. The same event twice gives one debit.
  4. Contract: the event format between Transfer and Ledger.
  5. E2E: create a transfer through the API, wait for COMPLETED, check both balances.

Example: e2e with waiting and a duplicate

The test does not check the status right after POST because the response returns PENDING. It waits for the final state, then repeats the same request with the same key and checks there is no new transfer.

What the duplicate test consists of

1const key = crypto.randomUUID();
const body = {
  from: 'acc-1',
  to: 'acc-2',
  amount: 100,
};
const post = () =>
  request.post('/transfers', {
    data: body,
    headers: {
      'Idempotency-Key': key,
    },
  });

const { id } = await (
  await post()
).json();

await expect
  .poll(
    async () =>
      (
        await (
          await request.get(
            '/transfers/' + id,
          )
        ).json()
      ).status,
    {
2      timeout: 15_000,
    },
  )
  .toBe('COMPLETED');

3const again = await (
  await post()
).json();
expect(again.id).toBe(id);
4expect(
  await balance('acc-1'),
).toBe(900);
  1. Key: one for both requests, otherwise the server treats the repeat as a new transfer.
  2. Wait: polling for the final status, with a 15-second timeout taken from the processing SLA.
  3. Repeat: the same body and the same key, so again.id must match the first transfer.
  4. Balance: 900 means one debit from 1000, while 800 means the repeat was executed again.
Figure 2. The numbers mark the four lines the idempotency check rests on.

Assumptions: the starting balance of acc-1 is 1000 and the idempotency key is accepted in the Idempotency-Key header. If the balance is 800 after the repeat, idempotency does not work: a double debit is found, which only a repeat test reveals.

Negative scenarios

  • Insufficient funds: status FAILED, the balance unchanged.
  • Ledger crashed mid-processing: after a restart the transfer completes exactly once.
  • An invalid event lands in the DLQ (dead-letter queue) and an alert fires.
  • 20 parallel transfers from one account for more than the balance: none ends negative.
  • Notification is down: the transfer still completes, the push is retried later.

What to observe

The number of transfers stuck in PENDING longer than N minutes, DLQ size, consumer lag, mismatches in balance reconciliation. These metrics show a problem before a customer complaint.

Limits and alternatives

One e2e run does not prove duplicates are impossible: redelivery and consumer crashes are more reliably reproduced in component tests where the test controls the queue. Even if the broker offers exactly-once within its own bounds, the consumer still has to be idempotent at the boundary with the database.

Common mistakes in the answer

  • Listing tools straight away without risks.
  • Only the happy path: duplicates, consumer crashes and concurrency are forgotten.
  • Checking status with sleep(5000) instead of waiting for the final state.

Check yourself

Why can an e2e test not check COMPLETED right after POST?

Answer

Processing is asynchronous: POST returns PENDING and Ledger finishes the transfer later. You need to wait for the final state with a timeout based on the SLA.

Which queue behaviour is the most dangerous for money and which test catches it?

Answer

Redelivery: a queue with an at-least-once guarantee may deliver the same event twice. A Ledger component test feeds the event twice and expects one debit.

In an interview. Junior: I start with risks: double debit, negative balance, getting stuck. Then unit for logic, component for each service and a few e2e tests that wait for the final status. Middle/Senior: The focus is on negative scenarios: duplicate event, consumer crash mid-processing, parallel debits, DLQ. I add a contract on the event format and observability: PENDING count above the SLA, consumer lag, balance reconciliation.

Eventual consistency and sagas in tests

Eventual consistency means that data in different parts of the system becomes consistent not at once but after some time. A delay between an event and its processing is normal; the bug is in a test that assumed instantness. The test polls the state with a timeout from the SLA, not a fixed sleep. A saga is tested by breaking every step: compensation, redelivery and a final state with no half-finished operations.

System design · Microservices

Ledger already shows the new balance, but the history does not. A bug or normal?

After a transfer the balance in Ledger has changed, but the history service has not yet received the event. The test opened the history at once and found no record: red. A second later the record appeared. This is not a system bug but eventual consistency: data in different parts of the system becomes consistent not at once but after some time. The bug is in the test, which assumed instantness.

How it works and why

Services talk by events through a queue and there is a delay between "event published" and "event processed". It is not always the same: it depends on load, consumer lag, retries. So a test that waits a fixed time is either too short (flaky) or too long (slow). The right form: poll the state until it becomes the expected one, but not longer than the limit the business promises.

How to wait for an async result

Bad

sleep / immediately

A fixed pause: either flaky or needlessly slow. An immediate check catches the "not arrived yet" state.

Good

poll + SLA

Polling until the expected state with a timeout from the SLA: fast when normal, fails on degradation.

Figure 1. A fixed pause versus polling.

The timeout must match the SLA. If the business promises an update within 5 seconds, a test with a 60-second timeout will miss a degradation: the system became ten times slower and the test is green.

Example: a saga with compensation

A saga performs a business operation across several services without a distributed transaction. Every step has a compensating action. An order: reserve stock, charge payment, create shipment. If the shipment cannot be created, the money must be refunded and the reservation released. The test breaks the last step and waits for the system to reach a consistent end by itself.

// Delivery is stubbed: always answers 503
await deliveryStub.failWith(503);
const { id } = await api.createOrder(cart);

await expect(async () => {
  const order = await api.getOrder(id);
  expect(order.status).toBe('CANCELLED');
  expect(order.refundStatus).toBe('REFUNDED');
  expect(await stock.reserved(cart.sku)).toBe(0);
}).toPass({ timeout: 10_000, intervals: [250, 500, 1000] });

toPass repeats the whole block until all three checks pass together. The reserve check matters: without it you can miss a "half-finished" state where the money is refunded but the stock stays reserved.

What else to test in a saga

  • A failure at each step and the matching compensation.
  • A failure of the compensation itself: is there a retry and an alert.
  • Redelivery of an event at each step: the handler must be idempotent.
  • A final state with no "half-finished" operations.

Limits and alternatives

Polling does not guarantee that the state ever converges: if an event is lost the test simply fails on the timeout, which is the right behaviour. When a service exposes events or webhooks a test can subscribe to them instead of polling, but polling is simpler and independent of internals. The "action, then wait" pair does not replace negative checks: a saga must also be tested against the failures you model.

Common mistakes

  • sleep(3000) instead of polling: unstable and slow.
  • A blanket 60-second timeout "so it does not fail": degradation stays invisible.
  • Checking only the order status and not the money and reserve: a "half-finished" state goes unnoticed.

Check yourself

A test with a 60 s poll timeout is green while the business promises 5 s. What is wrong?

Answer

The timeout is too generous: a degradation from 2 s to 40 s will not show. Take the timeout from the SLA with a margin for normal variance.

Why does a saga test check both the money and the reserve, not only the order status?

Answer

The CANCELLED status can appear while one of the compensations has not run yet. The final state is consistent only when all side effects are reverted.

In an interview. Junior: In an asynchronous system I do not check at once but wait for the final state by polling with a timeout, not with sleep. Middle/Senior: I take the timeout from the SLA so degradation is visible. For sagas I break each step and check the compensation, its redelivery and a final state with no half-finished operations: money, reserve and status are consistent.