118

From https://node-postgres.com/features/connecting , seems like we can choose between Pool or Client to perform query

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  client.end()
})

Their functionalities look very much the same. But, the documentation doesn't explain much the difference between Pool and Client.

May I know, what thing I should consider, before choosing between Pool or Client?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • have checked out the [environmental variables for PostgreSQL](https://www.postgresql.org/docs/9.1/static/libpq-envars.html). I have somewhat of an idea what's the difference. – ZombieChowder Feb 12 '18 at 16:53
  • 13
    `Client` is one static connection. `Pool` manages a dynamic list/pool of `Client` objects, with automatic re-connect functionality ;) Normally, you would just create a single `Pool` object and use it ;) – vitaly-t Feb 14 '18 at 15:39
  • 1
    Pool is recommended – mercury Oct 25 '21 at 20:44

2 Answers2

105

May I know, what thing I should consider, before choosing between Pool or Client?

Use a pool if you have or expect to have multiple concurrent requests. That is literally what it is there for: to provide a pool of re-usable open client instances (reduces latency whenever a client can be reused).

In that case you definitely do not want to call pool.end() when your query completes, you want to reserve that for when your application terminates because pool.end() disposes of all the open client instances. (Remember, the point is to keep up to a fixed number of client instances available.)

user268396
  • 11,576
  • 2
  • 31
  • 26
4

One of the most significant differences to know, is that you must use Client when you use transactions.
From the documentation:

You must use the same client instance for all statements within a transaction. PostgreSQL isolates a transaction to individual clients. This means if you initialize or use transactions with the pool.query method you will have problems. Do not use transactions with the pool.query method.

Shimon S
  • 4,048
  • 2
  • 29
  • 34
  • 1
    yes, but you can create a client from a pool instance https://node-postgres.com/features/pooling#examples – GViz Nov 08 '22 at 02:36
  • @GViz not sure I'm getting your point. Pool is a set of clients. In order to perform a transaction (two or more queries) all the transactions queries must be executed on shared client. Using Pool can not guaranty providing the same Client. – Shimon S Nov 08 '22 at 06:51
  • 1
    That's right, I thought you were implying that only an instance of Client can be used. – GViz Nov 09 '22 at 17:47