Video in progress
What happens in an orchestration saga if the response to one step never arrives? How do you design saga timeouts?
If no response arrives, the saga hangs: the order sits in "waiting for payment" forever and the reserved stock in the warehouse is never released. A deadline for each step is stored in the saga state, and a scheduler finds the expired ones and either resends the step or moves it to compensation.
📖 Answer
In an asynchronous saga a timeout doesn't happen by itself the way it does with HTTP. The orchestrator sent a ReserveStock command and is waiting. The warehouse service lost the message, or its reply ended up in the DLT, and the orchestrator will never find out.
That is why the deadline is part of the saga state:
CREATE TABLE order_saga (
order_id uuid PRIMARY KEY,
step text NOT NULL, -- RESERVING_STOCK, CHARGING, ...
deadline_at timestamptz NOT NULL,
attempts int NOT NULL DEFAULT 0,
version bigint NOT NULL
);
@Scheduled(fixedDelay = 10_000)
@SchedulerLock(name = "sagaTimeouts", lockAtMostFor = "PT1M")
public void handleTimeouts() {
for (OrderSaga s : repo.findExpired(Instant.now(), 100)) {
if (s.attempts() < 3) {
s.retryCurrentStep(); // resends the same command
} else {
s.startCompensation(); // release what was reserved
}
repo.save(s); // with version: protects against a concurrent reply
}
}
Subtle points:
- A resent command must be idempotent, so the warehouse doesn't reserve twice. The command carries
sagaId + stepas the key. - A late reply. Compensation started on the timeout, and then "reserved" arrives from the warehouse. The orchestrator ignores a reply that doesn't match the current step, but the stock may still be reserved on the warehouse side. So the compensation command is sent anyway, and written as "if there is no reservation, do nothing".
- For steps like payment, a timeout doesn't mean "failed": the money may have been charged. Ask for the state to find out before compensating.
- Deadlines are agreed with the business: 15 minutes for payment, 2 days for delivery. They differ.
Engines like Temporal or Camunda give you durable timers and retries out of the box. If you write it yourself, the table and scheduler above are the minimum.
Sign up to mark studied questions and save your progress.