SaaS Architecture Guide
A production SaaS architecture has six layers: presentation (Next.js), API (REST/tRPC), auth and identity (Supabase Auth + RBAC), data (PostgreSQL with RLS), billing (Stripe), and infrastructure (Vercel Edge + monitoring). Multi-tenant data isolation via row-level security is the most critical architectural decision — and must be designed before the first line of application code.
Getting the architecture wrong at the start is the most expensive mistake in SaaS development. This guide covers the exact patterns 4Byte Agency uses across 45+ shipped products.
▸ Architecture Overview
The six layers of a production SaaS product
Every scalable SaaS product is built on these six layers. Each has a defined responsibility — and a failure in any one of them creates problems that cascade across the entire system.
Presentation Layer
Frontend & UIThe user-facing interface — dashboards, onboarding flows, admin panels, and landing pages. Built with Next.js for SSR performance and SEO, React for component architecture, and Tailwind CSS for design consistency.
Technologies
API Layer
Business Logic & RoutingThe interface between frontend and data — handles authentication, authorisation, input validation, business logic execution, rate limiting, and structured error responses. Built with Next.js API routes or standalone Node.js.
Technologies
Auth & Identity Layer
Authentication & AuthorisationManages who users are and what they can access. Covers signup, login, email verification, session management, OAuth providers, and role-based access control. The security foundation of the entire product.
Technologies
Data Layer
Database & StorageWhere tenant data lives, is isolated, and is queried. PostgreSQL with row-level security policies for multi-tenant isolation, Prisma ORM for type-safe queries, and Supabase Storage for file uploads.
Technologies
Billing Layer
Subscriptions & PaymentsThe revenue engine — subscription plans, trial management, payment processing, webhook handling, invoice generation, and failed payment recovery. Stripe handles the complexity; we integrate it cleanly with your tenant and user model.
Technologies
Infrastructure Layer
Deployment & ObservabilityWhere the product runs and how you know it's healthy. Edge deployment via Vercel for global performance, CI/CD pipelines for zero-downtime deploys, and a monitoring stack covering errors, uptime, and performance.
Technologies
▸ Multi-Tenancy
Three multi-tenancy models — which one fits your SaaS
The multi-tenancy model you choose at architecture time determines your cost structure, compliance posture, and scaling ceiling. Here are the three options with honest trade-offs.
Shared Database, Shared Schema
RecommendedAll tenants share one database and one schema. Each table has an organisation_id column. Row-level security (RLS) policies enforce isolation at the database level — users can only query rows belonging to their organisation.
Advantages
- Lowest infrastructure cost
- Simplest to build and maintain
- Easy to query across tenants for analytics
- No database provisioning overhead
Trade-offs
- Noisy neighbour risk at extreme scale
- Harder to offer per-tenant database backups
- Requires careful RLS policy implementation
Best For
MVPs, early-stage SaaS, and products up to ~100,000 tenants
Shared Database, Separate Schemas
One database, but each tenant gets their own schema (namespace). Stronger logical isolation without the full cost of separate databases. Useful when tenants need per-schema customisation.
Advantages
- Stronger isolation than shared schema
- Per-tenant schema customisation possible
- Single database to manage
Trade-offs
- Schema migrations become complex at scale
- More infrastructure logic required
- Higher build complexity vs shared schema
Best For
B2B SaaS with enterprise buyers requiring stronger isolation guarantees
Separate Database Per Tenant
Each tenant gets a completely isolated database. Maximum data isolation, compliance-friendly, and allows per-tenant backups and retention policies. Highest operational complexity and cost.
Advantages
- Maximum data isolation
- Per-tenant backups and compliance
- No noisy neighbour risk
- Custom retention per tenant
Trade-offs
- Very high infrastructure cost
- Complex migration and maintenance
- Slow to provision new tenants
- Not viable for self-serve SaaS models
Best For
Healthcare, finance, and legal SaaS where data residency and compliance are contractual requirements
▸ Database Schema
The four core tables every SaaS schema must start with
These four tables are the foundation of every multi-tenant SaaS schema. Every other table in your product points back to one of these — primarily via organisation_id.
usersIndividual people with credentials. Auth-level identity — email, password hash, OAuth tokens.
Columns
id (uuid, PK)email (text, unique)full_name (text)avatar_url (text)created_at (timestamptz)updated_at (timestamptz)organisationsThe tenant entity. Each customer account is an organisation. All tenant data traces back here.
Columns
id (uuid, PK)name (text)slug (text, unique)plan (text)stripe_customer_id (text)created_at (timestamptz)membershipsJoin table connecting users to organisations with a role. Enables team features and RBAC from day one.
Columns
id (uuid, PK)user_id (uuid, FK → users)organisation_id (uuid, FK → orgs)role (enum: owner/admin/member)created_at (timestamptz)subscriptionsStripe subscription state. Synced via webhooks. Controls feature access via plan gating.
Columns
id (uuid, PK)organisation_id (uuid, FK → orgs)stripe_subscription_id (text)status (enum)plan_id (text)current_period_end (timestamptz)The Non-Negotiable Schema Rule
Every table that holds tenant data must have an organisation_id UUID NOT NULL column with a foreign key to the organisations table and a corresponding RLS policy. This is enforced from migration zero — retrofitting it onto a live database with existing data is painful, risky, and expensive.
▸ Row-Level Security
RLS policies — the last line of multi-tenant defence
Row-level security (RLS) is a PostgreSQL feature that enforces data access rules at the database level — independent of the application layer. Even if your API has a bug, RLS prevents one tenant from reading another's data.
Users can read their own profile
USING (auth.uid() = id)Members can read their organisation's data
USING (organisation_id IN (SELECT org_id FROM memberships WHERE user_id = auth.uid()))Only owners and admins can insert records
WITH CHECK (get_user_role(auth.uid(), organisation_id) IN ('owner', 'admin'))Members cannot read other organisations
USING (id IN (SELECT organisation_id FROM memberships WHERE user_id = auth.uid()))Testing RLS policies: Every RLS policy must be tested by attempting cross-tenant data access from a different user's session — not just verifying that authorised access works. 4Byte Agency runs dedicated security QA sessions specifically to attempt policy bypass before any product goes live.
▸ API Architecture
Six API patterns every SaaS backend must implement
These six patterns form the security and reliability foundation of every 4Byte API. Each one addresses a class of vulnerability or failure mode that will appear in production.
Authentication Middleware
Every protected API route verifies the JWT token, extracts the user ID, loads their organisation membership, and attaches both to the request context before any business logic runs.
// Every request: verify token → load user → load org → check roleOrganisation Scoping
All database queries in the API layer are automatically scoped to the requesting user's organisation. No query ever touches another tenant's data — enforced by both RLS policies and application-level scoping.
// All queries: WHERE organisation_id = ctx.user.organisationIdRole-Based Guard
Destructive and sensitive operations (delete, billing changes, member management) require an additional role check after authentication. Admin and owner roles are enforced at the API level, not just the UI.
// Sensitive routes: requireRole(['admin', 'owner'])Input Validation Layer
All API inputs are validated with Zod before they reach business logic. Malformed requests return structured 400 errors before any database query is executed.
// All inputs: schema.parse(body) before any db callStructured Error Responses
All errors return a consistent JSON structure with a code, message, and optional details field. Frontend components can handle errors generically without case-by-case parsing.
// All errors: { code: "NOT_FOUND", message: "...", details: {} }Rate Limiting
Authentication endpoints and public API routes are rate-limited to prevent brute force attacks and abuse. Limits are applied per IP and per user token separately.
// Auth routes: 10 req/min per IP. API routes: 100 req/min per token▸ Scalability Patterns
How to scale a SaaS product — in the right order
Premature optimisation is expensive. These patterns are sequenced by when they actually become necessary — not applied speculatively from day one.
Database Connection Pooling
Use PgBouncer (built into Supabase) to pool database connections. Direct PostgreSQL connections are expensive — connection pooling allows thousands of concurrent API requests on a small database instance.
Edge Caching for Static Content
Deploy to Vercel Edge Network. Static and ISR pages are cached globally and served from the nearest edge node — reducing server load and improving Core Web Vitals scores for international users.
Database Query Optimisation
Add indexes on foreign keys and frequently filtered columns. Use EXPLAIN ANALYZE to identify slow queries. Most SaaS performance issues at scale are missing indexes, not hardware limits.
Background Job Queue
Move slow operations (email sends, report generation, AI processing) to a background queue. Users get an immediate response; work completes asynchronously. Use Inngest, Trigger.dev, or BullMQ.
Read Replica for Analytics
Route heavy analytics queries to a PostgreSQL read replica. Keeps the primary database fast for user-facing writes and reads without expensive hardware upgrades.
CDN for File Storage
Serve all user uploads (images, documents, exports) from Supabase Storage with CDN delivery. Never serve binary files through your application server — it wastes compute and increases latency.
The scaling order: Fix slow queries before adding caches. Add caches before upgrading hardware. Upgrade hardware before re-architecting. Most SaaS products that "need to scale" actually need better indexes and query optimisation — not a microservices rewrite.
▸ Architecture Mistakes
SaaS architecture mistakes that cost thousands to fix later
These are the four architecture-level mistakes we see most often when teams come to 4Byte to rescue or rebuild a SaaS product. Every one of them is cheap to prevent and expensive to fix retroactively.
Not implementing RLS from day one
Consequence
Multi-tenant data leakage becomes possible when application-level scoping has a bug. RLS is your last line of defence — it must be there from the first migration.
4Byte Architecture Standard
Enable RLS on every table that holds tenant data before the first record is inserted. Retrofitting RLS policies onto a live database is painful and risky.
Storing sensitive data in JWT payload
Consequence
JWTs are base64-encoded, not encrypted. Storing plan tier, permissions, or sensitive business data in the token exposes it to the client and creates stale data problems when plans change.
4Byte Architecture Standard
Store only user ID and organisation ID in the JWT. Fetch permissions and plan tier from the database on each request through a lightweight middleware cache.
No organisation_id on every table
Consequence
Without an organisation_id column, you cannot write RLS policies or scope queries by tenant. Adding it retroactively requires a migration on live data — high risk with zero reward.
4Byte Architecture Standard
Every table that holds tenant data must have an organisation_id column and a foreign key to the organisations table. This is a non-negotiable schema rule from migration zero.
Building synchronous pipelines for async work
Consequence
Long-running operations (AI calls, PDF generation, bulk exports) block API responses. Users see timeouts. Serverless functions have execution limits of 10–60 seconds.
4Byte Architecture Standard
Identify any operation that may exceed 5 seconds and move it to a background job queue. Return a job ID immediately and poll or use webhooks for completion status.
▸ FAQ
Frequently asked questions about SaaS architecture
What is SaaS architecture?+
SaaS architecture is the structural design of a cloud-based software product — how the database, API, authentication system, frontend, and infrastructure are organised to serve multiple tenants securely, scale under load, and remain maintainable as the product grows.
What is multi-tenant architecture in SaaS?+
Multi-tenant architecture is a design pattern where a single application instance serves multiple customers (tenants), with each tenant's data isolated from others. The three models are: shared database with tenant ID columns (most common for SaaS MVPs), separate schemas per tenant, and separate databases per tenant (highest isolation, highest cost).
What database should I use for a SaaS product?+
PostgreSQL is the standard choice for SaaS products in 2025. It supports row-level security for multi-tenant data isolation, JSON columns for flexible data, full-text search, and scales to millions of rows without infrastructure changes. Most SaaS teams access it via Supabase (managed PostgreSQL with built-in auth and real-time) or direct connection with Prisma ORM.
How do you design a SaaS database schema?+
A SaaS database schema starts with four core tables: users, organisations (or tenants), memberships (user-to-organisation join with role), and subscriptions. Every other table includes an organisation_id foreign key for tenant isolation. Row-level security (RLS) policies enforce that users can only read and write their own organisation's data at the database level.
What is the best API architecture for a SaaS product?+
For most SaaS products in 2025, a RESTful API built with Next.js API routes or a dedicated Node.js backend is the most practical choice. The API layer should handle authentication via JWT or session tokens, authorisation via middleware, input validation, rate limiting, and structured error responses.
How does 4Byte Agency architect SaaS products?+
4Byte Agency uses a standardised SaaS architecture stack: Next.js for the frontend and API layer, Supabase for PostgreSQL database with row-level security and authentication, Prisma ORM for type-safe database queries, Stripe for billing, and Vercel for Edge deployment. This stack is production-proven across 45+ products.
▸ Related Resources
Go deeper into SaaS technical architecture
▸ Get architecture right from day one
Need your SaaS architected and built correctly?
We'll design your data model, define your API contracts, set up RLS policies, and build the entire product in 28 days — using the exact patterns from this guide, refined across 45+ products.