Design a cloud billing system with pro-rata plan changes and credit balances
Company: X (Twitter)
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a billing system for a cloud platform that manages plans, subscriptions, invoices and payment methods.
The system must support pro-rata billing when a user upgrades or downgrades their plan mid-cycle. Each billing cycle is 30 days. When a user changes plans on day `d` of the cycle, they receive a credit for `30 - d` unused days on their current plan and are charged for `30 - d` remaining days on the new plan. Both amounts are calculated as `price * (30 - d) / 30` using **integer division** (floor). If the net amount is negative (a downgrade), the invoice amount is `0` and the difference is added to the user's credit balance.
All monetary values are integers in cents, which avoids floating-point precision issues. A user must have a registered payment method to pay an invoice. When paying, any available credit balance is applied first, reducing the amount charged to the payment method.
Implement a class `CloudBillingSystem` with these methods:
- `addPlan(planId: int, name: str, monthlyPriceCents: int)`: register a new billing plan with the given id, name and monthly price in cents.
- `subscribe(userId: int, planId: int) -> int`: subscribe a user to a plan. Creates an invoice for the first full month and returns the invoice id. Returns -1 if the plan does not exist.
- `changePlan(userId: int, newPlanId: int, dayOfCycle: int) -> int`: change a user's plan mid-cycle on the given day (1 to 30). Calculates the pro-rata credit for unused old-plan days and the charge for the remaining new-plan days. Returns the new invoice id, or -1 if the user or the plan is not found.
- `addPaymentMethod(userId: int, methodType: str, details: str)`: register a payment method (for example, a credit card) for a user.
- `payInvoice(invoiceId: int) -> int`: pay an invoice with the user's payment method, applying any available credit balance first. Returns the amount charged to the payment method after credits, or -1 if the invoice is not found, is already paid, or the user has no payment method.
- `getInvoiceAmount(invoiceId: int) -> int`: return the total amount of an invoice in cents, or -1 if the invoice does not exist.
- `getInvoiceStatus(invoiceId: int) -> str`: return the payment status of an invoice: "paid", "unpaid" or "not_found".
- `getUserBalance(userId: int) -> int`: return the user's credit balance in cents.
- `getCurrentPlan(userId: int) -> str`: return the name of the user's current plan, or "none" if the user is not subscribed.
Here is one sequence of calls with the expected results. It assumes invoice ids start at 1 and increase by one for each invoice created.
```text
addPlan(1, "Basic", 3000)
addPlan(2, "Pro", 9000)
subscribe(100, 1) -> 1
payInvoice(1) -> -1
addPaymentMethod(100, "card", "visa-4242")
payInvoice(1) -> 3000
changePlan(100, 2, 10) -> 2
getInvoiceAmount(2) -> 4000
getCurrentPlan(100) -> "Pro"
changePlan(100, 1, 20) -> 3
getInvoiceAmount(3) -> 0
getUserBalance(100) -> 2000
payInvoice(2) -> 2000
getUserBalance(100) -> 0
getInvoiceStatus(2) -> "paid"
getInvoiceStatus(3) -> "unpaid"
payInvoice(2) -> -1
changePlan(200, 2, 5) -> -1
getCurrentPlan(200) -> "none"
getInvoiceStatus(42) -> "not_found"
```
The first `payInvoice(1)` fails because user 100 has no payment method yet. The upgrade on day 10 leaves 20 days, so the credit is 2000 and the charge is 6000, and invoice 2 is 4000. The downgrade on day 20 leaves 10 days: the credit is 3000 and the charge is 1000, so invoice 3 is 0 and the 2000 difference goes to the balance. Paying invoice 2 uses that 2000 of credit first and charges the card the remaining 2000. User 200 never subscribed, so `changePlan` returns -1.
```hint Pro-rata arithmetic
Compute the credit and the charge as two separately floored amounts before you subtract them. Try a case where the remaining days do not divide the prices evenly and compare with flooring the difference.
```
```hint Order of work in payInvoice
Run every failure check before you change the credit balance or the paid flag.
```
### Constraints & Assumptions
- `1 <= planId, userId <= 10^4`
- `0 <= monthlyPriceCents <= 100000`
- `1 <= dayOfCycle <= 30`
- Plan names and payment method types are non-empty strings.
- All monetary values are integers in cents.
- At most 1000 operations in total.
### Clarifying Questions to Ask
- What should `subscribe` do for a user who already has a plan?
- Should `payInvoice` still require a payment method when the credit balance covers the whole invoice?
- Is the net amount the difference of the two floored amounts, or the floor of the exact difference?
- Can a user hold several payment methods, and if so, which one is charged?
- Does the zero-amount invoice from a downgrade start as unpaid?
### What a Strong Answer Covers
- A data model that names each map, what it is keyed by, and how invoice ids are generated.
- The pro-rata calculation exactly as specified, including the integer floor on each amount and the downgrade path that moves the difference into the credit balance.
- The order of checks and state changes in `payInvoice`, and how much credit is consumed.
- Every sentinel return (-1, "none", "not_found") and edge cases such as day 30, free plans and zero-amount invoices.
- The time and space cost of each operation, and why integer cents are used.
### Follow-up Questions
- How would you support refunds or voiding an unpaid invoice without losing the history?
- How would the design change if each user's cycle started on their signup date and followed real calendar months of 28 to 31 days?
- How would you make `payInvoice` safe to retry when the call to the payment provider times out?
- How would you replace the single mutable credit balance with a ledger, and what would `getUserBalance` compute then?
Overview: Implement a cloud billing class that manages plans, subscriptions, invoices, payment methods and per-user credit balances in integer cents. It tests pro-rata math with floor division on mid-cycle plan changes, applying credit before charging a card, and careful handling of every failure return.