Tenant isolation
Prerequisite: node-streaming-rpc-and-versioning. Objective: Test tenant-scoped repository queries. Each example is independent. Tested with Node.js 22.16.0 on Linux. Save as main.mjs in a fresh disposable directory and run node main.mjs. These are static code blocks; external system behavior is not established by a local model.
How it works
A pooled table can use a composite tenant and resource key to avoid confusing equal IDs. Scope reads, updates and deletes; writes must set tenant from trusted context. Cache keys and jobs need the same boundary. PostgreSQL row-level security can provide another layer, but owners, privileged roles and policy configuration require explicit testing. SQLite below exercises repository logic, not PostgreSQL RLS.
Read only the selected tenant row
import {DatabaseSync} from 'node:sqlite';import assert from 'node:assert/strict';const db=new DatabaseSync(':memory:');try{db.exec("CREATE TABLE books(tenant TEXT,id TEXT,title TEXT,PRIMARY KEY(tenant,id)); INSERT INTO books VALUES('a','1','River'),('b','1','Forest')");const get=db.prepare('SELECT title FROM books WHERE tenant=? AND id=?');assert.equal(get.get('a','1').title,'River');assert.equal(get.get('c','1'),undefined);console.log(get.get('b','1').title);}finally{db.close();}Expected output:
ForestParameterized composite scope selects the correct row. The fixture disables the experimental warning for Node 22 SQLite; the API is experimental on this baseline.
Use an unambiguous cache key
import assert from 'node:assert/strict';const key=(tenant,id)=>JSON.stringify([tenant,id]);assert.notEqual(key('a:b','c'),key('a','b:c'));console.log(key('a','1'));Expected output:
["a","1"]Tuple serialization prevents delimiter ambiguity; authorization is still required.
Common mistake
A global resource ID or an AsyncLocalStorage context alone is not authorization. Missing context should deny access.
Practice
Add a tenant-scoped delete and prove that another tenant with the same resource ID keeps its row.
Reference candidate: node-tenant-isolation-lookup (route unverified). Documentation anchors: https://www.postgresql.org/docs/18/ddl-rowsecurity.html. External versions and full integration are pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tenant isolation — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Where should tenant scope originate?
Why include tenant in a cache key?
What did the SQLite example test?