Key highlights
- Choose a tenancy model deliberately, because it shapes cost, isolation, compliance and how you scale later.
- Tie every request and every row to a tenant, and back up application checks with database rules such as row level security.
- Check permissions on the server for every request, with deny by default and roles scoped to each tenant membership.
- Treat billing events as unreliable messages: verify them, store their IDs, process them once and expect them out of order.
- Move slow work to queues, cache carefully with tenant scoped keys and monitor latency, traffic, errors and saturation per tenant.
Most SaaS products work fine for their first twenty customers. Then a large customer imports two million records and slows the app for everyone. A payment event is processed twice and someone is billed double. A support agent opens a report and sees data from the wrong company. None of these are rare bugs. They are architecture decisions that were made, or skipped, in the first months. Fixing them later means changing a live system full of customer data, which is slower and riskier than designing for them early.
This guide collects the SaaS architecture best practices that prevent those problems. It covers multi tenancy, tenant isolation, authentication and role based access control, database and API design, billing, queues, caching and monitoring. It is written for founders who need to ask the right questions and for developers who need a practical blueprint, not a theory lecture.
A scalable SaaS application is one codebase that serves many customers safely. Every request is tied to a tenant, every permission is checked on the server, slow work runs in background queues, payment events are processed exactly once and the whole system is observable. Start with a modular monolith on a relational database and add complexity only when real metrics demand it.
- Pick a tenancy model on purpose
- Isolate tenant data in code and in the database
- Make billing, queues and monitoring part of version one
What makes SaaS architecture different
A normal web app serves one organization. A SaaS app serves many organizations from shared infrastructure, sells access through subscriptions and ships updates to every customer at once. That creates problems ordinary apps rarely face.
- Isolation: one customer must never see or affect another customer's data.
- Noisy neighbors: one heavy tenant can slow everyone else on shared resources.
- Self service: sign up, plan changes, invoices and cancellations happen without your team.
- Continuous change: every deployment reaches all customers, so mistakes spread fast.
Choosing tools is a separate decision, covered in our guide on choosing a tech stack for SaaS. This article focuses on how the pieces fit together.
Start with a modular monolith
For most teams, the best first shape is one deployable application split into clear modules: identity, tenants and memberships, billing, notifications and your core product domain. Each module owns its tables and exposes a small internal interface. You get one codebase to test and deploy, and if a module later needs to become its own service, the boundary already exists.
Choosing a multi tenancy model
Microsoft's Azure Architecture Center treats isolation as a spectrum, from fully shared to fully dedicated, and notes that a fully dedicated model is costly: if one tenant needs a certain infrastructure cost, a hundred tenants probably need a hundred times that. Most products sit somewhere in between.
| Model | How it works | Strengths | Trade offs |
|---|---|---|---|
| Shared database, shared tables | Every row carries a tenant_id column | Lowest cost, simple operations, easy analytics | Isolation depends on careful code and database rules |
| Schema per tenant | One database, a separate schema for each tenant | Clearer separation, per tenant backups possible | Migrations must run across many schemas |
| Database per tenant | Shared application, separate databases | Strong data isolation, fewer noisy neighbor issues | More databases to provision, patch and monitor |
| Dedicated deployment | Full stack per tenant, often called a stamp | Maximum isolation and custom configuration | Highest cost and heavy automation needs |
A common pattern is to start shared and offer dedicated databases or deployments as a premium tier for enterprise customers. Microsoft calls this mix a vertically partitioned deployment. To make it possible later, keep a tenant directory that maps each tenant to where its data lives.
Larger customers often ask where their data is stored and who can access it. A tenant directory that records each tenant's region and deployment makes it far easier to answer, and to move a tenant to a dedicated or regional deployment when a contract requires it.
Tenant isolation in code and in the database
In a shared model, isolation is your responsibility. Resolve the tenant once per request, from the subdomain, a header or the user's active membership, and pass it through every layer. Data access code should add the tenant filter automatically so a developer cannot forget it.
Then add a safety net in the database. PostgreSQL row level security lets you attach policies to tables. When it is enabled and no policy exists, PostgreSQL applies a default deny rule, so no rows are visible. A tenant policy can look like this:
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid);
-- per transaction, set by the application
SET LOCAL app.tenant_id = '6f1c...';One catch: table owners and superusers normally bypass these policies, so connect your application with a separate, limited database role, or use FORCE ROW LEVEL SECURITY. Finally, write automated tests that log in as tenant A and try to read tenant B's records. Those tests should fail loudly if isolation ever breaks.
Authentication and role based access control
Access control failures are the most common serious web risk. The OWASP Top 10:2025 keeps Broken Access Control at number one and reports that all of the applications it tested had some form of it.
For authentication, use a proven identity provider or framework rather than writing password handling yourself. Offer multi factor authentication early, and plan for single sign on through SAML or OpenID Connect, because business customers will ask for it.
Session handling matters as much as login. OWASP's prevention advice includes invalidating server side sessions on logout and keeping access tokens short lived, with revocable refresh tokens for longer access. When an admin removes someone from a workspace, their access to that tenant should end on the next request, not when a token happens to expire hours later.
For authorization, model it around memberships. A user can be an admin in one workspace and a viewer in another, so roles belong to the membership, not the user. A simple structure works well:
- tenants: one row per customer organization.
- users: one row per person, independent of any tenant.
- memberships: user_id, tenant_id and role.
- permissions: named actions such as invoice.approve, checked in code instead of role names.
The OWASP Authorization Cheat Sheet recommends least privilege, deny by default and validating permissions on every request. It also notes that pure RBAC struggles with object level rules, so be ready to add attribute or ownership checks, such as only the author can edit a draft.
Database design that survives growth
- Put tenant_id on every tenant owned table and make it the first column in composite indexes.
- Use non guessable IDs such as UUIDs in URLs and APIs, while still checking access on every lookup.
- Keep an audit log of who changed what and when. Enterprise customers will ask for it.
- Make migrations backward compatible: add the new column, deploy code that writes both, then remove the old one.
- Send heavy reporting to a read replica. PostgreSQL hot standby servers can serve read only queries.
- Archive or partition very large tables, such as events and logs, before they slow down daily queries.
Protect shared resources with per tenant limits. Rate limits, import size caps and query timeouts stop one customer's heavy job from becoming everyone's outage.
API architecture for customers and integrations
Your API serves your own frontend and, sooner or later, customer integrations. Design it as a product. REST with JSON is the usual default. Our guide on monolith vs microservices explains why one well organized backend is usually the right place to start.
- Version public endpoints, for example /v1/, and publish an OpenAPI description.
- Use cursor based pagination for large lists.
- Rate limit per tenant and per API key, and return clear headers when limits are hit.
- Accept idempotency keys on create operations so clients can safely retry.
- Offer signed outgoing webhooks so customers can react to events in your product.
Stripe's idempotency guidance is a good model: clients send a unique key, such as a random UUID, and the server returns the saved result for any retry with the same key instead of running the operation again.
Subscription billing without double charges
Use a billing provider for payments, invoices and tax, but keep plans, limits and feature entitlements in your own database so the app does not call the provider on every request. The provider tells you about changes through webhooks, and those need care. Stripe's webhook documentation warns that endpoints may receive the same event more than once, that events are not guaranteed to arrive in the order they were created, and that endpoints should return a success status quickly before running complex logic. In live mode, Stripe retries failed deliveries for up to three days.
A reliable webhook flow looks like this:
- 1
Receive and verify
Read the raw request body and verify the signature header with your signing secret. Reject anything that fails.
- 2
Record the event ID
Insert the event ID into a table with a unique constraint. If it already exists, return success and stop.
- 3
Queue the work
Put a job on a queue and immediately return a 2xx response to the provider.
- 4
Process in a worker
Fetch the latest subscription state from the provider instead of trusting event order, then update plans and entitlements.
- 5
Audit and alert
Log every change to billing state and alert the team when processing fails repeatedly.
Plan the business rules around billing too. Decide how upgrades are prorated, how long a grace period lasts after a failed payment, what happens to data when a customer downgrades and how reactivation works. A downgrade should restrict features, not delete records, so returning customers find their work where they left it.
Queues, background jobs and caching
Anything slow or unreliable should leave the request path: emails, PDF invoices, imports, exports, webhooks out and AI calls. Microsoft's queue based load leveling pattern describes a queue as a buffer that lets workers process spikes at their own pace. It also warns that most queues deliver messages at least once, so workers must be idempotent, and that messages that keep failing belong in a dead letter queue for investigation.
Fairness matters in a multi tenant queue. If one customer starts an export of a million rows, other customers' password reset emails should not wait behind it. Separate queues by job type and priority, cap how many jobs one tenant can run at once and break large jobs into smaller batches that can resume after a failure.
Caching speeds up repeated reads such as plan limits, settings and dashboard totals. With the cache aside pattern, the app reads from the cache, falls back to the database on a miss and invalidates the entry on writes. Update the database before removing the cached item, or a reader may put stale data back.
Build cache keys like tenant:42:dashboard:totals rather than dashboard:totals. It prevents one customer's data from appearing for another and lets you clear a single tenant's cache safely.
Monitoring and observability from day one
You cannot fix what you cannot see. Google's SRE book names four golden signals to watch for any service: latency, traffic, errors and saturation. For SaaS, add a tenant dimension to each one so you can tell whether a problem affects everyone or one large customer.
- Structured logs that include request ID, tenant ID and user ID on every line.
- Distributed tracing across the API, workers and database calls.
- Dashboards for queue depth, job failures and webhook processing delays.
- Alerts tied to user impact, such as error rate or slow checkouts, not raw CPU alone.
- Regular restore tests, because a backup you have never restored is only a hope.
Set service level objectives for the journeys customers care about, such as login, checkout and report generation, and publish a status page. Customers forgive short incidents far more easily when they can see that you noticed first and are already working on a fix.
Conclusion: scale comes from early discipline
Scalable SaaS is rarely about exotic technology. It comes from a handful of habits applied from the first release: a deliberate tenancy model, isolation enforced in two places, permissions checked on every request, billing events handled exactly once, slow work in queues and clear visibility into what each tenant experiences. Get these right and a simple stack can carry you a long way. If you are planning a SaaS product or untangling an existing one, our engineers would be happy to review your architecture with you.
Frequently asked questions
Multi tenancy means one running application serves many customer organizations, called tenants, while keeping each tenant's data separate. Tenants usually share code and infrastructure, which lowers cost per customer. The hard part is guaranteeing that no tenant can ever see another tenant's data.
Not usually at the start. A shared database with a tenant ID on every row is the cheapest and simplest to operate for many small customers. Separate databases or dedicated deployments make sense for large customers with strict compliance, performance or data residency needs, and many SaaS products end up offering both.
Role based access control is a good starting point for most products, especially when roles are scoped per tenant. As rules get more detailed, such as only the creator can edit a document, you will need attribute or relationship based checks as well. OWASP recommends considering those models for fine grained permissions.
No. Many SaaS products scale a long way on a well structured modular monolith with a relational database, background workers and caching. Microservices add network calls, deployments and monitoring overhead, so they are best introduced when team size or specific scaling problems justify them.
Use idempotency keys when your system creates charges or subscriptions, so a retried request does not repeat the operation. On the receiving side, store each payment event ID and skip events you have already processed, because providers may deliver the same event more than once.
Start with latency, traffic, errors and saturation for your main services, which Google's SRE book calls the four golden signals. Add queue depth, failed background jobs, payment webhook failures and per tenant usage. Alerts should point to user impact, not every small fluctuation.
Sources and references
- Tenancy models for a multitenant solution, Microsoft Azure Architecture Center
- A01:2025 Broken Access Control, OWASP Top 10
- Receive Stripe events in your webhook endpoint, Stripe Docs
- Monitoring Distributed Systems, Google SRE Book
Cover photo by Taylor Vick
Stay in the loop
Get our latest guides on software, SaaS and growth delivered to your inbox.
By subscribing, you agree to get updates from Brahmabyte Lab. You can unsubscribe any time.


