Getting Started

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.

The Dunning Schedule
d0
attempt 1Charge declined
⏸
email #1 · sleep 1 daySuspended until the timer fires
d1
attempt 2Charge declined
⏸
email #2 · sleep 3 daysSuspended
d4
attempt 3Charge declined
⏸
email #3 · sleep 7 daysSuspended
d11
attempt 4Charge declined — schedule exhausted
✗
suspend_subscriptionTerminal state — journaled like every other step
Any attempt that succeeds exits immediately: record_payment → status "paid".

Example: billing with a retry schedule

1
use orcher::prelude::*;
2
use anyhow::Result;
3
use std::time::Duration;
4
5
#[derive(Debug, Clone, Serialize, Deserialize)]
6
struct SubscriptionBilling {
7
subscription_id: String,
8
customer_id: String,
9
amount: f64,
10
payment_method_id: String,
11
}
12
13
#[derive(Debug, Clone, Serialize, Deserialize)]
14
struct BillingResult {
15
subscription_id: String,
16
paid: bool,
17
attempts: u32,
18
final_status: String,
19
}
20
21
#[task]
22
async 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
}
26
27
#[task]
28
async fn send_dunning_email(customer_id: String, attempt: u32) -> Result<()> {
29
email::send_payment_failed(&customer_id, attempt).await?;
30
Ok(())
31
}
32
33
#[task]
34
async fn suspend_subscription(subscription_id: String) -> Result<()> {
35
billing::suspend(&subscription_id).await?;
36
Ok(())
37
}
38
39
#[task]
40
async fn record_payment(subscription_id: String, charge_id: String) -> Result<()> {
41
billing::record_payment(&subscription_id, &charge_id).await?;
42
Ok(())
43
}
44
45
#[workflow(name = "subscription_billing", version = "1.0.0")]
46
pub async fn subscription_billing(
47
ctx: WorkflowContext,
48
billing: SubscriptionBilling,
49
) -> Result<BillingResult> {
50
// Retry schedule: immediate, 1 day, 3 days, 7 days
51
let retry_delays = [
52
Duration::from_secs(0),
53
Duration::from_secs(86400), // 1 day
54
Duration::from_secs(259200), // 3 days
55
Duration::from_secs(604800), // 7 days
56
];
57
58
for (attempt, delay) in retry_delays.iter().enumerate() {
59
if attempt > 0 {
60
// Send dunning email before retry
61
ctx.execute_task(
62
send_dunning_email, (billing.customer_id.clone(), attempt as u32)
63
).await?;
64
65
// Wait before retrying — durable timer
66
ctx.sleep(*delay).await?;
67
}
68
69
// Attempt the charge
70
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 return
77
ctx.execute_task(
78
record_payment, (billing.subscription_id.clone(), charge_id)
79
).await?;
80
81
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 retry
91
}
92
}
93
}
94
95
// All retries exhausted — suspend the subscription
96
ctx.execute_task(suspend_subscription, billing.subscription_id.clone()).await?;
97
98
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:

Task Retries vs. the Dunning Schedule
Task retries
Transient faults

Gateway timeout, network blip. Retried automatically by the platform within seconds — the workflow code never sees them.

Dunning schedule
Business declines

Insufficient funds, expired card. Surfaces as a task failure the workflow catches — answered with emails, days of waiting, and eventually suspension.

The match on attempt_charge is the boundary: task retries happen below it, business policy above it.

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_subscription fails, the task retries; the workflow can't silently finish leaving a delinquent account active. Every subscription ends in exactly one recorded terminal state: paid or suspended.

Next Steps