Web development · · 4 min read
How to Build a Scalable SaaS with Next.js and PostgreSQL
Architecture decisions that matter when building a SaaS or marketplace: multi-tenancy, data modelling, background jobs, real-time features, billing, and scaling without over-engineering.
"Scalable" is usually the first requirement in a new SaaS brief, and also the most misunderstood. Most products don't fail because they can't handle traffic. They fail because the codebase becomes too tangled to change quickly. Real scalability is mostly about making good early decisions on data and boundaries, and putting off heavy infrastructure until you need it.
These are the decisions we focus on when building products like DispatchLink, a two-sided freight marketplace, and Planfluence, our multi-tenant meeting-to-ticket SaaS.
1. Start with a modular monolith
A single Next.js application with a single PostgreSQL database will comfortably serve far more users than most products ever reach. Microservices bring network failures, distributed transactions, and deployment complexity, so add them when there is a specific need.
What makes a monolith scale is internal boundaries:
- Group code by domain (billing, projects, meetings, integrations) rather than by technical layer.
- Each domain owns its tables and exposes functions to the rest of the app. Other domains don't query its tables directly.
- Keep framework code (route handlers, server actions, React components) thin. Business logic lives in plain TypeScript modules you can test without a browser.
If one domain later needs to become its own service, these boundaries make that a refactor rather than a rewrite.
2. Decide on multi-tenancy on day one
For B2B SaaS, the tenant model is the hardest thing to change later. The common, practical choice is a shared database with a tenant ID on every row:
create table projects (
id uuid primary key default gen_random_uuid(),
org_id uuid not null references organizations(id),
name text not null,
is_private boolean not null default false,
created_at timestamptz not null default now()
);
create index on projects (org_id);Then make it impossible to forget the tenant filter:
- All data access goes through a function that takes the current organization from the session.
- Use PostgreSQL row-level security as a second line of defence where it fits.
- Write tests that try to read another tenant's data and expect failure.
Planfluence goes further, with private projects and outside collaborators who can see exactly one project. That works because access is modelled as data (memberships and project grants) rather than scattered if statements.
3. Model the core domain carefully
For a marketplace like DispatchLink, the important entities were users with two distinct roles (carriers and dispatchers), verified profiles, matching criteria such as equipment type and lanes, conversations, and two-sided reviews. Getting these relationships right early made features like matching and reputation straightforward to build.
Tips that apply to most products:
- Use database constraints (foreign keys, unique indexes, check constraints) to protect invariants. Application code has bugs. Constraints don't forget.
- Prefer explicit status columns and state transitions over many boolean flags.
- Keep an append-only event or audit table for important actions. You will need it for debugging, support, and analytics.
4. Move slow work to background jobs
Anything that takes more than a second or calls an external API should run in the background: sending email, processing uploads, calling LLMs, syncing to third-party tools, generating reports.
A simple, robust setup is a job queue (backed by PostgreSQL or Redis) with:
- Idempotent jobs, so retries are safe.
- Retries with exponential backoff for transient failures.
- A dead-letter queue and alerts for jobs that keep failing.
In Planfluence, the whole path from recording to transcript to AI analysis is a chain of background jobs. The user sees progress in the UI while the work happens asynchronously.
5. Add real-time features deliberately
Messaging, notifications, and live status updates feel essential to users. Use WebSockets or a managed real-time service for the parts that truly need it, such as chat in DispatchLink. Use simple polling or revalidation everywhere else. Real-time connections are stateful and harder to scale than ordinary requests, so keep them focused.
6. Get billing and usage right
Billing touches everything. Decide early:
- What is metered. Seats, usage (such as transcription minutes), or both.
- Where limits are enforced. At the point of use, with clear messages when someone hits a limit.
- How webhooks are handled. Your payment provider's webhooks should be the source of truth for subscription status, and processed idempotently.
Model plans as data (limits and features in a table or config), not hardcoded checks, so you can change pricing without a deploy.
7. Performance basics that cover most of scaling
- Add indexes for every frequent query, and check slow queries with
EXPLAIN ANALYZE. - Paginate every list with cursor-based pagination.
- Cache what is read often and changes rarely.
- Serve static and marketing pages statically. Next.js makes this easy.
- Put files in object storage behind a CDN, never in the database.
8. Observability from the start
Set up error tracking, structured logs, and basic metrics (request latency, job queue depth, error rates) before launch. When something goes wrong at 2 a.m., this is the difference between a five-minute fix and a lost day.
The short version
Build a well-structured monolith, take multi-tenancy and data modelling seriously from the start, push slow work into background jobs, and measure before you optimize. That covers the vast majority of SaaS products from launch to many thousands of users.
Planning a SaaS or marketplace? See our web development services or book a free call to talk through your architecture.
Topics: SaaS architecture, Next.js, PostgreSQL, multi-tenancy, scalability, marketplace development