---
title: "Subscription and Billing Lifecycle"
description: "Run 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."
canonical_url: "https://docs.superdurable.io/examples/subscription-and-billing-lifecycle/"
source: "docs/content/use-cases/subscription.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Subscription and Billing Lifecycle

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.go.md) · [Java](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.java.md) · [TypeScript](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.typescript.md) · [Rust](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.rust.md)

Run 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](https://docs.superdurable.io/concepts/primitives/timer.md), [Static Parallel Steps](https://docs.superdurable.io/design-patterns/parallel/static-parallel-steps.md).

**Flow graph: SubscriptionFlow**

**Steps**

1. `Initialize` (start Step): Store the customer and start the trial, cancel, and charge update paths. Next: `Cancel`, `Trial`, or `UpdateChargeAmount`. Writes `billing-period-number`, `customer`.
2. `Cancel`: Wait for a cancel request and end the subscription. Next: the Flow completes at once. Reads `customer`.
3. `ChargeCurrentBill`: Charge each billing period until the subscription ends. Next: the Flow completes at once, or `ChargeCurrentBill` again. Reads `billing-period-number`, `customer`; writes `billing-period-number`.
4. `Trial`: Wait for the trial period to end. Next: `ChargeCurrentBill`. Reads `customer`.
5. `UpdateChargeAmount`: Apply each new charge amount the customer requests. Next: `UpdateChargeAmount` again. Reads `customer`, `update-charge-amount`; writes `customer`.

**RPCs**

- `cancel_subscription_rpc`: Publishes to `cancel-subscription`.
- `describe`: Reads `customer`.
- `get_customer`: Reads `customer`.
- `update_charge`: Publishes to `update-charge-amount`.

Example: [examples/python/dex_examples/products/subscription/subscription_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/subscription/subscription_flow.py)

The graph and this description cover the Python, Go, Java, and TypeScript examples. The [Rust example](https://docs.superdurable.io/examples/subscription-and-billing-lifecycle.md#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:

1. Send a welcome email and charge nothing until the trial ends.
2. Charge once per billing period. After the last period, email the customer and end.
3. Accept a new charge amount at any time. Charges that start after the Flow applies it use it.
4. Accept a cancellation at any time. Email the customer and end the subscription.
5. Return the plan through the `describe` RPC.

## 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](https://docs.superdurable.io/concepts/step.md#idempotency-keys), 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.

**Python**

```python
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,
            self.billing_period_number,
            self.trial,
            self.cancel,
            self.update_charge_amount_step,
        )

    def get_steps(self) -> StepList[Customer]:
        return StepList.start_step(self.initialize).other_steps(
            self.trial,
            self.charge_current_bill,
            self.cancel,
            self.update_charge_amount_step,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.billing_period_number,
            self.customer_details,
            self.cancel_subscription,
            self.update_charge_amount,
        )

    @rpc
    def describe(self, context: Context) -> RPCResult[Subscription]:
        return RPCResult(self.customer_details.get(context).subscription)
```

Example: [examples/python/dex_examples/products/subscription/subscription_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/subscription/subscription_flow.py)

<a id="rust-example"></a>

## 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

<a id="demo"></a>

Start the examples of one language as in [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground). Then open **Subscription** in the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground):

1. **Start** returns the new Flow ID. It starts a 20-second trial and ten 10-second billing periods that charge 100 each.
2. **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.
3. **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.

[![Dex Web Timeline showing the subscription price update and cancellation](https://docs.superdurable.io/img/use-cases/subscription-timeline.png)](https://docs.superdurable.io/img/use-cases/subscription-timeline.png)

[![Dex Web Graph showing the subscription price update and cancellation](https://docs.superdurable.io/img/use-cases/subscription-graph.png)](https://docs.superdurable.io/img/use-cases/subscription-graph.png)

## Next

[User Onboarding Process](https://docs.superdurable.io/examples/user-onboarding-process.md)
