Build a Recurring Billing Engine for a Subscription Service
System DesignModel answerLast updated
Design the backend that manages subscriptions, handles recurring charges, processes plan changes mid-cycle, and retries failed payments at scale.
You're building the subscription and billing backend for a video streaming platform. Users sign up for a paid tier, are billed automatically each cycle, can move between tiers at any time, and may cancel whenever they choose. The system must always know whether a given account can access content and which tier's features apply. All monetary transactions flow through a third-party payment processor whose API can decline requests, time out, or return errors.
Your design should handle the complete subscription journey: initial signup, automated recurring charges, tier switches that happen mid-cycle, retries when payments fail, and cancellations. The conversation will move through each of these areas in turn, starting with a working end-to-end design and then drilling into the details of billing correctness, concurrency, and scale.
Scope and Assumptions
- The payment processor is external. You design the service that orchestrates calls to it and persists results, not the card network itself.
- Billing repeats on a fixed cadence—assume monthly unless you choose differently. No specific plan catalog, pricing, or traffic volume is given; state your own assumptions.
- Core guarantees: no user is ever double-charged for the same period, and a paying user never loses access due to an internal bug or transient failure.
- Video delivery is outside this design. The playback system only needs a fast way to ask "can this account stream right now, and under which tier?"
Questions to Consider
- When a user upgrades mid-cycle, should the new tier activate immediately? What about downgrades—immediate or deferred until renewal?
- After a renewal charge fails, how long does the user retain access while retries happen, and at what point does the subscription terminate?
- Are free trials, promotional discounts, or third-party billing (app stores, bundles) in scope, or only direct card charges?
- Which regions and currencies matter, and is tax computation handled here or delegated to another service?
- How quickly must a cancellation or tier change become visible to playback—is brief eventual consistency acceptable?
Part 1 — Data Model and Lifecycle
Define the core entities: accounts, tiers, subscriptions, invoices, and payment records. Map out the states a subscription passes through from creation to cancellation, the transitions between them, and what triggers each transition. Describe the APIs other services use to create, query, modify, and cancel subscriptions, and explain how the playback path determines entitlement.
Cover:
- Entities and their relationships, including how tier and pricing history is preserved
- An explicit state machine with clear triggers for each transition
- Management APIs and a separate, low-latency entitlement check suitable for every playback request
- Where the authoritative state lives and how other services learn about updates
Part 2 — Automated Recurring Charges
Walk through how the system identifies subscriptions due for renewal, generates the charge for the next cycle, invokes the payment processor, and records the outcome. Address what happens if a billing worker crashes mid-execution or if the processor call times out with no definitive response.
Cover:
- Scheduling renewals so that none are missed and none are processed more than once
- Idempotent charge creation and reconciliation with the processor's own ledger
- A durable, auditable trail of invoices and financial events
- Handling ambiguous results: timeouts, duplicate webhooks, out-of-order notifications
Part 3 — Mid-Cycle Tier Changes
A user on a lower tier upgrades partway through their billing period; another user downgrades. Describe when each change becomes effective, how the adjusted amount is computed, and how you prevent a tier change from racing with a concurrent renewal job.
Cover:
- Policy for when upgrades versus downgrades take effect and the impact on access
- Prorated charge calculation and how it appears on the invoice
- Concurrency control between user-initiated actions and background billing processes
- Behavior when the immediate charge for an upgrade is declined
Part 4 — Failure Recovery and Scaling
Design the retry strategy for declined renewals: when to retry, what the user sees and can do during retries, and when the subscription ultimately expires. Then explain how the design performs as the subscriber base grows and renewals cluster on the same calendar dates.
Cover:
- Retry scheduling that differentiates transient from permanent declines, with user notifications
- A grace period with access rules that stay consistent with billing state
- Distributing renewal load and keeping entitlement checks fast as volume increases
- Rate-limiting calls to the payment processor and recovering from processor downtime
Hints
Hint 1
Start with a simple state machine and add idempotency keys to every payment operation.
Hint 2
Separate the write path (billing, plan changes) from the read path (entitlement checks) so playback stays fast.
Hint 3
Use optimistic locking or versioning to prevent concurrent plan changes and renewals from interfering with each other.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong design separates three concerns: the authoritative subscription state, the orchestration of payment operations, and the fast entitlement read path. Begin with a clear data model and state machine, layer in idempotent billing with audit trails, handle concurrency explicitly, and only then introduce scale optimizations.
Part 1 — Data Model and Lifecycle
Entities
- Account: user identifier, contact info, current subscription reference
- Tier: a catalog entry describing features and base price (historical tiers remain queryable)
- Subscription: links an account to a tier, holds state, current period start and end, next billing date, version counter for optimistic locking
- Invoice: amount, line items (base charge, prorated adjustments, taxes), status (draft, finalized, paid, voided), idempotency key
- PaymentRecord: ties an invoice to a processor transaction ID, captures authorization/capture/refund events, stores raw processor responses for reconciliation
State Machine
A subscription moves through these states:
- Active: user has access, next renewal date is scheduled
- PastDue: renewal charge failed, retry window open, access may continue (grace period)
- Canceled: user or system ended the subscription, access revoked at period end or immediately
- Expired: final retry exhausted or period ended after cancellation
Transitions:
- Signup → Active when initial payment succeeds
- Renewal success while Active → stay Active, advance period
- Renewal failure → PastDue, schedule retry
- Retry success → Active
- Retry exhausted or user cancels during PastDue → Expired
- User cancels during Active → Canceled (effective at period end or immediately, depending on policy)
APIs
Management APIs (used by web, mobile):
POST /subscriptions— create subscription, charge immediately, return entitlementGET /subscriptions/{id}— full subscription detailPUT /subscriptions/{id}/tier— change tier, handle prorated chargeDELETE /subscriptions/{id}— cancel (immediate or end-of-period)
Entitlement API (used by playback):
GET /entitlements/{accountId}— returns{entitled: bool, tier: string, expiresAt: timestamp}- Reads from a denormalized cache (Redis or a replicated table) keyed by account ID
- Updated whenever subscription state changes
- Sub-millisecond latency, no dependency on billing or payment processor
Source of Truth
Subscriptions live in a primary relational database (Postgres). State changes publish events to a message bus (Kafka, SQS). The entitlement cache consumes these events and updates its view. Playback never queries the authoritative subscription table directly.
Part 2 — Recurring Billing
Scheduling Renewals
A background job polls every minute for subscriptions where state = 'active' AND next_billing_date <= now(). Each subscription is enqueued once into a durable task queue (SQS, RabbitMQ) with the subscription ID and version as the message payload.
To prevent double-processing:
- Mark the subscription's
billing_in_progressflag or increment its version when enqueuing - Workers acquire the subscription row with
SELECT ... FOR UPDATEor optimistic locking (WHERE version = ?) - If the row version mismatches, skip (another worker already processed it)
Charge Creation
- Generate an idempotency key:
renewal-{subscriptionId}-{periodStart}-{periodEnd} - Create an Invoice record in
draftstate, tied to this key - Call the payment processor:
POST /chargeswith idempotency key, amount, customer token - On success: finalize invoice, create PaymentRecord, transition subscription to next period, publish event
- On decline: transition to PastDue, schedule retry
- On timeout or unknown: poll the processor's GET endpoint with the idempotency key to retrieve the charge status, then reconcile
Audit and Reconciliation
Every invoice and payment record is immutable once finalized. A daily reconciliation job fetches the processor's ledger for the past day and matches transaction IDs to internal PaymentRecord entries, flagging discrepancies (missing charges, duplicate settlements) for manual review.
Handling Ambiguity
- Timeout: retry the same idempotency key; the processor returns the existing charge if it succeeded, or processes it if it never arrived
- Duplicate webhook: deduplicate by event ID in a processed-events table
- Out-of-order webhook: store events with timestamp, replay in order during reconciliation window
Part 3 — Mid-Cycle Tier Changes
Policy
- Upgrade: effective immediately; user is charged the prorated difference for the remainder of the period
- Downgrade: effective at the next renewal; no immediate charge
This balances user experience (instant access to better features) with churn prevention (user gets full value from the period they paid for).
Proration Calculation
days_remaining = (period_end - now).days
days_in_period = (period_end - period_start).days
proration_factor = days_remaining / days_in_period
amount_due = (new_tier_price - old_tier_price) * proration_factor
Line items:
- Credit for unused portion of old tier (negative)
- Charge for remaining portion of new tier (positive)
Concurrency Control
Use optimistic locking: every subscription has a version column.
When a user initiates a tier change:
- Read subscription with current version
- Calculate proration, create invoice
- Charge the processor
- Update subscription:
UPDATE ... SET tier = ?, version = version + 1 WHERE id = ? AND version = ? - If zero rows updated, another operation (renewal or concurrent tier change) won the race; retry from step 1 or return conflict error
The renewal worker uses the same pattern, so a renewal and tier change cannot both commit.
Failed Upgrade Charge
If the immediate charge for an upgrade declines:
- Keep the user on their current tier
- Return error to the client
- Optionally, offer to downgrade at renewal instead (deferred change)
Part 4 — Failure Recovery and Scaling
Retry Policy
Distinguish failure types using processor response codes:
- Retryable (insufficient funds, issuer timeout): retry 3 times over 7 days (day 1, day 3, day 7)
- Permanent (card expired, fraud block): move to Expired immediately, notify user
During PastDue:
- User retains access (grace period) for the first 3 days
- After day 3, revoke access but continue retries until day 7
- Send email on each retry, with a link to update payment method
Retries are scheduled as delayed tasks in the queue. Each retry follows the same idempotent charge creation flow, with a distinct idempotency key per attempt: retry-{subscriptionId}-{periodStart}-{attempt}.
Grace Period Consistency
The entitlement cache reflects the subscription's state:
- Active → entitled
- PastDue +
now < grace_end→ entitled - PastDue +
now >= grace_end→ not entitled - Expired or Canceled (past effective date) → not entitled
Playback checks the cache, which is updated within seconds of any state transition via the event stream.
Scaling Renewals
Spreading load: Hash subscription IDs to assign a billing_day_of_month (1–28) on signup. Monthly renewals spread evenly across the month instead of clustering on the 1st.
Entitlement read path: Redis cluster with replication, sharded by account ID. 10M subscribers × 100 bytes ≈ 1 GB; fits in memory. Cache miss falls back to the subscription database read replica.
Billing write path: Horizontal workers consume from the queue. With 10M subscribers and 28-day spread, ~350k renewals/day, ~4 renewals/second average, ~40/sec peak. A handful of workers handle this comfortably.
Protecting the Payment Processor
- Rate limiting: token bucket per worker, cap at processor's allowed QPS
- Backoff: exponential backoff with jitter on 429 or 503 responses
- Circuit breaker: if error rate exceeds threshold (e.g., 50% over 1 minute), pause new charge attempts, retry existing ambiguous ones, and alert ops
- Processor outage: queue charges locally, process when the circuit closes; notify users of delays
Complexity
Billing job scheduling and execution: O(n) where n is subscriptions due, embarrassingly parallel
Entitlement read: O(1) cache lookup
Proration and tier change: O(1) per operation
Common Mistakes
- Double-charging: forgetting idempotency keys or failing to check if a charge already succeeded before retrying
- Lost payments: not reconciling internal records with the processor's ledger
- Inconsistent access: putting billing logic or processor calls on the playback critical path, causing user-visible latency or outages
- Race conditions: allowing a tier change and renewal to both update the same subscription without coordination
- Unbounded retries: retrying declined charges forever, racking up processor fees and user frustration
- Tight coupling: making the entitlement check dependent on the subscription service being reachable, instead of serving from a cache
Trade-offs and Product Decisions
- Immediate upgrade, deferred downgrade improves conversion but requires proration logic and an immediate charge flow
- Grace period length balances user experience (more time to fix payment) against revenue loss; 3–7 days is common
- Retry cadence affects user churn and processor costs; too aggressive annoys users and burns API quota, too sparse loses recoverable revenue
- Proration method: daily granularity is simple and fair; some services skip proration on downgrades to avoid refund complexity
A production-ready design combines the state machine and idempotency foundation above with monitoring (charge success rate, retry conversion, p99 entitlement latency), alerting on anomalies (spike in declines, processor error rate), and operational tools (manual retry, invoice adjustment, subscription pause).