Money Transfer
View as MarkdownMove 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.
The graph and this description cover the Python, Go, Java, and TypeScript examples. The Rust example differs.
Product requirements
The transfer takes a source account, destination account, amount, and note. It must:
- Reject the transfer before any side effect when the source balance is too low.
- Create a debit memo, debit the source, create a credit memo, and credit the destination, in that order.
- Complete only after the credit.
- 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. 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, 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.
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),
)
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()
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
type MoneyTransferFlow struct {
dex.FlowDefaults
service service.MyService
}
func NewMoneyTransferFlow(applicationService service.MyService) *MoneyTransferFlow {
return &MoneyTransferFlow{service: applicationService}
}
func (flow *MoneyTransferFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(checkBalance{service: flow.service}),
dex.DefineStep(createDebitMemo{service: flow.service}),
dex.DefineStep(debit{service: flow.service}),
dex.DefineStep(createCreditMemo{service: flow.service}),
dex.DefineStep(creditStep{service: flow.service}),
dex.DefineStep(compensate{service: flow.service}),
}
}
func (*MoneyTransferFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{}
}
func (step compensate) Execute(
_ dex.Context,
request TransferRequest,
) (*dex.StepDecision, error) {
// NOTE: to improve, we can use Dex data attributes to track whether each step has been attempted to execute
// and check a flag to see if we should undo it or not
if err := step.service.UndoCredit(request.ToAccount, request.Amount); err != nil {
return nil, err
}
if err := step.service.UndoCreateCreditMemo(
request.ToAccount,
request.Amount,
request.Notes,
); err != nil {
return nil, err
}
if err := step.service.UndoCreateDebitMemo(
request.FromAccount,
request.Amount,
request.Notes,
); err != nil {
return nil, err
}
if err := step.service.UndoDebit(request.FromAccount, request.Amount); err != nil {
return nil, err
}
return dex.ForceFail(fmt.Sprintf(
"transfer has failed from %s to %s for amount %d",
request.FromAccount,
request.ToAccount,
request.Amount,
)), nil
}
func compensatedStepOptions(totalDuration time.Duration) *dex.StepOptions {
return &dex.StepOptions{
ExecuteRetry: &dex.RetryPolicy{TotalDuration: totalDuration},
ExecuteFailure: dex.ProceedToOnExecuteFailure(
compensate{},
&dex.StepOptions{
ExecuteRetry: &dex.RetryPolicy{TotalDuration: 24 * time.Hour},
},
),
}
}
@Component
public class MoneyTransferFlow implements Flow<TransferRequest> {
private final MyDependencyService service;
private final CheckBalance checkBalance = new CheckBalance();
private final CreateDebitMemo createDebitMemo = new CreateDebitMemo();
private final Debit debit = new Debit();
private final CreateCreditMemo createCreditMemo = new CreateCreditMemo();
private final Credit credit = new Credit();
private final Compensate compensate = new Compensate();
public MoneyTransferFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<TransferRequest> getSteps() {
return StepList.startStep(checkBalance)
.otherSteps(createDebitMemo, debit, createCreditMemo, credit, compensate);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of();
}
private StepOptions compensatedStepOptions(final Duration totalDuration) {
return StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder().totalDuration(totalDuration).build())
.onExecuteFailureProceedTo(
Compensate.class,
StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder()
.totalDuration(Duration.ofHours(24))
.build())
.build())
.build();
}
final class Compensate implements Step<TransferRequest> {
@Override
public Class<TransferRequest> getInputType() {
return TransferRequest.class;
}
@Override
public StepOptions getStepOptions() {
return StepOptions.newBuilder()
.executeRetry(RetryPolicy.newBuilder()
.totalDuration(Duration.ofHours(24))
.build())
.build();
}
@Override
public StepDecision execute(final Context context, final TransferRequest request) {
service.undoCredit(request.toAccount, request.amount);
service.undoCreateCreditMemo(request.toAccount, request.amount, request.notes);
service.undoCreateDebitMemo(request.fromAccount, request.amount, request.notes);
service.undoDebit(request.fromAccount, request.amount);
return StepDecision.forceFail(String.format(
"transfer has failed from %s to %s for amount %d",
request.fromAccount,
request.toAccount,
request.amount));
}
}
Example: examples/java/src/main/java/io/superdurable/dex/products/moneytransfer/MoneyTransferFlow.java
export class MoneyTransferFlow implements Flow<TransferRequest> {
private readonly checkBalance = new CheckBalance(this);
private readonly createDebitMemo = new CreateDebitMemo(this);
private readonly debit = new Debit(this);
private readonly createCreditMemo = new CreateCreditMemo(this);
private readonly credit = new Credit(this);
private readonly compensate = new Compensate(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getFlowType(): string {
return "MoneyTransferFlow";
}
public getSteps() {
return StepList.startStep(this.checkBalance).otherSteps(
this.createDebitMemo,
this.debit,
this.createCreditMemo,
this.credit,
this.compensate,
);
}
public getPersistenceSchema(): PersistenceSchema {
return {};
}
public compensatedStepOptions(totalDurationMs: number): StepOptions {
return {
executeRetry: { totalDurationMs },
executeFailure: ExecuteFailure.proceedTo(Compensate, {
executeRetry: { totalDurationMs: DAY_MS },
}),
};
}
class Compensate implements Step<TransferRequest> {
public constructor(private readonly flow: MoneyTransferFlow) {}
public getStepType(): string {
return "Compensate";
}
public getStepOptions(): StepOptions {
return { executeRetry: { totalDurationMs: DAY_MS } };
}
public execute(_context: Context, request: TransferRequest): StepDecision {
this.flow.service.undoCredit(request.toAccount, request.amount);
this.flow.service.undoCreateCreditMemo(request.toAccount, request.amount, request.notes);
this.flow.service.undoCreateDebitMemo(request.fromAccount, request.amount, request.notes);
this.flow.service.undoDebit(request.fromAccount, request.amount);
return forceFail(
`transfer has failed from ${request.fromAccount} to ${request.toAccount} for amount ${request.amount}`,
);
}
}
Example: examples/typescript/src/products/money-transfer/money-transfer-flow.ts
#[derive(Default)]
pub struct MoneyTransferFlow {
check_balance: CheckBalance,
create_debit_memo: CreateDebitMemo,
debit: Debit,
create_credit_memo: CreateCreditMemo,
credit: Credit,
compensate: Compensate,
}
impl Flow for MoneyTransferFlow {
type StartInput = TransferRequest;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.check_balance)
.and(&self.create_debit_memo)
.and(&self.debit)
.and(&self.create_credit_memo)
.and(&self.credit)
.and(&self.compensate)
}
}
impl Step for Compensate {
type Input = TransferRequest;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
context.record_event("undo-credit", input.amount_cents)?;
context.record_event("undo-credit-memo", input.amount_cents)?;
context.record_event("undo-debit", input.amount_cents)?;
context.record_event("undo-debit-memo", input.amount_cents)?;
Ok(StepDecision::force_fail(
"transfer failed; effects compensated",
))
}
fn options(&self) -> StepOptions<Self::Input> {
StepOptions::new().execute_retry(transfer_retry())
}
}
fn compensated_step_options() -> StepOptions<TransferRequest> {
StepOptions::new()
.execute_retry(transfer_retry())
.on_execute_failure_proceed_to(&Compensate)
}
fn transfer_retry() -> RetryPolicy {
RetryPolicy::new()
.initial_interval(Duration::from_secs(1))
.maximum_attempts(3)
}
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
Start the examples of one language as in Run an example from the playground. Then start a transfer from the examples playground, or call:
http://localhost:8080/products/money-transfer/start?fromAccount=test1&toAccount=test2&amount=100¬es=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.

