Skip to content
techpotions
SaaS Architecture · multi-tenant · tenancy · billing · impersonationNovember 19, 20269 min read

How to Design SaaS Architecture: Tenancy Before Features

Most SaaS architecture advice starts with database schemas. That's backwards. Tenancy, billing hooks, and support impersonation must be designed first — here's the order that prevented a complete rewrite in Chatberry.

Cover illustration for “How to Design SaaS Architecture: Tenancy Before Features”

If you’re searching how to design SaaS architecture, you’ve probably read the database‑per‑tenant versus shared‑schema debate. That’s the wrong starting point. The feature that breaks first — and the one that’s most expensive to fix — is tenancy. Order matters because you can stitch on new features, but changing the identity model after launch means a rewrite. In our work on Chatberry, an Arabic‑first WhatsApp marketing platform, we baked tenancy into the request lifecycle before writing a single automation rule. That sequence saved us from having to split a monolithic tenant later.

Most guides (like Clerk’s multi‑tenancy walk‑through) stop after the authentication flow. They miss the decisions that plague a live SaaS: how plan limits intercept a request, where billing hooks live, and why support impersonation is non‑negotiable from day one. The real question isn’t “which database pattern,” but “who is a tenant, and what does every request need to know about them?” Here’s the design sequence we follow at techpotions, built from the trenches of Chatberry and formalised in our undocumented multi‑tenant practices.

How to Design SaaS Architecture: Start with the Identity Model

The first code you write should declare what a tenant is. For Chatberry, that was a WhatsApp Business Account ID (WABA). One WABA could own multiple phone numbers, and the whole organisation — plus its agents, templates and billing — hung off that ID. Picking that anchor early meant every downstream system (queues, OpenAI contexts, webhook handlers) knew how to partition data without guessing.

Contrast that with a startup we advise: they initially defined a tenant as a “user” and later had to retrofit an organisation layer above it. That meant rewriting every WHERE user_id = ? to WHERE org_id = ?, including the billing tables. Their three‑month pivot turned into a nine‑month migration. The lesson: identity model before feature model.

Once you’ve named your tenant, the architecture needs to resolve it on every request. A Next.js middleware that extracts the tenant from the JWT and attaches it to the request context is lightweight but critical:

TypeScript
// middleware.ts — runs on every API call
import { getAuth } from '@clerk/nextjs/server';
import type { NextRequest } from 'next/server';

export function middleware(req: NextRequest) {
  const { userId, orgId } = getAuth(req);
  // orgId is our tenant anchor (WABA ID in Chatberry)
  req.tenantId = orgId;
  // Attach plan limits early (loaded from cache or DB)
  req.tenantPlan = await getPlanLimits(orgId);
}

This context then flows into every business logic call. No developer has to remember to pass tenantId — it’s part of the request’s DNA. If you’re still deciding whether to build or rent this auth layer, our platform services can embed multi‑tenancy by default, and the build‑vs‑rent analysis will help you choose the right investment.

Carve the Tenancy Boundary Before Touching a Feature

Data isolation models — shared table, separate schema, separate database — are well documented (Azure’s article outlines the classic silo/pool/shared patterns). What those diagrams don’t show is how the choice either enables or cripples future business needs like plan limits, billing, and data residency.

Isolation Level

Advantages

Pain Points

Shared table with tenant_id

Simple queries, lowest infra cost

Noisy neighbour, compliance harder

Separate schema per tenant

Logical isolation, easy backup per tenant

Connection pooling complexity

Separate database per tenant

Strongest isolation, region placement

High ops overhead at scale

For Chatberry, we started with a shared table model because the early customers were small businesses with moderate throughput. But we knew that Saudi enterprises would demand local data residency later. So we designed the connection layer to accept a tenant‑specific database URL when a tenant object carries a region flag. That swap was a config change, not a schema migration. Our multi‑tenant practice guide details how to co‑locate the tenant map and the connection pool without coupling them.

Plan Limits Need to Live in the Request Context, Not a Feature Flag

Feature flags at the UI level are comfortable until a customer discovers the API endpoint that wasn’t gated. We learned this when a Chatberry client on the Starter plan accidentally uploaded 10,000 WhatsApp contacts via a webhook that skipped the front‑end quota check. The message queue ballooned, and Meta’s rate limiter flagged the number.

The fix: store plan limits as a JSON blob on the tenant record and load them into the request context at the middleware level. Every API route then gets a canPerformAction(limitType, count) guard that blocks overage before work happens, not after billing.

TypeScript
// Example guard used in an API route
if (!req.tenantPlan.canSendMessages(req.tenantUsage.messagesThisMonth + 1)) {
  return new Response("Monthly message quota reached", { status: 429 });
}
// Proceed to send the message

A simple table maps the limit shape to plans:

Plan

Messages/month

Templates

Agent seats

Free

1,000

3

1

Pro

10,000

20

5

Business

100,000

Unlimited

20

The plan_limits column on the organisation row contained exactly that structure, versioned so future plan changes don’t break existing checks. This is one of the “nobody documents” patterns: plan limits as an application‑level schema, not a billing‑after‑the‑fact chore.

Billing Hooks Must Block, Not Just Meter

Stripe webhooks that tell you someone’s payment failed are necessary, but they’re reactive. By the time the webhook fires, the tenant may have already consumed resources you can’t claw back. Architects like the ones at AWS talk about metering and throttling, but real‑world SaaS needs to pre‑authorise expensive operations against the current plan state.

In Chatberry, sending a WhatsApp template message consumes credit from Meta and our own plan quota. We wired billing hooks into the same request lifecycle that checks limits. A canSendTemplate(templateId) function looks up the current billing tier, the month‑to‑date usage, and the plan limit — all from the request context — and returns false before the API call to Meta even fires. The actual billing webhook from Stripe only updates the authoritative state; it doesn’t gate operations. This pattern avoids the dreaded “free ride” where a customer whose card expired yesterday still sends 5,000 messages because the webhook lagged.

For a deep dive into these enforcement hooks, see the section in our multi‑tenant practices on building a “decision‑point” that sits between the tenant and the paid resource.

Support Impersonation Is Not a Nice‑to‑Have

A multi‑agent shared inbox — like the one Chatberry built for WhatsApp — means a support agent needs to see exactly what the tenant sees: the conversation history, the bot’s replies, the template drafts. Asking for a password or screen‑sharing is a support nightmare and a security hole.

We built a tenant‑override mechanism that lets an authenticated support user switch context to any tenant they’re authorised to help. The middleware recognises a special X-Tenant-Override header, logs the impersonation, and then serves the request as if the tenant themselves made it.

TypeScript
// Middleware snippet for support impersonation
if (req.headers.get('X-Tenant-Override') && req.user.role === 'support') {
  const targetOrgId = req.headers.get('X-Tenant-Override');
  // Verify support agent is assigned to that org
  if (await isSupportAssignedToOrg(req.user.id, targetOrgId)) {
    req.tenantId = targetOrgId;
    req.tenantPlan = await getPlanLimits(targetOrgId);
    logImpersonation(req.user.id, targetOrgId, req.url);
  }
}

Without this backdoor, every debug session turns into a guessing game. With it, the support team in Chatberry resolves issues in seconds, and the audit trail satisfies any enterprise security review. It’s a feature that costs almost nothing if you build it with the initial identity model; retrofitting it requires touching every data access layer.

Data Residency Shapes Your Tenancy Model

Arabic‑speaking markets — the core audience for Chatberry — have strict data sovereignty requirements. Saudi Arabia’s PDPL, for instance, demands that certain personal data stays within the kingdom. If you’ve hard‑coded a single database connection string, you’re suddenly in violation.

Because we chose tenant ID as the anchor from day one, routing to a region‑specific database became a matter of adding a region field to the tenant record and a connection pool router that selects the right database cluster based on that field. No query rewriting, no data migration — we simply provisioned a new RDS instance in Riyadh, updated the tenant’s region column, and the same req.tenantId abstraction did the rest.

The same logic applies to file storage, queues, and even AI model endpoints. Every resource address must be parameterised by the tenant. The Azure Architecture Center calls this “deployment stamp” pattern; we call it non‑negotiable for any SaaS that plans to sell across borders.

How to Design SaaS Architecture Without a Rewrite (Yes, It’s Possible)

If you already have a monolith that treats user_id as the tenant, start by carving out the organisation entity and introducing a context object on every server‑side request — even if it temporarily defaults to user‑id. Then tackle the sequence we described:

  1. Solidify the identity model – what uniquely defines a tenant and how does every request know it?
  2. Embed plan limits in the request context, not the UI.
  3. Move billing to a pre‑authorisation gate so it blocks, not just reports.
  4. Add support impersonation before your team wastes hours on shared screens.
  5. Parameterise every backend resource by tenant so data residency is a config toggle, not a migration.

This order isn’t theoretical. It’s the exact sequence that let us go from a WhatsApp chatbot prototype to a production multi‑tenant platform for businesses across the Gulf, without ever unpicking the core. When you search how to design SaaS architecture, what you really need is a sequence that honours the hardest problem first. Tenancy is that problem.

FAQ

What’s the hardest part of SaaS architecture to change later?

Tenancy boundary: who a tenant is and how their data gets isolated. Changing it later means rewriting authentication, every query, and billing. We saw this risk when building Chatberry — starting with the WhatsApp Business Account ID as the tenant saved us from having to retrofit a hierarchy later.

How do you enforce plan limits in a multi‑tenant SaaS without slowing down the app?

Encode plan limits directly in the request context, not just feature flags. In Chatberry, we stored a plan_limits JSON on the organisation record, loaded it into middleware, and used it to gate every API call — so a user hitting their monthly message quota gets blocked before the work happens, not billed after.

What’s the safest way to give support access to a customer’s account in SaaS?

Build a dedicated impersonation endpoint that logs every override. In Chatberry, support agents use an X-Tenant-Override header that middleware checks against their support role, giving them exactly the tenant’s view for the shared WhatsApp inbox — no password sharing, every action auditable.

Written by
techpotions
All entries
A SaaS Architecture Example, Annotated
The weekly

One email a week, from the workshop.

What we published, what we shipped, and the free packs as they land. No drip sequence, no webinar, unsubscribe in one click.