Video in progress
How do you test a distributed business process built with sagas (order → payment → subscription → author share)?
I test each step and its compensation separately, unit test the saga orchestrator as a state machine with all its transitions and errors, and at the integration level I inject failures on purpose and check that the system reaches a consistent final state. The most important test is the failure halfway through.
📖 Answer
Testing a saga's happy path is easy and nearly worthless. The bugs live in the compensation: the payment went through, the subscription wasn't created, so was the money refunded? The refund failed too, so then what?
The layers:
-
The orchestrator state machine. A unit test with no outside world: every state × every event (success, error, timeout, duplicate) → the next state and the commands sent. As a table with a parameterized test; sometimes with a property-based test, random sequences of events and an invariant: "if money was charged, eventually either there's a subscription or there's a refund".
-
Each step and its compensation. For every participating service: the command is idempotent, the compensation is idempotent, and the compensation works correctly even if it arrives before the original command (out-of-order delivery).
-
Integration failure scenarios. Broker and databases through Testcontainers, the external payment provider in WireMock. The scenarios:
- the subscription service crashes at step 3 → the payment is refunded;
- the refund is temporarily down at the provider → retry, then success;
- the orchestrator restarts in the middle of a saga → it continues from its state, and steps aren't repeated;
- two sagas start in parallel for the same order → only one remains.
- Observability in prod. An alert for "stuck" sagas (in one state for more than N minutes) and a daily reconciliation: payments compared with the provider's report.
Trade-off: you can't cover the full combinations in integration tests; they're slow. So I split the combinatorial part into unit-level state machine tests, and the real infrastructure behavior into a few selected integration scenarios.
Sign up to mark studied questions and save your progress.