Design a Subscription Billing System
0%
Editorial Solution
System Requirements
Capacity Estimation
Scale anchors
API Design
Core resources
Database Design
Core tables
High-Level Design
The five tiers
Request Flows
Detailed Component Design
Subscription state machine
Trade-offs and Technology Choices
Synchronous vs asynchronous billing cycle execution
Failure Scenarios and Bottlenecks
Future Improvements
Table of Contents
System Requirements
Capacity Estimation
Scale anchors
API Design
Core resources
Database Design
Core tables
High-Level Design
The five tiers
Request Flows
Detailed Component Design
Subscription state machine
Trade-offs and Technology Choices
Synchronous vs asynchronous billing cycle execution
Failure Scenarios and Bottlenecks
Future Improvements
Subscription billing is easy to describe and hard to build correctly. Every SaaS company has one, and nearly every SaaS company has at some point double-charged a customer, failed to invoice for usage, or lost revenue to dunning bugs. The reason is that "the happy path" looks trivial — charge a card, mark an invoice paid — but the real product is the dozens of edge cases around proration, retries, partial failures, usage metering, and financial consistency.
The shape of this problem is opposite to most consumer-facing services. Read QPS is modest (merchants pull invoices occasionally), write rates are concentrated in bursts (month-end billing), but every write must be exactly correct. A single duplicate charge is a customer-support ticket and possibly a chargeback; a single missed renewal is lost revenue; a single wrong invoice is an accounting incident.
Billing systems fail quietly. A dropped message in a chat app creates visible confusion; a dropped charge in a billing system is a silent revenue leak that shows up in reconciliation weeks later. Design every component on the assumption that failure modes are silent until proven otherwise.
Billing is a burst-oriented system. Most charges fire around cycle boundaries (1st of month, renewal anniversary), so average load understates peak substantially.
Scale anchors
- 100K merchants using the platform (Stripe Billing has ~250K at this point; 100K is a reasonable mid-market scale).
- 100M active end-customer subscriptions across all merchants (averages 1000/merchant, heavy-tailed).
- 10M billing events/day — charges, state transitions, usage aggregations.
- 500M webhook deliveries/day (at-least-once to potentially many endpoints per event).
- 10B usage events/day at peak (metered billing across all merchants).
The API exposes four main resources: subscriptions, invoices, payments, and events. Conventions borrowed heavily from Stripe's API because it's the industry standard and merchants expect it.
Core resources
1# Subscriptions
2POST /v1/subscriptions # create
3GET /v1/subscriptions/{id} # retrieve
4POST /v1/subscriptions/{id} # update (plan change, seat count, etc.)
5DELETE /v1/subscriptions/{id} # cancel
6POST /v1/subscriptions/{id}/pause # pause collection
7POST /v1/subscriptions/{id}/resume # resume from pause
8
9# Invoices
10GET /v1/invoices/{id}
11GET /v1/invoices?subscription=S&limit=20
12POST /v1/invoices/{id}/pay # manual payment attempt
13POST /v1/invoices/{id}/void # void an open invoice
14
15# Usage (metered billing)
16POST /v1/subscription_items/{id}/usage_records
17 body: { quantity: N, timestamp: T, action: "increment" | "set", idempotency_key: K }
18
19# Payment attempts (read-only; created by system)
20GET /v1/payment_attempts/{id}
21
22# Customers
23POST /v1/customers
24GET /v1/customers/{id}
25POST /v1/customers/{id}/payment_methods
26
27# Events (for polling-based reconciliation; complements webhooks)
28GET /v1/events?type=invoice.paid&since=TBilling is a textbook relational workload — structured, ACID, joins across subscription/invoice/payment_attempt. Postgres (or MySQL) is the right default. The schema is dense with foreign keys because financial data's integrity constraints are load-bearing.
Core tables
1CREATE TABLE customers (
2 id UUID PRIMARY KEY,
3 merchant_id UUID NOT NULL,
4 external_id TEXT, -- merchant's internal customer ID
5 email TEXT,
6 default_payment_method_id UUID,
7 tax_id TEXT,
8 address JSONB,
9 metadata JSONB,
10 created_at TIMESTAMPTZ NOT NULL,
11 INDEX (merchant_id, created_at)
12);
13
14CREATE TABLE plans (
15 id UUID PRIMARY KEY,
16 merchant_id UUID NOT NULL,
17 name TEXT,
18 amount_cents BIGINT NOT NULL,
19 currency CHAR(3) NOT NULL,
20 interval TEXT NOT NULL, -- month/year/week/day
21 interval_count INT NOT NULL DEFAULT 1,
22 usage_type TEXT, -- licensed/metered
23 trial_period_days INT
24);
25
26CREATE TABLE subscriptions (
27 id UUID PRIMARY KEY,
28 merchant_id UUID NOT NULL,
29 customer_id UUID NOT NULL,
30 plan_id UUID NOT NULL,
31 state TEXT NOT NULL, -- trialing/active/past_due/canceled/unpaid/incomplete
32 quantity INT NOT NULL DEFAULT 1,
33 current_period_start TIMESTAMPTZ NOT NULL,
34 current_period_end TIMESTAMPTZ NOT NULL,
35 next_billing_at TIMESTAMPTZ, -- indexed for scheduler
36 trial_end TIMESTAMPTZ,
37 cancel_at_period_end BOOLEAN DEFAULT FALSE,
38 canceled_at TIMESTAMPTZ,
39 created_at TIMESTAMPTZ NOT NULL,
40 updated_at TIMESTAMPTZ NOT NULL,
41 version BIGINT NOT NULL DEFAULT 1,
42 INDEX (next_billing_at) WHERE state IN ('active', 'past_due', 'trialing'),
43 INDEX (merchant_id, state)
44);
45
46CREATE TABLE invoices (
47 id UUID PRIMARY KEY,
48 merchant_id UUID NOT NULL,
49 subscription_id UUID NOT NULL,
50 cycle_number INT NOT NULL,
51 state TEXT NOT NULL, -- draft/open/paid/void/uncollectible
52 subtotal_cents BIGINT NOT NULL,
53 tax_cents BIGINT NOT NULL DEFAULT 0,
54 total_cents BIGINT NOT NULL,
55 amount_paid_cents BIGINT NOT NULL DEFAULT 0,
56 currency CHAR(3) NOT NULL,
57 period_start TIMESTAMPTZ NOT NULL,
58 period_end TIMESTAMPTZ NOT NULL,
59 due_date TIMESTAMPTZ,
60 finalized_at TIMESTAMPTZ,
61 paid_at TIMESTAMPTZ,
62 created_at TIMESTAMPTZ NOT NULL,
63 UNIQUE (subscription_id, cycle_number),
64 INDEX (merchant_id, state, created_at)
65);
66
67CREATE TABLE invoice_line_items (
68 id UUID PRIMARY KEY,
69 invoice_id UUID NOT NULL REFERENCES invoices(id),
70 type TEXT NOT NULL, -- subscription/proration/usage/tax/discount
71 description TEXT,
72 quantity NUMERIC NOT NULL,
73 unit_amount_cents BIGINT NOT NULL,
74 amount_cents BIGINT NOT NULL, -- quantity * unit_amount (signed)
75 period_start TIMESTAMPTZ,
76 period_end TIMESTAMPTZ,
77 metadata JSONB,
78 INDEX (invoice_id)
79);
80
81CREATE TABLE payment_attempts (
82 id UUID PRIMARY KEY,
83 invoice_id UUID NOT NULL,
84 attempt_number INT NOT NULL,
85 idempotency_key TEXT NOT NULL UNIQUE, -- derived from (invoice_id, attempt_number)
86 provider_charge_id TEXT,
87 status TEXT NOT NULL, -- pending/succeeded/failed/timeout
88 decline_code TEXT,
89 amount_cents BIGINT NOT NULL,
90 currency CHAR(3) NOT NULL,
91 attempted_at TIMESTAMPTZ NOT NULL,
92 completed_at TIMESTAMPTZ,
93 UNIQUE (invoice_id, attempt_number),
94 INDEX (invoice_id)
95);
96
97CREATE TABLE usage_events (
98 subscription_item_id UUID NOT NULL,
99 period_id UUID NOT NULL, -- (subscription_id, cycle_number)
100 event_id TEXT NOT NULL, -- customer-provided idempotency key
101 quantity NUMERIC NOT NULL,
102 event_timestamp TIMESTAMPTZ NOT NULL,
103 received_at TIMESTAMPTZ NOT NULL,
104 PRIMARY KEY (subscription_item_id, period_id, event_id),
105 INDEX (period_id)
106) PARTITION BY RANGE (received_at);
107
108CREATE TABLE events ( -- the audit/webhook event log
109 id UUID PRIMARY KEY,
110 merchant_id UUID NOT NULL,
111 type TEXT NOT NULL,
112 object_id UUID NOT NULL, -- subscription/invoice/etc.
113 data JSONB NOT NULL, -- snapshot of the object
114 created_at TIMESTAMPTZ NOT NULL,
115 INDEX (merchant_id, created_at),
116 INDEX (object_id, created_at)
117) PARTITION BY RANGE (created_at);
118
119CREATE TABLE idempotency_keys (
120 merchant_id UUID NOT NULL,
121 key TEXT NOT NULL,
122 endpoint TEXT NOT NULL,
123 request_hash BYTEA NOT NULL,
124 response_body JSONB,
125 status_code INT,
126 created_at TIMESTAMPTZ NOT NULL,
127 expires_at TIMESTAMPTZ NOT NULL, -- 24h after created_at
128 PRIMARY KEY (merchant_id, endpoint, key)
129);
130
131CREATE TABLE webhook_deliveries (
132 id UUID PRIMARY KEY,
133 event_id UUID NOT NULL,
134 endpoint_id UUID NOT NULL,
135 attempt_number INT NOT NULL,
136 status TEXT NOT NULL, -- pending/delivered/failed
137 next_retry_at TIMESTAMPTZ,
138 response_code INT,
139 last_error TEXT,
140 INDEX (next_retry_at) WHERE status = 'pending'
141);Five tiers carry the system: the merchant-facing API, the scheduler that drives billing cycles, the worker pool that executes them, the webhook delivery service, and the event log that fans events to webhooks. Each is separately scalable.

The five tiers
Four flows cover the product: creating a subscription, executing a billing cycle, changing plans mid-cycle (proration), and dunning after a failed charge.
### Flow 1: Create a subscription
1. **Merchant → API**: `POST /v1/subscriptions` with `Idempotency-Key: retry-abc` and body `{customer: cus_X, plan: plan_pro_monthly, trial_period_days: 14}`.
2. **API validates**: merchant auth, customer exists, plan exists, idempotency key not already used.
3. **Reserve idempotency key**: INSERT into idempotency_keys with status=in_flight. If constraint violation (key already exists), look up and either return cached response (status=complete) or wait briefly (status=in_flight).
4. **Compute subscription state**:
- If trial_period_days > 0: state=trialing, trial_end=now+14d, next_billing_at=trial_end.
- Else: state=active, next_billing_at=now+plan.interval.
5. **Transaction**: INSERT subscription + INSERT event(type=customer.subscription.created, data=snapshot) + UPDATE idempotency_keys.response_body + UPDATE idempotency_keys.status=complete. All or nothing.
6. **If trial**: no invoice yet; trial_will_end event scheduled for 3 days before trial_end.
7. **If not trial**: invoice creation (see Flow 2) runs as part of this transaction or is scheduled for immediate dispatch.
8. **API returns 201** with the subscription body.
9. **CDC streams event** → Webhook service → merchant's webhook endpoint receives `customer.subscription.created`.
Latency: under 200ms p99 for the API response. Webhook delivery: under 30s p99.
### Flow 2: Billing cycle execution
<PositionedImage src="/uploads/design-a-subscription-billing-system/03_billing_cycle_execution.gif" alt="Billing cycle execution" width="800" />
Scenario: subscription S for customer C on plan Pro Monthly ($30/mo), cycle ending now.
1. **Scheduler tick (every minute)**: queries subscriptions ready to bill. Finds S with `next_billing_at <= now`, state=active.
2. **Scheduler enqueues job** with key (S.id, cycle_number=5) onto the billing queue.
3. **Worker claims job** with a 5-minute lease.
4. **Worker opens transaction**:
- INSERT invoices (subscription_id=S, cycle_number=5, period_start, period_end, state=draft, currency=USD).
- Compute line items: base plan $30, usage aggregation for metered items (via the usage aggregator in §7), proration for any mid-cycle changes during cycle 5.
- INSERT invoice_line_items for each.
- Compute tax via Stripe Tax / TaxJar with invoice line items + customer address → tax_cents.
- UPDATE invoices SET subtotal_cents, tax_cents, total_cents, state='open'.
- INSERT event(type=invoice.created).
5. **Worker commits transaction**.
6. **Worker begins payment attempt**:
- INSERT payment_attempts(invoice_id, attempt_number=1, idempotency_key=f"ch-{invoice_id}-1", status=pending).
- Call payment provider: `provider.charge(amount=total, payment_method=C.default_pm, idempotency_key=f"ch-{invoice_id}-1")`.
7. **On provider success**:
- UPDATE payment_attempts(status=succeeded, provider_charge_id).
- UPDATE invoices(state=paid, paid_at=now, amount_paid_cents=total).
- UPDATE subscriptions(current_period_start=period_end, current_period_end=period_end + interval, next_billing_at=period_end + interval).
- INSERT event(type=invoice.paid); INSERT event(type=charge.succeeded).
- COMMIT.
8. **On provider failure**:
- UPDATE payment_attempts(status=failed, decline_code).
- UPDATE invoices(state=open) — remains open for retry.
- UPDATE subscriptions(state=past_due).
- INSERT event(type=invoice.payment_failed).
- Schedule dunning retry: INSERT into a billing_retries table with next_retry_at based on dunning schedule and decline_code.
- COMMIT.
9. **On provider timeout**:
- UPDATE payment_attempts(status=timeout).
- Schedule a reconciliation check: call provider's Get-Charge API with idempotency_key to discover actual status.
Latency target: 30s p99 for happy-path. Dominated by tax provider (500ms) and payment provider (1s), plus DB writes.
### Flow 3: Plan change mid-cycle (proration)
<PositionedImage src="/uploads/design-a-subscription-billing-system/04_proration_on_plan_change.gif" alt="Proration on plan change" width="800" />
Scenario: subscription S is on Basic ($10/mo). On day 10 of a 30-day cycle, customer upgrades to Pro ($30/mo).
1. **Merchant → API**: `POST /v1/subscriptions/{S}` body `{plan: plan_pro_monthly, proration_behavior: "create_prorations"}`.
2. **API validates** merchant auth, new plan exists, proration_behavior value.
3. **Compute proration** inside a transaction:
- remaining_days = 20 (days 10-30 of the cycle).
- credit_amount = (20/30) × $10 = $6.67 — the unused Basic.
- charge_amount = (20/30) × $30 = $20.00 — the prorated Pro.
- net = $20.00 - $6.67 = $13.33.
4. **Create a proration invoice** (or attach proration line items to the next invoice — merchant-configurable):
- INSERT invoice (subscription_id=S, type=proration, state=open).
- INSERT invoice_line_items: one with amount=+$20.00 (Pro prorated), one with amount=-$6.67 (Basic credit).
- INSERT event(type=invoice.created).
5. **Update the subscription**:
- UPDATE subscriptions SET plan_id=pro_monthly.
- current_period_start remains (we're mid-cycle).
- current_period_end remains.
- next_billing_at unchanged (next full cycle is at period_end).
6. **Dispatch based on proration_behavior config**:
- If `always_invoice` (immediate charge, the default in this flow): dispatch the proration invoice for payment attempt using Flow 2 payment-attempt logic. On success, fire invoice.paid.
- If `create_prorations` (deferred): leave the proration line items attached, don't charge now; they get rolled into the next regular cycle's invoice at period_end.
7. **Emit events**: customer.subscription.updated is always emitted. invoice.created fires in both modes. invoice.paid fires only in `always_invoice` mode on successful charge.
The trade-off between the two modes: `always_invoice` charges the customer twice this month (one proration, one regular cycle) but collects immediately; `create_prorations` keeps the charge count down but delays collection until period_end and bundles it into what looks like a larger regular invoice. The underlying math is identical.
Key invariant: the cycle_number on the subscription does not advance — proration is not a new cycle, it's an adjustment within the current cycle. The next regular cycle at period_end bills full Pro at $30.
### Flow 4: Dunning after failed charge
<PositionedImage src="/uploads/design-a-subscription-billing-system/05_dunning_retry_workflow.gif" alt="Dunning retry workflow" width="800" />
Scenario: subscription S's cycle 5 payment failed with decline_code=insufficient_funds. Invoice is state=open, subscription is state=past_due.
1. **Dunning scheduler** (runs hourly): queries `SELECT FROM billing_retries WHERE next_retry_at <= now()`. Finds S.
2. **Classify decline code**:
- soft_decline (insufficient_funds, processing_error, issuer_not_available, try_again_later, do_not_honor): retry with schedule [day+1, day+3, day+5, day+7]. Smart-retry adjustment: try at a different time of day than the previous attempt (clustering suggests salary deposits reset funds mid-month). Note: `do_not_honor` is ambiguous — issuer-side rejection that often clears — so it's treated as retryable rather than hard.
- hard_decline (card_expired, stolen_card, fraudulent, lost_card, pickup_card): skip retries, move subscription directly to unpaid. `card_expired` specifically should trigger a "please update your card" email to the customer alongside the merchant webhook.
3. **Launch retry** with a fresh attempt_number:
- INSERT payment_attempts(attempt_number=2, idempotency_key=f"ch-{invoice_id}-2", status=pending).
- Call provider charge again with the new key.
4. **On success**:
- UPDATE invoices(state=paid).
- UPDATE subscriptions(state=active).
- INSERT event(type=invoice.paid).
- DELETE from billing_retries for this invoice.
5. **On failure**:
- UPDATE payment_attempts(status=failed).
- If `attempt_number < max_retries` (typically 4): reschedule retry at next step in dunning schedule.
- If attempt_number >= max_retries: UPDATE invoices(state=uncollectible), UPDATE subscriptions(state=unpaid), DELETE from billing_retries. Fire both events: INSERT event(type=invoice.marked_uncollectible) and INSERT event(type=customer.subscription.updated) with state=unpaid. Notify merchant via webhook.
6. **Merchant action**: merchant sees the unpaid webhook, reaches out to customer. Resolution paths: customer updates payment method (merchant calls `POST /v1/subscriptions/{S}/pay` to retry with new method), or merchant cancels the subscription, or subscription auto-cancels after merchant-configured unpaid timeout (typically 30 days).
The smart-retry logic lives in the dunning classifier. Industry data suggests retries at day+3 and day+5 recover 40% of soft declines (salary cycle hits); this is not a cost-free schedule to invent — it's calibrated against actual retry-success data per decline code.
Zooming into four components: the subscription state machine, the idempotency enforcement layer, the proration calculator, and the usage aggregator.
Subscription state machine

Four decisions shape this system's personality. Each alternative has a compelling pitch; each is wrong for specific reasons at billing scale.
Synchronous vs asynchronous billing cycle execution
Synchronous: merchant calls API to trigger a cycle; platform processes end-to-end in the request; returns success/failure.
The real failure classes, in decreasing order of pain.
Payment provider outage
Symptom: Stripe is down (or rate-limiting, or responding 500s). Charges fail en masse. Every subscription in the middle of a cycle goes to past_due, dunning schedules get crowded.
Billing is a mature domain; the frontier is in refinement and new adjacent products.
ML-driven dunning optimization
Today's smart retries use fixed decline-code rules. The next generation trains a model on per-merchant retry outcomes and learns optimal retry schedules per customer. Signals: decline code, time of day, day of week, historical pattern for this customer, merchant segment. Model predicts probability of success at each possible retry time; chooses the highest-expected-value retry. This is live at a few platforms (Stripe's Smart Retries, Adyen's RevenueAccelerate) and recovers 10-20% more revenue than fixed schedules.
Try this problem yourself
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
Concepts used in this design
The building blocks this design relies on, each explained in its own lesson.
0%
Editorial Solution
System Requirements
Capacity Estimation
Scale anchors
API Design
Core resources
Database Design
Core tables
High-Level Design
The five tiers
Request Flows
Detailed Component Design
Subscription state machine
Trade-offs and Technology Choices
Synchronous vs asynchronous billing cycle execution
Failure Scenarios and Bottlenecks
Future Improvements
Table of Contents
System Requirements
Capacity Estimation
Scale anchors
API Design
Core resources
Database Design
Core tables
High-Level Design
The five tiers
Request Flows
Detailed Component Design
Subscription state machine
Trade-offs and Technology Choices
Synchronous vs asynchronous billing cycle execution
Failure Scenarios and Bottlenecks
Future Improvements