# Add Read Replicas to a Prisma App

Yes. An agent adds Prisma's read-replicas extension, routes reads to a replica URL from the environment, keeps writes on the primary, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-read-replicas/prisma/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts from how the client is built. In an app laid out like trpc/examples-next-prisma-starter, `package.json` has `@prisma/client` and `prisma` at `^6.7.0`, Next.js 15, React 19, tRPC 11 and Zod 4, and the scripts `generate`, `migrate-dev`, `migrate` (`prisma migrate deploy`), `prebuild` (`run-s generate migrate`), `test-unit` (Vitest) and `test-e2e` (Playwright). `prisma/schema.prisma` has a `postgres` datasource on `env("DATABASE_URL")`, the `prisma-client-js` generator and one `Post` model with a UUID id, title, text and timestamps, with four migrations in `prisma/migrations`. `src/server/prisma.ts` creates a single `PrismaClient` with query logging in development and caches it on `globalThis` outside production; `src/server/env.ts` validates `DATABASE_URL` and `NODE_ENV` with a Zod schema that is also imported by `next.config.ts`, so a missing variable fails the build. `src/server/routers/post.ts` reads with `findMany` (cursor pagination, `take: limit + 1`) and `findUnique`, and writes with `create`; `post.test.ts` calls `add` then `byId` through `createCaller`. `.github/workflows/main.yml` runs on Node 22 with pnpm against a `postgres` service, then `pnpm prebuild`, `pnpm build`, `pnpm test-e2e` and `tsc`.

The version decides the package. `@prisma/extension-read-replicas` 0.5.0 targets Prisma 7 and its driver adapters; for a Prisma 6 client the supported release is 0.4.1, so the agent installs `@prisma/extension-read-replicas@0.4.1` with pnpm and says why in the pull request. In `env.ts` it adds `DATABASE_REPLICA_URL` as an optional URL (a comma-separated list is split into several), and in `prisma.ts` it wraps the client: when the variable is set, `new PrismaClient({...}).$extends(readReplicas({ url }))`, otherwise the plain client, so a developer without a replica runs unchanged. The extension creates one extra client per replica URL, sends every non-transactional read to a replica chosen at random, and keeps writes, interactive and batch transactions, `$queryRaw` and `$executeRaw` on the primary; `prisma.$primary()` forces the primary for one call and `prisma.$replica()` forces a replica. The extension must be applied last if others are added, and the agent leaves a comment saying so.

The exported type changes from `PrismaClient` to the extended client, so the agent exports it as `typeof prisma` and fixes the two places that import it. Then it reads the routers for reads that must see their own writes: the `add` mutation already returns the created row with `select`, so the page that shows a new post does not read it back, and `byId` stays on the replica. For an app whose create flow redirects to a page that reads the row by id, the agent would wrap that read in `$primary()` and say so, because replication lag is the one behavioural change a replica introduces.

To test the routing without a second database, the agent sets `DATABASE_REPLICA_URL` to the same Postgres in `.env` and in the workflow's `env`, so `pnpm test-unit` and `pnpm test-e2e` exercise the extended client path, and adds a Vitest case that calls `prisma.$replica().post.count()` and `prisma.$primary().post.count()` to prove both routes resolve. It installs PostgreSQL in the sandbox with `apt-get`, runs `pnpm prebuild`, `pnpm build`, both test scripts and `pnpm typecheck`, and opens the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add read replica support to the Prisma client in this repository. Read package.json, pnpm-lock.yaml's prisma entries, prisma/schema.prisma, src/server/prisma.ts, src/server/env.ts, src/server/routers, next.config.ts, .env, vitest.config.mts and .github/workflows first. Install the version of @prisma/extension-read-replicas that matches the installed Prisma major (0.4.x for Prisma 6, 0.5.x for Prisma 7) and explain the choice. Add an optional DATABASE_REPLICA_URL to the env schema, accepting a comma-separated list, and extend the client with readReplicas only when it is set so a developer without a replica runs unchanged. Export the extended client type and fix imports. Review every read that follows a write in the routers and use $primary() where read-your-writes matters, explaining each. Set the replica URL to the primary in .env and in CI so the tests cover the extended path, add a unit test that calls $primary() and $replica(), install PostgreSQL in the sandbox, run prebuild, build, the unit and e2e tests and the type check, and open a pull request that quotes the test output and documents the new variable.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `package.json` and `pnpm-lock.yaml` for the extension, `src/server/env.ts` for the optional variable, `src/server/prisma.ts` for the conditional `$extends`, `.env` and `.github/workflows/main.yml` for the test wiring, and adds a Vitest case beside `post.test.ts`; it changes a router only where a read follows a write. Its description names the extension version and the Prisma major it matches, lists each read it considered and the decision, and quotes the unit, e2e and type-check output from the sandbox.

A reviewer checks the read-after-write list against their own knowledge of the UI, because the agent can only see the code paths and not production traffic, and confirms the variable is unset in environments that have no replica so the plain client is used. They also note that raw queries stay on the primary unless a call opts in with `$replica()`.

From then on pointing `DATABASE_REPLICA_URL` at a replica moves the list and detail reads off the primary, and a second URL in the list adds another replica without a code change.

## Run it on every service that reads more than it writes

A team with several Prisma services sends this body once per repository from its own server, each a `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own `package.json` and client file: a Prisma 7 service gets the 0.5 extension with its driver adapter, a service that already stacks extensions gets `readReplicas` applied last, and one whose routers read right after writing gets `$primary()` on those reads.

Give the key a `webhook_url` and Rush POSTs `run.completed` to it when each turn ends, signed per Standard Webhooks, with `data.session_url` to read the pull request from. A follow-up on `POST /o/{org}/sessions/{id}/messages`, once the turn has finished, wakes the same sandbox to move one more read to the primary or to add a second replica URL.

## Why run it on Rush?

The extension is one call, but the judgement is in the reading: which Prisma major is installed, which reads follow a write, whether the env schema will fail a build when the variable is absent, and whether the tests still pass through the extended client. The agent reads the schema, the client file and every router in its own sandbox, runs the migrations and both test suites against a real Postgres, and the output comes back with the pull request.

A team with many services can start the same request against each repository at once; every run makes its own version and read-after-write decisions from that repository, and the pull requests arrive small and uniform enough to review in one sitting.

## Frequently asked questions

### Why version 0.4.1 of the extension?

The 0.5 line requires Prisma 7, which needs a driver adapter or an Accelerate URL on every client. This app runs Prisma 6.7 with the classic engine, and 0.4.1 is the release the extension's maintainers point Prisma 6 users to. When the app moves to Prisma 7, the extension moves with it, and the `readReplicas` call stays the same shape.

### What happens when DATABASE_REPLICA_URL is not set?

The plain `PrismaClient` is used, exactly as before. The variable is optional in the Zod schema so neither `next build` nor the dev server fails without it, and a developer with one local Postgres sees no difference. In CI the variable points at the primary so the extended code path is still exercised.

### Which queries stay on the primary?

Every write, every interactive or batch transaction, and `$queryRaw` and `$executeRaw`, because the extension cannot tell whether a raw query reads or writes. Any read can be forced to the primary with `$primary()`, which the agent applies where a read follows a write, and a raw read can be sent to a replica with `$replica()`.

### How is replication lag handled?

It is not hidden; it is routed around. A read that must see a write the same request just made goes through `$primary()`, and everything else accepts that a replica may be a moment behind. The pull request lists the reads it reviewed so a reviewer who knows the UI can add one it missed.

## More Prisma jobs

- [Add a Seed Script to a Prisma Project](https://getrush.ai/run/add-seed-data/prisma/)
- [Add Slow Query Logging to a Prisma App](https://getrush.ai/run/add-slow-query-logging/prisma/)
- [Add Soft Delete to a Prisma Schema](https://getrush.ai/run/add-soft-delete/prisma/)

## The same job on other stacks

- [Add Read Replicas to a TypeORM App](https://getrush.ai/run/add-read-replicas/typeorm/)
- [Add Read Replicas to a Drizzle App](https://getrush.ai/run/add-read-replicas/drizzle/)

## More jobs like this: Hand off a long task

- [Add Reading Time to an Eleventy Blog](https://getrush.ai/run/add-reading-time/eleventy/)

## Keep reading

- [What an agent can do in Prisma itself, once you connect it](https://getrush.ai/integrations/prisma/)
- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
