# A SaaS Architecture Example, Annotated

*Originally published at* [*techpotions.com*](https://techpotions.com/lab/saas-architecture-example-annotated)*.*

This SaaS architecture example annotates the real multi-tenant stack we built for [Taqaddum](https://techpotions.com/work/taqaddum), a bilingual school assessment platform that tracks student attainment across Arabic, Islamic Education and Social Studies. Schools had been assembling each exam round in spreadsheets; the platform replaced that with a unified exam builder, automated baseline-to-end-of-year comparison, and one-click Excel exports, all while keeping Arabic and English as perfect peers. The architecture underneath had to handle multi-tenancy from the first request, so here's exactly how we did it.

## The SaaS architecture example: request path and tenant resolution

**Takeaway:** resolve the tenant as early as possible, before any business logic runs, and thread that context through every layer. In a multi-tenant SaaS, a delayed or ambiguous tenant ID is the fastest route to data leaks.

Every HTTP request to the Taqaddum platform arrives at a subdomain like `al-noor.taqaddum.com`. Our Express middleware strips the subdomain, looks up the tenant record (tenant slug, preferred language, branding token), and attaches it to `req.tenant`:

```javascript
// middleware/tenantResolution.js
app.use(async (req, res, next) => {
  const host = req.headers.host;
  const subdomain = host.split('.')[0]; // e.g. 'al-noor'

  const tenant = await Tenant.findOne({ slug: subdomain });
  if (!tenant) return res.status(404).json({ error: 'Tenant not found' });

  req.tenant = tenant;
  // Also set PostgreSQL parameter for RLS (see next section)
  await db.query(`SET LOCAL app.tenant_id = '${tenant.id}'`);
  next();
});
```

For API-only clients that don't use a subdomain, we also accept an `X-Tenant-ID` header. The pattern, early, explicit tenant resolution, is a staple of Node.js multi-tenant design ([Stackademic's walkthrough](https://blog.stackademic.com/designing-multi-tenant-saas-systems-with-node-js-4a12688dba27) covers similar middlewares). Once `req.tenant` is set, every downstream controller, service, and query naturally carries the right ownership context.

## Tenant data isolation: row-level security in a shared PostgreSQL

**Takeaway:** a single database with row-level security (RLS) gives you strong per-tenant isolation while keeping operational overhead close to zero. The database itself enforces the boundary, so even a stray missing `WHERE` can't leak data.

Taqaddum uses one PostgreSQL instance for all schools. Every table, students, assessments, exam rounds, reports, includes a `tenant_id` column. Instead of trusting application code to filter every query, we let PostgreSQL enforce the rule:

```sql
-- Enable RLS on the students table
ALTER TABLE students ENABLE ROW LEVEL SECURITY;

-- Policy: a tenant can only see its own rows
CREATE POLICY tenant_isolation ON students
FOR ALL
TO app_user
USING (tenant_id = current_setting('app.tenant_id')::uuid);
```

The middleware already called `SET LOCAL app.tenant_id` on the connection, so any query on that connection automatically scopes to the current tenant. This shared-database-with-RLS pattern is one of the most recommended approaches in multi-tenant architecture guides (see [Launchpad's best-practices breakdown](https://launchpad.io/blog/multi-tenant-saas-architecture-best-practices) and [Arun Seetharaman's deep dive](https://medium.com/@arunseetharaman/multi-tenant-saas-architecture-a-deep-dive-into-database-patterns-281320fd8816)). The subtlety is getting every connection path, web workers, background jobs, migrations, to set the parameter correctly; we captured the pitfalls we hit in our piece on [undocumented multi-tenant practices](https://techpotions.com/lab/8-multi-tenant-saas-practices-nobody-documents).

## Background jobs: exporting Excel reports without freezing the UI

**Takeaway:** anything that takes more than a heartbeat, cohort attainment reports, per-student Excel exports, belongs in a background worker. Rent the queue, focus on the job logic.

For Taqaddum, an end-of-year progress report for a 200-student cohort involves thousands of assessment entries, aggregation, and generation of a styled bilingual Excel workbook. That's not something you do on an HTTP thread. We push the job onto a managed queue, and a separate worker tier picks it up:

```javascript
// jobs/exportService.js
async function enqueueCohortExport(tenantId, cohortId, rounds) {
  await queue.add('generate-excel', {
    tenantId,
    cohortId,
    rounds,
  });
}
```

The worker then re-establishes the tenant context (via `SET LOCAL`), runs the queries, builds the workbook with a library like ExcelJS, uploads it to cloud storage, and sends a notification. This async pattern is a textbook [serverless multi-tenant pattern](https://aws.amazon.com/blogs/apn/building-a-multi-tenant-saas-solution-using-aws-serverless-services/), and because we rent the queue and storage, we never worry about queue durability or object replication.

## The pieces we rent instead of building

**Takeaway:** renting the undifferentiated heavy lifting, authentication, managed database, queue, storage, email, lets a small team ship a multi-tenant platform that feels like an enterprise product.

| Component | What we rented | Why |
| --- | --- | --- |
| Identity | Auth0 / Clerk (IDP) | Multi-tenant login, social SSO, passwordless flows |
| Database | Managed PostgreSQL (RDS / Aurora) | RLS, backups, point-in-time recovery |
| Queue | Managed message queue (SQS / Redis) | Zero-ops job delivery for exports & notifications |
| Storage | Object storage (S3) | Bulk Excel files, student uploads, static assets |
| Email | Transactional email service | Password resets, export-ready notifications |
| CDN + WAF | Global CDN + web application firewall | Fast RTL-aware asset delivery, DDoS protection |

Each of these costs a few dollars per month per tenant, far less than building and operating our own equivalents. We regularly help teams assemble the same rented stack through our [platform development service](https://techpotions.com/services/platforms), because it lets them concentrate on the product logic that makes their SaaS unique rather than on infrastructure plumbing. If you need a full-stack partner for your multi-tenant product, [our SaaS development company](https://techpotions.com/solutions/saas-development-company) has shipped this architecture before (the [Taqaddum case study](https://techpotions.com/work/taqaddum) is a concrete example).

## Bilingual by default: keeping Arabic and English first-class citizens

**Takeaway:** for a multi-tenant app that serves varied locales, bilingual support must be an architectural concern, not a bolt-on. Plan for right-to-left layout, pluralisation rules, and locale-aware exports from day one.

Taqaddum's entire UI, assessment content, and exported reports exist in perfect Arabic-English parity. Under the hood:

- Tenant config stores a `preferred_locale` field (ar or en), loaded at tenant resolution time.
- Translations live in a shared JSON/ICU store, keyed by locale, delivered server-side via Next.js internationalization.
- The Excel export layer uses locale-aware number and date formats and flips sheet direction for Arabic.
- CSS layout flips with logical properties (`margin-inline-start`, `text-align: start`) so RTL behaviour is automatic.

By treating language as a first-class tenant attribute, we avoided the nightmare of retrofitting i18n after launch, and gave Arabic-speaking schools exactly the same experience as English-speaking ones.

## FAQ

### What are the main database isolation patterns for multi-tenant SaaS?

The three main approaches are: (1) database-per-tenant (strongest isolation, highest cost), (2) shared database with separate schemas (a middle ground), and (3) a fully shared database with [row-level security](https://medium.com/@arunseetharaman/multi-tenant-saas-architecture-a-deep-dive-into-database-patterns-281320fd8816) plus application-level filters. For Taqaddum we chose the third pattern, a single PostgreSQL database with RLS, because it gives us strong per-tenant isolation without multiplying operational overhead, and the policies are enforced by the database itself.

### How do you handle background jobs in a multi-tenant SaaS?

We push any long-running work, like generating Excel attainment reports for a cohort of 200 students, onto a background queue. A tenant-aware worker picks up the job, re-establishes the tenant context, builds the file, uploads it to cloud storage, and notifies the user. The key: the worker must reuse the same tenant resolution logic as the web tier so that every query carries the correct `tenant_id`. We rented a managed message queue ([a serverless pattern shown by AWS](https://aws.amazon.com/blogs/apn/building-a-multi-tenant-saas-solution-using-aws-serverless-services/)) so we never touch queue infrastructure.

### Why use row-level security instead of separate databases per tenant?

Separate databases give you hard physical isolation but explode operational complexity, you have to migrate, backup and monitor N near-identical databases. With row-level security on a shared PostgreSQL we get the same logical isolation (the database prevents cross-tenant reads even if a bug forgets a `WHERE` clause) while keeping maintenance as simple as one database. The trade-off is that you must be obsessive about setting the tenant context on every connection, we've [documented those gotchas](https://techpotions.com/lab/8-multi-tenant-saas-practices-nobody-documents).
