SYSTEM DESIGN · DESIGN PROBLEMS · BUSINESS PLATFORMS · HARD · 48 OF 51

Design a Subscription Billing System: Cycles, Proration, Invoices and Dunning

Design the billing engine behind a SaaS product: plans and versioned prices, billing cycles that survive month ends and time zones, a scheduler that renews millions of subscriptions without double billing, proration on upgrades, immutable invoices, idempotent charges, dunning when cards fail, entitlements that follow payment status, and a ledger that finance can trust.

Reported atRazorpay

Try it on the practice board Drag the blocks, wire them up, and check your design against the reference.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
1 / 20

Press play to hear the narration, or step through at your own pace.

Notes

Listen

Listen. We sell plans billed monthly or yearly, priced flat, per seat or by usage, with trials and coupons. Each subscription renews on its cycle date. Customers upgrade or downgrade at any time, with proration. Each charge produces an invoice with tax, sent by email. Failed payments are retried, customers can cancel now or at period end, and the product unlocks features based on the plan. The card network itself is out of scope; a payment provider handles it.

The qualities. Exactly one invoice per subscription per cycle, and at most one successful charge per invoice. Amounts must be exact, stored as integers in the smallest currency unit, with rounding rules written down. Issued invoices are legal documents, so they are immutable and auditable. Renewals should happen on time, within an hour or so, across many currencies and customer time zones.

Functional
  • plans: monthly or yearly,
  • flat, per seat, or usage
  • free trials, coupons
  • renew on each cycle date
  • upgrade or downgrade any time
  • with proration
  • invoices with tax, emailed
  • retry failed payments
  • cancel now or at period end
  • unlock features by plan
Non-functional
  • exactly one invoice per cycle
  • exactly one successful charge
  • per invoice
  • amounts exact: integer minor
  • units, explicit rounding
  • auditable: invoices immutable
  • once issued
  • renewals on time, ± an hour
  • many currencies, time zones

Ask scale

Scale. Ten million active subscriptions. When each renews on its own signup anniversary, that is about three hundred thirty thousand renewals a day, only four a second. But business customers are often billed on the first of the month, so two million renewals may land in a six-hour window, about ninety-three a second. A hundred twenty million invoices a year at three kilobytes is under half a terabyte. If eight percent of first attempts fail, eight hundred thousand a month enter dunning.

Back of the envelope
10M active subscriptions
anniversary billing:
  10M / 30 ≈ 333k renewals/day
  ≈ 4/s on average
calendar billing (B2B, the 1st):
  2M renewals in a 6 h window
  2M / 21,600 s ≈ 93/s
invoices 120M/yr × 3 KB ≈ 360 GB
first-try failures, say 8%:
  800k/month into dunning

Define API

The API. Creating a subscription takes a customer, a price, a quantity and an optional trial, with an idempotency key. Changes take the new price or seat count and say explicitly whether proration happens now or at the next cycle. Cancel takes now or period end. Usage events carry their own event id, so a resent event is not billed twice. Plus invoice listing and a signed webhook from the payment provider.

API
POST  /v1/subscriptions  (Idem-Key)
  { customer, price_id, qty, trial }
PATCH /v1/subscriptions/{id}
  { price_id, qty,
    proration: now | next_cycle }
POST  /v1/subscriptions/{id}/cancel
  { at: now | period_end }
POST  /v1/usage  { item, qty, ts,
  event_id }
GET   /v1/invoices?customer=
POST  /webhooks/provider  (signed)

Data model

The data model is relational, because every change must be transactional. Prices are immutable versions: raising a price creates a new price, and existing customers keep theirs until migrated. Subscriptions hold their status, an anchor date, the current period, the customer's time zone and a version for safe updates. Invoices have a unique key on subscription and period start, which is the backbone of our no-double-billing guarantee. Then invoice lines and a double-entry ledger.

Tables (SQL)
prices(id, plan, amount_minor,
  currency, interval, version)  immutable
subscriptions(id, customer, status,
  anchor, period_start, period_end,
  tz, cancel_at, version)
sub_items(sub_id, price_id, qty)
invoices(id, sub_id, period_start,
  status, total, number,
  UNIQUE(sub_id, period_start))
invoice_lines(invoice, kind, amount)
ledger_entries(txn, account, amount)

High-level design

Trace a signup. The billing API reads the price from the catalog, creates the subscription with today as its anchor, and asks the invoice engine for the first invoice. The engine builds lines, applies coupons and tax, finalizes the invoice and hands it to the payment service, which charges the saved payment method through the provider, using the invoice id as the idempotency key.

Renewals are driven by the cycle scheduler, which finds subscriptions whose period has ended and asks the invoice engine to bill the next one. Every finalized invoice and payment writes ledger entries. Results go out as events through an outbox: the entitlements service unlocks or locks features, email sends receipts, and a failed charge is handed to the dunning worker.

Deep dive: the clock

Deep dive one: the billing clock. Many scheduler workers poll for subscriptions whose period has ended, using select for update skip locked, so each worker claims different rows without blocking. For each row, one transaction inserts the invoice and advances the period. If a worker crashes and the row is processed again, the unique key on subscription and period start makes the second insert a no-op. A rerun is always safe.

Calendars are where billing bugs live. A customer anchored on January thirty-first renews February twenty-eighth, then March thirty-first, so clamp to the month end but remember the original anchor day. Never model a month as thirty days. The first of the month in Tokyo begins nine hours before it does in UTC, so compute period boundaries in the customer's time zone and store the resulting instants in UTC. Leap days need the same clamping.

Renewing without double billing
SELECT id FROM subscriptions
 WHERE period_end <= now()
   AND status IN (ACTIVE, PAST_DUE)
 ORDER BY period_end LIMIT 500
 FOR UPDATE SKIP LOCKED

per row, one transaction:
  INSERT invoice (sub, period_start)
    ON CONFLICT DO NOTHING
  advance period_start, period_end
crash + rerun → conflict, no dupe
Calendar traps
  • anchor on the 31st:
  • Jan 31 → Feb 28 → Mar 31
  • clamp to month end, but keep
  • the anchor day = 31
  • never add 30 days for a month
  • customer in Tokyo vs UTC:
  • "the 1st" starts 9 h earlier
  • compute in the customer tz,
  • store the result in UTC
  • yearly on Feb 29 → Feb 28

Deep dive: proration

Deep dive two: proration. A customer on a thirty dollar plan upgrades to the ninety dollar plan on day ten of a thirty-day period. Twenty of thirty days remain. Credit two thirds of the old plan, twenty dollars, and charge two thirds of the new plan, sixty dollars, so forty dollars is due now. Compute the fraction in seconds, round each line once with a documented rule, and show both lines on the invoice so the customer can follow the math.

Proration is also a product decision. Upgrades usually bill immediately and unlock features at once. Downgrades usually take effect at period end, which avoids refunds. Seats added mid-cycle are either prorated now or trued up on the next invoice. Leftover credits become a balance applied to the next invoice. Usage-based items are summed per period, and the period closes only after a grace window for late events.

Upgrade on day 10 of 30
old: Basic 3,000 cents / month
new: Pro   9,000 cents / month
remaining: 20 of 30 days

credit unused Basic
  -3,000 × 20/30 = -2,000
charge rest of Pro
  +9,000 × 20/30 = +6,000
due now: 4,000 cents

compute in seconds, round once
Policy choices
  • upgrade: prorate now, unlock
  • features immediately
  • downgrade: schedule for period
  • end, no refund to compute
  • seat added mid-cycle: prorated
  • line, or true-up next cycle
  • credits: negative balance,
  • used on the next invoice
  • usage: aggregate per period,
  • close after a late-event grace

Deep dive: invoices

Invoices move through a lifecycle. A draft is editable for about an hour, which absorbs late usage and last-minute changes. Finalizing happens in one transaction: assign the next sequential invoice number for that selling entity, since many tax regimes require gapless numbering, freeze the lines and write ledger entries. Then it is open, and becomes paid, void or uncollectible. A mistake after issue is fixed with a credit note, never by editing.

Invoice lifecycle
DRAFT   editable, ~1 h window
  for usage and late changes
FINALIZE  in one transaction:
  assign number INV-2026-000913
  (per seller counter, no gaps)
  freeze lines, write ledger
OPEN → PAID | UNCOLLECTIBLE
     → VOID (before payment)
wrong amount after issue?
  credit note, never an edit

Deep dive: payments

Deep dive three: collecting. Each charge attempt uses a key built from the invoice id and the attempt number, so a retry of the same attempt can never charge twice. A timeout is an unknown, not a failure: query the provider with the same key or wait for its webhook before deciding. This is the same discipline as Design Problems thirty, the payment system, and billing should reuse that service rather than reinvent it.

Deep dive: dunning

Dunning recovers failed renewals. Soft declines, like insufficient funds, are retried on a schedule, say days one, three, five and seven. Hard declines, like a stolen card, are never retried; ask the customer for a new card. Each attempt sends an email and shows an in-app banner. The subscription goes past due during a grace period, then unpaid, and the entitlements service locks paid features. When the customer updates the card, retry right away.

Dunning schedule
  • soft decline (funds, limit):
  • retry day 1, 3, 5, 7
  • at a time of day that
  • tends to succeed
  • hard decline (stolen card):
  • no retry, ask for a new card
  • email + in-app banner each try
  • status: PAST_DUE (grace),
  • then UNPAID: lock features
  • card updated → retry now

Deep dive: ledger

Finance needs a ledger. Finalizing a yearly invoice for a hundred twenty dollars debits receivables and credits deferred revenue, because the service has not been delivered yet. The payment debits cash and clears the receivable. Each month, ten dollars moves from deferred revenue to revenue. Refunds and credit notes are new entries, never edits. If the entries do not sum to zero, there is a bug.

Ledger entries
invoice finalized, yearly 120.00:
  debit  receivable       120.00
  credit deferred_revenue 120.00
payment succeeded:
  debit  cash             120.00
  credit receivable       120.00
each month (recognition):
  debit  deferred_revenue  10.00
  credit revenue           10.00
refund / credit note: new entries

Trade-offs

Trade-offs. On the first of the month, spread renewals across hours and respect the provider's rate limit, rather than charging two million cards at midnight. If the scheduler is down, rows simply stay due and are caught up later, still exactly once. If the provider is down, invoices stay open and are retried. Price changes create new price versions and move customers at renewal. One relational primary handles this load; shard by customer only when you must.

Monitor renewals overdue by more than an hour, a check that no subscription ever has two invoices for one period, first-try success and dunning recovery rates, churn caused by failed payments, and the ledger imbalance, which must be zero. Reconcile daily against the provider's settlement report. At ten times the size, shard by customer id and run one scheduler per shard.

Trade-offs and failures
  • spike on the 1st: jitter work
  • across hours, respect the
  • provider rate limit
  • scheduler down: rows stay due,
  • caught up later, still once
  • provider down: invoice stays
  • OPEN, retry; never mark paid
  • price change: new version,
  • migrate subscribers on renewal
  • one SQL primary, shard later
Monitor and grow
  • renewals overdue > 1 h
  • invoices per sub per period
  • (must be ≤ 1)
  • first-try and recovered rates
  • involuntary churn after dunning
  • ledger imbalance (must be 0)
  • daily recon vs provider
  • 10x: shard by customer id,
  • scheduler per shard

Interview summary

In the interview: low average load, with a spike on the first of the month. Immutable price versions. A scheduler that claims rows with skip locked, and a unique key per subscription and period, so reruns never double bill. Cycles computed in the customer's time zone with month-end clamping. Proration as credit plus charge for the remaining time. Frozen invoices with credit notes, a charge key per invoice attempt, dunning tied to entitlements, and a double-entry ledger.

Say it like this
  • 4/s avg, ~100/s on the 1st
  • immutable price versions
  • scheduler: SKIP LOCKED +
  • UNIQUE(sub, period_start)
  • cycles in customer tz, UTC
  • storage, clamp month ends
  • proration: credit old, charge
  • new, by seconds remaining
  • invoices frozen, credit notes
  • charge key = invoice + attempt
  • dunning, entitlements, ledger

Interview questions

How do you make sure a subscription is never billed twice for the same period?

Put a unique constraint on subscription id and period start in the invoices table and create the invoice and advance the period in one transaction. A crashed or duplicated scheduler run then hits the constraint and does nothing.

How do multiple scheduler workers avoid picking the same subscription?

They poll for due rows with SELECT ... FOR UPDATE SKIP LOCKED in small batches, so each worker locks different rows without waiting, and the unique invoice key covers any remaining race.

How do you calculate proration when a customer upgrades mid-cycle?

Credit the unused fraction of the old price and charge the same fraction of the new price, measured in seconds of the period remaining, round each line once with a fixed rule, and show both lines on the invoice.

How do you handle a monthly subscription that started on the 31st?

Keep the anchor day as 31 and clamp each period end to the last day of shorter months, so it renews on Feb 28 and then Mar 31. Never treat a month as a fixed number of days.

Why are invoices immutable after they are finalized?

Issued invoices are legal and tax documents with sequential numbers. Corrections are made with credit notes and new ledger entries, which keeps a complete audit trail.

What is dunning?

The process of recovering failed recurring payments: retrying soft declines on a schedule, asking for a new card on hard declines, notifying the customer, and moving the subscription through grace, past due and unpaid states that restrict access.

How do you avoid charging a card twice when the payment provider times out?

Use an idempotency key derived from the invoice id and attempt number, treat a timeout as unknown, and resolve it by querying the provider with the same key or waiting for its webhook before retrying.

How do you handle a price increase for existing customers?

Create a new immutable price version, keep existing subscriptions on their current version, and migrate them at their next renewal after notice, so past invoices always reference the price that applied.