Belajar
← All lessons

How connection pooling works

What a new connection costs

App
Pool
Database

connect.js

// a new connection for every requestconst client = new pg.Client(config);await client.connect(); // TCP, TLS and auth: 6 round tripsconst { rows } = await client.query("SELECT * FROM orders WHERE id = $1", [42]);await client.end(); // or: keep connections open and reuse themconst pool = new pg.Pool({ ...config, max: 10 });const res = await pool.query("SELECT * FROM orders WHERE id = $1", [42]);

wire.txt

SYN  ->  SYN-ACKSSLRequest  ->  'S'ClientHello  ->  ServerHello ... FinishedStartupMessage  ->  AuthenticationSASLSASLInitialResponse  ->  AuthenticationSASLContinueSASLResponse  ->  AuthenticationSASLFinal, AuthenticationOk, ..., ReadyForQueryQuery  ->  RowDescription, DataRow, CommandComplete

A burst against a pool waiting for a free connection

Pool size3

Each query takes 300 ms. A request gives up after waiting 1000 ms

Waiting
Connections
Finished

pool.js

const pool = new pg.Pool({  max: 3,                          // pool size  connectionTimeoutMillis: 1000,}); async function handle(req) {  const client = await pool.connect(); // waits here when every connection is busy  try {    return await client.query("SELECT * FROM orders WHERE id = $1", [req.id]);  } finally {    client.release(); // back to the pool, not closed  }}

Too many connections app servers vs max_connections

App servers2
Pool size on each10
In betweennothingPgBouncer
max_connections = 100

Every Postgres connection is a whole OS process. Hundreds of idle ones still cost memory and slow the server

postgresql.conf

# postgresql.conf, one process per connectionmax_connections = 100superuser_reserved_connections = 3

pgbouncer.ini

# pgbouncer.ini[databases]app = host=10.0.0.5 dbname=app [pgbouncer]pool_mode = transactionmax_client_conn = 1000default_pool_size = 20

Topics

Next: How message queues work

Open lesson