Databases2 minutes to readChecked

Use a PostgreSQL connection pool in a hosted Node.js app

Create one TLS-verified node-postgres pool per process, set a connection budget, and diagnose database timeouts without leaking app credentials.

Budget connections across web apps and workers

Reuse one pool for each long-running Node.js process that connects to PostgreSQL. Creating a pool for each request can turn a brief traffic burst into many database connections. If one web process and two workers each have a pool with a maximum of four, they can use up to twelve connections together.

Leave capacity for administrative clients, scheduled jobs, and restarts where two processes may briefly overlap. Check your database with SHOW max_connections and choose a lower per-process cap based on the number of clients. Test your own workload before increasing it. node-postgres pool options.

Create a TLS-verified pool once

Install pg in your server’s package. Set DB_HOST and DB_PORT from the database’s Connection page. Put the two PEM files in a private location readable by your server process. Set the file paths in your app’s Variables. The downloaded client PEM contains both the certificate and its private key.

db.mjs with a small example pool
import { readFileSync } from 'node:fs';
import pg from 'pg';

const identity = readFileSync(process.env.DB_CLIENT_PEM);
export const pool = new pg.Pool({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT),
  database: 'app',
  user: 'app',
  ssl: {
    ca: readFileSync(process.env.DB_CA_PEM),
    cert: identity,
    key: identity,
    rejectUnauthorized: true,
  },
  max: 4,
  connectionTimeoutMillis: 3000,
});
pool.on('error', () => console.error('Idle database connection failed'));

Use the database hostname for certificate verification. This example keeps the TLS settings in the pool configuration. node-postgres TLS options.

Check a session and watch for clients waiting

Run await pool.query('SELECT current_database(), current_user') through the deployed server or a manual script with the same configuration. Both values should be app. Reuse pool.query for single statements. For a transaction, acquire one client, use it for all statements and release it in a finally block.

If pool.waitingCount grows while the connection count stays at the configured maximum, check for slow queries and clients that were never released. If a single connection times out, confirm the engine state, hostname, port and allowed client IP list when shown. Test with the certificate-based psql connection to isolate driver configuration.