01Many institutes, one database, no leaks
- Problem
- The software had to serve many institutes, but a server per client multiplies RAM, migrations, backups and certificates.
- Approach
- A shared schema with institute_id on 33 tables and a row-level security policy on each, two least-privilege database roles (tenant and platform), composite (institute_id, id) foreign keys, and a runtime that sets the institute with set_config(..., true) inside each transaction and binds it to AsyncLocalStorage. The tenant database handle is a Proxy that throws if a query runs outside an institute transaction.
- Why it was hard
- An application-level filter can be forgotten on one route, a session-level setting leaks across pooled connections, a nested transaction would take a second connection, and a promise that resolves after commit could run inside the next request's transaction. Each case has its own guard.
- Result
- An automated sweep reads the generated OpenAPI document, seeds two institutes and calls every operation as one institute with the other's IDs, asserting a refusal and unchanged data. A new route is covered without anyone remembering to add a test.



