Every developer's first billing integration looks deceptively simple: create a checkout session, redirect the user back to /dashboard?success=true, and flip is_pro = true in the database.
Then real customers arrive. Someone closes the browser tab before the redirect completes. A payment gateway delivers invoice.paid twice in three seconds. A corporate card expires mid-month, a customer upgrades from three seats to twelve on day nineteen of a thirty-day cycle, and suddenly support tickets pile up because paid users are locked out—or canceled accounts still have free access.
Reliable subscription billing is not a checkout button. It is a state machine synchronized through an idempotent local ledger.
Core Principle: Separate Billing Events from Feature Entitlements
Never query Stripe Billing or any external gateway synchronously inside your application middleware to decide whether a workspace can create a project. External APIs introduce 150–400ms latency, strict rate limits, and unnecessary failure modes.
Instead, maintain two clean layers:
- Billing Sync Layer: Handles Checkout sessions, Customer Portal redirects, and asynchronous webhook reconciliation.
- Local Entitlement Ledger: Stores current plan tier, subscription status, seat allowance, and billing period boundaries in your own PostgreSQL or MySQL database.
Every controller and mobile API endpoint checks your local database (or short-lived signed entitlement tokens derived from it, as detailed in our client story on web-first mobile SaaS billing).
Designing the Local Billing & Webhook Schema
To make webhook handling safe under retries and out-of-order delivery, persist every received event ID and track the provider's event timestamp before mutating workspace state.
CREATE TABLE billing_webhook_events (
id BIGSERIAL PRIMARY KEY,
provider VARCHAR(32) NOT NULL,
provider_event_id VARCHAR(120) NOT NULL,
event_type VARCHAR(120) NOT NULL,
payload JSONB NOT NULL,
processed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (provider, provider_event_id)
);
CREATE TABLE workspace_subscriptions (
id BIGSERIAL PRIMARY KEY,
workspace_id BIGINT NOT NULL UNIQUE REFERENCES workspaces(id),
provider_customer_id VARCHAR(120) NOT NULL,
provider_subscription_id VARCHAR(120) UNIQUE,
plan_code VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL,
seat_limit INTEGER NOT NULL DEFAULT 1,
current_period_end TIMESTAMPTZ,
grace_ends_at TIMESTAMPTZ,
last_synced_event_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Handling Out-of-Order Webhooks
Gateways do not guarantee strict FIFO webhook delivery. If a user upgrades and immediately cancels, customer.subscription.deleted can occasionally arrive milliseconds before an earlier customer.subscription.updated. Checking event.created_at >= subscription.last_synced_event_at—or fetching the latest canonical subscription snapshot from the provider inside your background webhook worker—prevents stale events from resurrecting canceled plans.
Subscription State Machine & Access Rules
Model subscription transitions explicitly so engineers, finance teams, and customer support agree on what each state allows:
| Subscription Status | Trigger Event | App Access Policy | User-Facing Action |
|---|---|---|---|
trialing |
Workspace created or checkout trial started | Full tier features up to trial cap | Show days remaining + add payment method CTA |
active |
invoice.paid / subscription.updated |
Full access within seat_limit |
Standard usage + self-serve portal link |
past_due |
invoice.payment_failed |
Full or soft-limited access during grace_ends_at (7–14 days) |
Top banner for Workspace Owner to update card |
paused / unpaid |
Grace period exhausted without payment recovery | Read-only export access; block new writes | Prompt reactivation before archival |
canceled |
Period ended after cancellation | Downgrade to free tier or archive workspace | Preserve data cleanly for configurable retention window |
Notice past_due. Cutting off access the instant a renewal fails punishes legitimate customers whose corporate card hit a daily fraud check or expired quietly. Giving workspace owners a 7-to-14-day grace window paired with automated payment retries routinely saves revenue without support intervention.
Implementing Seat-Based Billing & Proration
B2B SaaS platforms quickly outgrow flat single-user pricing. Once companies invite multiple team members, you have two common architectures:
- Pre-paid seat packs (
quantityon subscription item): When an admin adds a seat, your backend calls the billing API with an idempotency key to incrementquantityand lets the gateway calculate prorated charges on the current or next invoice. - Soft-limit seat billing with pre-invoice sync: Teams invite members freely up to an upper threshold, and a nightly reconciliation job syncs active seat counts prior to billing period close.
Whichever model you choose, enforce seat limits inside the database transaction that accepts an invitation using row-level locking (SELECT ... FOR UPDATE on workspace_subscriptions). Without locking, two concurrent invite accepts can slip past a seat_limit check at the exact same millisecond.
Verification, Tax, and Reconciliation Checklist
Before calling your billing implementation production-ready, verify these five edge cases on a test-clock environment:
- Signature verification on raw request body: Always verify webhook HMAC signatures against the unparsed raw payload bytes, not re-serialized JSON middleware output.
- Fast
200 OKacknowledgment: Validate the signature, insert the event row intobilling_webhook_events, push processing onto a background queue, and return200 OKwithin 2 seconds so gateways do not time out and spam retries. - Idempotency keys on all mutations: Pass deterministic idempotency keys (e.g.,
upgrade-{workspace_id}-{plan}-{timestamp_bucket}) when creating checkout sessions or updating seat quantities. - Tax & VAT/GST collection: Enable automated tax calculation at checkout rather than maintaining brittle regional tax rate tables in your own database.
- Nightly drift reconciliation: Run a scheduled background job comparing active local subscriptions against gateway records—inspired by defensive data practices highlighted in Martin Fowler's architectural patterns—to catch missed webhooks during maintenance windows.
Production Billing Without Revenue Leaks
Getting subscription billing right protects both cash flow and customer trust. At SmitDev, we engineer custom SaaS web platforms and growth billing integrations with clean webhook ledgers, prorated team seats, dunning automation, and mobile/web entitlement sync—available at $55/day (8–9 hours of senior work) or $1,999/month dedicated delivery.
Need to wire up clean recurring billing or untangle a brittle webhook setup? Talk to us about your billing architecture.