Designing reliable money flows with Temporal
Billing is where bugs cost real money
Plans, quotas, usage aggregation, overage pricing, invoicing — get any of it wrong and you either lose revenue or overcharge customers. Both erode trust. The hard part isn't the arithmetic. It's making a pipeline with half a dozen steps, several external systems and a monthly deadline survive failure without losing or double-counting anything.
This post walks through how I built metered billing for a multi-tenant API platform: plan management, quota enforcement, usage aggregation from ClickHouse, overage pricing and invoice generation, all as durable Temporal workflows. The code below is illustrative, not lifted from that codebase, but the shape is the one that shipped.
Write the invariants before the workflow
Before any workflow code, I wrote the billing design down: 20 system invariants, 13 user stories across five personas, and 19 functional requirements, each one testable. That sounds like ceremony. It turned out to be the most useful thing in the module, because every later decision — what fails closed, what retries, what is allowed to change after the fact — was already answered.
A few of the invariants, paraphrased:
- No plan means deny. An organisation without a resolvable plan gets no access to metered resources. Billing never guesses.
- Invoices are immutable. Once issued, an invoice is not edited. Corrections are new records.
- One active subscription per organisation. Subscriptions are append-only, so
plan history is preserved, and the database enforces "only one
ACTIVErow" with a partial unique index rather than trusting application code. - Authorisation fails closed; rate limiting fails open. If the auth path is unsure, it denies. If the rate-limit cache is unavailable, traffic keeps flowing. These are deliberately different, and writing them side by side forces you to decide which failure you'd rather explain to a customer.
The last one is the kind of thing that never gets decided explicitly unless you write it down. It just emerges from whoever wrote the code that day.
The billing cycle as one workflow
The monthly cycle is a single workflow made of seven activities:
collectUsagequeries a ClickHouse materialised view of monthly usage per organisation.computeQuotaStatusaggregates requests and compute units and flags any organisation at or above 80% of its quota.resolvePricingmerges the plan's pricing with any per-organisation override.generateInvoiceskips unbilled organisations and otherwise creates the invoice, with a usage summary stored alongside it.advanceSubscriptionmoves the subscription into its next period.sendInvoiceEmailsends the invoice if a billing email is set.notifyStakeholderssends quota warnings at 80%.
The point of making this one workflow, not seven cron jobs, is that Temporal records the result of every completed activity. If the worker dies after step 4, the replay doesn't regenerate the invoice; it resumes at step 5 with step 4's result already in history. The pipeline becomes one auditable thing you can inspect, rather than a set of jobs whose combined state lives only in the database and in your head.
// Illustrative sketch of the workflow shape.
export async function quotaBillingWorkflow(orgId: string, period: Period) {
const usage = await collectUsage(orgId, period);
const status = await computeQuotaStatus(orgId, usage);
const pricing = await resolvePricing(orgId);
const invoice = await generateInvoice(orgId, period, usage, pricing);
await advanceSubscription(orgId, period);
if (invoice) await sendInvoiceEmail(orgId, invoice.id);
if (status.warn) await notifyStakeholders(orgId, status);
}
I went further than billing: every asynchronous job on the platform was a Temporal workflow — organisation provisioning, invitation lifecycles, billing. No background job runner, no cron, no in-process event emitters. One mechanism for async work means one place to look when something is stuck.
Retry policies are a design decision, not a default
Each activity ran with a 60-second start-to-close timeout, at most three attempts, and exponential backoff from one second to thirty. Those numbers are less important than the fact that they are per activity and chosen on purpose.
// Illustrative: activity options set explicitly, not inherited.
const { collectUsage, generateInvoice } = proxyActivities<typeof activities>({
startToCloseTimeout: "60s",
retry: {
maximumAttempts: 3,
initialInterval: "1s",
maximumInterval: "30s",
backoffCoefficient: 2,
},
});
Retries are only safe if the activity is safe to repeat. Temporal guarantees an activity's result is recorded once it completes, but an activity can still run more than once: the worker can crash after writing to the database and before reporting success. So any activity with a side effect needs to be idempotent on its own terms. The general technique, which I'd apply to any billing pipeline:
- Derive a natural key for the side effect — for an invoice, the organisation and the billing period — and make the database reject a second row for it with a unique constraint.
- Treat "already exists" as success, returning the existing record.
- Keep reads and writes in separate activities where you can, so the expensive, retry-prone query isn't coupled to the write.
// Illustrative: an idempotent write keyed by org + period.
async function generateInvoice(orgId: string, period: Period, ...rest) {
const existing = await invoices.findByOrgAndPeriod(orgId, period);
if (existing) return existing; // retry after a crash: no duplicate
return invoices.insert({ orgId, period, ...computeInvoice(rest) });
}
Immutable invoices make this easier. If invoices could be edited, "already exists" would be ambiguous: the existing one might be a half-finished earlier attempt. Because they can't be, an existing invoice for the period is the answer.
The money maths, kept boring
Overage pricing was a flat base fee plus usage above the plan's included compute units, charged in blocks: the base price, plus the overage divided by 100,000 and rounded up, multiplied by the per-block rate in cents. Two choices there are worth copying:
- Integer cents throughout. No floating point anywhere near money.
- Round up in one place, inside a pure function with its own tests, not scattered across the codebase.
The arithmetic lived behind a module boundary. The backend was built on contract-based dependency injection across eight modules, so billing talked to quotas, organisations and the rest only through injected interfaces, with in-memory adapters for tests. The pricing function, the quota checks and the workflow could each be tested without a database or a Temporal server, and inputs were validated at the boundary with Zod schemas.
Where quota checks go: two layers
Quotas were enforced in two places, for two different questions.
- At the gateway, on every request: a fast path backed by a cache, answering "is this caller within its rate limit?" in under a millisecond. This is the layer that fails open — losing the cache must not take the API down.
- In the backend, at creation time: hard limits on resources — gateways, projects, members, API keys per gateway — checked against the organisation's resolved quotas whenever someone creates one. This layer fails closed: no resolvable plan means the creation is refused.
Splitting them stops you from putting a database query in the request path, and from putting a cache in front of a decision that must be exact.
// Illustrative: the backend hard-limit check fails closed.
async function enforceProjectsQuota(orgId: string) {
const quotas = await billing.getResolvedQuotas(orgId);
if (!quotas) throw new ForbiddenException("No plan: denied");
const limit = quotas.projects;
if (limit === undefined) return; // absent field = unlimited
if ((await projects.countFor(orgId)) >= limit) {
throw new ForbiddenException("Project quota reached");
}
}
Note the asymmetry in that sketch, which was also in the spec: a missing plan denies, but a missing quota field means unlimited. Without the explicit rule, someone eventually reads "undefined" as zero and locks a paying customer out.
Per-customer deals without new plans
Sales will always want "the Pro plan, but with double the API keys". Creating a
plan row per deal leads to a plans table nobody can reason about. Instead, each
organisation's billing profile carried a custom_plan JSONB override for
quotas, pricing and features. Resolution is a merge: plan values first, override
on top. New deals need no new plan rows and no migrations, and the resolved
values flow through the same quota checks and pricing step as everyone else's.
What I'd keep, and what I'd add
Keep:
- Invariants written before code, and turned into tests.
- One workflow per business process, with explicit per-activity retry policies.
- Idempotent side effects keyed by a natural key and enforced by the database.
- Fail-closed for authorisation and hard limits; fail-open only where an outage would be worse than the overage.
The payment side — plan changes with downgrade checks, and a grace-period escalation when a payment fails — was designed as follow-on workflows and stubbed, with Stripe integration left for a later phase. If I were starting again, I'd build the payment-failed path earlier: it is where the invariants about immutable invoices and single active subscriptions get their hardest test.
Building something in this space?