A
A
andreyyka2018-08-13 01:48:20
JavaScript
andreyyka, 2018-08-13 01:48:20

How to properly use pg-pool in nodejs?

Can't figure out how to properly use node-pg-pool ( https://github.com/brianc/node-pg-pool) or if it helps me at all.
The essence of the problem. It seems to be expected that the connection pool should reduce the cost of connecting to the database (the first reason to use pg-pool at the link https://node-postgres.com/features/pooling ), which wastes time (well, i.e. if for each new connections to open and close a new connection - excess load and additional delays), because the pool will store a pre-prepared set of connections, which, if necessary, are taken from the pool, and after use can be returned to the pool.
I can’t make a normal script so that connections are returned to the pool, or at least unused connections are stored in it (see code). Well, i.e. I either constantly accumulate new connections (whose number rests on max and then the creation of a new connection ends with an error), or the used connections are immediately closed. As a result, the only thing the pool copes with is limiting the maximum number of connections, but does not optimize the work in any way.

// Используется это https://github.com/brianc/node-pg-pool
const { Pool } = require('pg');

// Создаём пул подключений
pool = new Pool({
  user: 'qwerty',
  host: 'localhost',
  database: 'qwerty',
  password: 'qwerty',
  port: 5432,
  max: 10, // Ограничивает количество подключений, работает правильно
  min: 5, // не понимаю как работает, у меня client.release() всегда закрывает подключение
  idleTimeoutMillis: 1000, // тоже не понимаю как работает
  connectionTimeoutMillis: 3000
});

async function someFunction() {
  // Выбираем одно подключение из пула. Или же это всегда значит именно новый коннект?
  var connection = await pool.connect();

  // Что-то делаем-с с этим подключением.
  await connection.query('SELECT 1');

  // Если освобождать вручную при помощи .release(), то всё подключение к БД закрывается сразу. Если же это не использовать, то подключение начинает простаивать и за max вызовов функции someFunction пул полностью забивается бесполезными подключениями, а pool.connect() в свою очередь делает ошибку.
  // connection.release();
  
  // Ставлю вызов этой же функции через несколько секунд
  setTimeout(() => {
    someFunction().then(() => {}).catch((e) => {
      console.log(e);
    })
  }, 5000);
}

someFunction().then(() => {}).catch((e) => {console.log(e);});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Uspensky, 2018-08-15
@andreyyka

A couple of years ago I tried to rivet a demo application on a node to my requirements: a complete failure. Libraries for working with pg are underdeveloped in the trash.
Regarding the pool, you can solve it the other way: pgBouncer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question