Subscription Billing with Dunning
Recurring subscription billing requires retry logic that spans days — if a payment fails, you don't just retry immediately. You wait hours or days, send dunning emails, try alternate payment methods, and eventually suspend the account. Orcher's durable timers make this natural: the workflow sleeps between retries with zero resource consumption.
How it works
The example's plain for-loop is actually an eleven-day state machine. Each failed attempt sends a dunning email, sleeps for the next interval in the schedule, and tries again; any success exits immediately with the payment recorded. Between attempts the workflow is suspended — a fleet of 100,000 subscriptions in dunning holds no threads and no connections.
Example: billing with a retry schedule
1use orcher::prelude::*;2use anyhow::Result;3use std::time::Duration;45#[derive(Debug, Clone, Serialize, Deserialize)]6struct SubscriptionBilling {7 subscription_id: String,8 customer_id: String,9 amount: f64,10 payment_method_id: String,11}1213#[derive(Debug, Clone, Serialize, Deserialize)]14struct BillingResult {15 subscription_id: String,16 paid: bool,17 attempts: u32,18 final_status: String,19}2021#[task]22async fn attempt_charge(customer_id: String, amount: f64, method_id: String) -> Result<String> {23 let charge = gateway::charge(&customer_id, amount, &method_id).await?;24 Ok(charge.id)25}2627#[task]28async fn send_dunning_email(customer_id: String, attempt: u32) -> Result<()> {29 email::send_payment_failed(&customer_id, attempt).await?;30 Ok(())31}3233#[task]34async fn suspend_subscription(subscription_id: String) -> Result<()> {35 billing::suspend(&subscription_id).await?;36 Ok(())37}3839#[task]40async fn record_payment(subscription_id: String, charge_id: String) -> Result<()> {41 billing::record_payment(&subscription_id, &charge_id).await?;42 Ok(())43}4445#[workflow(name = "subscription_billing", version = "1.0.0")]46pub async fn subscription_billing(47 ctx: WorkflowContext,48 billing: SubscriptionBilling,49) -> Result<BillingResult> {50 // Retry schedule: immediate, 1 day, 3 days, 7 days51 let retry_delays = [52 Duration::from_secs(0),53 Duration::from_secs(86400), // 1 day54 Duration::from_secs(259200), // 3 days55 Duration::from_secs(604800), // 7 days56 ];5758 for (attempt, delay) in retry_delays.iter().enumerate() {59 if attempt > 0 {60 // Send dunning email before retry61 ctx.execute_task(62 send_dunning_email, (billing.customer_id.clone(), attempt as u32)63 ).await?;6465 // Wait before retrying — durable timer66 ctx.sleep(*delay).await?;67 }6869 // Attempt the charge70 match ctx.execute_task(attempt_charge, (71 billing.customer_id.clone(),72 billing.amount,73 billing.payment_method_id.clone(),74 )).await {75 Ok(charge_id) => {76 // Payment succeeded — record and return77 ctx.execute_task(78 record_payment, (billing.subscription_id.clone(), charge_id)79 ).await?;8081 return Ok(BillingResult {82 subscription_id: billing.subscription_id,83 paid: true,84 attempts: attempt as u32 + 1,85 final_status: "paid".to_string(),86 });87 }88 Err(e) => {89 println!("Attempt {} failed: {}", attempt + 1, e);90 // Continue to next retry91 }92 }93 }9495 // All retries exhausted — suspend the subscription96 ctx.execute_task(suspend_subscription, billing.subscription_id.clone()).await?;9798 Ok(BillingResult {99 subscription_id: billing.subscription_id,100 paid: false,101 attempts: retry_delays.len() as u32,102 final_status: "suspended".to_string(),103 })104}Two layers of retries
Don't confuse the dunning schedule with task retries — they solve different problems, and this workflow uses both:
Gateway timeout, network blip. Retried automatically by the platform within seconds — the workflow code never sees them.
Insufficient funds, expired card. Surfaces as a task failure the workflow catches — answered with emails, days of waiting, and eventually suspension.
By the time the workflow's match sees an error from attempt_charge, the platform has already exhausted its retries for transient faults. What's left is a real decline — and that's a business event, not an infrastructure one.
Design notes
- Distinguish hard and soft declines. A soft decline (insufficient funds) may resolve on payday, so the 1/3/7-day schedule earns its keep. A hard decline (stolen card, closed account) never will — branch on the decline code and suspend immediately instead of burning eleven days.
- Scope idempotency keys per attempt. Unlike one-shot payment processing, each dunning attempt is a distinct charge intent. Derive keys from (subscription, billing period, attempt) so retries of one attempt deduplicate without blocking the next attempt.
- The schedule is versioned logic. This workflow lives for up to eleven days, and replay must walk the same path — treat the retry schedule as part of the workflow's versioned definition, not runtime config you mutate under running instances.
- Suspension is a journaled step too. If
suspend_subscriptionfails, the task retries; the workflow can't silently finish leaving a delinquent account active. Every subscription ends in exactly one recorded terminal state:paidorsuspended.
Next Steps
- Next pattern: Fraud Detection with Human Review
- Previous: Payment Processing with Saga Rollback
- Back to Payment Workflows overview