Skip to main content
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.1
A multi-tenant SaaS backend on CockroachDB: Next.js route handlers, Prisma, and row-level security (RLS) that keeps every tenant’s rows away from every other tenant, enforced by the database rather than by WHERE clauses you might forget.
  • Stack: Next.js 16 (App Router route handlers), Prisma 6 with the cockroachdb provider, 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

  1. Each request runs in one transaction that starts with SELECT set_config('application_name', 'tenant:<uuid>', true). The true makes the setting last for that transaction only, so a pooled connection never carries it into the next request (lib/db.ts).
  2. current_tenant_id() reads it back, returning NULL for anything that isn’t a well-formed tenant setting (db/security.sql).
  3. 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.
  4. The app connects as saas_app, which owns no tables, and every table has FORCE ROW LEVEL SECURITY.
Two things RLS doesn’t cover, and how this schema handles them (Row-level security limitations):
  • 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.
Because 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 the cockroach binary.
Try it:

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.
  1. Create a Basic cluster and a SQL user, then copy its connection string from Connect (Connect to your cluster).
  2. Create the database: CREATE DATABASE saas;
  3. Set DIRECT_DATABASE_URL to your SQL user’s connection string for saas, and run npm run db:migrate.
  4. Give the app role a password as that user: ALTER ROLE saas_app WITH PASSWORD '<a strong password>';
  5. Set DATABASE_URL to the same host with saas_app and that password, then deploy the app.
This path follows the CockroachDB Cloud docs; the automated tests in the Cookbook repository run against a local single node.

Two things to know about Prisma on CockroachDB v26.1+

  • Tables are created schema-locked by default (create_table_with_schema_locked), and ADD CONSTRAINT, which Prisma emits for every foreign key, can’t unlock them automatically. The migration starts with SET create_table_with_schema_locked = false; (online schema changes).
  • prisma migrate deploy can’t apply RLS statements (ALTER TABLE ... ROW LEVEL SECURITY, CREATE POLICY): it fails with “only implemented in the declarative schema changer”. scripts/apply-security.mjs sends them one at a time, which works. npm run db:migrate runs both steps.

Transactions and retries

CockroachDB runs transactions at SERIALIZABLE 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:
  1. ALTER DATABASE ... SET PRIMARY REGION, ADD REGION and SURVIVE REGION FAILURE (or ZONE with DB_SURVIVE=zone). Surviving a region failure needs at least three regions (survival goals).
  2. db/multi-region.sql: tenants, users, memberships and api_keys become GLOBAL (read on almost every request, written only at sign-up), and projects and tasks stay REGIONAL BY TABLE in the primary region (table localities).
  3. A lease preference that keeps the system database’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.
What it costs, measured. Median of 9 requests through 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 GLOBAL tables, and writes to GLOBAL tables 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 FAILURE keeps five replicas.
See it locally.
With 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.

License

The code is Apache-2.0 licensed.