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 | สำหรับ | จุดเด่น |
|---|---|---|
| PgBouncer | PostgreSQL | Lightweight, transaction-level pooling |
| pgpool-II | PostgreSQL | Load balancing + pooling |
| ProxySQL | MySQL | Query routing + pooling |
PgBouncer Pooling Modes
| Mode | ความหมาย |
|---|---|
| Session | 1 client = 1 connection ตลอด session |
| Transaction | connection กลับ pool หลัง commit (แนะนำ) |
| Statement | connection กลับ 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
Related
- PostgreSQL — PgBouncer, pgpool-II
- MySQL — ProxySQL
- Database Security — TLS handshake cost ที่ pooling ช่วยลด
- Database Replication — pgpool-II ทำ load balancing ไป replicas ได้