Read Replicas
List your read replicas and Turbine spreads read-only queries across them round-robin, while every write stays on the primary. Query code does not change.
import { turbine } from './generated/turbine/index.js';
const db = turbine({
connectionString: process.env.DATABASE_URL, // primary
replicas: [process.env.REPLICA_URL_1!, process.env.REPLICA_URL_2!],
});What routes where#
Read-only operations issued outside a transaction go to a replica. Everything else uses the primary.
| Goes to a replica | Always uses the primary |
|---|---|
findMany, findFirst, findUnique | create, createMany |
findFirstOrThrow, findUniqueOrThrow | update, updateMany, delete, deleteMany, upsert |
count, aggregate, groupBy | Everything inside a $transaction, reads included |
findManyStream, findManyStreamBatches | pipeline, raw, sql |
$listen / $notify, observability flushes |
A transaction is one connection, so its reads stay on the primary with its writes.
Connection strings or pools#
Each entry in replicas is a connection string or a pool:
- Connection string: Turbine opens a
pg.Poolfor it with the primary's pool settings, anddisconnect()closes it. PgCompatPool(Neon, Vercel Postgres, a sharedpg.Pool): Turbine registers no type parsers on it and never closes it, as with a supplied primary pool.
Omitting replicas, or passing [], keeps the single-pool path with no routing.
Reading your own writes#
Replicas lag behind the primary, so a read routed to one can miss a row you just wrote. Pin that read to the primary with $primary():
const created = await db.orders.create({ data: { total: 100 } });
// May hit a lagging replica and miss `created`:
const maybeStale = await db.orders.findUnique({ where: { id: created.id } });
// Always sees the write:
const fresh = await db.$primary().orders.findUnique({ where: { id: created.id } });$primary() returns a cached view of the client that sends every operation to the primary. With no replicas configured it returns the client itself.
Turbine does not measure lag or wait for a replica to catch up. Send reads that must see a recent write through $primary(), or run them in the same $transaction as the write.
Global filters#
Global filters apply the same way on a replica: a routed read carries the same WHERE it would on the primary.
PowDB#
replicas is PostgreSQL only. PowDB 0.14+ serves a copy of its data directory read-only instead, and you route to it by hand. A write against the snapshot throws ReadOnlyError (TURBINE_E018) with reason: 'snapshot', so catch it and send the write to the primary. The data is as fresh as your last snapshot. See PowDB read-only snapshots.
See also#
- Serverless & Edge: the supplied-pool contract replicas reuse.
- Transactions: why transaction bodies stay on the primary.
- Global Filters: filters apply to replica reads too.