Blueprint · Works on: Cockroach Continuum, CockroachDB Cloud, self-hosted · Tested: weekly in CI against the latest CockroachDB · Stack: Next.js 16, Prisma 6, TypeScript · Code:
blueprints/multi-tenant-saas-nextjs v1.1.1WHERE clauses you might forget.
- Stack: Next.js 16 (App Router route handlers), Prisma 6 with the
cockroachdbprovider, TypeScript, Vitest - Database: CockroachDB v26.1 or later: a local single node, a CockroachDB Basic or Standard cluster, or a multi-region cluster (Grow it to multi-region)
- Time: about 15 minutes to run locally; the companion course takes about an hour
- Cost: nothing locally. A CockroachDB Basic cluster includes a free monthly allowance for pay-as-you-go organizations (Plan a Basic cluster)
What it builds
The API:
Every route but sign-up needs
Authorization: Bearer <api key>.
How tenant isolation works
- Each request runs in one transaction that starts with
SELECT set_config('application_name', 'tenant:<uuid>', true). Thetruemakes the setting last for that transaction only, so a pooled connection never carries it into the next request (lib/db.ts). current_tenant_id()reads it back, returningNULLfor anything that isn’t a well-formed tenant setting (db/security.sql).- A policy on each tenant-owned table,
USING (tenant_id = current_tenant_id()) WITH CHECK (...), hides other tenants’ rows on reads and rejects writes for another tenant. No tenant set means no rows. - The app connects as
saas_app, which owns no tables, and every table hasFORCE ROW LEVEL SECURITY.
- Foreign key checks bypass RLS. Each child table’s foreign key includes
tenant_id((tenant_id, project_id) REFERENCES projects (tenant_id, id)), so a row can only point at a parent in its own tenant. - Unique constraints bypass RLS. Each one includes
tenant_id(UNIQUE (tenant_id, name)), so one tenant can’t learn that another already used a name.
tenant_id leads the primary key, the policy turns into a scan of that tenant’s key span, not a full table scan.
Get the code
The code is in the Cockroach Cookbook repository. To fetch only this project at the version this page describes:Run it locally
Needs Node 20+ and thecockroach binary.
Run it on CockroachDB Basic
These steps use a CockroachDB Basic cluster, which existing CockroachDB Cloud organizations can create. New organizations are on Cockroach Continuum: create a cluster with the Continuum quickstart and use its connection string in the same steps. Continuum pricing differs from the Basic prices on this page; see Continuum pricing.
- Create a Basic cluster and a SQL user, then copy its connection string from Connect (Connect to your cluster).
- Create the database:
CREATE DATABASE saas; - Set
DIRECT_DATABASE_URLto your SQL user’s connection string forsaas, and runnpm run db:migrate. - Give the app role a password as that user:
ALTER ROLE saas_app WITH PASSWORD '<a strong password>'; - Set
DATABASE_URLto the same host withsaas_appand that password, then deploy the app.
Two things to know about Prisma on CockroachDB v26.1+
- Tables are created schema-locked by default (
create_table_with_schema_locked), andADD CONSTRAINT, which Prisma emits for every foreign key, can’t unlock them automatically. The migration starts withSET create_table_with_schema_locked = false;(online schema changes). prisma migrate deploycan’t apply RLS statements (ALTER TABLE ... ROW LEVEL SECURITY,CREATE POLICY): it fails with “only implemented in the declarative schema changer”.scripts/apply-security.mjssends them one at a time, which works.npm run db:migrateruns both steps.
Transactions and retries
CockroachDB runs transactions atSERIALIZABLE by default. When two transactions conflict, one is aborted with
SQLSTATE 40001 and must be retried (transaction retry errors).
transaction() in lib/db.ts retries the whole transaction with exponential backoff and jitter; Prisma reports the abort as P2034.
The test suite runs 20 concurrent read-modify-write transactions on one row and checks that all 20 land.
Start small, grow without switching
- The same code runs on a laptop node and on a CockroachDB Basic cluster that scales to zero when idle. If the app later needs more throughput, more regions or to survive a region failure, the database you started on already does that, behind the same PostgreSQL wire protocol, Prisma and driver. The next section shows that path.
- If your app uses a PostgreSQL extension, check PostgreSQL compatibility before you start.
Grow it to multi-region
The same app grows in three stages. Each is a tag in the Cookbook repository, and the companion course walks through them.git diff blueprints/multi-tenant-saas-nextjs/stage-1-basic blueprints/multi-tenant-saas-nextjs/stage-3-multi-region -- .
shows the whole change.
Basic to Standard. A Basic cluster changes plan to Standard in place, from the Cloud Console, the Cloud API or
Terraform; the change takes up to five minutes and the cluster stays up on its current plan meanwhile
(Change a cluster’s plan between Basic and Standard).
Nothing in the project changes for it. The docs don’t say whether the connection string changes, so check
Connect afterwards.
Add regions. Add the regions to the cluster first (Cloud Console, cluster Settings, Regions), then, as the owner:
scripts/apply-multi-region.mjs runs, idempotently:
ALTER DATABASE ... SET PRIMARY REGION,ADD REGIONandSURVIVE REGION FAILURE(orZONEwithDB_SURVIVE=zone). Surviving a region failure needs at least three regions (survival goals).db/multi-region.sql:tenants,users,membershipsandapi_keysbecomeGLOBAL(read on almost every request, written only at sign-up), andprojectsandtasksstayREGIONAL BY TABLEin the primary region (table localities).- A lease preference that keeps the
systemdatabase’s leaseholders in the primary region, which the multi-region overview recommends. It matters here because each query on an RLS table, inside a transaction, reads the system table that records which roles may bypass RLS. On the local demo cluster below, that read cost a cross-region round trip (66 ms) per query until the leaseholders moved to the app’s region (1 ms). Whether a CockroachDB Cloud cluster accepts this zone configuration wasn’t tested; if it refuses, the script says so and goes on.
node scripts/measure-latency.mjs, with one copy of the app in
each region, on the local 9-node demo cluster (cockroach demo --global, which simulates the latency between its three
regions; real clusters differ). Before: the database in us-east1 only. After: stage 3 with SURVIVE REGION FAILURE.
- Reads from the other regions are about three times faster, mostly because authentication now reads a local copy
of
api_keys; the tenant’s projects and tasks still come from us-east1. - Every write pays for surviving a region: at least the round trip to the nearest other region. With
DB_SURVIVE=zone, writes in us-east1 stay about as fast as before (8 ms to create a project), but every table’s voting replicas are then in us-east1, so losing it stops the app. - Sign-up writes four
GLOBALtables, and writes toGLOBALtables are slow by design: about 0.8 s here. - Cost: on Basic, cross-region writes consume more Request Units and each extra replica adds storage
(Plan a Basic cluster); on Standard,
compute is priced at the most expensive region, cross-region transfer is billed at the cloud provider’s price, and
replicas beyond three are billed (costs).
SURVIVE REGION FAILUREkeeps five replicas.
SURVIVE REGION FAILURE and every region passing check-placement.mjs, killing all three us-east1 nodes left the
app working through us-west1: the first write took 6 s while leases moved, then reads took about 5 ms and sign-ups
0.8 s. With DB_SURVIVE=zone, the same outage stopped writes and reads on projects. Test a failure only after
check-placement.mjs passes: until then a region can still hold a majority of some range’s replicas.
Checks
Verified on CockroachDB v26.1.4 and Node 24, October 2026.

