skip to content

Connection & Deployment

Running Prisma 7 for real: prisma.config.ts, a driver adapter and its pool, PgBouncer, serverless and edge limits, and an explicit generate in CI. Teams get burned on connections and stale clients.

on this pageshow

explore

questions

6

In Prisma 7, why should a Node.js application share one PrismaClient instance per process, and how do you stop dev hot reload from multiplying it?

level: juniorimportance: must knowfreq 50%

answer

  1. instances are not free
  2. each client brings its own pool
  3. module cache versus re-evaluated modules
  4. globalThis outside production

basics

~20 s

Each PrismaClient gets its own connection pool from its driver adapter, so every extra instance opens extra database connections. Create one in a module and reuse it; in development, keep it on globalThis so hot reload reuses it.

solid answer

~40 s

In Prisma 7 a `PrismaClient` is built with a driver adapter such as `PrismaPg`, and that adapter creates its own pool when the client first connects (on `$connect()` or the first query). Two clients means two pools, so the rule is one instance per process: export it from a module and let Node's module cache hand the same object to every importer. Dev servers with hot reload re-evaluate that module on each edit, which would build a new client and pool every time, so the documented pattern stores the client on `globalThis` outside production and reuses it when present. In a long-running server you do not call `$disconnect()` per request; it closes the pool, so it belongs in one-off scripts and short-lived clients.

code

typescript · 13 lines
typescript
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

function createClient() {
  const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
  return new PrismaClient({ adapter });
}

export const prisma = globalForPrisma.prisma ?? createClient();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

go deeper

for a junior

Remember the rule: one PrismaClient per process, imported from one module, and the globalThis trick only in development.

for a middle

Explain why: each client's driver adapter builds its own pool on first connect, and hot reload re-evaluates the module that would build another one.

for a senior

Show you can spot clients created per request or per class in a code review, and know when $disconnect() is right, such as scripts and short-lived clients.

for a principal

Treat client construction as a team convention: one shared module, a lint or review rule against stray constructors, and pool settings owned in one place.

## What a PrismaClient holds in Prisma 7 `PrismaClient` is the class that `prisma generate` writes into the folder named by the generator's `output` path. In Prisma 7 you construct it with a **driver adapter**: for PostgreSQL that is `PrismaPg` from `@prisma/adapter-pg`, which wraps the node-postgres driver. When the client first connects, either because you call `$connect()` or because the first query does it for you, the adapter creates a **connection pool**. The pool keeps a set of open database connections and lends one to each query. That ownership is the whole story. A pool is not shared through some global registry: each `PrismaClient` gets the pool its own adapter built. Ten clients in one process can hold ten pools, and with the `pg` default of `max: 10` per pool that is up to a hundred connections from a single process. ## One instance per process The documented pattern for a long-running application is simple: - create **one** `PrismaClient` in a dedicated module; - export it, and import that module wherever you need database access; - rely on Node's **module cache**: a module is evaluated once, and later imports receive the same exported object. You do not need to copy the pattern literally. Building the client once at startup and passing it to request handlers through a context object achieves the same thing. What matters is that a request never constructs its own client. ## Hot reload and the globalThis pattern Development servers that support **hot reload** re-evaluate changed modules without restarting the process. If the module that constructs `PrismaClient` is re-evaluated, a fresh client, and with it a fresh pool, appears after every save, while the old ones linger. After an afternoon of edits the local database can refuse new connections. The fix in the Prisma docs is to park the client on `globalThis`, which survives module re-evaluation, and to do so **only outside production**: 1. Read `globalThis.prisma` (through a typed alias). 2. If it is set, reuse it; otherwise construct a new client with its adapter. 3. When `NODE_ENV` is not `production`, store the client back on `globalThis`. Production skips step 3 because nothing re-evaluates the module there: the module cache already guarantees one instance per process. | Situation | What to do | |---|---| | Long-running server | One module-level client, reused by every request | | Dev server with hot reload | Same, plus the `globalThis` cache outside production | | Nightly script inside a long-running service | Create a client, do the work, then `await prisma.$disconnect()` | | Request handler | Import the shared client; never `new PrismaClient()` here | ## When $disconnect() is right `$disconnect()` cancels any interactive transactions still open on that client and then disposes the driver adapter. For a pool that `PrismaPg` created itself, disposing means ending the pool and closing its connections. If you handed `PrismaPg` an existing `pg.Pool`, it is left open unless you set `disposeExternalPool: true`. Because opening connections takes time, calling `$disconnect()` after each request in a server only slows it down. It is the right call when work is genuinely finished: a script that runs once and exits, or a temporary client created for one job inside a service that never shuts down. Without it, every run of that job leaves another pool behind. ## Common mistakes - Constructing `new PrismaClient({ adapter })` inside a request handler or a helper called per request. - Creating one client per repository or service class, so a single process owns several pools. - Disconnecting at the end of every request "to keep things clean". - Assuming hot reload is harmless because modules are cached; re-evaluation bypasses that cache. ## How to check you really have one client A quick audit catches most problems before they reach production: 1. Search the codebase for `new PrismaClient(`. In an application, as opposed to scripts and tests, there should be one hit, in the shared module. 2. Search for `new PrismaPg(` as well. An adapter built per call can hide behind a helper even when the client constructor appears once. 3. In development, watch the database's count of active connections while you save files repeatedly. With the `globalThis` cache it stays flat; without it, it climbs with every reload. 4. In production, compare connections per process with the adapter's `max`. A count well above `max` means more than one client per process. Get these right and connection counts stay predictable: one pool per process, sized by the adapter's options.

  • What exactly does prisma.$disconnect() do in Prisma 7?
    It cancels any interactive transactions still open on that client, then disposes the driver adapter. For a pool `PrismaPg` created from a connection string or config, that ends the pool and closes its connections. If you passed your own `pg.Pool` into `PrismaPg`, the adapter only detaches its error listener and leaves the pool open, unless you set `disposeExternalPool: true`.
  • Why is the globalThis assignment skipped when NODE_ENV is production?
    Production does not hot reload, so the client module is evaluated once per process and the module cache already returns the same instance to every importer. The global cache exists only to survive module re-evaluation during development; in production it would add nothing but shared mutable state.

  • Creating a new PrismaClient in each request handler is fine because clients are cheap.
  • Calling $disconnect() after every request keeps the connection count low.
  • Every PrismaClient in a process automatically shares one connection pool.
  • Hot reload cannot create extra clients because Node caches every module.
open as a page

In Prisma 7, what reads the datasource.url in prisma.config.ts, and where does Prisma Client get its connection string at runtime?

level: middleimportance: should knowfreq 30%

basics

~20 s

In Prisma 7, datasource.url in prisma.config.ts is read by the Prisma CLI for migrate, db and introspection commands. Prisma Client never reads it; at runtime it connects through the driver adapter you pass, such as PrismaPg with its connectionString.

open as a page

In Prisma 7 with PrismaPg, where do you set the connection pool size and timeouts, and which defaults changed from Prisma 6?

level: middleimportance: should knowfreq 25%

basics

~20 s

In Prisma 7 the pool belongs to node-postgres, so you set it in the PrismaPg constructor: max (default 10), connectionTimeoutMillis (default 0, no limit) and idleTimeoutMillis (default 10 seconds). Prisma 6's connection_limit and pool_timeout URL parameters no longer apply.

open as a page

With Prisma 7 behind PgBouncer in transaction mode, why can prisma migrate fail through the pooled URL, and how do you set up the two connection strings?

level: seniorimportance: should knowfreq 25%

basics

~10 s

Prisma Migrate's Schema Engine expects a single dedicated connection and can fail through PgBouncer with 'prepared statement "s0" already exists'. Point datasource.url in prisma.config.ts at a direct URL and give PrismaPg the pooled one.

open as a page

A Prisma 7 API on a serverless platform starts failing with too-many-connections errors during a traffic spike; why does it happen, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Every function instance runs its own PrismaClient and PrismaPg pool, default max 10, so a spike multiplies connections by the instance count. Build the client outside the handler, shrink max, cap concurrency, and route runtime traffic through a connection pooler.

open as a page

A Prisma 7 app's Docker image throws PrismaClientValidationError 'Unknown field' for a column the schema already has; why is the client stale, and how should the build generate it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Prisma 7 never generates the client by itself: no install hook runs it, and migrate dev and db push stopped calling it. The image ships whatever the output folder held. Run prisma generate in the build, after copying the schema.

open as a page