Search code examples
database-connectionconnection-poolingnode-postgres

Using the node-postgres library, why would I ever use the Client constructor over the Pool constructor for establishing a database connection?


Looking at the node-postgres documentation on connecting to a database server it looks like the Client and Pool constructor are functionally equivalent.

My understanding is that using the Pool constructor provides you with the same functionality as using the Client constructor except that connections are made from a connection pool.

Isn't this always desirable? What are the conditions that I would choose to use the Client constructor over the Pool constructor?


Solution

  • One fairly good explanation can be found here: https://gist.github.com/brianc/f906bacc17409203aee0. As part of this post:

    I would definitely use a single pool of clients throughout the application. node-postgres ships with a pool implementation that has always met my needs, but it's also fine to just use the require('pg').Client prototype and implement your own pool if you know what you're doing & have some custom requirements on the pool.

    The drawback to using a pool for each piece of middleware or using multiple pools in your application is you need to control how many open clients you have connected to the backend, it's more code to maintain, and likely wont improve performance over using a single pool. If you find requests often waiting on available clients from the pool you can increase the size of the built in pool with pg.defaults.poolSize = 100 or something. I've set the default at 20 which is a sane default I think. If you have long running queries during web requests you probably have bigger problems than increasing your pool size is going to solve.