PostgreSQL Connection Pool

3.13.0 · active · verified Tue Apr 21

pg-pool is a specialized connection pooling library for Node.js applications using `node-postgres` to interact with PostgreSQL databases. Currently stable at version 3.13.0, it is actively maintained as part of the `node-postgres` family, with releases typically aligning with updates to the core `pg` client. This library is designed to improve application performance and reliability by managing a set of reusable database connections, thus reducing the overhead of repeatedly establishing and tearing down connections. Key features include configurable connection limits (`max`), idle timeouts (`idleTimeoutMillis`), connection establishment timeouts (`connectionTimeoutMillis`), and the ability to replace connections after a certain number of uses (`maxUses`). A crucial differentiator from some other database clients is that `pg-pool` does not directly accept a database URL string; instead, developers must parse the URL into a configuration object before passing it to the Pool constructor. It offers a modern, promise-based API that integrates smoothly with `async/await` patterns, simplifying resource management (client acquisition and release) compared to manual connection handling. It also supports pooling both the standard `pg.Client` and `pg.native.Client` instances.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `pg-pool` by parsing a database URL, acquire and release clients using `async/await`, and use the convenient `pool.query` helper, along with proper error handling and pool shutdown.

const Pool = require('pg-pool');
const { URL } = require('url'); // Node.js built-in URL parser

// In a real application, ensure process.env.DATABASE_URL is set,
// e.g., DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
const databaseUrl = process.env.DATABASE_URL || 'postgres://testuser:testpass@localhost:5432/testdb';

const params = new URL(databaseUrl);
const auth = params.username && params.password ? params.username.split(':') : [params.username, params.password];

const config = {
  user: auth[0],
  password: auth[1],
  host: params.hostname,
  port: parseInt(params.port || '5432'), // Default PostgreSQL port
  database: params.pathname.split('/')[1],
  ssl: params.protocol === 'https:' || (process.env.NODE_ENV === 'production' && databaseUrl.includes('sslmode=require')), // Use SSL in production or if protocol specifies
  max: 10, // Max clients in the pool
  idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
  connectionTimeoutMillis: 2000, // Return error after 2 seconds if connection not established
};

const pool = new Pool(config);

(async () => {
  let client;
  try {
    // Acquire a client from the pool
    client = await pool.connect();
    console.log('Client acquired from pool.');

    // Execute a query using the client
    const res = await client.query('SELECT $1::text as message', ['Hello from pg-pool with async/await!']);
    console.log('Query result:', res.rows[0].message);

    // Demonstrate direct pool.query (acquires, queries, and releases client automatically)
    const timeRes = await pool.query('SELECT NOW() as current_time');
    console.log('Current database time via direct query:', timeRes.rows[0].current_time);

  } catch (err) {
    console.error('Database operation failed:', err.message, err.stack);
  } finally {
    // Release the client back to the pool to prevent resource leaks
    if (client) {
      client.release();
      console.log('Client released back to pool.');
    }
    // It's good practice to end the pool when the application is shutting down
    // For a quickstart, we end it here, but in a real app it's usually on process exit.
    await pool.end();
    console.log('Pool has been ended.');
  }
})();

view raw JSON →