Design a Subscription Billing System
MediumReal World SystemsBilling CyclePlan ManagementProrationPayment RetryInvoicing
Problem Statement
Design a subscription billing and management system like Stripe Billing or Chargebee — handling subscription plans, billing cycles, invoicing, payment retries, upgrades/downgrades, and dunning.
Requirements
Functional Requirements
- Subscription plans: BASIC, PROFESSIONAL, ENTERPRISE — each with monthly/annual pricing, feature limits
- Customer subscribes to a plan; billing cycle starts on subscription date
- Auto-generate invoices at the start of each billing period
- Payment processing: attempt payment; on failure, retry with schedule (1, 3, 7, 14 days)
- Plan changes: upgrade (prorate immediately) or downgrade (effective next billing cycle)
- Cancellation: immediate (refund prorated amount) or end-of-period
- Invoice history and payment history per customer
- Free trial: configurable trial period before billing starts
- Dunning: suspend account after all payment retries exhausted
Non-Functional Requirements
- Scheduled billing jobs run daily
- Thread-safe invoice and payment processing
- Singleton BillingService
Key Entities
- Plan: id, name, priceMonthly, priceAnnual, features, limits
- Subscription: id, customer, plan, status, currentPeriodStart, currentPeriodEnd, cancelAt
- Invoice: id, subscription, amount, dueDate, status (DRAFT/OPEN/PAID/VOID), lineItems
- Payment: id, invoice, amount, status (PENDING/SUCCEEDED/FAILED), attemptNumber
- BillingScheduler: daily job that generates and collects invoices
- BillingService: Singleton
Constraints
- Proration calculated as (remainingDays / totalDays) × planDiff for upgrades
- Free trial: no charge during trial period
- Retry schedule: day 1, day 3, day 7, day 14 after failure; suspend after all fail
- Annual plan discount: typically 20% over monthly
!Constraints
- Proration on upgrade: charge for remaining days of new plan minus credit for old plan
- Downgrade effective at end of current billing period (no immediate change)
- Free trial period: no invoice generated
- 4 payment retry attempts before subscription suspended
- Thread-safe invoice generation for concurrent billing runs
Output
Run or submit your code to see output here.