{"id":15756,"library":"pg-pool","title":"PostgreSQL Connection Pool","description":"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.","status":"active","version":"3.13.0","language":"javascript","source_language":"en","source_url":"git://github.com/brianc/node-postgres","tags":["javascript","pg","postgres","pool","database"],"install":[{"cmd":"npm install pg-pool","lang":"bash","label":"npm"},{"cmd":"yarn add pg-pool","lang":"bash","label":"yarn"},{"cmd":"pnpm add pg-pool","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"pg-pool is built on top of node-postgres and requires it as a peer dependency for database connectivity.","package":"pg","optional":false}],"imports":[{"note":"pg-pool exports the Pool constructor as its default (module.exports) in CommonJS. Destructuring will result in `undefined`.","wrong":"const { Pool } = require('pg-pool')","symbol":"Pool","correct":"const Pool = require('pg-pool')"},{"note":"When using ESM syntax to import this CommonJS package, the default export (the Pool constructor) is accessed directly, not via named import destructuring.","wrong":"import { Pool } from 'pg-pool'","symbol":"Pool (ESM)","correct":"import Pool from 'pg-pool'"},{"note":"For TypeScript type imports, follow the same pattern as runtime ESM imports to correctly resolve the default export of the CommonJS module.","wrong":"import type { Pool } from 'pg-pool'","symbol":"Pool (TypeScript Type)","correct":"import type Pool from 'pg-pool'"}],"quickstart":{"code":"const Pool = require('pg-pool');\nconst { URL } = require('url'); // Node.js built-in URL parser\n\n// In a real application, ensure process.env.DATABASE_URL is set,\n// e.g., DATABASE_URL=postgres://user:password@localhost:5432/mydatabase\nconst databaseUrl = process.env.DATABASE_URL || 'postgres://testuser:testpass@localhost:5432/testdb';\n\nconst params = new URL(databaseUrl);\nconst auth = params.username && params.password ? params.username.split(':') : [params.username, params.password];\n\nconst config = {\n  user: auth[0],\n  password: auth[1],\n  host: params.hostname,\n  port: parseInt(params.port || '5432'), // Default PostgreSQL port\n  database: params.pathname.split('/')[1],\n  ssl: params.protocol === 'https:' || (process.env.NODE_ENV === 'production' && databaseUrl.includes('sslmode=require')), // Use SSL in production or if protocol specifies\n  max: 10, // Max clients in the pool\n  idleTimeoutMillis: 30000, // Close idle clients after 30 seconds\n  connectionTimeoutMillis: 2000, // Return error after 2 seconds if connection not established\n};\n\nconst pool = new Pool(config);\n\n(async () => {\n  let client;\n  try {\n    // Acquire a client from the pool\n    client = await pool.connect();\n    console.log('Client acquired from pool.');\n\n    // Execute a query using the client\n    const res = await client.query('SELECT $1::text as message', ['Hello from pg-pool with async/await!']);\n    console.log('Query result:', res.rows[0].message);\n\n    // Demonstrate direct pool.query (acquires, queries, and releases client automatically)\n    const timeRes = await pool.query('SELECT NOW() as current_time');\n    console.log('Current database time via direct query:', timeRes.rows[0].current_time);\n\n  } catch (err) {\n    console.error('Database operation failed:', err.message, err.stack);\n  } finally {\n    // Release the client back to the pool to prevent resource leaks\n    if (client) {\n      client.release();\n      console.log('Client released back to pool.');\n    }\n    // It's good practice to end the pool when the application is shutting down\n    // For a quickstart, we end it here, but in a real app it's usually on process exit.\n    await pool.end();\n    console.log('Pool has been ended.');\n  }\n})();","lang":"javascript","description":"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."},"warnings":[{"fix":"Use `const { URL } = require('url');` to parse your `process.env.DATABASE_URL` into a configuration object with `user`, `password`, `host`, `port`, and `database` properties.","message":"The `Pool` constructor does not accept a database URL string directly. Developers must manually parse the URL (e.g., using Node.js's built-in `URL` module) into a configuration object before passing it to the Pool constructor.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Monitor connection metrics and client acquisition times if `maxUses` is enabled. Adjust the value based on your application's workload and desired connection lifetime.","message":"The `maxUses` configuration option causes a client to be disconnected and replaced after it has been used a specified number of times. While useful for preventing resource leaks in long-running applications, it can lead to unexpected connection churn if not understood, potentially impacting performance due to frequent client recreation.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Ensure `pg` is installed in your project: `npm install pg`. Check your `package.json` for compatible versions of `pg` as specified by `pg-pool`'s peer dependency.","message":"`pg-pool` requires `node-postgres` (`pg`) as a peer dependency. If `pg` is not installed or if its version does not meet `pg-pool`'s requirements (e.g., `>=8.0`), `pg-pool` will not function correctly.","severity":"gotcha","affected_versions":">=3.0"},{"fix":"Always ensure `client.release()` is called in a `finally` block when acquiring clients manually with `pool.connect()`. Consider using the `pool.query()` helper method for simple queries, as it automatically acquires and releases the client.","message":"Failing to release a client back to the pool after use (e.g., by omitting `client.release()` in a `finally` block) will exhaust the connection pool, causing subsequent `pool.connect()` calls to hang indefinitely or time out. This is a common source of application unresponsiveness.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Configure SSL explicitly. Use `ssl: true` for default behavior, and consider `ssl: { rejectUnauthorized: false }` only when absolutely necessary for self-signed certificates in development or tightly controlled environments. For production, ensure your database provides trusted certificates and enable `rejectUnauthorized: true`.","message":"While `ssl: true` is commonly used, its default behavior (e.g., `rejectUnauthorized`) can vary. In some environments (like Heroku), `ssl: { rejectUnauthorized: false }` might be necessary, but this reduces security. In production, ensure proper SSL certificate validation.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify that the PostgreSQL server is running and listening on the specified host and port (default 5432). Check firewall rules and ensure the database user has network access.","cause":"The application could not establish a connection to the PostgreSQL database. This usually indicates the database server is not running, is not accessible from the application's host, or has incorrect firewall rules.","error":"Error: connect ECONNREFUSED ::1:5432"},{"fix":"Ensure every `pool.connect()` call is paired with a `client.release()` call, typically within a `try...finally` block to guarantee release even if errors occur.","cause":"A client was acquired from the pool using `pool.connect()` but was not returned via `client.release()`, leading to resource exhaustion.","error":"Error: Client was not released to the pool"},{"fix":"For CommonJS, use `const Pool = require('pg-pool')`. For ESM, use `import Pool from 'pg-pool'`.","cause":"The `Pool` constructor was imported incorrectly, most commonly by trying to destructure a CommonJS default export (e.g., `const { Pool } = require('pg-pool')`) or by using a named import for a CommonJS default export in an ESM context (e.g., `import { Pool } from 'pg-pool'`).","error":"TypeError: Pool is not a constructor"},{"fix":"Review your `pg-pool` configuration object. Ensure all mandatory properties are present and their values are of the correct type (e.g., strings for `user`, `password`, `host`, `database`, number for `port`). Double-check your URL parsing logic if using `process.env.DATABASE_URL`.","cause":"A required configuration property (like `user`, `host`, `database`, `password`) for the `Pool` constructor is missing or has an incorrect type, often due to faulty URL parsing.","error":"Error: parameter \"user\" must be a string"}],"ecosystem":"npm"}