HomeBlogHow to Implement Subscription Billing in...

Engineering Guide · 8 min read · May 8, 2026

How to Implement Subscription Billing in a SaaS Application

Reliable SaaS billing never relies on synchronous payment gateway calls during user requests. This engineering guide details how to maintain an authoritative local entitlement ledger, deduplicate out-of-order webhooks, manage prorated team seats, and implement grace periods that recover failed renewals without locking out paying teams.

Author
Smit Desai
Published
May 8, 2026
Read time
8 min read
Topic
SaaS Engineering
Services
Custom Web · Mobile Apps · All Services

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:

  1. Billing Sync Layer: Handles Checkout sessions, Customer Portal redirects, and asynchronous webhook reconciliation.
  2. 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:

  1. Pre-paid seat packs (quantity on subscription item): When an admin adds a seat, your backend calls the billing API with an idempotency key to increment quantity and lets the gateway calculate prorated charges on the current or next invoice.
  2. 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 OK acknowledgment: Validate the signature, insert the event row into billing_webhook_events, push processing onto a background queue, and return 200 OK within 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

saas engineering

Why shouldn't my SaaS query Stripe on every page load to check if a user is subscribed?

Calling an external payment gateway on every HTTP request adds latency, hits API rate limits, and ties your app's uptime to third-party network health. Instead, sync subscription status into your local database via webhooks and read entitlements locally.

How do I prevent duplicate or out-of-order billing webhooks from corrupting subscription state?

Store every incoming provider event ID in a unique-indexed webhook_events table inside a database transaction, and compare event timestamps or subscription state versions before overwriting local plan records.

What should happen immediately when a subscription renewal invoice fails?

Avoid revoking access on the first failed charge. Transition the workspace to a past_due state with a configurable grace window—typically 7 to 14 days—show an admin banner to update the card, and let your payment provider's Smart Retries recover the invoice.

How should seat-based billing stay in sync with team invitations?

Treat your application database as the gatekeeper for invited seats while updating subscription quantity via idempotent API calls to the billing provider. Reconcile active seat counts against webhook updates so prorated mid-cycle additions and removals stay accurate.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.