Too many clients already (!?)
Hey guys, been using Drizzle for a few weeks now and I think since last week this issue has started (look at screenshot).
I'm using the
postgres
paackge to connect Drizzle to my PostgreSQL database that's deployed to Railway.
Drizzle connection code 👇 :
Dunno what I might be doing wrong, please help me 🙏6 Replies
If you're in development and use HMR, everytime you make changes to your files a new postgres instance will be created
You'll need to create a singleton to avoid that problem
I suspect that is your issue, but I might be wrong
Here is an example I found of a singleton implementation:
https://discordapp.com/channels/1043890932593987624/1043890932593987627/1141696708099711148
that makes a lot of sense, I'm gonna try it tomorrow and then come back here to give an update, thank you in advance 🤝
Think I'm running into the same issue, getting this message from tRPC:
tRPC failed: no more connections allowed (max_client_conn)
Is this only going to be an issue in dev? Nothing here impacts production?
Yes, this is a dev-only issue due to HMR, I solved it like this:
For create-t3-app users, the schema will be in another file - not in your main Drizzle client file by default. Just add this generic type to
PostgresJsDatabase
to fix this issue:
So the final file will look like:
I get the too many clients error on railway.app, but it runs perfect on localhost and vercel... What could be wrong:
import { drizzle } from "drizzle-orm/postgres-js"
import postgres from "postgres"
import * as schema from "./schema"
import { type PostgresJsDatabase } from "drizzle-orm/postgres-js"
// Declare global to prevent multiple instances during hot reloading in development
declare global {
// eslint-disable-next-line no-var
var db: PostgresJsDatabase<typeof schema> | undefined
}
const connectionPool = postgres(process.env.DATABASE_URL!, {
max: 20, // Reduced to a more reasonable number
idle_timeout: 30,
max_lifetime: 60 * 30, // 30 minutes
})
function createDb() {
return drizzle(connectionPool, { schema })
}
let db: PostgresJsDatabase<typeof schema>
if (process.env.NODE_ENV === "production") {
db = createDb()
} else {
if (!global.db) {
global.db = createDb()
}
db = global.db
}
export { db }