"FATAL: sorry, too many clients already" postgres error in develop mode on
See original GitHub issueBug 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:
Error in connector: Error querying the database: db error: FATAL: sorry, too many clients already
at PrismaClientFetcher.request
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:
// this is imported in my api route
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default prisma;
How to reproduce
Steps to reproduce the behavior:
- create a file pages/api/graphql.ts inside that, use prisma client
- it probably needs some code changes that result in a rebuilding of this file /api/graphql.ts or its imports
- 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
Issue Analytics
- State:
- Created 3 years ago
- Reactions:11
- Comments:60 (16 by maintainers)
@cimchd You should indeed refactor it so that the code is using a single instance of the Prisma client. Every new call to
new PrismaClient()
will spin up a new connection pool.@macrozone You can try the following code to make sure next js hot reloading doesn’t create a new prisma instance every hot reload:
This snippet was originally posted here: https://github.com/prisma/prisma-client-js/issues/228#issuecomment-618433162
For those having this issue, I solved it by creating a singleton:
Then wherever I used the client I did:
You can then use it like normal.