Database-per-Tenant in Postgres: Never Adopt a Database You Did Not Build

Database-per-Tenant in Postgres: Never Adopt a Database You Did Not Build

#postgresql#multi-tenancy#saas#nodejs#compliance

Fifth post from the compliance-ready backend kit, after nested JWTs, append-only audit logs, key rotation and RFC 9457 errors.

I have already written about the shared-table way to isolate tenants, row-level security. This is the stronger tier: one Postgres database per tenant. The interesting part is not the routing, which is easy. It is provisioning, because that is where a careless retry hands one company another company’s users.

What actually changes

With a shared table, isolation is a predicate. Every query must carry WHERE tenant_id = $1, forever, including the one written at 6pm by someone who did not know the rule. RLS moves that predicate into the database, which helps a lot, but it still depends on a session setting being right on every connection checkout. A pooled connection that kept the previous request’s setting is a cross-tenant read.

With a database per tenant, the connection is attached to a database that does not contain the other tenant’s rows. So where the risk lives changes:

ModelWhere isolation livesWhat a mistake does
Shared table, app-side WHEREevery query, forevera missed predicate returns another tenant’s rows, silently
Shared table, RLSa session setting on every checkouta leaked setting reads as the previous request’s tenant
Database per tenantwhich pool a request is handedone routing decision per request, checked once

A forgotten predicate stops being a leak. Code that never thinks about tenants is still correct, because the connection can only reach one tenant’s rows. The risk does not vanish, it moves to a single place: which database this request is bound to. The kit checks that once, in the authentication guard, by refusing any token whose tenant claim does not match the tenant the header resolved.

For regulated data that is the whole argument. An assessor asking how one hospital’s records are kept from another’s gets a much shorter answer when the answer is “they are not in the same database”.

It also makes three operations coherent that are otherwise scary: exporting one tenant, deleting one tenant, and restoring one tenant to a point in time. Each becomes “this database” rather than a large DELETE you have to trust.

The kit splits it into two planes:

master database                    tenant_acme                tenant_globex
  tenants                            users                      users
  config_keys                        roles                      roles
  audit_events (control plane)       permissions                permissions
                                     role_permissions           role_permissions
                                     user_roles                 user_roles
                                     audit_events (acme)        audit_events (globex)

A request names its tenant in the x-tenant-id header. A guard resolves it against the master registry and attaches a client for that tenant’s database. Nothing downstream ever chooses a database.

Provisioning is the hard part

Creating a tenant means creating a database, building a schema in it, seeding its roles, and registering it. The obvious design is one transaction around all of that.

You cannot have it. From the Postgres docs: CREATE DATABASE cannot be executed inside a transaction block. So provisioning is a sequence of separately committed steps, and any of them can fail with the earlier ones already done.

The kit’s sequence, with the ordering doing real work:

  1. Derive tenant_<slug> and validate it against ^[a-z][a-z0-9_]{0,62}$, because it ends up in DDL.
  2. Take an advisory lock for that database name, held for the whole run.
  3. Insert the registry row with status provisioning, or continue the one a failed run left.
  4. CREATE DATABASE, unless a failed run already did.
  5. In one transaction inside the new database: the schema, the audit-log triggers, the permission catalogue, the admin role, and as the last statement, a marker saying which registry row this database was built for.
  6. Mark the row active.
  7. Append tenant.provisioned to the master audit chain.

The status column is what makes steps 4 and 5 safe to fail. The tenant guard resolves only active tenants, so a half-built database is never served. And Postgres DDL is transactional, so step 5 either produces a complete tenant database or leaves it empty.

That ordering matters for one row in particular. The audit table’s append-only triggers are not something Prisma’s schema can express, so they live in a separate SQL file. If they were a follow-up step, a failure in between would leave a tenant whose audit log accepts UPDATE and DELETE. Inside the same transaction, that state cannot exist.

Retrying without adopting a stranger’s database

Here is the part I got wrong first.

The original provisioning was not resumable. A run that died after CREATE DATABASE left the row in provisioning, the row made the slug taken, and every retry was a 409 until someone edited the registry by hand.

The obvious fix is “if the database already exists, carry on”. That fix is a data leak.

A database named tenant_acme is not necessarily this tenant’s. Delete a tenant’s registry row and keep its database, which is exactly what a cautious operator does, and the next customer to sign up as acme gets a retry path that finds a database with their name on it. Carry on, and they inherit the previous customer’s users and audit log. That is the one outcome database-per-tenant exists to rule out, produced by the retry logic.

So the last statement of the build transaction writes a marker into the database’s own comment:

// LAST, so the marker commits with everything above or not at all.
await client.query(`COMMENT ON DATABASE "${databaseName}" IS 'crbk-tenant:${tenantId}'`);

Both values are checked against strict patterns first (an identifier and a uuid), because COMMENT cannot take bind parameters.

Because the marker commits in the same transaction as the schema, a database carries the marker exactly when its build committed, and it names the registry row it was built for. A retry reads it back with shobj_description(oid, 'pg_database') and decides:

What the retry findsMeaningAction
Marker names this rowbuilt, but the run died before activenothing to do
No marker, no tenant tablescreated, build never committedbuild it
Marker names another rowbuilt for someone elserefuse, touch nothing
Tenant tables, no markera deleted tenant’s leftovers, or pre-markerrefuse, touch nothing

A refusal is a 500 whose log names TenantDatabaseConflictError, not a 4xx. The request was valid; the conflict is in the cluster, and a human has to decide what that database is.

One detail in that last row. “No tenant tables” is detected by the schema failing with a duplicate-object error (42P07 for a table, 42710 for a type), not by checking the database is empty. It need not be empty: CREATE DATABASE copies template1, and a cluster that installs an extension there gives every new database that extension’s objects. An emptiness check would refuse every tenant on such a cluster.

Two concurrency details worth stealing

The lock lives on its own connection. It has to be session-level, since no single transaction spans the run. But a session-level advisory lock belongs to the connection that took it. Take it on a pooled connection and release that connection back to the pool, and the lock stays held by an idle connection, keeping that tenant name locked until the pool happens to close it. So the kit opens a dedicated Client, and ending that client is the release. If the process dies, Postgres drops the lock with the session.

const client = new Client({ connectionString: this.opts.masterUrl });
client.on("error", (err) => this.opts.onPoolError?.(err, "master"));
await client.connect();

const { rows } = await client.query(
  "SELECT pg_try_advisory_lock($1, $2) AS locked",
  provisioningLockKeys(databaseName), // [0x6372626b, 32 bits of sha256(name)]
);

pg_try_advisory_lock rather than the blocking form, so a second request gets an immediate 409 TENANT_PROVISIONING_IN_PROGRESS instead of hanging.

Two-key locks and one-key locks never collide. The audit chain already takes an advisory lock whose single 64-bit key starts with the same “crbk” bytes. I worried they could serialise against each other. They cannot: Postgres keeps the two forms apart, showing a bigint key with objsubid = 1 in pg_locks and a pair of int4 keys with objsubid = 2. Pick the two-key form for a different subsystem and the namespaces are disjoint by construction.

Resolving a tenant has a 500 hiding in it

The header accepts a slug or a uuid. An early version looked both up in one query, id = $1 OR slug = $1.

Every slug lookup then failed with Postgres error 22P02, invalid input syntax for type uuid. The value has to be cast to uuid to be compared with the id column, and "acme" cannot be, so the query errors before any row is considered. The result was a 500 and an error-log flood where a clean 404 belonged. The fix is to branch on the shape of the input in application code and query one column.

The same bug class is why the key registry’s kid column is TEXT, not uuid. An attacker-supplied non-uuid against a uuid column turns a 401 into a 500, and a 500 is both noisier and more informative than you want.

The first admin is not the first user to register

Provisioning creates no users. The tenant’s first administrator comes from a seed command an operator runs:

SEED_ADMIN_PASSWORD=... pnpm db:seed:admin --tenant acme --email admin@acme.example

The tempting alternative is “the first user to register becomes admin”. Registration is unauthenticated, so that is a race for anyone who learns a tenant slug: whoever registers first administers a company they do not work for. Making it an operator action removes the race, and keeps creating infrastructure and granting a human administrative access as two separately audited events.

The route that creates tenants is a separate trust boundary too. It once shipped unauthenticated, guarded by nothing but a source comment, and that was the worst hole the kit has had. It now requires a control-plane bearer key with no default, so it cannot be open merely because nobody set a variable.

What it costs, stated plainly

None of these are hidden in the kit, and none should be hidden in yours.

  • Connection pressure. One pool per active tenant. node-postgres defaults a pool to 10 clients, and Postgres defaults max_connections to 100. Two hundred active tenants at the default pool size is 2,000 potential connections per app instance. The kit’s per-tenant pool cache is currently unbounded, because safe eviction needs reference counting (closing a pool while a request holds a client from it breaks that request). It is left visible rather than done subtly wrong. PgBouncer is the usual answer at scale.
  • Migrations fan out. A schema change must be applied to every tenant database. The kit does not do this yet: only new tenants get current DDL. That is a real limitation, and it bites authorization too, which is the next post.
  • No cross-tenant queries. Reporting across tenants needs a separate pipeline.
  • No global ordering of audit events, since each tenant has its own chain.
  • Every pool needs an error listener. node-postgres emits error from the pool when an idle client’s backend drops, and an error event with no listener crashes the Node process. With database-per-tenant that one dropped connection takes every tenant down with it.
pool.on("error", (err) => this.opts.onPoolError?.(err, databaseName));

When to choose it

Database-per-tenant is the right default when tenants are companies holding regulated data, when per-tenant export, deletion or residency are real requirements, and when tenant count is in the hundreds rather than the hundreds of thousands. Shared tables with RLS are the right default for many small tenants and cheap cross-tenant analytics. This overview lays out the middle option, schema-per-tenant.

The part worth taking with you

  1. Isolation by database turns a silent leak into a loud error. That is the property you are buying; everything else is cost.
  2. CREATE DATABASE is outside any transaction, so give the tenant a status column and serve only active.
  3. Never adopt a database by name. Write a marker in the same transaction as the build, and refuse anything that does not carry yours.
  4. Hold session-level advisory locks on a dedicated connection, never a pooled one.
  5. One pool per tenant means one crash for all tenants if a pool has no error listener.

The code is in packages/db/src/connection-manager.ts in the kit repo, and pnpm provisioning:probe stages each failure state against real Postgres. Next in this series: the permission catalogue, and why a permission that is checked but never granted becomes a permanent 403.

Get new posts by email

Backend, auth, and shipping compliant systems. No spam, unsubscribe anytime.