Getting Started

Payment Processing with Saga Rollback


The core payment pattern: charge the customer, reserve inventory, and send a confirmation. If any step fails, you compensate the previously completed steps — refunding the charge and releasing the inventory reservation — with logic you define; Orcher runs those compensations durably, retrying until they complete even across crashes. This is the saga pattern applied to payment processing.

How it works

Look closely and this workflow applies a different failure policy to every step — that's the real design work in a payment saga. Failing early costs nothing; failing after money moved requires compensation; and some steps aren't worth failing over at all.

If This Step Fails…
1
validate_paymentFail fast — nothing has happened yet
2
charge_payment_gatewayFail — the idempotency key guards a partial capture
3
reserve_inventoryCompensate: refund_charge, then fail — money is never held without goods
4
send_confirmationSwallowed — the payment is complete; email is best-effort
One workflow, three failure policies: fail-fast, compensate-then-fail, and best-effort.

The compensation itself is a journaled task with the same durability as the forward path — see the saga walk-through in the overview for what happens when a rollback is interrupted.

Example: charge, reserve, confirm

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use serde::{Deserialize, Serialize};
4
5
#[derive(Debug, Clone, Serialize, Deserialize)]
6
struct PaymentInput {
7
order_id: String,
8
customer_id: String,
9
amount: f64,
10
currency: String,
11
idempotency_key: String,
12
}
13
14
#[derive(Debug, Clone, Serialize, Deserialize)]
15
struct PaymentResult {
16
charge_id: String,
17
status: String,
18
order_id: String,
19
}
20
21
#[derive(Debug, Clone, Serialize, Deserialize)]
22
struct ChargeResult {
23
charge_id: String,
24
status: String,
25
}
26
27
#[task]
28
async fn validate_payment(input: PaymentInput) -> Result<PaymentInput> {
29
// Validate card, check limits, verify customer
30
if input.amount <= 0.0 {
31
anyhow::bail!("Invalid payment amount");
32
}
33
Ok(input)
34
}
35
36
#[task]
37
async fn charge_payment_gateway(
38
amount: f64, currency: String, idempotency_key: String,
39
) -> Result<ChargeResult> {
40
// Call Stripe/Braintree with idempotency key to prevent double charges
41
let charge = gateway::create_charge(amount, &currency, &idempotency_key).await?;
42
Ok(ChargeResult { charge_id: charge.id, status: "succeeded".to_string() })
43
}
44
45
#[task]
46
async fn reserve_inventory(order_id: String) -> Result<()> {
47
// Reserve items in warehouse system
48
warehouse::reserve(&order_id).await?;
49
Ok(())
50
}
51
52
#[task]
53
async fn refund_charge(charge_id: String) -> Result<()> {
54
// Compensating action: refund the charge
55
gateway::refund(&charge_id).await?;
56
Ok(())
57
}
58
59
#[task]
60
async fn send_confirmation(customer_id: String, order_id: String) -> Result<()> {
61
// Send order confirmation email
62
email::send_receipt(&customer_id, &order_id).await?;
63
Ok(())
64
}
65
66
#[workflow(name = "process_payment", version = "1.0.0")]
67
pub async fn process_payment(
68
ctx: WorkflowContext,
69
input: PaymentInput,
70
) -> Result<PaymentResult> {
71
// Step 1: Validate
72
let validated = ctx.execute_task(validate_payment, input.clone()).await?;
73
74
// Step 2: Charge payment gateway (with idempotency key)
75
let charge = ctx.execute_task(charge_payment_gateway, (
76
validated.amount, validated.currency.clone(), validated.idempotency_key.clone()
77
)).await?;
78
79
// Step 3: Reserve inventory — compensate on failure
80
if let Err(e) = ctx.execute_task(reserve_inventory, validated.order_id.clone()).await {
81
// Saga compensation: refund the charge
82
ctx.execute_task(refund_charge, charge.charge_id.clone()).await?;
83
return Err(e);
84
}
85
86
// Step 4: Send confirmation (best-effort, don't fail the payment)
87
let _ = ctx.execute_task(send_confirmation, (
88
validated.customer_id.clone(), validated.order_id.clone()
89
)).await;
90
91
Ok(PaymentResult {
92
charge_id: charge.charge_id,
93
status: "completed".to_string(),
94
order_id: validated.order_id,
95
})
96
}

Two layers of idempotency

The journal guarantees charge_payment_gateway never re-executes once its result is recorded. But there's a window the journal can't see: the worker dies inside the task — after the gateway captured the money, before the result was journaled. That's what the gateway idempotency key is for.

Crash Inside the Charge
1
charge_payment_gatewayCalls the gateway with key ord_1042
✓
gateway captures $49.00Response in flight back to the worker
✗
worker diesNo journal entry written
↻
task retriesSame call, same key ord_1042
✓
gateway returns the original chargeDeduplicated by the provider — no second capture
The journal dedupes between tasks; the idempotency key dedupes inside them. Payments need both.

The overview's charged-once diagram covers a crash between tasks — the journal handles that alone. This one covers a crash inside the charge task, where only the provider can tell the retry "you already paid."

Design notes

  • Derive the idempotency key from the order, not the attempt. The key must be stable for one logical payment (input.idempotency_key, set by the caller from the order ID). A key generated per retry would defeat the gateway's deduplication exactly when you need it.
  • Compensation can fail too. refund_charge is a journaled task with retries, but if the gateway is down long enough, the workflow fails holding a captured charge. That's the correct behavior: the journal records precisely which compensations completed, giving your ops process an exact worklist instead of a mystery.
  • Best-effort is a policy, not an accident. The confirmation's ignored error is deliberate — a receipt email must never refund a good payment. If notifications matter more than that, move them to their own workflow triggered by a completion event.
  • Use minor units in production. The examples pass amount as a float for brevity; real payment systems should carry integer minor units (cents) end-to-end to avoid rounding drift.

Next Steps