FG
💻 Software🗄️ DatabasesVercel

"FATAL: sorry, too many clients already" postgres error in develop mode on

Fresh5 days ago
Mar 14, 20260 views
Confidence Score77%
77%

Problem

Bug description I use prisma inside an api-route of https://nextjs.org/ (this is by the way an awesome setup) for a graphql-api. After some time you will get this error: [code block] I guess the hot-reloading or refreshing of nextjs might mess with the connection-pool of prisma. I verified that the prisma-client that is used in the route is a singleton: [code block] How to reproduce Steps to reproduce the behavior: 1. create a file pages/api/graphql.ts inside that, use prisma client 2. it probably needs some code changes that result in a rebuilding of this file /api/graphql.ts or its imports 3. at some point you should get the error Expected behavior should not throw this error i guess? Prisma information Environment & setup - OS: macOS - Database: [PostgreSQL - Prisma version: prisma2@2.0.0-preview024, binary version: 377df4fe30aa992f13f1ba152cf83d5770bdbc85 - Node.js version: v12.13.1 EDIT: Solution as many still comment on this thead, I though it would be good to pin the solution here. This issue happens because many platforms as nextjs (and probably nestjs as well) do hot reload of parts of your code. Usually you initialize the PrismaClient once in your application (as a singleton). But hot reload results in multiple initializations of this PrismaClient so the solution is to kindof "cache" the client in a global variable. See this comment: https://github.com/prisma/prisma/issues/1983#issuecomment-620621213

Error Output

Error in connector: Error querying the database: db error: FATAL: sorry, too many clients already

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Implement Global Prisma Client Caching to Prevent Connection Overload

Low Risk

The error 'FATAL: sorry, too many clients already' occurs because Next.js hot reloads the application, leading to multiple instances of the PrismaClient being created. Each instance opens a new connection to the PostgreSQL database, exceeding the maximum allowed connections.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Create a Global Prisma Client Instance

    Define a global variable to hold the PrismaClient instance. This ensures that only one instance is created and reused across hot reloads.

    typescript
    let prisma;
    
    if (process.env.NODE_ENV === 'development') {
      if (!global.prisma) {
        global.prisma = new PrismaClient();
      }
      prisma = global.prisma;
    } else {
      prisma = new PrismaClient();
    }
  2. 2

    Update API Route to Use Global Prisma Client

    Modify your API route to use the global Prisma client instance created in the previous step. This will prevent multiple instances from being created during hot reloads.

    typescript
    import { PrismaClient } from '@prisma/client';
    
    let prisma;
    
    if (process.env.NODE_ENV === 'development') {
      if (!global.prisma) {
        global.prisma = new PrismaClient();
      }
      prisma = global.prisma;
    } else {
      prisma = new PrismaClient();
    }
    
    export default async function handler(req, res) {
      // Use prisma instance here
    }
  3. 3

    Test the Changes

    Run your Next.js application in development mode and make requests to the API route. Monitor the database connections to ensure they do not exceed the maximum limit.

    bash
    npx next dev
  4. 4

    Monitor Database Connections

    Use PostgreSQL tools or queries to check the number of active connections to ensure that the number remains stable and does not exceed the limit.

    sql
    SELECT count(*) FROM pg_stat_activity;

Validation

Confirm that the error no longer appears after implementing the global Prisma client caching. Additionally, verify that the number of active connections remains within the PostgreSQL limit during development.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

prismaormpostgresqlbug/0-unknownkind/bugtopic:-connections