Payments & Integrations Bug Report

A retried saga step refunded the same customer twice

Our order saga's refund compensation timed out, the orchestrator retried it, and both attempts succeeded at the payment provider. Sixty customers got double refunds. Why compensations need the same idempotency as forward steps, and the saga log changes that made each step run exactly once in effect.

Ravi Subramanian Ravi Subramanian @ravisubramanian · November 25, 2026 · 8 min read · 69 Views
Banner: a saga compensation step executed twice after a retry

Our finance team flagged a reconciliation mismatch: refunds issued through the payment provider exceeded refunds recorded in our ledger by about 4,100 EUR over one weekend. The provider's report showed 60 orders with two refunds each, each for the full order amount. Every one of those orders had gone through the failure path of our order saga.

Our order flow is an orchestrated saga: authorise payment, reserve stock, create shipment, capture payment. If a step fails, the orchestrator runs compensations in reverse. One of those compensations, for orders that failed after capture, is a refund.

The orchestrator's log for one affected order:

2026-10-31T14:02:11Z saga=ord-77120 step=create_shipment status=failed reason=carrier_unavailable
2026-10-31T14:02:11Z saga=ord-77120 compensate=refund_payment attempt=1 started
2026-10-31T14:02:41Z saga=ord-77120 compensate=refund_payment attempt=1 error=timeout after 30s
2026-10-31T14:02:43Z saga=ord-77120 compensate=refund_payment attempt=2 started
2026-10-31T14:02:44Z saga=ord-77120 compensate=refund_payment attempt=2 ok refund_id=re_8812b

And the provider's records for the same charge:

refund re_88129  amount=68.40  created=2026-10-31T14:02:39Z  status=succeeded
refund re_8812b  amount=68.40  created=2026-10-31T14:02:44Z  status=succeeded

The first attempt succeeded at the provider, 28 seconds in, but its response arrived after our 30 second timeout (or was lost on the way back). From the orchestrator's point of view it had failed, so it retried. The retry issued a second, independent refund.

That weekend the provider had elevated latency, which is why it happened 60 times instead of never.

The compensation code

class RefundPayment(Compensation):
    def run(self, saga: OrderSaga) -> None:
        provider.refunds.create(
            charge_id=saga.state["charge_id"],
            amount=saga.state["captured_amount"],
        )

No idempotency key. The forward step, capture_payment, did use one; we had been careful there because "never charge twice" was a well-known rule. Nobody had applied the same thinking to the undo.

Timeouts mean "unknown", not "failed"

When a call times out, there are three possibilities: the request never arrived, it arrived and failed, or it arrived and succeeded but the response was lost or slow. The caller cannot tell which. Treating a timeout as a failure and retrying is only safe if doing the action twice has the same effect as doing it once.

Compensations are actions too

Sagas are often described as "do, and undo on failure". That framing makes compensations sound like rollbacks, which happen inside a database and cannot be applied twice. A refund is not a rollback. It is a new financial action at a third party, with its own failure modes: timeouts, partial failures, retries. Everything that makes forward steps hard applies equally to compensations:

  • They can time out with an unknown outcome.
  • They can be retried by the orchestrator, by a redelivered message, or by an operator clicking "retry".
  • They must eventually succeed, because a saga stuck halfway through compensation leaves the system inconsistent.

The combination, "must be retried until it succeeds" and "may have already succeeded", has only one safe solution: idempotency.

Two layers of duplicate risk

We had duplicates from two sources:

  1. Within one execution: the orchestrator's own retry after a timeout (the case above).
  2. Across executions: if the orchestrator crashed after the refund but before recording it, on restart it would replay the saga from its last recorded step and run the refund again. We had not seen this in production yet, but a crash test showed it.

Environment

Item Value
Orchestrator in-house, Python 3.12, saga state in PostgreSQL
Payment provider card API with optional idempotency keys on refunds
Retry policy 3 attempts per step, 30 s timeout, 2 s backoff
Impact 60 double refunds, 4,104 EUR

1. Idempotency keys on every external action, forward and backward

Each saga step gets a deterministic key built from the saga ID and the step name. The key is the same on every retry and every replay of that step, and different for any other step:

def step_key(saga_id: str, step: str) -> str:
    return f"saga:{saga_id}:{step}"

class RefundPayment(Compensation):
    def run(self, saga: OrderSaga) -> None:
        result = provider.refunds.create(
            charge_id=saga.state["charge_id"],
            amount=saga.state["captured_amount"],
            idempotency_key=step_key(saga.id, "refund_payment"),
        )
        saga.record(step="refund_payment", refund_id=result.id)

With the key, the provider returns the original refund for the second request instead of creating a new one. A retry after a lost response now gets the first refund's ID back.

Keys must be derived from the saga, not generated at call time. A uuid4() created inside run() would be different on every attempt and protect nothing.

2. Record intent before acting, and outcome after

The saga log records two entries per step: "started" before the external call and "completed" with the result after it. On restart, the orchestrator handles each state explicitly:

Log state for a step On restart
no entry run the step
started, not completed run the step again with the same idempotency key
completed skip, use the recorded result
def execute(saga: OrderSaga, step: Step) -> None:
    entry = saga.log.get(step.name)
    if entry and entry.completed:
        return
    if not entry:
        saga.log.start(step.name)                # committed before the call
    step.run(saga)                               # idempotent by key
    saga.log.complete(step.name)                 # committed after the call

The "started but not completed" case is exactly the ambiguous one. Re-running it is safe only because the external call is idempotent. Without the key, the log alone cannot prevent the duplicate; it only tells you one might have happened.

3. Make internal compensations idempotent by state

Not every compensation calls a provider. Releasing a stock reservation is a local operation. We made those idempotent with conditional updates:

UPDATE reservations SET status = 'released', released_at = now()
WHERE id = :reservation_id AND status = 'held';

Running it twice changes nothing the second time. The handler checks the row count and treats 0 as "already released", not as an error.

4. Check before retrying when the provider allows it

For refunds specifically, after a timeout the orchestrator now first looks up refunds for the charge (filtered by our metadata) before retrying. That is defence in depth: the idempotency key already prevents the duplicate, but the lookup also gives a clearer log and covers providers whose idempotency window is short.

5. Recover the money

For the 60 double refunds, we could not reverse the second refund through the provider. Finance contacted the affected customers; most agreed to a new charge for the duplicate amount, and the rest were written off.

1. A test with a slow provider. A fake provider processes the refund, then delays its response beyond the orchestrator's timeout:

def test_refund_retry_after_timeout_refunds_once(fake_provider, saga_runner):
    fake_provider.respond_after(seconds=35)            # refund succeeds, response too late
    saga = saga_runner.run_until_failure(order_with_failing_shipment())

    assert fake_provider.refund_count(saga.state["charge_id"]) == 1
    assert saga.log.get("refund_payment").completed

On the old code, two refunds. On the new code, one, and the second request returned the first refund's ID.

2. Crash test. We killed the orchestrator process right after the refund call returned and before the log write, then restarted it. It found "started, not completed", re-ran the refund with the same key, received the existing refund, and completed the saga. One refund at the provider.

3. Audit of all steps. We reviewed every forward step and compensation in all four sagas we run. Two more lacked keys: a payout reversal and a gift card re-credit. Both fixed. A unit test now fails if any Step or Compensation class makes an external call without passing idempotency_key.

4. Reconciliation. Finance's daily reconciliation now compares refunds per charge at the provider with our ledger and alerts on any charge with more than one refund. It has been clean since.

5. Security implications. Duplicate refunds were also a fraud opportunity: anyone able to make the refund path slow, for example by triggering many failing orders during a provider slowdown, could have been paid twice. Idempotent compensations close that.

Takeaways

  • A timeout means the outcome is unknown. Retrying is safe only if the action is idempotent.
  • Compensations are new actions, not rollbacks. They need idempotency as much as forward steps do.
  • Derive idempotency keys from the saga and step, never generate them per attempt.
  • Log "started" before and "completed" after each step, and re-run ambiguous steps with the same key.

References: Microsoft Azure Architecture Center, Saga pattern, Microsoft Azure Architecture Center, Compensating Transaction pattern, IETF draft: The Idempotency-Key HTTP Header Field.

Add a label

#idempotency #retries #saga-pattern #refunds #distributed-systems
Written by
Ravi Subramanian @ravisubramanian

I have spent the past decade on systems where work moves through queues and events: order processing, notifications, payment flows and the services around them. I have helped split a monolith into services and, a few years later, helped merge some of them back. Distributed systems fail in ways that are hard to see from one log file. A poison message that blocks a queue for hours, a consumer that hoards messages, a schema change that silently drops events, a compensation step that ran twice, updates lost because two clocks disagreed. My posts trace each failure across the services involved, explain the guarantee we assumed and did not have, and show the design change that fixed it. For the bigger topics like sagas, CAP and service boundaries, I stay with concrete examples from systems I worked on rather than diagrams alone.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.