Problem & Constraints
Design a SaaS billing platform (think Stripe Billing / Chargebee): 100K business subscriptions, hybrid pricing = monthly/annual fixed fee (seat-based) + usage-based charges (API calls, storage GB). Customers upgrade/downgrade and add/remove seats at any time, across 30+ countries, in multiple currencies, with automatic tax. This is the upstream of Day 17 payments: payments solve "how to safely collect a charge," billing solves "how much to collect this month, from whom, and why."
Key constraints to clarify in an interview:
- Always integer money: store minor units (cents), never float — rounding drift accumulates into reconciliation breaks.
- Explainable invoices: every line item must trace back to "why this amount" — regulators and customer disputes both demand it.
- Idempotent changes: a re-run billing cron or a double-clicked "upgrade" must not generate a second invoice.
- Scale: ~100K invoices/month for fixed fees, but ~1B usage events/day — the real throughput bottleneck is metering, not invoicing.
- Latency: invoice generation can be async (minutes), but proration preview must be sync (< 300ms) so the customer sees the delta on the spot.
High-level Architecture
graph TD
CAT[Pricing Catalog
products/prices/plans] --> SUB[Subscription Service
lifecycle state machine]
EV[usage events ~1B/day] --> ING[Metering Ingest
dedup + idempotent]
ING --> AGG[Aggregation Rollup
Redis→Postgres]
SUB --> BILL[Billing Engine
cycle trigger / proration]
AGG --> BILL
TAX[Tax Engine
rates + rules] --> BILL
BILL --> INV[(Invoice Store
immutable invoices)]
INV --> PAY[Payment / collection
Day 17 idempotent charge]
PAY -->|failure| DUN[Dunning
retry + recovery]
INV --> LED[(Ledger
double-entry / rev rec)]
Component roles: ① Pricing Catalog defines products, prices, plans (versioned, so price changes don't touch existing subscriptions); ② Subscription Service holds each subscription's lifecycle state machine; ③ Metering dedupes and aggregates massive usage events into billable quantities; ④ Billing Engine is the core — at cycle end it rolls "fixed fee + usage + proration adjustments + tax" into one invoice; ⑤ the invoice goes to Day 17's idempotent payment for collection, failures enter Dunning; ⑥ all amounts land in the Ledger for revenue recognition and reconciliation.
Key Technical Points
① Subscription Lifecycle State Machine + Cycle Trigger — bill on time, never miss, never double
Core trade-off: an explicit persisted state machine replaces if-else scattered everywhere and the risk of double-billing.
[Principle] A subscription isn't a boolean "active/inactive" but a state machine: trialing → active → past_due → canceled / unpaid. Transitions are driven by two event types: time (cycle end = time to invoice) and actions (upgrade, cancel, payment success/failure). On-time billing has two trigger styles: a scan cron (every minute query next_billing_at <= now) or a scheduled job registered per subscription. The key is idempotency: use (subscription_id, period_start) as a unique key for "generate invoice for period P," so a re-run cron only hits the existing invoice and never double-bills.
Options compared:
- Scan cron: simple, self-compensating (a miss gets picked up next round); but 100K subscriptions due on the same day create a billing spike (e.g. the 1st), so you must spread anchor dates or shard.
- Per-subscription scheduled job (timer queue): naturally smooth load; but the scheduler must be HA — a lost timer = a missed charge, needing reconciliation as backstop.
- Persisted state machine vs implicit state: an explicit
status column + transition log is auditable and replayable; cobbling state from multiple booleans produces illegal combinations (both trialing and past_due) and eventual bugs.
# pseudo-code: idempotent cycle billing (cron every minute)
def bill_due_subscriptions(now):
for sub in db.query("status IN ('active','past_due') AND next_billing_at <= %s", now):
period = (sub.current_period_start, sub.current_period_end)
# unique-key dedup: one invoice per period
inv = db.get_or_create_invoice(sub.id, period[0])
if inv.status != 'draft': # already issued -> skip
continue
add_recurring_lines(inv, sub) # fixed fee / seats
add_metered_lines(inv, sub, period)# usage (see point ③)
finalize_and_charge(inv) # finalize -> hand to payment
sub.advance_period() # advance to next cycle
Real-world cases:
- Stripe Billing: subscription is an explicit state machine (
trialing / active / past_due / canceled / unpaid), one invoice per cycle, billing_cycle_anchor controls the billing date, deliberately staggering customers onto different days.
- Chargebee / Recurly: same "subscription + per-cycle invoice" core model, supporting trials, pauses, renewals.
- AWS: bills aggregate monthly; the month-start billing spike is a classic "billing run" batch-processing problem.
② Proration — how to "settle the difference" on mid-cycle changes
Core trade-off: proration makes pricing fair and immediate, but every change injects a positive and negative adjustment line, raising complexity and explainability cost.
[Principle] A customer upgrading mid-cycle from $10/mo to $20/mo can't be charged a full month at the new price. Proration splits at the change point: refund the unused portion of the old plan's remaining time (negative credit), charge the new plan's remaining time (positive). Upgrade halfway through → -$5 (old price unused) + $10 (new price remaining) = net $5. These accumulate as invoice line items, settled next cycle or immediately. The proration factor = remaining seconds / total period seconds — computed by the second, not the day, or boundaries get unfair.
Options compared:
- Immediate proration (default): fair, what-you-see-is-what-you-get; but frequent up/downgrades (A/B testing plans) spew ± adjustment lines, making the invoice a ledger of churn that's costly to explain.
- No proration (next cycle): clean invoice; but "upgraded now, pay end of month / downgraded but still at high price this month" feels unfair.
- Credit to balance vs immediate refund: negative proration usually does not auto-refund cash but records an account credit against the next bill — avoiding refund fees and fraud (upgrade-then-refund cash-out).
# pseudo-code: upgrade proration (by-second factor)
def prorate_change(sub, new_price, now):
total = sub.period_end - sub.period_start # total period seconds
remain = sub.period_end - now # remaining seconds
factor = remain / total
credit = -round(sub.current_price * factor) # refund old-price unused (minor units)
charge = round(new_price * factor) # charge new-price remaining
add_line(sub.invoice, "unused time credit", credit)
add_line(sub.invoice, "remaining time @ new", charge)
sub.current_price = new_price # balance credit applied, no cash refund
Real-world cases:
- Stripe Prorations: up/downgrades auto-generate positive and negative proration line items by the second; negative proration defaults to a credit, not a cash refund, and you can
preview the delta first (matching our <300ms sync-preview need).
- GitHub / Slack seat billing: adding seats mid-cycle charges a prorated difference, removing them records a credit against renewal — the canonical form of seat-based proration.
③ Usage Metering — aggregating 1B events/day into a few numbers
Core trade-off: balance accuracy (count every event) against throughput/cost (aggregate then record), plus the risk of late events corrupting a finalized invoice.
[Principle] The metering pipeline has four stages: Emit (app sends usage events) → Ingest (validate + idempotent dedup) → Meter (aggregate into billable quantity) → Invoice (roll into the bill). Writing 1B/day one row at a time blows up the DB; the industrial approach is two-level aggregation: first accumulate in app memory/Redis keyed by (customer, meter, hour), flush to a Postgres rollup table every minute, and at billing time just SUM a few thousand hourly buckets. Aggregation functions are limited: typically only sum / count / last — for "peak concurrency" or "average daily storage" you compute it yourself and report the final number as a last value. Events must carry an idempotency key (event_id) for dedup, or client retries = over-billing.
Options compared:
- Event-level precision (every event to DB): auditable per-event; but the write and storage cost of 1B/day explodes, and billing-time aggregation scans are slow.
- Two-level pre-aggregation: high throughput, fast billing; but loses single-event detail (disputes only get hourly granularity), and a memory-layer crash loses the un-flushed window → needs at-least-once + idempotent dedup as backstop.
- Late event handling: an event arriving after the period boundary — stuff it into a closed invoice (must reopen, messy) or count it next period (simple but mis-attributes)? Most systems set a grace window; events outside it go to the next period flagged.
# pseudo-code: two-level aggregation + idempotent dedup
def ingest(event):
if not redis.set(f"seen:{event.id}", 1, nx=True, ex=DAY): # idempotent
return # drop duplicate event
key = (event.customer, event.meter, hour_bucket(event.ts))
redis.hincrby("usage", key, event.qty) # in-memory accumulate
def flush_every_minute(): # level 2: to Postgres
for key, qty in redis.hgetall("usage"):
db.upsert_rollup(key, qty) # hourly bucket
# billing: SELECT SUM(qty) ... WHERE customer=? AND ts IN [period]
Real-world cases:
- Stripe Billing Meters: report usage events, aggregated by
sum/count/last into the billing period; the docs recommend accumulating in the app and flushing one aggregated event periodically for high-frequency cases, to avoid hitting API limits and quotas.
- Datadog / Snowflake / Cloudflare: usage-based billing exemplars — massive metering events are rolled up in a data pipeline before feeding billing.
- AWS metering: each service reports usage, aggregated into bill lines at month end, with late/corrected data handled via later adjustments.
④ Multi-currency & Tax — one engine serving the globe
Core trade-off: local-currency pricing gives the best experience, but introduces FX risk, tax-rule complexity, and a reconciliation-dimension explosion.
[Principle] Two things must be right. Currency: store each price in minor units + ISO currency code (JPY has no decimals, dinar has three — don't assume two); cross-currency do not convert at billing time but preset a price per currency, so FX swings don't make the invoice non-reproducible. Tax: whether tax is added on (exclusive, common in the US) or included (inclusive, EU VAT) is determined by region/currency; products carry a tax code deciding rate and exemption. Tax is frozen into the invoice at the rate in effect at billing time; later rate changes don't rewrite historical invoices.
Options compared:
- Preset multi-currency prices vs real-time FX: preset prices give reproducible invoices and no FX risk, but you maintain N price sets; real-time FX is flexible but the same action yields different amounts at different moments, making reconciliation and refunds a nightmare.
- In-house tax engine vs third-party (Stripe Tax / Avalara): in-house avoids fees but you chase global rate/threshold changes (compliance hell); third-party costs more but outsources compliance risk.
- Tax inclusive vs exclusive: inclusive display is customer-friendly (EU regulation requires it) but back-computing net has rounding; exclusive keeps net clear but makes US customers wonder "why did the amount go up" at checkout.
Real-world cases:
- Stripe Tax: auto-selects tax behavior by currency (USD/CAD default exclusive, others inclusive), multi-currency prices can be overridden per currency; uses product tax codes to compute tax across 100+ countries.
- Apple App Store / Google Play: global pricing uses regional "price tiers" rather than real-time FX — exactly the preset-price model.
Scaling & Optimization
- Billing spike: spread anchor dates across the whole month (not all on the 1st), shard the billing run across workers in parallel; compute usage rollups incrementally within the cycle so billing only does the finishing touches.
- Dunning: a failed payment isn't churn yet — retry with backoff (e.g. days 1/3/5/7), combined with smart retry (avoid issuer decline peaks), email reminders, and finally downgrade to
unpaid. This is the key revenue-recovery lever for SaaS.
- Revenue recognition (RevRec): annual prepay collects cash once but recognizes revenue monthly (ASC 606 / IFRS 15) — the Ledger separates "cash collected" from "revenue recognized"; prepayment is a liability, converted to revenue month by month.
- Pricing experiments: version the Pricing Catalog, new prices apply only to new subscriptions, grandfather existing ones (keep old price); a price change must never mutate the reference of existing subscriptions.
- Reconciliation: invoice total ⇄ payment collected ⇄ ledger revenue, reconciled line by line (hooking into Day 17's reconciliation job); any break must be locatable to a line item.
Common Pitfalls + Interview Follow-ups
1. Storing money as float. 0.1 + 0.2 ≠ 0.3; cumulative rounding error eventually surfaces as a cents-level break in reconciliation. Always use integer minor units, and remember not all currencies have two decimals.
2. Non-idempotent billing. Re-run cron, redelivered messages, a frantically clicked upgrade — without a (sub_id, period) unique key you double-bill and double-charge. Idempotency is the floor for billing.
3. Proration by day, not by second. Boundary-day attribution makes customers over/underpay, breeding disputes; and you must state the policy: charge immediately on upgrade, credit on downgrade.
4. Mutating existing subscriptions on price change. Prices must be versioned, existing subscriptions referencing the old version; otherwise one price change rewrites every legacy customer's bill — make the news.
5. Stuffing late usage events into a finalized invoice. A finalized invoice should be immutable; late events go to the next period or a explicit credit note, not a silent rewrite of history.
Frequent follow-ups: ① Cron vs per-subscription timer for cycle billing — how do you guarantee no miss, no double? ② Walk me through mid-cycle upgrade proration step by step (by second). ③ How do you design metering for 1B usage events/day, and handle late events? ④ How does annual prepay do revenue recognition, and why separate cash from revenue? ⑤ Inclusive vs exclusive tax, and why not real-time FX for multi-currency?
Crossovers
- Evolution · Periodical cicadas: North American periodical cicadas emerge en masse every 13 or 17 years, satiating predators with sheer numbers: they survive by creating a spike. Billing does the opposite, scattering anchor dates across the month so the spike never overwhelms the system or the payment layer downstream.
- Philosophy · Ship of Theseus: After a plan change, new seats and a new price version, is it still the same subscription? Billing answers by pinning identity to subscription_id and freezing each period's invoice as an immutable snapshot. The planks keep changing; the logbook never does.
- Psychology · Loss aversion: Kahneman and Tversky's 1979 prospect theory showed that a loss hurts more than an equal gain pleases. Grandfathering legacy prices and crediting downgrades instead of refunding both spare existing customers the "price hike" loss frame. The difference: billing does this mainly to block refund fraud and fees; the psychology is a side effect.
- Neuroscience · Memory consolidation: The hippocampus records the day quickly, then during sleep the gist is transferred to the cortex and detail falls away. Two-level metering works the same way: Redis accumulates, then flushes into Postgres hourly buckets, trading per-event detail for aggregates. Unlike the brain, which rewrites a memory each time it is recalled, a finalized invoice may never change.
Ten takeaways
- Always store money as integer minor units; float rounding error eventually surfaces as a cents-level reconciliation break.
- A subscription is an explicit state machine (trialing, active, past_due, canceled); stitching state from booleans creates illegal combinations.
- Cycle billing keys each invoice on (subscription_id, period_start), so a re-run cron only hits the invoice that already exists.
- Proration splits the period by the second: a negative credit for unused time at the old price, a positive charge for the rest at the new one.
- Negative proration usually becomes account credit against the next bill rather than a cash refund, avoiding fees and upgrade-then-refund fraud.
- Billing's throughput bottleneck is metering roughly 1 billion usage events a day, handled by two-level aggregation in Redis and Postgres.
- Late usage events never rewrite a finalized invoice: inside the grace window they count this period, outside it they go through an auditable credit note.
- Multi-currency billing presets a price per currency instead of converting live, and tax is frozen into the invoice at the moment of billing.
- If 100,000 subscriptions all bill on the 1st, the spike is severe; scattering anchor dates also smooths the load on downstream payments.
- Annual prepaid cash is first booked as deferred revenue and recognized month by month, so the ledger must keep cash and revenue separate.
Further Resources
- Stripe Billing — Subscriptions Overview & Prorations (overview / prorations): authoritative implementation of the lifecycle state machine and by-second proration.
- Stripe — Designing robust and predictable APIs with idempotency (stripe.com/blog/idempotency): the engineering basis for idempotent billing and changes.
- Stripe Billing Meters / Usage-based billing (recording usage): usage aggregation sum/count/last and official high-frequency reporting advice.
- Stripe Tax — Tax behavior & multi-currency (tax behavior): inclusive/exclusive and multi-currency tax rules.
- TigerBeetle — Debit/Credit schema (docs): modeling revenue recognition as a double-entry invariant.
- Designing Data-Intensive Applications (Kleppmann): the underlying principles of batch billing, idempotency, and reconciliation.
Going Deeper (click to expand)
1. 100K subscriptions all bill on the 1st and the billing run can't cope. Beyond "add machines," give two structural fixes and their costs.
- Spread anchor dates: distribute the billing date evenly across days 1–28 by creation date or hash, flattening the spike to 1/30. Cost: customers don't share a billing date; enterprise customers doing financial reconciliation may want a unified period, so support a "custom alignment date" exception.
- Shard parallel + incremental pre-aggregation: shard the billing run by
customer_id % N across workers in parallel, and roll up usage incrementally within the cycle so day 1 only does "finishing + finalize" rather than scanning 1B events from scratch. Cost: incremental state must be persisted and consistent, complicating crash recovery.
One level deeper: the billing spike propagates to the payment side — 100K invoices charging at once blows the PSP quota and hits issuer rate limits, so spreading billing dates also smooths the downstream charge load, a cross-topic second-order benefit.
2. A customer upgrades→downgrades→upgrades three times within one cycle. What does the invoice look like, and how do you keep it explainable?
Each change generates a pair of ± proration line items by the second, so three changes = 6 adjustment lines plus their remaining-time charges — the invoice reads like a churn ledger. Explainability rests on a few things:
- Each line item carries period_start/end + the associated price_id + the proration factor, so you can reconstruct "why this amount."
- Negative proration goes to the account credit balance rather than an immediate refund, so the final bill = net amount, avoiding repeated refund fees and cash-out fraud.
- Offer a
preview so the customer sees the delta on each change on the spot (matching the <300ms sync-preview need), reducing after-the-fact complaints.
Pitfall: frequent changes can enable "plan-trial arbitrage" — some systems cap multiple downgrades in one cycle or only settle at cycle end, trading cleanliness for fairness.
3. A usage event arrives 2 hours after the cycle ends (client buffering/network delay). Stuff it into the closed invoice, count it next period, or something else? Where does each break?
- Reopen the closed invoice: correct attribution, but modifying a finalized/collected invoice violates "invoice immutability," and if already reconciled it creates a break, which regulators dislike.
- Count it next period: simple to implement, invoice stays immutable; but revenue is mis-attributed (this month's usage billed next month), so RevRec and customer reconciliation won't line up.
- Grace window + credit note: set a billing grace window (e.g. finalize N hours after period end) so late events within it still count this period; events outside it use an explicit credit/debit note as an auditable adjustment to the historical invoice, rather than secretly editing the original.
This is fundamentally the watermark / late-data problem from Day 20 stream processing projected onto the billing domain: you set a watermark between "how long to wait before finalizing" (completeness) and "how fast to bill" (timeliness), and prepare an auditable compensation channel for out-of-window data.
4. You collected $1200 on an annual prepay — why can't you recognize $1200 of revenue this month? What does this require of the data model?
Accounting standards (ASC 606 / IFRS 15) require revenue recognized by service-delivery progress: of the cash collected on annual prepay, the undelivered portion is deferred revenue (a liability), converted to recognized revenue monthly ($100/mo) as service is delivered. The reason: collecting cash isn't earning it — if the customer cancels in month two, over-recognized revenue must be reversed.
What this requires of the system: cash flow and revenue flow must be recorded separately. The Ledger uses double-entry: on collection, debit cash / credit deferred revenue; each month, debit deferred revenue / credit recognized revenue. This is exactly where TigerBeetle-style debit/credit invariants apply — at any moment "cash collected = recognized + to-be-recognized" must hold, with single-sided writes becoming illegal states rather than hidden bugs. Refund/mid-term cancel reverses the remaining deferred revenue + refunds cash, moving both legs.
5. Can the billing system and Day 17's payment system share one idempotency key? Where's the boundary?
Not simply — they're idempotent over different layers of operation:
- Billing idempotency key =
(subscription_id, period_start), guaranteeing "this cycle generates only one invoice." It prevents double-billing.
- Payment idempotency key = each charge's idempotency key (e.g. invoice_id or a one-off UUID), guaranteeing "this invoice is charged once." It prevents double-charging.
The boundary: one invoice may be charged across multiple attempts (dunning: retry on days 1/3/5). These retries should share the same payment idempotency key (for that invoice) so the PSP recognizes them as one charge; but each retry is a legitimate transition of the billing state machine and must not be dropped by billing-layer idempotency as a "duplicate." So the two layers decouple: billing guarantees "no double invoice," payment guarantees "no double charge," and dunning orchestrates retries between them — the classic layered-idempotency design.