postgres icon indicating copy to clipboard operation
postgres copied to clipboard

PostgresJS Prevents Natural Process Exit

Open granthusbands opened this issue 1 year ago • 3 comments

On Node, if PostgresJS has been used at all, the process won't exit naturally, as it has some number of pooled connections still open. It seems that people are expected to call sql.end() or set a low connection timeout. However, I think there's a simpler solution for end users. If PostgresJS can call soc.unref() on idle connections entering the pool and call soc.ref() when they're taken back out of the pool, the idle connections will no longer keep the process alive.

To be clear, unref() tells node that the socket is not important enough to keep the process alive, and ref() tells it that the socket is again important enough. The documentation implies that it's a toggle, rather than a counter, so it should be low risk. Also note that it's probable that some timers (for idle timeout and such) will also need unref called on the object returned from setTimeout or setInterval. They can probably just stay unref.

granthusbands avatar May 16 '24 09:05 granthusbands

At least this should be only opt-in. This behavior will be especially useful in one time scripts, but not in long living services.

At the wire protocol level, PostgreSQL does have a specific termination message that clients send to properly close a connection.

See https://github.com/porsager/postgres/blob/b0d8c8f363e006a74472d76f859da60c52a80368/src/connection.js#L416

This cannot be enforced when you unref socket.

langpavel avatar May 12 '25 18:05 langpavel

I think explicit resource management feature (using keyword) is proper way of closing connection, even pool

langpavel avatar May 12 '25 18:05 langpavel

The main reason to pool connections is to move their lifetime management away from lexical contexts for efficiency, so using doesn't quite fit that model. Connections that are in a pool are necessarily unused but ready, so signalling this to Node is correct behaviour. If Node offered a clean-disconnect option for background sockets, that would be better, but in the absence of that, dropping unused connections when they're the only thing keeping the process alive is not going to cause problems for PostgreSQL.

granthusbands avatar May 14 '25 09:05 granthusbands