---
title: "Money Transfer"
description: "Move money between two accounts. When an operation still fails after its retries, the Flow calls the undo operations and fails."
canonical_url: "https://docs.superdurable.io/examples/money-transfer/"
source: "docs/content/use-cases/money-transfer.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Money Transfer

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/examples/money-transfer.go.md) · [Java](https://docs.superdurable.io/examples/money-transfer.java.md) · [TypeScript](https://docs.superdurable.io/examples/money-transfer.typescript.md) · [Rust](https://docs.superdurable.io/examples/money-transfer.rust.md)

Move money between two accounts. When an operation still fails after its retries, the Flow calls the undo operations and fails.

**SDKs:** Python · Go · TypeScript · Java · Rust

**Shows:** [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md).

**Flow graph: MoneyTransferFlow**

**Steps**

1. `CheckBalance` (start Step): Check that the source account can cover the amount. Next: the Flow fails, or `CreateDebitMemo`.
2. `Compensate`: Undo every transfer change after a Step fails, then fail the Flow. Next: the Flow fails.
3. `CreateCreditMemo`: Record a credit memo on the destination account. Next: `Credit`, or `Compensate` if it keeps failing.
4. `CreateDebitMemo`: Record a debit memo on the source account. Next: `Debit`, or `Compensate` if it keeps failing.
5. `Credit`: Credit the amount to the destination account and complete. Next: the Flow completes, or `Compensate` if it keeps failing.
6. `Debit`: Debit the amount from the source account. Next: `CreateCreditMemo`, or `Compensate` if it keeps failing.

Example: [examples/python/dex_examples/products/money-transfer/money_transfer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/money-transfer/money_transfer_flow.py)

The graph and this description cover the Python, Go, Java, and TypeScript examples. The [Rust example](https://docs.superdurable.io/examples/money-transfer.md#rust-example) differs.

## Product requirements

The transfer takes a source account, destination account, amount, and note. It must:

1. Reject the transfer before any side effect when the source balance is too low.
2. Create a debit memo, debit the source, create a credit memo, and credit the destination, in that order.
3. Complete only after the credit.
4. Call every undo operation and fail when an operation still fails after its retries.

## Flow design

Each operation is its own Step, so Dex Web shows the retries of each one. A retry of **Credit** does not run **Debit** again, because **Debit** already finished.

An insufficient balance force-fails the Flow in **CheckBalance**. Nothing needs undoing, because no money has moved.

Each of the four side-effecting Steps retries for up to one hour. Its `ExecuteFailure` policy then moves the Flow to **Compensate**, which retries for up to 24 hours. **Compensate** calls all four undo operations, then force-fails the Flow, so a caller never takes a failed transfer for a success. If **Compensate** also exhausts its retries, the Flow fails and some effects may remain. **Compensate** also calls the undo of operations that never ran. Each undo must therefore do nothing when there is nothing to undo; see [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md). In the graph, ⚠ on a Step marks a failure route; select the Step to see where it goes.

A real bank call needs an [idempotency key](https://docs.superdurable.io/concepts/step.md#idempotency-keys), because a Step that was cut off can run again. The example passes none. Without a key, the bank can receive a debit twice, for example when it applied the debit but the response was lost. Send a stable key with every memo, debit, credit, and undo call. The bank, or an adapter that reconciles the provider's outcome, must use it to drop the repeat.

## Core implementation

The code below sets the retries and the failure route of the operation Steps, and shows **Compensate**.

**Python**

```python
def compensated_step_options(
    total_duration: timedelta,
) -> StepOptions:
    return StepOptions(
        execute_retry=RetryPolicy(total_duration=total_duration)
    ).on_execute_failure_proceed_to(
        Compensate,
        StepOptions(execute_retry=COMPENSATE_RETRY),
    )
```

```python
class MoneyTransferFlow(Flow[TransferRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.compensate = Compensate(service)
        options = compensated_step_options(timedelta(hours=1))
        self.credit = Credit(service, options)
        self.create_credit_memo = CreateCreditMemo(service, self.credit, options)
        self.debit = Debit(service, self.create_credit_memo, options)
        self.create_debit_memo = CreateDebitMemo(service, self.debit, options)
        self.check_balance = CheckBalance(service, self.create_debit_memo)

    def get_steps(self) -> StepList[TransferRequest]:
        return StepList.start_step(self.check_balance).other_steps(
            self.create_debit_memo,
            self.debit,
            self.create_credit_memo,
            self.credit,
            self.compensate,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of()
```

```python
class Compensate(Step[TransferRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_retry=COMPENSATE_RETRY)

    def execute(self, context: Context, input: TransferRequest) -> StepDecision:
        self.service.undo_credit(input.to_account, input.amount)
        self.service.undo_create_credit_memo(
            input.to_account,
            input.amount,
            input.notes,
        )
        self.service.undo_create_debit_memo(
            input.from_account,
            input.amount,
            input.notes,
        )
        self.service.undo_debit(input.from_account, input.amount)
        return force_fail(
            f"transfer has failed from {input.from_account} "
            f"to {input.to_account} for amount {input.amount}"
        )
```

Example: [examples/python/dex_examples/products/money-transfer/money_transfer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/money-transfer/money_transfer_flow.py)

<a id="rust-example"></a>

## Rust example

The Rust example has the same Steps, but they record events instead of calling a service. **CheckBalance** fails the Flow only when the amount is not positive. The four side-effecting Steps and **Compensate** each make at most three attempts, so its integration test finishes quickly. If **Compensate** fails three times, the Flow fails. Its start endpoint reads only `workflowId` and ignores the business parameters. Every run moves 1000 cents from `a` to `b` with the note `notes`.

## Run it

<a id="demo"></a>

Start the examples of one language as in [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground). Then start a transfer from the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground), or call:

```text
http://localhost:8080/products/money-transfer/start?fromAccount=test1&toAccount=test2&amount=100&notes=hello
```

The shared dependency service is a stub: the balance check passes and every call succeeds. To watch retries and compensation, make one of its methods return an error.

This run moved 42 units from **checking-account** to **savings-account**. In Dex Web, **Events** → **Timeline** shows the input and output of each operation, and **Graph** shows the five Steps in order.

[![Dex Web Timeline showing the five operations in the completed transfer](https://docs.superdurable.io/img/use-cases/money-transfer-timeline.png)](https://docs.superdurable.io/img/use-cases/money-transfer-timeline.png)

[![Dex Web Graph showing the five operations in the completed transfer](https://docs.superdurable.io/img/use-cases/money-transfer-graph.png)](https://docs.superdurable.io/img/use-cases/money-transfer-graph.png)

## Next

- [Job Seeker Engagement](https://docs.superdurable.io/examples/job-seeker-engagement.md)
- [Execute Failure Recovery](https://docs.superdurable.io/design-patterns/failure-handling/execute-failure-recovery.md)
- [Failure Handling](https://docs.superdurable.io/design-patterns.md#failure-handling)
- [Step options](https://docs.superdurable.io/reference/python/step-options.md)
