question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

pool.end() not working

See original GitHub issue

Hi folks, currently writing integration tests with jest and facing some troubles with closing pool.

Per docs pool can be closed by calling pool.end(), but for me pool still exists.

Please observe code below.

const { Pool } = require('pg');
const logger = {
  info: console.log
};

const connectionString = "the_connection_string";
const dbName = "the_db";

let pool = null;

const initClient = async () => {
  if (!pool) {
    pool = new Pool({
      connectionString: `${connectionString}/${dbName}`,
      max: 1,
      min: 1,
      idleTimeoutMillis: 1000,
    });

    pool.connect((err) => {
      if (err) {
        logger.error(`Can not connect to postgres at host ${connectionString}, ${err.stack}`);
      } else {
        logger.info(`Postgres connected to host: '${connectionString}'`);
      }
    });
  }

  return pool;
};


initClient();

setTimeout(() => {
   pool.end(() => {
      console.log('pool has ended'); // cb never called
});

   /pool.end().then(() => console.log('pool has ended')) // promise never called
}, 5000);

setInterval(() => {
   console.log(pool.ended); // always false.
}, 3000);


module.exports = {
  initClient,
};

So pool created instantly by calling initClient(), after 5 second pool.ended() called, but it’s callback never called. pool.ended always show false.

Am i doing something wrong or any ideas how to close pool?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

6reactions
charmandercommented, Dec 20, 2019

The pool won’t call the end callback until all the clients have been returned to it (because it can’t close clients it doesn’t own). You need to release the client you acquired with pool.connect:

pool.connect((err, client) => {
  if (err) {
    logger.error(`Can not connect to postgres at host ${connectionString}, ${err.stack}`);
  } else {
    logger.info(`Postgres connected to host: '${connectionString}'`);
    client.release();
  }
});

initClient still mixes async and callbacks in a way that doesn’t make much sense, though.

0reactions
Tchoupinaxcommented, Dec 22, 2019

Same issue for me, i called the end function on my pool and something happens because pool.ended becomes true after it.

  log: [Function (anonymous)],
  Client: [Function: Client] { Query: [Function: Query] },
  Promise: [Function: Promise],
  _clients: [],
  _idle: [],
  _pendingQueue: [],
  _endCallback: [Function: cb],
  ending: true,
  ended: true

However, mocha tests does not give back terminal control and it comes from postgres… (It works well when no connection has been created).

I called pool.end(), i waited > 1 minute, ended is marked as “ended” but when i stopped Postgres, Node.js process has crashed.

events.js:196
      throw er; // Unhandled 'error' event
      ^

error: terminating connection due to unexpected postmaster exit

It shows that the connection keeps alive.

    _Promise: [Function: Promise],
    _types: TypeOverrides { _types: [Object], text: {}, binary: {} },
    _ending: true,
    _connecting: false,
    _connected: true, <= ????
    _connectionError: false,
    _queryable: false,
    connection: Connection {
      _events: [Object: null prototype],
      _eventsCount: 22,
      _maxListeners: undefined,
      stream: [Socket],
      _keepAlive: false,
      _keepAliveInitialDelayMillis: 0,
      lastBuffer: false,
      lastOffset: 0,
      buffer: null,
      offset: 111,
      encoding: 'utf8',
      parsedStatements: [Object],
      writer: [Object],
      ssl: false,
      _ending: true,
      _mode: 0,
      _emitMessage: false,
      _reader: [Object]
    },
    queryQueue: [],
    binary: false,
    processID: 64,
    secretKey: -2040677091,
    ssl: false,
    _connectionTimeoutMillis: 300000,
    release: [Function (anonymous)],
    activeQuery: null,
    readyForQuery: true,
    hasExecuted: true
  }

It is not the first time i met this problem and i would like to understand…

My pool is created as the following

let postgresql = new pg.Pool({
  ...config.postgres,
  connectionTimeoutMillis: 500,
  Client: pg.NativeClient,
});

// Query function
    return postgresql.connect()
      .then((client) => client.query(args)
        .then((res) => {
          client.release();
          return res;
        })
        .catch((err) => {
          client.release();
          throw err;
        }));
Read more comments on GitHub >

github_iconTop Results From Across the Web

When should I use pool.end() - node.js - Stack Overflow
1. You should close the connection only when you dont want to perform queries any more. like close/shutdown the server/program. · So const...
Read more >
Connecting – node-postgres
Connection URI. You can initialize both a pool and a client with a connection string URI as well. This is common in environments...
Read more >
Connection Pools with MariaDB Connector/Node.js (Promise ...
pool.end() → Promise. Ends or closes the connection pool and the underlying connections after all running queries have completed. Returns a Promise object ......
Read more >
Connection pools - psycopg 3.1.8.dev1 documentation
Ideally you may want to call close() when the use of the pool is finished. Failing to call close() at the end of...
Read more >
How do you work with closing pools/connections?
Closing the Pool using pool.end() will gracefully close all open Connections (not just the current). You'd need to recreate the Pool to get ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found