// Replication & HA

PostgreSQL Replication & HA

สร้างระบบ High Availability ด้วย PostgreSQL Streaming Replication, Logical Replication และ Automatic Failover

🔄
Streaming Replication
Physical Replication ระดับ Block — Replica ใช้ WAL Stream จาก Primary แบบ Real-time
📡
Logical Replication
Replicate เฉพาะบาง Table หรือ Database — ข้ามเวอร์ชัน PostgreSQL ได้
🏗️
Patroni
Framework HA อัตโนมัติ — Auto Failover, Leader Election ด้วย etcd/Consul/ZooKeeper
⚖️
pgBouncer
Connection Pooler — ลด Connection Overhead จาก Application
🔀
HAProxy / pgpool-II
Load Balancer — กระจาย Read Queries ไป Replica หลายตัว
🔁
pg_auto_failover
Automatic Failover แบบ Simple Setup — เหมาะสำหรับ 2-3 Nodes
// Architecture

HA Architecture ที่แนะนำ

┌─────────────────────────────────────────────┐ │ Load Balancer (HAProxy) │ │ Port 5432 → Primary (Write) │ │ Port 5433 → Replicas (Read) │ └──────────┬──────────────────┬────────────────┘ │ │ ┌──────▼──────┐ ┌───────▼─────┐ │ PRIMARY │ │ STANDBY 1 │ │ PostgreSQL │──►│ PostgreSQL │ │ (Write) │ │ (Read) │ └─────────────┘ └─────────────┘ ┌──────▼──────┐ │ STANDBY 2 │ │ (DR Site) │ └─────────────┘ -- Patroni: ตรวจสอบสถานะ Cluster $ patronictl -c /etc/patroni/config.yml list -- ดู Replication Lag SELECT client_addr, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn)) AS lag FROM pg_stat_replication;