Subscription and Billing Lifecycle
View as MarkdownRun a subscription through its trial, billing periods, price changes, and cancellation. The Flow waits on durable Timers and Channels, so one subscription can run for months.
SDKs: Python · Go · TypeScript · Java · Rust
Shows: Recurring Timer loop, Static Parallel Steps.
The graph and this description cover the Python, Go, Java, and TypeScript examples. The Rust example differs.
Product requirements
The plan sets the trial length, the billing-period length, the number of billing periods, and the charge amount. The subscription must:
- Send a welcome email and charge nothing until the trial ends.
- Charge once per billing period. After the last period, email the customer and end.
- Accept a new charge amount at any time. Charges that start after the Flow applies it use it.
- Accept a cancellation at any time. Email the customer and end the subscription.
- Return the plan through the
describeRPC.
Flow design
Initialize stores the customer and a billing-period counter in Attributes, then starts three branches. Trial sends the welcome email and waits for the trial Timer. ChargeCurrentBill then loops: its WaitFor counts the next period and waits for that period's Timer, and its Execute charges and moves back to ChargeCurrentBill. After the last period it emails the customer and force-completes the Flow. Cancel waits for a cancel message, emails the customer, and force-completes the Flow. UpdateChargeAmount applies one new amount at a time and moves back to itself.
Two choices shape this design:
- Every branch reads the customer and plan from Attributes. The update RPC queues the new amount, and UpdateChargeAmount writes it. A billing Execute that starts after that Step commits reads it. A charge already running keeps the old amount, also on retry.
- Force-completing the Flow also ends the waits of the other branches, so no branch has to stop the others.
A cancellation can arrive while a charge is running. Cancel ends the Flow, but a charge already sent to the payment provider can still complete. Your refund and entitlement policy decides that case.
A real payment call needs an idempotency key, because a Step that was cut off can run again. The example passes none. A good key is the Flow ID with the billing-period number. WaitFor commits that number before Execute charges, so every retry of one charge sends the same key, and the provider can drop the repeat. The welcome, end, and cancellation emails need their own keys too, such as the Flow ID with the email's purpose.
Core implementation
Each tab shows the Flow class of the runnable example. The graph above comes from the Python Flow; Go, TypeScript, and Java have the same Steps.
class SubscriptionFlow(Flow[Customer]):
billing_period_number = Attribute("billing-period-number", int)
customer_details = Attribute("customer", Customer)
cancel_subscription = Channel[None]("cancel-subscription", type(None))
update_charge_amount = Channel("update-charge-amount", int)
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.charge_current_bill = ChargeCurrentBill(
service,
self.customer_details,
self.billing_period_number,
)
self.trial = Trial(
service,
self.customer_details,
self.billing_period_number,
self.charge_current_bill,
)
self.cancel = Cancel(
service,
self.customer_details,
self.cancel_subscription,
)
self.update_charge_amount_step = UpdateChargeAmount(
self.customer_details,
self.update_charge_amount,
)
self.initialize = Initialize(
self.customer_details,
Example: examples/python/dex_examples/products/subscription/subscription_flow.py
type SubscriptionFlow struct {
dex.FlowDefaults
service service.MyService
}
func NewSubscriptionFlow(applicationService service.MyService) *SubscriptionFlow {
return &SubscriptionFlow{service: applicationService}
}
func (flow *SubscriptionFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(initializeStep{}),
dex.DefineStep(trial{service: flow.service}),
dex.DefineStep(chargeCurrentBill{service: flow.service}),
dex.DefineStep(cancelStep{service: flow.service}),
dex.DefineStep(updateChargeAmountStep{}),
}
}
func (flow *SubscriptionFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.Describe, nil),
dex.DefineRPC(flow.GetCustomer, nil),
dex.DefineRPC(flow.Cancel, nil),
dex.DefineRPC(flow.UpdateCharge, nil),
}
}
func (*SubscriptionFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Attributes: []dex.AttributeDef{BillingPeriodNumber, CustomerDetails},
Channels: []dex.ChannelDef{CancelSubscription, UpdateChargeAmount},
}
}
func (*SubscriptionFlow) Describe(
ctx dex.Context,
_ dex.None,
) (*dex.RPCResult[Subscription], error) {
customer, err := CustomerDetails.Get(ctx)
if err != nil {
return nil, err
}
return &dex.RPCResult[Subscription]{Output: customer.Subscription}, nil
}
@Component
public class SubscriptionFlow implements Flow<Customer> {
private static final String SUBSCRIPTION_OVER_KEY = "subscription-over";
public final Attribute<Integer> billingPeriodNumber =
Attribute.define("billing-period-number", Integer.class);
public final Attribute<Customer> customerDetails =
Attribute.define("customer", Customer.class);
public final Channel<Void> cancelSubscription =
Channel.define("cancel-subscription", Void.class);
public final Channel<Integer> updateChargeAmount =
Channel.define("update-charge-amount", Integer.class);
private final MyDependencyService service;
private final Initialize initialize = new Initialize();
private final Trial trial = new Trial();
private final ChargeCurrentBill chargeCurrentBill = new ChargeCurrentBill();
private final Cancel cancel = new Cancel();
private final UpdateChargeAmount updateChargeAmountStep = new UpdateChargeAmount();
public SubscriptionFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<Customer> getSteps() {
return StepList.startStep(initialize)
.otherSteps(trial, chargeCurrentBill, cancel, updateChargeAmountStep);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(
billingPeriodNumber,
customerDetails,
cancelSubscription,
updateChargeAmount);
}
@RPC
public RPCResult<Subscription> describe(final Context context) {
return RPCResult.of(customerDetails.get(context).subscription);
}
Example: examples/java/src/main/java/io/superdurable/dex/products/subscription/SubscriptionFlow.java
export class SubscriptionFlow implements Flow<Customer> {
public readonly billingPeriodNumber = new Attribute("billing-period-number", doubleCodec);
public readonly customerDetails = new Attribute("customer", customerCodec);
public readonly initialize = new Initialize(this);
public readonly trial = new Trial(this);
public readonly chargeCurrentBill = new ChargeCurrentBill(this);
public readonly cancel = new Cancel(this);
public readonly updateChargeAmountStep = new UpdateChargeAmount(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getFlowType(): string {
return "SubscriptionFlow";
}
public getSteps() {
return StepList.startStep(this.initialize).otherSteps(
this.trial,
this.chargeCurrentBill,
this.cancel,
this.updateChargeAmountStep,
);
}
public getPersistenceSchema(): PersistenceSchema {
return {
attributes: [this.billingPeriodNumber, this.customerDetails],
channels: [cancelSubscription, updateChargeAmount],
};
}
@rpc()
public describe(context: Context): RPCResult<Subscription> {
return { output: this.customerDetails.get(context).subscription };
}
Example: examples/typescript/src/products/subscription/subscription-flow.ts
#[derive(Default)]
pub struct SubscriptionFlow {
welcome: Welcome,
billing: Billing,
control: Control,
}
impl SubscriptionFlow {
fn describe(&self, context: &mut Context) -> HandlerResult<RpcResult<SubscriptionState>> {
Ok(RpcResult::new(STATE.get(context)?.unwrap_or_default()))
}
fn update_charge(&self, context: &mut Context, amount: i64) -> HandlerResult<()> {
COMMANDS.publish(context, SubscriptionCommand::Charge(amount))
}
fn cancel(&self, context: &mut Context) -> HandlerResult<()> {
COMMANDS.publish(context, SubscriptionCommand::Cancel)
}
}
impl Flow for SubscriptionFlow {
type StartInput = SubscriptionRequest;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.welcome)
.and(&self.billing)
.and(&self.control)
}
fn persistence(&self) -> PersistenceSchema {
PersistenceSchema::new()
.attribute(&STATE)
.channel(&COMMANDS)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new()
.function_without_input(DESCRIBE_SUBSCRIPTION, Self::describe)
.procedure(UPDATE_SUBSCRIPTION_CHARGE, Self::update_charge)
.procedure_without_input(CANCEL_SUBSCRIPTION, Self::cancel)
}
}
Rust example
The Rust example is smaller and calls no service. Welcome stores the subscription state and records a welcome event; there is no trial. It then starts two branches. Billing waits for a one-day Timer, then adds one to the count of charged periods. Control takes one message at a time from a command Channel that both the update and the cancel RPC publish to. It writes the new amount or the cancellation into the state, and a cancellation force-completes the Flow. After the last period, Billing requests a graceful completion, which waits for Control to end, so the run ends only with a cancellation. Both Steps read and write the whole state without a lock, so one can overwrite the other's change.
In the playground, Start creates a plan of three periods at 1000 cents. Call Update charge amount, then Describe with the returned Flow ID until it shows the new amount. Describe returns the amount, the charged-period count, and the cancel flag. Cancel ends the run.
Run it
Start the examples of one language as in Run an example from the playground. Then open Subscription in the examples playground:
- Start returns the new Flow ID. It starts a 20-second trial and ten 10-second billing periods that charge 100 each.
- Update charge amount with that Flow ID queues the new amount. Call Describe until it shows the amount; charges that start after that use it.
- Cancel queues the cancellation, and the Cancel Step then ends the subscription.
In Dex Web, open the run's Events. Timeline shows the price update and the cancellation. Graph shows which Steps completed and which were still waiting when the cancellation ended the Flow.

