Tenant isolation in multi-tenant SaaS: why tenant_id isn't enough

What we learned turning a single-Page bot into multi-tenant SaaS: tenant scoping at the database driver, leak tests with fault injection, webhooks and cron.

Written by
DevTech365 Engineering
Published
Reading time
8 minutes

The usual advice for tenant isolation in multi-tenant SaaS is to add a tenant_id column, filter every query by it and trust code review to catch the misses. We are building PagePilot, which turns a Facebook Page automation bot (AI-written daily posts, retrieval-grounded Messenger replies and public comment replies) into SaaS where many businesses connect their own Pages. Before porting the single-Page code, we audited it for everything that would break with a second tenant.

This article covers the leaks a column does not fix and how we enforce isolation below application code. PagePilot is pre-launch and waiting on Meta App Review, with 678 tests passing across 13 packages.

Where a tenant ID column falls short

The audit turned up five leak paths that a per-query filter would not close:

  • One webhook, many tenants. Meta sends every connected Page's events to one endpoint, sometimes batched across Pages in one request. Code that flattens the batch throws away the Page ID, the only reliable tenant key.
  • Global unique indexes. A unique index on a knowledge chunk's key lets one tenant's sync overwrite another's pricing. A deduplication key without the Page ID collides across Pages and silently drops a real customer's message as already processed.
  • In-process caches. A module-level cache of knowledge chunks, served on fallback paths, hands whichever tenant warmed it to every other tenant's prompts.
  • Per-Page identities. Messenger issues sender IDs per Page, so keying conversation memory on the sender ID alone can merge two businesses' customers into one thread.
  • Cron on every replica. A scheduler in process memory fires once per replica, so three replicas publish three different posts to the same customer's Page.

None of these is a missing WHERE clause, which is why we stopped treating isolation as a coding convention.

Enforce the tenant at the database driver

Passing a tenant context around guarantees the tenant is available, not that anyone uses it. In PagePilot, one package is the only code allowed to import the MongoDB driver, and it never hands out a raw collection. Callers load a tenant context and receive scoped collections from it. The wrapper applies the scope on every operation:

  • Filters are combined with the scope using $and, so a caller's top-level $or cannot escape it.
  • Inserts write the scope last, so a forged tenant ID loses.
  • Updates that touch tenant or Page fields are rejected. Otherwise a caller could move a document they own into another tenant's namespace, such as a poisoned knowledge chunk into a competitor's prompt.
  • Aggregations pass a stage allowlist, and stages such as $out, $merge and $lookup are denied.
  • A tenant ID written into a filter by hand throws, because the caller has left the abstraction.
  • Every document read is checked against the context's tenant, and a mismatch throws. The wrapper forces the tenant field into projections, so this check cannot pass vacuously.
// Simplified: the only way application code can read tenant data
async function find(ctx: TenantContext, name: TenantCollection, filter: Filter) {
  if (mentionsScopeField(filter)) throw new TenantScopeViolation(name);
  const docs = await driver(name)
    .find({ $and: [{ tenantId: ctx.tenantId }, filter] })
    .toArray();
  for (const doc of docs) {
    if (!doc.tenantId.equals(ctx.tenantId)) throw new TenantScopeViolation(name);
  }
  return docs;
}

Types add a compile-time layer. Collection names are split into disjoint unions for tenant-scoped and Page-scoped data, so asking for conversation messages without first choosing a Page is a compile error. Indexes add another. The knowledge text index starts with the tenant ID, and MongoDB requires an equality match on every key that precedes the text key in a compound text index, so a search that forgets the tenant fails instead of returning every tenant's chunks.

We also rejected an implicit tenant context through async local storage. A missing value there becomes undefined flowing into a filter, while a missing explicit context fails at the call site. When the failure mode is cross-tenant disclosure, boring beats clever.

Prove it with a leak suite that tries to fail

Around the wrapper sit three more checks. A tenant-safety lint in CI bans raw collection access outside the data package and raw error logging everywhere, and an exception needs a written reason or it is ignored. A runtime command monitor inspects database commands and flags any command on a scoped collection that lacks the tenant predicate. An index-drift check compares live indexes with the same manifest that drives migrations, and fails on a missing or unexpected index.

Then the leak suite tries to break all of it. A shared fixture seeds two tenants whose data contains unique sentinel strings, a second Page under the first tenant and the same Messenger sender ID in both. Tests read as one tenant and assert the other's sentinel never appears. Fault injection targets the places leaks hide: a planted document carrying the wrong tenant ID, a projection that drops the tenant field, a forged tenant ID on insert and a caller-supplied $or. It runs as a named, blocking CI step.

One webhook, many tenants

Meta delivers every Page's events to one endpoint and expects a quick 200. Sustained failures can get Pages unsubscribed, and that failure is not per tenant: one slow model call on the request path could cost every customer their webhook. So ingest is a separate process whose package does not even depend on the AI SDK or the Graph API client, so an accidental import fails to resolve.

Each request follows the same short path:

  1. Read the raw bytes and verify Meta's signature over them, failing closed.
  2. Parse and validate the payload, then loop over each entry. Never flatten.
  3. Resolve the Page ID to a tenant from an in-memory directory, with no database read per event.
  4. Store each event with a deduplication key that includes the Page ID. Duplicate-key errors count as Meta redeliveries; any other write error fails the request.
  5. Return 200. Workers pick up the stored events later.

Ingest never returns a 5xx for a tenant-specific problem: an unknown or suspended Page still gets a 200, and its event is stored with a status explaining why it will not run. Only a bad signature, a malformed body or a failed write changes the answer, and ingest never says 200 before the write succeeds, so Meta retries rather than losing events. With nothing slow on the request path, ingest always answers Meta within five seconds.

Jobs and schedules that survive replicas

The job queue lives in MongoDB. A job is claimed with a single findOneAndUpdate that sets a lease, so a lost race is impossible rather than handled. A worker can extend its lease with a heartbeat, and a reaper reclaims expired leases with exponential backoff and full jitter, dead-lettering a job after its last attempt. Every later write is guarded on the claim ID, so a slow worker cannot overwrite a job the reaper has already handed to someone else. A tenant pause or a provider outage defers a job without spending an attempt, because a deferral is not a failure.

Shutdown follows the same rule. The worker stops claiming new work and exits without releasing claims for jobs that may still be running; the reaper picks them up after their leases expire, so a deploy cannot produce a duplicate reply. Every queue need fits in MongoDB, so Redis waits until measured queue times say otherwise.

In-process cron is gone. Schedules are rows, and a sweeper in every worker claims due ones atomically, so scheduling stays correct at any replica count without leader election. Next runs are computed in each tenant's time zone with a date library, not hand-written DST math, so a time inside a spring-forward gap rolls forward to the next valid instant. Runs advance from the previous scheduled time, not from now, so an outage does not skip a day, and runs past a staleness bound are skipped, so a long outage cannot publish days of posts at once. A run key of local date plus time slot, backed by a unique index, guards against double posting, including in a repeated fall-back hour.

This is where cloud and DevOps decisions meet application code: the moment you run a second replica, anything held in process memory becomes a bug.

Encrypt credentials so a copied row fails to decrypt

A Page access token can post, delete and message everyone who has ever written to that Page, and it does not expire. One leaked connection string or stolen backup would expose every customer's Page at once, and disk encryption at rest helps with neither.

Page tokens are encrypted with AES-256-GCM under a versioned key ring. The additional authenticated data binds each ciphertext to its tenant, Page connection and field, so a row copied into another tenant's namespace fails to decrypt instead of silently working. Tokens are decrypted in one place, the worker's runtime loader, which hands them straight to the Graph API client. Logs are structured and redacted, Messenger user IDs are hashed with a server key, and the lint bans logging raw error objects, since one careless log line can copy a token into a log aggregator.

A shared platform also means shared fate. Every tenant's public comment replies go out through one Meta app, so a prompt injection on one Page could put all of them at risk. Public replies pass a four-layer guard: loop and flood limits, a classifier that fails closed, a safety judge that sees only the candidate reply and also fails closed, and deterministic checks that reject unapproved links, mentions, phone numbers, email addresses and leaked classifier output. Comment replies default to draft mode.

What we'd do again

  • Enforce scope where data is read, not only where the request starts. A wrapper around the driver also covers the code nobody reviewed.
  • Treat indexes, caches and schedulers as tenant boundaries. That is where our audit found the leaks.
  • Write the leak test first, and make it prove it can fail.
  • Keep the webhook path boring: verify, route, store, answer.
  • Bind secrets to their owner with authenticated encryption, so a misplaced row is useless.

None of this is exotic SaaS development, and it sits alongside the other multi-tenant SaaS architecture decisions worth making early. It is cheap on day one and painful as a migration, which is the best argument for building it before the second tenant arrives.

  • multi-tenant SaaS
  • SaaS development
  • MongoDB

DevTech365 Engineering

Software engineering team

The engineers who build DevTech365's mobile apps, web platforms, APIs and AI systems, writing about the decisions behind production software.

Have a software idea?Let's turn it into something real.

Tell us what you want to build and where you are today. We'll reply with questions, next steps and an honest view of how we can help.