MongoDB
Designing a Subscription Billing System
Build a recurring billing engine — handling plan management, billing cycles, prorations, dunning, and invoice generation at scale.
S
srikanthtelkalapally888@gmail.com
Designing a Subscription Billing System
Subscription billing handles recurring charges, plan changes, and payment lifecycle management.
Core Concepts
Plan: $29/month, Pro features
Subscription: Customer A on Pro plan since Jan 2026
Invoice: $29 due on 2026-03-01
Billing cycle: Monthly, quarterly, annual
Data Model
plans(id, name, price, interval, features)
subscriptions(
id, customer_id, plan_id,
status, -- active, canceled, past_due, trialing
current_period_start,
current_period_end,
trial_end,
canceled_at
)
invoices(
id, subscription_id, customer_id,
amount, status, -- draft, open, paid, void
due_date, paid_at
)
line_items(invoice_id, description, amount, period_start, period_end)
Billing Cycle
Scheduler runs daily:
Find subscriptions where current_period_end <= tomorrow
↓
Generate invoice
↓
Charge payment method
↓
Success → Advance period, set next billing date
Failure → Start dunning process
Proration
When customer upgrades mid-cycle:
Pro: $29/month
Enterprise: $99/month
Upgrade on day 15 of 30-day cycle:
Credit remaining Pro: $29 × (15/30) = $14.50
Charge Enterprise: $99 × (15/30) = $49.50
Net charge: $49.50 - $14.50 = $35.00
Dunning Management
Failed payment retry schedule:
Day 0: Payment fails → Notify customer
Day 3: Retry payment
Day 7: Retry payment → Downgrade service
Day 14: Retry payment → Cancel subscription
Send email at each step (dunning emails)
Trial Handling
Trial period: 14 days, no credit card required
Day 12: "Trial ends in 2 days" email
Day 14: Convert to paid (charge card on file)
No card: → Expire, lock features
Idempotency
Billing jobs must be idempotent:
Each billing run identified by (subscription_id, period_start)
If invoice already exists for this period → Skip
Conclusion
Subscription billing requires careful state management, idempotent billing jobs, prorated upgrades, and multi-step dunning for failed payments.