# Playbook: SaaS & members

> Build a production SaaS app or paid membership community with clean tables, server-enforced tier quotas, 0%-fee Stripe billing, and automated emails.

- Canonical: https://exaspark.ai/docs/playbook-saas-memberships/

## Architecture overview: SaaS tools vs membership communities

Paid SaaS utilities and paid member communities share the exact same underlying full-stack architecture: authenticated accounts, relational workspace or content tables, server-enforced tier gates, **0%-fee Stripe subscriptions**, and automated lifecycle emails.

| Architecture dimension | Paid SaaS utility / workspace tool | Paid membership community / course hub |
| --- | --- | --- |
| **Core value object** | User-owned workspaces, projects, reports, or AI runs | Gated lessons, templates, private PDF downloads, member directory |
| **Primary billing hook** | Usage quotas (projects, seats, monthly exports) + power features | Content tiers (`Basic` vs `All-Access`) + community privileges |
| **Access boundary** | Strictly owner-scoped or workspace-member scoped rows | Tier-scoped read access (`tier >= 'pro'`) + admin publishing controls |
| **Media & storage needs** | User avatars + private uploaded CSVs or generated PDF exports | Public lesson thumbnails + private member-only PDF workbooks |
| **Retention anchor** | Saved workflows, team seats, and monthly usage summaries | Weekly drops, member directory, and frictionless billing portal |

You keep 100% of your subscription revenue minus standard Stripe processing fees (**0% ExaSpark platform fee**), and ExaSpark keeps your **Preview** test environment completely isolated from **Live** customer accounts and live Stripe billing.

## Relational database schema

Start with five focused tables so accounts, billing state, entitlements, usage metering, and Stripe webhook idempotency stay cleanly normalized from day one:

```text
users
  id                      PK (uuid)
  email                   text, unique, not null
  full_name               text, not null
  avatar_key              text, nullable
  role                    enum('member', 'admin'), default 'member'
  stripe_customer_id      text, unique, nullable
  has_used_trial          boolean, default false
  created_at              timestamp (UTC)

subscriptions
  id                      PK (uuid)
  user_id                 FK -> users.id, unique, not null
  stripe_subscription_id  text, unique, not null
  stripe_price_id         text, not null
  plan_code               enum('free', 'starter', 'pro'), not null
  status                  enum('trialing', 'active', 'past_due', 'canceled'), not null
  current_period_start    timestamp (UTC), not null
  current_period_end      timestamp (UTC), not null
  cancel_at_period_end    boolean, default false
  updated_at              timestamp (UTC)

workspace_items           -- projects (SaaS) OR gated_resources (Memberships)
  id                      PK (uuid)
  owner_id                FK -> users.id, not null
  title                   text, not null
  min_tier                enum('free', 'starter', 'pro'), default 'free'
  file_storage_key        text, nullable               -- private storage path for downloads
  status                  enum('active', 'archived'), default 'active'
  created_at              timestamp (UTC)
  INDEX (owner_id, status)

usage_counters
  id                      PK (uuid)
  user_id                 FK -> users.id, not null
  period_key              text, not null               -- e.g. "2026-11"
  metric_name             text, not null               -- e.g. "exports_count"
  used_count              integer, default 0
  UNIQUE (user_id, period_key, metric_name)

processed_stripe_events
  stripe_event_id         PK (text)                    -- e.g. "evt_1Q9x..."
  event_type              text, not null
  processed_at            timestamp (UTC)
```

Using a composite `UNIQUE (user_id, period_key, metric_name)` constraint on `usage_counters` lets your server increment monthly counters atomically and automatically resets allowances when a new month starts — zero fragile cron resets required.

## Server-enforced roles, tier gating, and usage quotas

The most common security flaw in early SaaS apps is **UI-only gating** — hiding an **Export CSV** button or blurring a member-only playbook in the browser while leaving the underlying API route open to anyone with a Free session cookie.

Enforce every role, tier, and numeric quota **on the server** inside every data mutation and private file download route:

| Role / Tier | Server entitlement check | Allowed actions | Behavior when over limit |
| --- | --- | --- | --- |
| **Guest** | No session | Browse marketing page, monthly/annual pricing, public sample posts | Redirected to sign-in when starting checkout |
| **Free Member** | Authenticated, no active paid sub | Up to **3 active projects**, 5 monthly exports, free library articles | HTTP `403` with clean upgrade prompt; existing data stays intact |
| **Starter / Pro Member** | `subscriptions.status IN ('trialing', 'active')` (+ optional `past_due` grace) | Higher project/export limits, private PDF signed downloads, member directory | Instant unlock via webhook; Customer Portal self-serve upgrades |
| **Admin** | `session.user.role === 'admin'` | Publish gated resources, inspect MRR & churn metrics, assist members | Isolated `/admin` routes reject non-admins with HTTP `403` |

### Protecting private member files

For paid membership communities offering PDF playbooks, design kits, or templates, store downloadable files under `private/resources/...` in managed storage. When a member clicks **Download workbook**, verify both their session and `subscriptions.status IN ('trialing', 'active')` on the server before returning a short-lived signed download URL. See [Images, PDFs & upload safety](https://exaspark.ai/docs/media-uploads-and-limits/).

### Graceful downgrade handling

If a Pro member downgrades to Free with 12 existing projects, **never delete their older records**. Keep all 12 projects readable and exportable, display a calm quota banner (`12 / 3 active projects`), and block creating a 13th project until they archive down or resubscribe.

## Checkout, upgrades, and transactional email lifecycle

- **Monthly vs annual toggle:** Offer clear savings (e.g., `$19/mo` vs `$180/yr`) and pass `allow_promotion_codes: true` on Stripe Checkout.
- **Single-use trials:** Check `users.has_used_trial` before applying `trial_period_days: 7` (or `14`) so returning users bill immediately.
- **Self-serve Customer Portal:** Route existing subscribers clicking **Manage billing** into Stripe Customer Portal instead of spawning duplicate Checkouts.
- **Automated lifecycle emails:** Wire four idempotent sends — **Welcome**, **3-day trial reminder** (`trial_will_end`), **Payment receipt** (`invoice.paid`), and **Failed renewal nudge** (`invoice.payment_failed`). Monthly allowances: **Free** `100/mo` (auth only), **Starter** `1,000/mo` (`1` custom domain), **Pro** `10,000/mo` (up to `3` domains).

## Build and launch in five structured passes

1. **Generate core schema, auth, and roles** — Build `users`, `subscriptions`, `workspace_items`, `usage_counters`, and Google/email sign-in with owner isolation in **Cloud → Preview**.
2. **Wire Stripe Checkout, Portal, and webhooks** — Connect Stripe Test mode, map every `price_id` server-side, deduplicate via `processed_stripe_events`, and verify upgrades and cancellations.
3. **Verify server quotas and private PDFs** — Confirm Free accounts hit HTTP `403` on Pro actions and private member workbooks reject incognito downloads.
4. **Authenticate email and connect your domain** — On **Starter** or **Pro**, complete [SPF, DKIM & DMARC setup](https://exaspark.ai/docs/email-authentication-dns/), connect your domain, and remove the badge.
5. **Switch Stripe to Live and Publish** — Recreate Live prices in Stripe, toggle to Live mode, click **Publish**, and run one personal-card checkout + refund smoke test.

## Copy-paste starter prompts

### Starter prompt A: Multi-tier SaaS workspace app

> **Example prompt (App):** Build a multi-tier SaaS app with Google/email auth plus `users`, `subscriptions`, `workspace_items`, `usage_counters`, and `processed_stripe_events` tables. Enforce quotas server-side: Free ($0, 3 active projects, 5 exports/mo), Starter ($19/mo or $180/yr, 15 projects, 50 exports/mo), Pro ($49/mo or $480/yr, unlimited). Add a single-use 7-day trial guarded by `users.has_used_trial`, `allow_promotion_codes: true`, a Stripe Customer Portal link, and idempotent webhooks for `checkout.session.completed`, `invoice.paid`, `invoice.payment_failed`, `customer.subscription.trial_will_end`, `customer.subscription.updated`, and `customer.subscription.deleted`. Keep `past_due` access open with a slim update-card banner, keep existing items readable on downgrade, and add an admin-only MRR dashboard.

### Starter prompt B: Paid membership community & resource library

> **Example prompt (App):** Build a paid membership community with Google/magic-link sign-in, Member and Admin roles, and two Stripe tiers: Insider ($15/mo or $144/yr) for articles and member directory, and All-Access ($35/mo or $336/yr) adding private PDF workbooks and workshop replays. Store PDF workbooks in private storage and serve short-lived signed downloads only after verifying an `active` or `trialing` All-Access subscription server-side. Include Customer Portal billing, idempotent webhooks, branded welcome and 3-day trial emails, and an Admin CMS.

## Pre-launch failure modes to verify in Preview

| Failure mode | Preview verification check | Clean fix |
| --- | --- | --- |
| **Free user hits Pro route** | Call Pro export or PDF URL while signed in on Free | Verify `subscriptions.status` and `plan_code` server-side on every gated route |
| **Duplicate active subscriptions** | Click **Upgrade** twice as an active Starter user | Route active subscribers to Customer Portal instead of fresh Checkout |
| **Quota never resets monthly** | Inspect `usage_counters` across a new `YYYY-MM` key | Key rows by `(user_id, YYYY-MM, metric_name)` for automatic monthly reset |
| **Canceled user locked out early** | Cancel in Test Portal and check access immediately | Revoke tier only on `customer.subscription.deleted`, not `cancel_at_period_end` |
| **Live checkout fails on Price ID** | Check Live Stripe prices before toggling Live | Keep separate Test and Live `price_...` IDs per environment |

## Next steps

- [Subscriptions & proration](https://exaspark.ai/docs/subscriptions-and-upgrades/) — Master mid-cycle upgrades, proration rules, and dunning recovery.
- [Row-level data privacy](https://exaspark.ai/docs/row-level-data-privacy/) — Enforce ironclad tenant and owner isolation across every table.
- [Launch readiness checklist](https://exaspark.ai/docs/production-checklist/) — Complete pre-launch audit across auth, DNS, billing, and monitoring.

## From the blog

- [How to build a SaaS product](https://exaspark.ai/blog/how-to-build-a-saas-product/) — Architecture, pricing tiers, and retention habits for founders.
- [Build a membership website](https://exaspark.ai/blog/how-to-build-a-membership-website/) — Launch gated content, member tiers, and recurring billing fast.
- [Why ExaSpark excels at the business layer](https://exaspark.ai/blog/why-exaspark-excels-at-the-business-layer/) — See how Cloud, auth, email, and 0%-fee Stripe work together.
