Connection Pooling

Pre-establish connections ไว้แล้ว reuse — ลด overhead ของ TCP + TLS handshake ที่เกิดทุก request

ทำไมต้อง Pooling?

เปิด connection ใหม่ทุก request:

  • TCP handshake: ~1-3 ms
  • TLS handshake: ~5-50 ms
  • DB authentication: ~5-50 ms
  • รวม: 10-100ms overhead ต่อ request

Pooling = pre-establish connections → reuse → 0 overhead

ตัวอย่างใน Node.js

const { Pool } = require('pg');
const pool = new Pool({
  max: 20,           // max connections in pool
  idleTimeoutMillis: 30000,
});
 
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
// connection กลับเข้า pool อัตโนมัติ

External Poolers

Poolerสำหรับจุดเด่น
PgBouncerPostgreSQLLightweight, transaction-level pooling
pgpool-IIPostgreSQLLoad balancing + pooling
ProxySQLMySQLQuery routing + pooling

PgBouncer Pooling Modes

Modeความหมาย
Session1 client = 1 connection ตลอด session
Transactionconnection กลับ pool หลัง commit (แนะนำ)
Statementconnection กลับ pool หลังทุก statement (จำกัดมาก)

Key Points

  • TCP + TLS handshake = 10-100ms ต่อ connection → pooling ลดเหลือ 0
  • PgBouncer (transaction mode) = lightweight pooler ยอดนิยมสำหรับ Postgres
  • ProxySQL = pooler สำหรับ MySQL
  • Connection pool ใน application (เช่น HikariCP, pg-pool) ก็ช่วยได้ แต่ external pooler ดีกว่าเมื่อมีหลาย app servers