Skip to content

Building a SaaS That Scales: The Architecture Patterns Senior Engineers Rely On

A practical guide to multi-tenant SaaS architecture: tenancy models, Postgres RLS, modular monoliths, auth, billing, jobs, and what to build at each stage.

By SaaS DevelopmentUpdated 23 min read

On this page

Over 18 years of building full-stack systems, I've learned the hardest part of SaaS isn't writing code. Code is the easy part. The hard part is a SaaS architecture that scales predictably: one that grows from ten customers to ten thousand without forcing a panic rewrite at 2 a.m. while support tickets pile up.

This guide is for founders and engineering leads who are about to build a SaaS product, or who already have one and can feel the seams starting to strain. If you want the short version of how to build a scalable SaaS: pick a tenancy model on day one (shared Postgres with row-level security is the right default for most B2B products), ship a modular monolith instead of microservices, keep your servers stateless, move slow work onto queues, buy auth and billing instead of building them, and instrument everything with a tenant ID. Then add complexity only when real usage forces you to.

Most SaaS failures I've seen weren't market failures. They were architecture failures. The product found traction, traffic doubled, and the system folded because nobody designed for the second order of magnitude. Below are the patterns I actually rely on, the ones that earn their complexity, and the order I add them in.

What a SaaS architecture actually has to get right

Strip away the diagrams and every SaaS product has the same skeleton. These are the parts I design deliberately on every project, because each one is expensive to retrofit:

ConcernThe decisionCost of getting it wrong later
TenancyHow customers' data is separatedVery high: touches every table and query
Code structureMonolith, modular monolith, or servicesHigh: reorganizing boundaries under load
IdentityUsers, organizations, roles, SSOHigh: auth rewrites break every session
BillingPlans, entitlements, subscription stateMedium-high: money bugs erode trust fast
Async workQueues, retries, idempotencyMedium: lost jobs and double charges
ObservabilityLogs, metrics, traces with tenant contextMedium: you debug blind until you fix it
Data scalingPooling, replicas, partitioningGrows with you, but has hard cliffs

Everything else, the framework, the CSS library, the hosting provider, is replaceable. These seven are load-bearing.

Multi-tenant SaaS architecture: pick a tenancy model on day one

Tenancy is the one decision you cannot defer. Retrofitting tenant isolation onto a system that assumed a single customer is one of the most expensive migrations in software, because the assumption leaks into every table, every query, every cache key, and every background job. Pick a model deliberately before you write the first migration.

There are three mainstream multi-tenant SaaS architecture models:

ModelIsolationOps costMigrationsNoisy-neighbor riskBest for
Shared schema + row-level securityLogical, enforced by the DBLowestRun onceHighestMost B2B SaaS, MVP to scale
Schema-per-tenantStrong logicalMediumRun N timesMediumMid-market, per-tenant customization
Database-per-tenantPhysicalHighestRun N times, across N serversLowestRegulated industries, enterprise, data residency

Shared schema with Postgres row-level security

My default is one database, one schema, a tenant_id column on every tenant-scoped table, and Postgres row-level security (RLS) enforcing isolation. The point of RLS is that the database itself refuses to return another tenant's rows, so a missing WHERE tenant_id = ... in application code is a bug, not a breach.

-- Every tenant-scoped table carries tenant_id, and it is indexed.
CREATE TABLE invoices (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id  uuid NOT NULL REFERENCES tenants(id),
  amount     integer NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX invoices_tenant_id_created_at_idx ON invoices (tenant_id, created_at);
 
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
 
-- current_setting(name, true) returns NULL instead of erroring when unset,
-- and NULL never equals anything, so an unset tenant sees zero rows.
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.current_tenant', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.current_tenant', true)::uuid);

The application sets the tenant at the start of every transaction, scoped to that transaction only:

// Every tenant-scoped unit of work goes through this helper.
export async function withTenant<T>(
  tenantId: string,
  fn: (tx: Tx) => Promise<T>,
): Promise<T> {
  return db.transaction(async (tx) => {
    // is_local = true: the setting dies with the transaction,
    // so it can never leak to the next request on a pooled connection.
    await tx.execute(sql`select set_config('app.current_tenant', ${tenantId}, true)`);
    return fn(tx);
  });
}

Four details here matter more than they look:

  1. FORCE ROW LEVEL SECURITY. Per the Postgres docs, the table owner normally bypasses RLS. If your app connects as the owner (very common, because migrations run as the same user), your policies silently do nothing. Either force RLS or, better, connect the app as a separate non-owner role.
  2. Superusers and BYPASSRLS roles always bypass policies. Never run the application as a superuser. Keep a separate, privileged role for migrations and admin jobs, and know exactly which code paths use it.
  3. Transaction-scoped settings. set_config(..., true) only lasts until the transaction ends (Postgres docs). That is what makes this safe behind a transaction-mode pooler like PgBouncer, which does not support session-level SET in that mode. A session-level SET on a pooled connection is how tenant A's context ends up on tenant B's request.
  4. Default-deny. With RLS enabled and no matching policy, Postgres returns no rows. That's the failure mode you want: an empty page is a bug report, a leaked invoice is an incident.

RLS is not free. Policies add a predicate to every query, so tenant_id needs to lead your composite indexes (see my notes on Postgres indexing), and you should check the plans with EXPLAIN ANALYZE on your hottest queries. In my experience the overhead is small when indexes are right and painful when they're not.

Schema-per-tenant

Each tenant gets its own Postgres schema with identical tables, and the app switches search_path per request. You get cleaner per-tenant backups and restores, the option to customize a tenant's schema, and less reliance on policies being correct.

The costs show up in operations. Every migration runs N times, and a migration that fails on tenant 412 of 900 leaves you in a half-migrated state you have to reason about. Catalog bloat becomes real in the thousands of schemas. Cross-tenant analytics need a separate pipeline. I use this model when a mid-market product genuinely needs per-tenant customization, and almost never as a default.

Database-per-tenant

Physical separation: each tenant has its own database, sometimes its own server or region. This is the answer when a contract or a regulator demands it: data residency, customer-managed encryption keys, or a hard requirement that one customer's data never shares hardware with another's. It's also the answer for very large enterprise tenants whose load would dominate a shared cluster.

It is the most expensive model to operate. You need tenant routing, automated provisioning, fleet-wide migrations, and per-database monitoring. Don't pay for isolation you don't need.

The hybrid most products end up with

The realistic end state for a successful B2B product is a pooled shared database for most tenants, plus dedicated databases for a handful of enterprise tenants who pay for it. If your code always resolves a tenant to a connection through one function (tenant ID in, database handle out), moving one tenant to dedicated infrastructure later is a data migration, not a rewrite. Build that indirection on day one even if it always returns the same pool.

Structure the code as a modular monolith

The first of the two most expensive mistakes I see is premature microservices. Teams split into fifteen services before product-market fit, then spend their runway debugging distributed transactions, versioned internal APIs, and network partitions instead of shipping features.

Start with a modular monolith: one deployable, organized internally into modules with explicit boundaries.

src/
  modules/
    identity/        # users, orgs, memberships, roles
      api.ts         # the ONLY file other modules may import
      service.ts
      repo.ts
      schema.ts
    billing/         # plans, subscriptions, entitlements, Stripe webhooks
      api.ts
      ...
    projects/        # the actual product
      api.ts
      ...
    notifications/   # email, in-app, webhooks out
      api.ts
      ...
  platform/          # db, queue, cache, logger, config: shared infra
  app/               # HTTP routes, pages, server actions: thin adapters

The rules that make this work:

  • Modules talk only through their api.ts. No reaching into another module's repository or tables. Enforce it with a lint rule (ESLint's no-restricted-imports or a dependency-cruiser config), because conventions erode under deadline pressure.
  • Each module owns its tables. Billing doesn't join against projects. If it needs project data, it asks the projects module.
  • Cross-module side effects go through events. When a subscription is cancelled, billing emits subscription.cancelled, and projects reacts. This is the same seam you'd cut along to extract a service later.
  • Route handlers and pages stay thin. They authenticate, validate input (I use Zod at the edges), call one module function, and render. Business logic in a route handler is business logic you can't reuse from a background job.

Extract a service when you have a concrete reason: a genuinely different scaling profile (a CPU-heavy PDF renderer, an ML inference workload), a different runtime, or a separate team that needs to deploy independently. "It feels cleaner" is not a reason.

Make the servers stateless

A scalable service holds no request state in memory. Sessions live in signed or encrypted cookies or in a shared store, uploads go to object storage, and job state lives in the database or the queue. Once any instance can serve any request, scaling is running more instances behind a load balancer, and a crashed instance is a non-event instead of an outage.

The corollary: never keep anything in a local process that you'd cry about losing. Sticky sessions, files written to local disk, and in-memory caches that drift between instances are how "it works on one box" quietly becomes "it breaks on three." This is also what lets you run on serverless or autoscaling containers without surprises.

Identity: auth, organizations, and RBAC

In B2B SaaS, the customer is an organization, not a user. The data model that has held up across every B2B product I've built:

CREATE TABLE organizations (id uuid PRIMARY KEY, name text NOT NULL, plan text NOT NULL);
CREATE TABLE users         (id uuid PRIMARY KEY, email citext UNIQUE NOT NULL);
CREATE TABLE memberships (
  organization_id uuid REFERENCES organizations(id),
  user_id         uuid REFERENCES users(id),
  role            text NOT NULL,          -- 'owner' | 'admin' | 'member' | 'viewer'
  PRIMARY KEY (organization_id, user_id)
);

A user can belong to many organizations, and their role lives on the membership, not on the user. Get this wrong (a role column on users, or an organization_id on users) and the first customer who wants a consultant in two workspaces forces a migration across your whole auth layer. The organization is also your tenant, so organization_id is the tenant_id your RLS policies key on.

Buy authentication, own authorization. Password hashing, MFA, social login, magic links, session rotation, and enterprise SSO (SAML and OIDC) are a solved problem and a large attack surface. Use a provider such as WorkOS AuthKit, Clerk, or a self-hosted library like Better Auth. I walk through a full setup in my guide to Next.js authentication with WorkOS AuthKit. Enterprise SSO in particular is something your first big customer will ask for, and you want it to be a configuration change, not a quarter of work.

Authorization, though, is your product logic. Start with a small fixed set of roles mapped to permissions in code, check permissions (not role names) at every entry point, and design so you can add custom roles later. I cover the full progression from RBAC to attribute-based rules in designing a permissions system.

const PERMISSIONS = {
  owner:  ["project:read", "project:write", "member:manage", "billing:manage"],
  admin:  ["project:read", "project:write", "member:manage"],
  member: ["project:read", "project:write"],
  viewer: ["project:read"],
} as const;
 
export function can(role: keyof typeof PERMISSIONS, permission: string) {
  return (PERMISSIONS[role] as readonly string[]).includes(permission);
}

Every privileged action (role changes, data exports, deletions, SSO configuration) should also land in an append-only audit log. Enterprise buyers ask for it during security review, and you'll want it the first time a customer asks "who deleted this?" Here's what to capture in SaaS audit logs and how to store them.

Billing: Stripe holds the money, your database holds the entitlements

The billing mistake I fix most often is code that calls the Stripe API on every request to decide what a customer can do. It's slow, it rate-limits you, and it fails closed when Stripe has a bad minute.

The pattern that works:

  1. Stripe is the source of truth for money: customers, subscriptions, invoices, payment state.
  2. Your database holds a local projection of what matters for access: the organization's plan, subscription status, seat count, and period end.
  3. Webhooks keep the projection in sync. Verify the signature, dedupe on event ID, process idempotently, and handle out-of-order delivery by re-fetching the subscription rather than trusting the event payload's order.
  4. Entitlements are checked locally. canUse(org, "sso") reads your table, not Stripe.

Stripe Billing's pay-as-you-go pricing is a percentage of billing volume on top of payment processing, so factor it into margin from the start. The edge cases (proration, failed payments, dunning, plan downgrades with over-limit usage, tax) are where billing actually gets hard, and I go through them in Stripe billing for SaaS. Webhook reliability itself is its own discipline, covered in webhooks done right.

Background jobs: do slow work asynchronously, correctly

Anything slow or external belongs on a queue, not in the request path: sending email, generating a PDF, calling a payment provider, syncing a CRM, running an LLM call. Users get fast responses, and spikes get absorbed instead of toppling you.

The two patterns that make async work reliable are idempotency keys and the transactional outbox. Idempotency keys let a caller retry safely without double-charging. The outbox guarantees you never commit a database change but lose its side effect: you write the event in the same transaction as the data, then a relay publishes it.

// Idempotent charge + transactional outbox, in one DB transaction.
async function chargeCustomer(db: DB, key: string, tenantId: string, cents: number) {
  return db.transaction(async (tx) => {
    // Idempotency: first writer wins; retries return the prior result.
    const existing = await tx.findIdempotent(key);
    if (existing) return existing.result;
 
    const charge = await tx.insertCharge({ tenantId, cents, status: "pending" });
 
    // Outbox row committed atomically with the charge, so it is never lost.
    await tx.insertOutbox({
      topic: "payment.requested",
      payload: { chargeId: charge.id, tenantId, cents },
    });
 
    const result = { chargeId: charge.id };
    await tx.saveIdempotent(key, result);
    return result;
  });
}
// A separate relay polls the outbox, publishes to the queue,
// and marks rows dispatched: at-least-once delivery, no lost events.

Consumers must be idempotent too, because at-least-once delivery means they will occasionally see a message twice. Design every handler to be safely replayable, put the tenant ID in every job payload, and re-establish tenant context in the worker exactly the way the web request does. A worker that queries without tenant context is the most common RLS bypass I find in codebases I inherit.

For the queue itself, you don't need Kafka at the start. A Postgres-backed queue or Redis with BullMQ carries most products a very long way. The details (retries with backoff, dead-letter queues, scheduling, concurrency per tenant) are in background jobs at scale.

Caching: only where you've measured

Caching is leverage, and it's also where the second expensive mistake lives: premature optimization. Don't cache until you've measured a real hot path, and first ask whether you need a cache at all (I wrote a whole post on whether you actually need Redis). When you do, reach for read-through caching with tag-based invalidation so you can clear related entries in one shot instead of guessing key names.

async function getWithCache<T>(
  key: string,
  tags: string[],
  ttl: number,
  load: () => Promise<T>,
): Promise<T> {
  const hit = await redis.get(key);
  if (hit) return JSON.parse(hit) as T;
 
  const value = await load();
  const tx = redis.multi();
  tx.set(key, JSON.stringify(value), "EX", ttl);
  for (const tag of tags) tx.sadd(`tag:${tag}`, key); // remember keys per tag
  await tx.exec();
  return value;
}
 
// Invalidate everything touching a tenant's products in one operation:
async function invalidateTag(tag: string) {
  const keys = await redis.smembers(`tag:${tag}`);
  if (keys.length) await redis.del(...keys, `tag:${tag}`);
}

Two rules. Every cache key in a multi-tenant system includes the tenant ID, no exceptions, because a shared cache key is a data leak that RLS can't catch. And always set a TTL even with explicit invalidation: it's your safety net for the invalidation you'll forget to wire up.

Scale the database before it becomes the ceiling

The database is almost always the first thing to fall over, so plan for it.

  • Connection pooling. Postgres connections are expensive, and serverless or autoscaled app tiers open a lot of them. Put a pooler such as PgBouncer in front, in transaction mode, so hundreds of app instances share a small pool. This is exactly why the tenant setting above must be transaction-scoped. More on this in connection pooling in serverless.
  • Read replicas. Route reporting, dashboards, and exports to replicas; keep writes on the primary. Be deliberate about replication lag on read-your-own-writes flows, or users will save a record and not see it.
  • Partitioning. When a table crosses tens of millions of rows, partition it: by time for events and logs, or by tenant for the largest accounts. Indexes stay smaller, and you drop old partitions instead of running enormous DELETEs.
  • Safe migrations. At scale, a careless ALTER TABLE takes a lock that stops the product. Expand, migrate, contract. The full playbook is in zero-downtime database migrations.

Protect tenants from each other

In multi-tenancy, one tenant's runaway import or API script can starve everyone else: the noisy-neighbor problem. Rate-limit per tenant, not just globally, so one customer can't consume the whole pool (rate-limiting strategies covers token bucket versus sliding window and where to enforce each). For heavy async work, give large tenants their own queues or concurrency budgets so a flood from one doesn't delay everyone. Put per-tenant limits on expensive features (exports, AI calls, bulk operations) and tie them to plan entitlements. Fairness isn't a nicety; it's the difference between one unhappy customer and a platform-wide incident.

Observability: you can't scale what you can't see

When something breaks at scale, logs alone won't save you. I instrument three things from the start, using OpenTelemetry so I'm not locked into one vendor:

  • Structured logs (JSON) with tenant_id, user_id, request_id, and trace_id on every line, so you can slice an incident by customer.
  • Distributed traces across web requests, queue jobs, and outbound calls, so you can see exactly where a request spent its 4 seconds and which job it enqueued.
  • The metrics that predict outages: request latency at p95 and p99 (not the average, which hides the slow tail), error rate, queue depth and oldest-job age, and database pool saturation.

Per-tenant dashboards pay for themselves the first time a customer says "it's slow for us" and you can answer in two minutes whether it's them, a specific endpoint, or the whole platform. The fundamentals are in logs, metrics, and traces for developers.

Ship safely: feature flags and gradual rollouts

Big-bang deploys are a bet you don't need to make. Put risky changes behind feature flags and roll them out gradually: internal users, then a handful of friendly tenants, then a percentage, then everyone, watching the metrics above at each step. In multi-tenant SaaS, flags keyed on tenant are also how you run betas and enterprise-only features without branching the code. When something's wrong, you flip a flag instead of scrambling a rollback. Pair this with blue-green or canary deployments for infrastructure-level changes.

How to build a scalable SaaS: what to do at 10, 1,000, and 100,000 users

You don't build all of this on day one. Matching the architecture to the stage is the whole game. User counts here are rough guides for a typical B2B product; what really moves the line is requests per second, data volume, and how heavy each tenant is.

Around 10 users: the MVP

Goal: learn whether anyone wants this, without building anything you'll have to rip out.

  • One modular monolith, one Postgres database with RLS, tenant_id everywhere, and the tenant-to-connection indirection.
  • Bought auth with organizations from the start, even if every org has one user.
  • Stripe Checkout and the customer portal, a webhook handler, and a local subscription table.
  • A simple Postgres- or Redis-backed job queue for email and anything slow.
  • Structured logging with tenant IDs, error tracking, and uptime checks.
  • Managed hosting and a managed database. No Kubernetes.

Resist every urge to over-build. If you want a realistic picture of what this stage costs, I broke it down in how much a SaaS MVP costs to build.

Around 1,000 users: product-market fit

Goal: reliability becomes a feature. Customers are paying, and outages now cost money and trust.

  • Connection pooling, and a read replica for reporting.
  • Caching on hot paths you've measured, with tenant-scoped keys.
  • Per-tenant rate limits and plan-based entitlements.
  • The outbox pattern for every side effect that involves money or external systems.
  • Distributed tracing, p95/p99 alerting, and queue-age alerts.
  • Feature flags and gradual rollouts.
  • Audit logs, role management, and SSO, because your first enterprise prospect will send a security questionnaire.
  • Zero-downtime migration discipline and a CI pipeline that runs them.

Around 100,000 users: scale

Goal: remove the ceilings before you hit them.

  • Partition the largest tables; archive or tier cold data.
  • Dedicated queues and concurrency budgets for your largest tenants.
  • Extract services only along the seams the monolith already gave you, and only for modules with a genuinely different scaling profile.
  • Move specific enterprise tenants to dedicated databases if contracts require it.
  • Formal SLOs, on-call, incident reviews, and capacity planning.
  • Cost reviews on a schedule, because cloud spend grows faster than revenue if nobody owns it.

What a scalable SaaS architecture costs to run

Infrastructure cost follows the stage. These are my estimates for a typical B2B web product on managed services, not quotes, and they assume no heavy compute (video, ML training) and a sensible design:

StageMonthly infrastructure (estimate)What drives it
MVPTens to low hundreds of USDManaged DB tier, hosting, email, error tracking
Product-market fitHundreds to low thousands of USDBigger DB, replica, Redis, observability ingest
ScaleThousands to tens of thousands of USDDB size and IOPS, observability volume, egress, dedicated tenants

What moves these numbers more than anything: observability data volume (logs are the silent budget killer), database size and IOPS, data egress, per-user third-party pricing, and LLM API calls if you have AI features. Third-party services price in different ways, so model them early. For example, WorkOS lists AuthKit as free for the first million monthly active users with SSO priced per connection, and Stripe Billing takes a percentage of billing volume. Those choices change your unit economics at scale far more than your choice of framework does.

Engineering time is the larger cost by an order of magnitude at every stage. The cheapest architecture is the one that doesn't need a rewrite. For where cloud money actually goes once you're live, see cloud cost optimization.

The mistakes I see most often

In projects I've taken over, the same handful of problems account for most of the pain:

  • No tenant ID on some tables, usually "global" ones that turned out not to be global. Every table gets a decision, written down.
  • The app connects as the table owner or a superuser, so RLS policies exist but do nothing.
  • Session-level SET for tenant context behind a transaction pooler. It works in development and leaks in production.
  • Cache keys and job payloads without tenant IDs.
  • Roles on the user instead of the membership.
  • Entitlements checked against the Stripe API on every request.
  • Microservices before customers, each with its own database, joined together with HTTP calls in loops.
  • Logs without tenant context, so every incident starts with an hour of guessing.

None of these are hard to avoid on day one. All of them are expensive to fix at 10,000 tenants.

Frequently asked questions

What is the best architecture for a multi-tenant SaaS?

For most B2B products, a shared Postgres database with a tenant_id on every table and row-level security enforcing isolation, inside a modular monolith. It's the cheapest to run and migrate, and it scales further than most teams expect. Move specific tenants to dedicated databases only when a contract or regulation requires physical separation.

Should I start my SaaS with microservices?

No. Start with a modular monolith with strict internal boundaries, and extract a service only when a module has a concrete reason to be separate: a different scaling profile, runtime, or team. Microservices before product-market fit mostly buy you distributed-systems problems while you still need to be shipping features.

Is Postgres row-level security fast enough for production SaaS?

Yes, when your indexes lead with tenant_id and your policies are simple equality checks. The policy becomes another predicate the planner can use. Check your hottest queries with EXPLAIN ANALYZE, and avoid policies that call expensive functions or subqueries per row.

How do I handle a customer who wants their own database?

Build a single function that maps a tenant to a database connection from day one, even if it always returns the shared pool. Then serving one enterprise tenant from a dedicated database is a provisioning and data-migration job, not a code change. Price that option accordingly, because it costs you real operational effort.

When should a SaaS add caching or Redis?

When you've measured a specific hot path that the database can't serve fast enough with proper indexes. Many SaaS products run a long time on Postgres alone. When you add a cache, include the tenant ID in every key and always set a TTL.

Should I build my own authentication for a SaaS?

Build your own authorization, buy your authentication. Login, MFA, session handling, and enterprise SSO are security-critical and well served by providers and mature libraries. Your roles, permissions, and entitlements are product logic and should live in your code.

How many users can a single Postgres database handle?

It depends on query patterns and data volume far more than user count, but a well-indexed Postgres instance with connection pooling and a read replica comfortably serves many SaaS products into the tens or hundreds of thousands of users. The usual first bottlenecks are missing indexes and connection exhaustion, not raw capacity.

Working with me

If you're planning a SaaS build or your current architecture is starting to creak (tenancy bolted on late, a billing integration nobody trusts, a database at its ceiling), this is the work I do most. I design and build multi-tenant SaaS products end to end and take over existing ones to make them scale. See how I approach SaaS development, or get in touch with where you are and where you're trying to get to.