Skip to main content

Read replicas

Read replicas enable you to distribute workloads across database replicas for high-traffic workloads. The read replicas extension, @prisma/extension-read-replicas, adds support for read-only database replicas to Prisma Client.

The read replicas extension supports Prisma ORM versions 5.2.0 and higher. If you run into a bug or have feedback, create a GitHub issue here.

Setup the read replicas extension

Install the extension:

npm install @prisma/extension-read-replicas

Initialize the extension by extending your Prisma Client instance and provide the extension a connection string that points to your read replica in the url option of the extension.

import { PrismaClient } from '@prisma/client'
import { readReplicas } from '@prisma/extension-read-replicas'

const prisma = new PrismaClient().$extends(
readReplicas({
url: process.env.DATABASE_URL_REPLICA,
})
)

// Query is run against the database replica
await prisma.post.findMany()

// Query is run against the primary database
await prisma.post.create({
data: {/** */},
})

All read operations, e.g. findMany, will be executed against the database replica with the above setup. All write operations — e.g. create, update — and $transaction queries, will be executed against your primary database.

If you run into a bug or have feedback, create a GitHub issue here.

Configure multiple database replicas

The url property also accepts an array of values, i.e. an array of all your database replicas you would like to configure:

const prisma = new PrismaClient().$extends(
readReplicas({
url: [
process.env.DATABASE_URL_REPLICA_1,
process.env.DATABASE_URL_REPLICA_2,
],
})
)

If you have more than one read replica configured, a database replica will be randomly selected to execute your query.

Executing read operations against your primary database

You can use the $primary() method to explicitly execute a read operation against your primary database:

const posts = await prisma.$primary().post.findMany()

Executing operations against a database replica

You can use the $replica() method to explicitly execute your query against a replica instead of your primary database:

const result = await prisma.$replica().$queryRaw`SELECT ...`