PostgresDriver: destroy() hangs forever when called while a connection is being acquired
Summary
db.destroy() never resolves if PostgresDriver.acquireConnection() is still waiting on pool.connect() when it is called. The pending query fails with TypeError: Cannot read properties of undefined (reading 'Client'), and the pg client it was handed is never released, so pool.end() waits forever.
We hit this through MikroORM 7, which runs its SQL through Kysely: queries that are still opening connections when the app shuts down leave the process hanging until it is killed.
Versions
- kysely 0.29.6 (the code is the same on
master) - pg 8.16.3
- Node 24
Reproduction
import { Kysely, PostgresDialect, sql } from 'kysely'
import pg from 'pg'
// Resolves once the driver has asked the pool for a connection.
let connectCalled
const connecting = new Promise((resolve) => (connectCalled = resolve))
class Pool extends pg.Pool {
connect(...args) {
const client = super.connect(...args)
connectCalled()
return client
}
}
const db = new Kysely({
dialect: new PostgresDialect({
// min: 0, so the query has to open a new connection.
pool: new Pool({ connectionString: process.env.DATABASE_URL, min: 0, max: 10 }),
}),
})
const query = sql`select 1`.execute(db).then(() => 'ok', (error) => error.message)
await connecting // pool.connect() is in flight
const destroyed = db.destroy().then(() => 'resolved')
const after = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value))
console.log('query:', await Promise.race([query, after(5000, 'pending')]))
console.log('destroy():', await Promise.race([destroyed, after(5000, 'still pending after 5s')]))
process.exit(0)Output:
query: Cannot read properties of undefined (reading 'Client')
destroy(): still pending after 5sThe Pool subclass only makes the timing deterministic. Without it, the same thing happens whenever destroy() lands while a connection is being opened.
Cause
destroy() sets this.#pool = undefined before awaiting pool.end(). When the pending this.#pool.connect() resolves, acquireConnection() reads this.#pool again (this.#pool.Client, this.#pool.options). That throws before the connection is registered, so the client is never released, and pool.end() waits for it indefinitely.
Suggested fix
Keep the pool the connection was acquired from in a local:
- const client = await this.#pool!.connect()
+ const pool = this.#pool!
+ const client = await pool.connect()
let connection = this.#connections.get(client)
if (!connection) {
connection = new PostgresConnection(client, {
- controlClient: this.#config.controlClient || this.#pool!.Client,
+ controlClient: this.#config.controlClient || pool.Client,
cursor: this.#config.cursor ?? null,
- poolOptions: this.#pool!.options,
+ poolOptions: pool.options,
})With that change the reproduction prints query: ok and destroy(): resolved. We are running it as a local patch for now, and I'm happy to open a PR with a test if that helps.
Source: kysely-org/kysely