← Back to SQL, page 20

sql-0396 · Hard senior

Design tables for subscription billing with plans, upgrades and monthly invoices.

Keep plans (with versioned prices), subscriptions (customer, plan, status, current period start and end) and an append-only subscription_events history. Invoices and invoice lines are generated per period and store the amounts charged, including proration for mid-period changes. Never compute past invoices from current plan prices.

Full answer
text
plans(id, name)
plan_prices(id, plan_id, currency, amount_minor, interval, valid_from, valid_to)
subscriptions(id, customer_id, plan_price_id, status, current_period_start,
              current_period_end, cancel_at_period_end)
subscription_events(id, subscription_id, kind, from_price_id, to_price_id, at)
invoices(id, customer_id, period_start, period_end, status, total_minor)
invoice_lines(invoice_id, description, quantity, amount_minor, subscription_id)

Upgrade mid-month: record an event, switch plan_price_id, and add proration lines (a credit for unused time on the old price, a charge for the new one) to the next invoice. Price changes create a new plan_prices row, and existing subscribers move only when the business decides.

Status transitions (trialing, active, past_due, cancelled) are driven by a scheduled job and payment outcomes, and each one is logged. A unique key on (subscription_id, period_start) for generated invoices makes the billing job safe to rerun.

Key points

  • Versioned prices
  • Subscriptions hold the current period
  • Append-only event history
  • Invoices store amounts charged
  • Idempotent invoice generation

Common mistakes

  • Recomputing old invoices from current prices
  • Overwriting plan prices in place

Follow-ups

  • How would you handle failed payments and retries?
  • How would usage-based charges fit?

Tips

  • Explain proration