Connecting from Node.js with a Connection Pool
Applications typically use a connection pool to reuse database connections rather than creating a new connection for every query. Pool size should be considered across all application instances, not just one process: several replicas each configured with a large pool can exhaust the database's connection limit. Set timeouts, handle errors, and release checked-out clients reliably.
Keep database credentials in environment configuration or a secret manager. A connection pool manages connectivity, not authorization; the database role still needs appropriately scoped privileges.
Use node-postgres safely
import pg from "pg";
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000
});
const result = await pool.query(
"SELECT id, name FROM customers WHERE id = $1",
[customerId]
);💡 This example uses the
pg package. Choose a pool size based on total application replicas and database capacity, and ensure the application closes the pool during graceful shutdown.Key Takeaways
- Use a pool for typical server applications.
- Calculate total connections across all replicas.
- Use bound parameters and graceful shutdown handling.
Knowledge Check
Why can a pool size of 20 per process be dangerous with many replicas?