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.
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
1use orcher::prelude::*;2use anyhow::Result;3use serde::{Deserialize, Serialize};45#[derive(Debug, Clone, Serialize, Deserialize)]6struct PaymentInput {7 order_id: String,8 customer_id: String,9 amount: f64,10 currency: String,11 idempotency_key: String,12}1314#[derive(Debug, Clone, Serialize, Deserialize)]15struct PaymentResult {16 charge_id: String,17 status: String,18 order_id: String,19}2021#[derive(Debug, Clone, Serialize, Deserialize)]22struct ChargeResult {23 charge_id: String,24 status: String,25}2627#[task]28async fn validate_payment(input: PaymentInput) -> Result<PaymentInput> {29 // Validate card, check limits, verify customer30 if input.amount <= 0.0 {31 anyhow::bail!("Invalid payment amount");32 }33 Ok(input)34}3536#[task]37async 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 charges41 let charge = gateway::create_charge(amount, ¤cy, &idempotency_key).await?;42 Ok(ChargeResult { charge_id: charge.id, status: "succeeded".to_string() })43}4445#[task]46async fn reserve_inventory(order_id: String) -> Result<()> {47 // Reserve items in warehouse system48 warehouse::reserve(&order_id).await?;49 Ok(())50}5152#[task]53async fn refund_charge(charge_id: String) -> Result<()> {54 // Compensating action: refund the charge55 gateway::refund(&charge_id).await?;56 Ok(())57}5859#[task]60async fn send_confirmation(customer_id: String, order_id: String) -> Result<()> {61 // Send order confirmation email62 email::send_receipt(&customer_id, &order_id).await?;63 Ok(())64}6566#[workflow(name = "process_payment", version = "1.0.0")]67pub async fn process_payment(68 ctx: WorkflowContext,69 input: PaymentInput,70) -> Result<PaymentResult> {71 // Step 1: Validate72 let validated = ctx.execute_task(validate_payment, input.clone()).await?;7374 // 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?;7879 // Step 3: Reserve inventory — compensate on failure80 if let Err(e) = ctx.execute_task(reserve_inventory, validated.order_id.clone()).await {81 // Saga compensation: refund the charge82 ctx.execute_task(refund_charge, charge.charge_id.clone()).await?;83 return Err(e);84 }8586 // 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;9091 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.
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_chargeis 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
amountas a float for brevity; real payment systems should carry integer minor units (cents) end-to-end to avoid rounding drift.
Next Steps
- Next pattern: Subscription Billing with Dunning
- Back to Payment Workflows overview