ข้ามไปที่เนื้อหา

PostgreSQL High Availability ด้วย Patroni: ฉบับปี 2026

รัน PostgreSQL แค่ instance เดียวใน production เท่ากับแบกความเสี่ยงไว้เต็ม ๆ วันไหน database ล่ม (และวันนั้นมาแน่) application ก็ล่มตามไปด้วย สำหรับ database ใน production แล้ว high availability ไม่ใช่ของเสริม แต่เป็นขั้นต่ำที่ต้องมี

ไกด์นี้พาสร้าง PostgreSQL HA cluster ระดับ production ด้วย community stack ที่ open-source ทั้งชุด: PostgreSQL 17 จาก PGDG, Patroni 4.x, etcd 3.5, pgbackrest 2.58 และ HAProxy ไม่มี package ของ vendor เจ้าไหน ไม่ต้องพึ่ง repository แบบ proprietary ทุกอย่างรันบน Rocky Linux 9 หรือ AlmaLinux 9 และเป็น open-source ล้วน


หน้าตาของระบบที่จะสร้าง

                        ┌─────────────────────────────┐
   Applications         │         HAProxy              │
   ──────────►          │  :5000 (writes → primary)    │
                        │  :5001 (reads → replicas)    │
                        └──────┬──────┬──────┬─────────┘
                               │      │      │
                               ▼      ▼      ▼
                          ┌────┐  ┌────┐  ┌────┐
                          │pg1 │  │pg2 │  │pg3 │  ← PostgreSQL 17 + Patroni 4
                          │    │  │    │  │    │
                          │etcd│  │etcd│  │etcd│  ← etcd 3.5 (DCS)
                          └────┘  └────┘  └────┘
                               │      │      │
                               └──────┴──────┘
                                      │
                                      ▼
                               ┌─────────────┐
                               │  S3 Bucket  │  ← pgbackrest 2.58 backups
                               └─────────────┘

ใช้ทั้งหมด 4 host:

Host IP Role
pg1 172.31.47.229 PostgreSQL primary (ช่วงแรก) + etcd
pg2 172.31.34.169 PostgreSQL replica + etcd
pg3 172.31.39.118 PostgreSQL replica + etcd
haproxy 172.31.10.50 HAProxy load balancer

เวอร์ชันที่ใช้ (พฤษภาคม 2026):

Component Version Source
Rocky/AlmaLinux 9.x OS
PostgreSQL 17.x PGDG community repo
Patroni 4.1.3 pip (PyPI)
etcd 3.5.x GitHub binary release
pgbackrest 2.58.0 PGDG community repo
HAProxy 2.4+ EPEL / system repo

Part 1: เตรียม OS (ทุก PostgreSQL node)

ทำทุกขั้นในส่วนนี้บน pg1, pg2 และ pg3

1.1 Hostname และ /etc/hosts

# On pg1
hostnamectl set-hostname pg1

# On all nodes, add to /etc/hosts:
cat >> /etc/hosts << 'EOF'
172.31.47.229 pg1 pg1.example.com
172.31.34.169 pg2 pg2.example.com
172.31.39.118 pg3 pg3.example.com
EOF

1.2 SELinux และ Firewall

ถ้าเป็น private network ที่คุมได้เอง ปิดทั้งสองตัวไปเลย จะได้ไม่ยุ่งยาก:

setenforce 0
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

systemctl stop firewalld
systemctl disable firewalld

แต่ถ้า security policy บังคับให้เปิด firewall ไว้ ก็เปิด port เหล่านี้แทน:

firewall-cmd --permanent --add-port={2379,2380,5432,8008}/tcp
firewall-cmd --reload

1.3 Kernel Parameters

เพิ่มค่าเหล่านี้ใน /etc/sysctl.conf บนทุก PostgreSQL node:

# Shared memory
kernel.shmall = 2097152
kernel.shmmax = 134217728
kernel.shmmni = 4096

# Memory overcommit — prevents OOM kills during large sorts
vm.overcommit_memory = 2
vm.overcommit_ratio = 80

# Network tuning
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 10000
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 10

# File handles
fs.file-max = 65536

แล้ว apply ทันที:

sysctl -p

1.4 Process Limits

เพิ่มใน /etc/security/limits.conf:

postgres soft nofile 65536
postgres hard nofile 65536
postgres soft nproc 16384
postgres hard nproc 16384

Part 2: ติดตั้ง etcd (ทุก PostgreSQL node)

etcd คือ distributed configuration store (DCS) ที่ Patroni ใช้เลือก leader และเก็บ state ของ cluster ในไกด์นี้รัน etcd 3 node บนเครื่องเดียวกับ PostgreSQL เลย

2.1 ติดตั้ง etcd Binary

ETCD_VER=v3.5.21
DOWNLOAD_URL=https://github.com/etcd-io/etcd/releases/download

wget ${DOWNLOAD_URL}/${ETCD_VER}/etcd-${ETCD_VER}-linux-amd64.tar.gz
tar xzf etcd-${ETCD_VER}-linux-amd64.tar.gz
sudo mv etcd-${ETCD_VER}-linux-amd64/etcd* /usr/local/bin/
rm -rf etcd-${ETCD_VER}-linux-amd64*

etcd --version   # verify

2.2 สร้าง etcd User และ Directory

sudo groupadd --system etcd
sudo useradd -s /sbin/nologin --system -g etcd etcd

sudo mkdir -p /var/lib/etcd /etc/etcd
sudo chown -R etcd:etcd /var/lib/etcd
sudo chmod 0700 /var/lib/etcd

2.3 ไฟล์ config ของ etcd

สร้าง /etc/etcd/etcd.conf บนทุก node แล้วเปลี่ยน IP ให้ตรงกับแต่ละ host

pg1 (172.31.47.229):

cat > /etc/etcd/etcd.conf << 'EOF'
ETCD_NAME=pg1
ETCD_DATA_DIR=/var/lib/etcd
ETCD_LISTEN_PEER_URLS=http://172.31.47.229:2380
ETCD_LISTEN_CLIENT_URLS=http://172.31.47.229:2379,http://127.0.0.1:2379
ETCD_INITIAL_ADVERTISE_PEER_URLS=http://172.31.47.229:2380
ETCD_ADVERTISE_CLIENT_URLS=http://172.31.47.229:2379
ETCD_INITIAL_CLUSTER=pg1=http://172.31.47.229:2380,pg2=http://172.31.34.169:2380,pg3=http://172.31.39.118:2380
ETCD_INITIAL_CLUSTER_STATE=new
ETCD_INITIAL_CLUSTER_TOKEN=pg-etcd-cluster-01
EOF

pg2 (172.31.34.169) — ใช้เนื้อหาเดียวกัน แค่เปลี่ยนเป็นค่าของ pg2
pg3 (172.31.39.118) — ใช้เนื้อหาเดียวกัน แค่เปลี่ยนเป็นค่าของ pg3

2.4 etcd systemd Service

cat > /etc/systemd/system/etcd.service << 'EOF'
[Unit]
Description=etcd distributed key-value store
Documentation=https://etcd.io/docs/
After=network-online.target
Wants=network-online.target

[Service]
User=etcd
Type=notify
EnvironmentFile=/etc/etcd/etcd.conf
ExecStart=/usr/local/bin/etcd
Restart=on-failure
RestartSec=10s
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now etcd

2.5 ตรวจสอบ etcd Cluster

# Set API version for v3 commands
export ETCDCTL_API=3

etcdctl --endpoints=http://127.0.0.1:2379 member list -w table
etcdctl --endpoints=http://172.31.47.229:2379,http://172.31.34.169:2379,http://172.31.39.118:2379 endpoint health -w table
etcdctl --endpoints=http://172.31.47.229:2379,http://172.31.34.169:2379,http://172.31.39.118:2379 endpoint status -w table

ที่ควรเห็น: member ครบ 3 ตัว healthy ทั้งหมด และมีตัวหนึ่งขึ้น IS LEADER=true


Part 3: ติดตั้ง PostgreSQL (ทุก PostgreSQL node)

3.1 ติดตั้ง PGDG Repository

PGDG (PostgreSQL Global Development Group) repository คือแหล่ง package ทางการของ community สำหรับ PostgreSQL ทุกเวอร์ชัน ติดตั้ง RPM ตัวเดียวก็ได้ทุกเวอร์ชันที่ยัง support อยู่

# Install PGDG repo
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# Disable the built-in PostgreSQL module (conflicts with PGDG packages)
sudo dnf -qy module disable postgresql

# Install PostgreSQL 17
sudo dnf install -y postgresql17-server postgresql17-contrib

เสร็จแล้วจะได้ PostgreSQL 17 ที่มี binary อยู่ใน /usr/pgsql-17/bin/ และ data directory default อยู่ที่ /var/lib/pgsql/17/data/

3.2 ติดตั้ง pgbackrest

pgbackrest มีอยู่ใน PGDG repo แล้ว ไม่ต้องตั้งค่าอะไรเพิ่ม:

sudo dnf install -y pgbackrest

3.3 อย่าเพิ่งรัน initdb

ตอนบูตครั้งแรก Patroni จะรัน initdb สร้าง data directory ของ PostgreSQL ให้เอง ถ้าไปรันเองก่อนจะชนกัน เพราะฉะนั้นข้าม postgresql-17-setup initdb ไปเลย


Part 4: ติดตั้ง Patroni (ทุก PostgreSQL node)

ติดตั้ง Patroni 4.x ผ่าน pip จะได้เวอร์ชันล่าสุด ต้องมี Python 3.9+

4.1 ติดตั้ง Dependencies

sudo dnf install -y python3 python3-pip python3-devel gcc

4.2 ติดตั้ง Patroni

ติดตั้งด้วย system user postgres พร้อม extras etcd3 และ psycopg3:

sudo -u postgres pip3 install --user 'patroni[psycopg3,etcd3]'

# Add to postgres user's PATH
echo 'export PATH=$HOME/.local/bin:/usr/pgsql-17/bin:$PATH' >> /var/lib/pgsql/.bash_profile
source /var/lib/pgsql/.bash_profile

patroni --version   # should show Patroni 4.1.x

ทำไมต้อง psycopg3?

Patroni 4.x ใช้ psycopg3 (PostgreSQL adapter รุ่นใหม่) เป็น default ส่วน psycopg2 ตัวเก่าก็ยังใช้ได้ แต่ psycopg3 รองรับ async และจัดการ async connection ได้ดีกว่า ถ้าติดตั้งใหม่ให้เลือกตัวนี้


Part 5: ตั้งค่า Patroni (ทุก PostgreSQL node)

สร้าง /var/lib/pgsql/patroni.yml บนทุก node ค่าที่ต่างกันในแต่ละ node มีแค่ name, restapi.listen, restapi.connect_address, postgresql.listen และ postgresql.connect_address นอกนั้นเหมือนกันหมด

5.1 ไฟล์ config ของ Patroni

pg1 (172.31.47.229):

scope: pg_cluster
name: pg1

restapi:
  listen: '172.31.47.229:8008'
  connect_address: '172.31.47.229:8008'

# etcd3 section — uses etcd v3 API (recommended for etcd 3.5+)
etcd3:
  hosts: 'pg1:2379,pg2:2379,pg3:2379'
  protocol: http

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    postgresql:
      use_pg_rewind: true
      use_slots: true
      parameters:
        hot_standby: 'on'
        wal_keep_size: 256MB        # replaces deprecated wal_keep_segments
        max_wal_senders: 10
        max_replication_slots: 10
        wal_level: replica
        archive_command: 'pgbackrest --stanza=pg_cluster archive-push %p'
        archive_mode: 'on'

  initdb:
    - encoding: UTF8
    - locale: en_US.UTF-8
    - data-checksums            # enables page checksums — catches data corruption

  pg_hba:
    - local all all trust
    - host all postgres 0.0.0.0/0 trust
    - host replication replicator 172.31.47.229/32 scram-sha-256
    - host replication replicator 172.31.34.169/32 scram-sha-256
    - host replication replicator 172.31.39.118/32 scram-sha-256
    - host all all 0.0.0.0/0 scram-sha-256

  users:
    admin:
      password: 'ChangeMe2026!'
      options:
        - createrole
        - createdb

postgresql:
  listen: '172.31.47.229:5432'
  connect_address: '172.31.47.229:5432'
  bin_dir: /usr/pgsql-17/bin
  data_dir: /var/lib/pgsql/17/data
  pgpass: /tmp/pgpass0

  authentication:
    replication:
      username: replicator
      password: 'Rep-Pass-2026!'
    superuser:
      username: postgres
      password: 'PgSuperPass2026!'
    rewind:
      username: rewind_user
      password: 'Rewind-Pass-2026!'

  create_replica_methods:
    - pgbackrest
    - basebackup

  pgbackrest:
    command: 'pgbackrest --stanza=pg_cluster --delta restore'
    keep_data: true
    no_params: true

  basebackup:
    checkpoint: fast

tags:
  nofailover: false
  noloadbalance: false
  clonefrom: false
  nosync: false

pg2 และ pg3: ใช้ไฟล์เดียวกัน เปลี่ยน name: เป็น pg2/pg3 แล้วแก้ IP ทั้งใน section restapi และ postgresql

เปลี่ยน password ทั้งหมด

password ในไฟล์นี้เป็นแค่ตัวอย่าง เปลี่ยนให้หมดก่อน deploy ใน production ให้เก็บไว้ใน secrets manager หรือ Ansible vault อย่าเก็บ credential เป็น plaintext ในไฟล์ config ที่ commit เข้า git

5.2 Patroni systemd Service

cat > /etc/systemd/system/patroni.service << 'EOF'
[Unit]
Description=Patroni — HA PostgreSQL orchestrator
After=syslog.target network.target etcd.service
Wants=etcd.service

[Service]
Type=simple
User=postgres
Group=postgres
Environment=PATH=/var/lib/pgsql/.local/bin:/usr/pgsql-17/bin:/usr/local/bin:/usr/bin:/bin
Environment=PGDATA=/var/lib/pgsql/17/data
ExecStart=/var/lib/pgsql/.local/bin/patroni /var/lib/pgsql/patroni.yml
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=process
TimeoutSec=30
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now patroni

5.3 ตรวจสอบ Cluster

ดู log ระหว่างที่ Patroni initialize พอ start ครั้งแรก จะมี node หนึ่งขึ้นเป็น primary และสร้าง data directory ให้:

journalctl -u patroni -f

เช็คสถานะ cluster:

patronictl -c /var/lib/pgsql/patroni.yml list

ที่ควรเห็น:

+ Cluster: pg_cluster (7234567890123456789) ----+----+-----------+
| Member | Host            | Role    | State   | TL | Lag in MB |
+--------+-----------------+---------+---------+----+-----------+
| pg1    | 172.31.47.229:5432 | Leader  | running |  1 |           |
| pg2    | 172.31.34.169:5432 | Replica | running |  1 |         0 |
| pg3    | 172.31.39.118:5432 | Replica | running |  1 |         0 |
+--------+-----------------+---------+---------+----+-----------+

Part 6: ตั้งค่า pgbackrest (ทุก PostgreSQL node)

6.1 สร้าง Directory

sudo mkdir -p /var/log/pgbackrest /etc/pgbackrest /var/lib/pgbackrest
sudo chmod 0750 /var/lib/pgbackrest
sudo chmod 770 /var/log/pgbackrest
sudo touch /etc/pgbackrest/pgbackrest.conf
sudo chmod 640 /etc/pgbackrest/pgbackrest.conf
sudo chown -R postgres:postgres /var/lib/pgbackrest /var/log/pgbackrest /etc/pgbackrest

6.2 Config ของ pgbackrest

/etc/pgbackrest/pgbackrest.conf — ใช้เนื้อหาเดียวกันทั้งสาม node:

[pg_cluster]
pg1-path=/var/lib/pgsql/17/data
pg1-port=5432
pg1-user=postgres

[global]
start-fast=y
process-max=4
archive-timeout=300
compress-type=lz4          # lz4 is faster than gz; available in pgbackrest 2.38+

repo1-type=s3
repo1-path=/pgbackrest/pg_cluster
repo1-retention-full=4
repo1-retention-diff=14

repo1-s3-bucket=your-pgbackrest-bucket
repo1-s3-endpoint=s3.ap-southeast-1.amazonaws.com
repo1-s3-key=YOUR_ACCESS_KEY
repo1-s3-key-secret=YOUR_SECRET_KEY
repo1-s3-region=ap-southeast-1
repo1-s3-uri-style=path

log-level-console=info
log-level-file=detail
log-path=/var/log/pgbackrest

[global:archive-push]
compress-level=3

6.3 Initialize และตรวจสอบ

รันบน primary (pg1) ที่เดียว:

sudo -u postgres pgbackrest --stanza=pg_cluster stanza-create
sudo -u postgres pgbackrest --stanza=pg_cluster check
sudo -u postgres pgbackrest --stanza=pg_cluster backup --type=full
sudo -u postgres pgbackrest info

6.4 ตั้งเวลา Backup

เพิ่มใน crontab ของ user postgres (crontab -u postgres -e):

# Full backup every Sunday at 01:00
0 1 * * 0  pgbackrest --type=full --stanza=pg_cluster backup
# Differential backup Mon-Sat at 01:00
0 1 * * 1-6  pgbackrest --type=diff --stanza=pg_cluster backup
# Incremental backup every 4 hours
0 */4 * * *  pgbackrest --type=incr --stanza=pg_cluster backup

Part 7: HAProxy Load Balancer (host haproxy)

7.1 ติดตั้ง HAProxy

sudo dnf install -y haproxy

7.2 Config ของ HAProxy

/etc/haproxy/haproxy.cfg:

global
    maxconn 1000
    log /dev/log local0

defaults
    log global
    mode tcp
    retries 2
    timeout client 30m
    timeout connect 4s
    timeout server 30m
    timeout check 5s

# Statistics dashboard
listen stats
    mode http
    bind *:7000
    stats enable
    stats uri /
    stats refresh 10s
    stats show-node

# Write traffic → primary only
# Patroni REST API: GET /primary returns 200 only on the current leader
listen postgres_write
    bind *:5000
    option httpchk GET /primary
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server pg1 172.31.47.229:5432 maxconn 100 check port 8008
    server pg2 172.31.34.169:5432 maxconn 100 check port 8008
    server pg3 172.31.39.118:5432 maxconn 100 check port 8008

# Read traffic → replicas, with primary as fallback
# Patroni REST API: GET /replica returns 200 only on replicas
listen postgres_read
    bind *:5001
    balance leastconn
    option httpchk GET /replica
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server pg1 172.31.47.229:5432 maxconn 100 check port 8008
    server pg2 172.31.34.169:5432 maxconn 100 check port 8008
    server pg3 172.31.39.118:5432 maxconn 100 check port 8008

Health check endpoint — อัปเดตปี 2026

ไกด์ฉบับปี 2024 ใช้ OPTIONS /master ใน Patroni 4.x /master ยังใช้ได้ในฐานะ alias เพื่อ compatibility แต่ endpoint หลักตอนนี้คือ /primary (สำหรับ leader) และ /replica (สำหรับ standby) และให้ใช้ GET แทน OPTIONS เพราะ option httpchk GET /primary ของ HAProxy อ่านง่ายกว่า และตรงกับ HTTP semantics มาตรฐาน

7.3 Start HAProxy

systemctl enable --now haproxy

ดูสถานะได้จาก stats dashboard ที่ http://172.31.10.50:7000


Part 8: Testing

8.1 ตรวจสอบ Replication

สร้างข้อมูลบน primary แล้วลองอ่านจาก replica:

# On any host — connects through HAProxy write port
psql -h 172.31.10.50 -p 5000 -U postgres << 'SQL'
CREATE DATABASE demo;
\c demo
CREATE TABLE orders (id serial, product text, created_at timestamptz DEFAULT now());
INSERT INTO orders (product) VALUES ('widget'), ('gadget'), ('doohickey');
SELECT * FROM orders;
SQL

# Read through HAProxy read port (hits a replica)
psql -h 172.31.10.50 -p 5001 -U postgres -d demo -c "SELECT * FROM orders;"

8.2 ทดสอบ Automatic Failover

หยุด Patroni บน primary ตัวปัจจุบัน แล้วดู cluster เลือก leader ตัวใหม่:

# On pg1 (the current primary)
sudo systemctl stop patroni

# On pg2 or pg3 — watch the election happen in seconds
watch -n2 "patronictl -c /var/lib/pgsql/patroni.yml list"

Patroni จะเลือก primary ตัวใหม่ ปกติไม่เกิน 30 วินาทีตามค่า ttl ส่วน HAProxy จะเห็นการเปลี่ยนแปลงผ่าน health check ภายใน ~10 วินาที แล้ว route write ไปที่ primary ตัวใหม่ให้เอง

พอ start primary ตัวเก่ากลับขึ้นมา ก็จะกลับเข้า cluster เป็น replica:

sudo systemctl start patroni

8.3 Planned Switchover

ถ้าจะทำ maintenance หรือ rolling upgrade ให้สั่ง switchover เองแบบควบคุมได้:

patronictl -c /var/lib/pgsql/patroni.yml switchover pg_cluster

Patroni จะถามว่าจะ promote node ไหน รอให้ replica ตามทันก่อน แล้วค่อย switchover โดยไม่เสียข้อมูลเลย


Part 9: Day-2 Operations

เปิด Synchronous Replication

สำหรับ workload ที่ห้ามเสียข้อมูลเด็ดขาด:

patronictl -c /var/lib/pgsql/patroni.yml edit-config --apply - --force << 'JSON'
{
  "synchronous_mode": true,
  "synchronous_mode_strict": true,
  "postgresql": {
    "parameters": {
      "synchronous_commit": "on"
    }
  }
}
JSON
patronictl -c /var/lib/pgsql/patroni.yml reload pg_cluster

Reinitialize replica ที่ข้อมูลเสีย

ถ้า data directory ของ replica เสีย หรือตามหลัง primary ไปไกลมาก:

patronictl -c /var/lib/pgsql/patroni.yml reinit pg_cluster pg2

Patroni จะสร้าง replica ขึ้นใหม่จาก pgbackrest (ทางเร็ว) หรือใช้ pg_basebackup (ทางสำรอง)

เปลี่ยน PostgreSQL Parameters

บน HA cluster อย่าไปแก้ postgresql.conf ตรง ๆ ให้ Patroni เป็นคนกระจายค่าใหม่ไปทุก node:

patronictl -c /var/lib/pgsql/patroni.yml edit-config

คำสั่งนี้เปิด $EDITOR พร้อม DCS configuration ปัจจุบัน แก้เสร็จแล้วค่าใหม่จะมีผลทั้ง cluster และเก็บไว้ใน etcd

Restore จาก pgbackrest Backup

ถ้าจะ restore ย้อนไปยังเวลาที่ต้องการบน cluster ใหม่:

sudo -u postgres pgbackrest --stanza=pg_cluster \
  --delta \
  --target="2026-05-25 14:30:00" \
  --target-action=promote \
  restore

Part 10: Disaster Recovery

HA ช่วยได้เวลา node พัง ภายใน site เดียว เช่น disk เสีย process crash หรือ kernel update พัง แต่ช่วยไม่ได้ถ้าเจอเหตุระดับ site เช่น data center ล่ม cloud region ดับ หรือข้อมูลเสียหายหนักแล้ว replicate ไปทุก replica ก่อนใครจะทันสังเกต

DR เลยต้องมีอีก site แยกออกมา และต้อง promote ขึ้นเป็น production ได้เองโดยไม่ต้องพึ่ง primary cluster

Section นี้ใช้สองวิธีที่เสริมกัน:

วิธี RTO RPO ความซับซ้อน
Patroni Standby Cluster (warm standby) 2–5 นาที ระดับวินาที ปานกลาง
pgbackrest PITR Restore (cold standby) 30–120 นาที สูงสุด 4 ชั่วโมง ต่ำ

ใช้ทั้งคู่: standby cluster ไว้ failover ตามแผนหรือตอนที่ต้องการความเร็ว ส่วน pgbackrest restore เป็นด่านสุดท้าย เผื่อ standby cluster เองก็ใช้ไม่ได้


10.1 DR Architecture

PRIMARY SITE (ap-southeast-1)           DR SITE (ap-southeast-2)
─────────────────────────────           ──────────────────────────
  HAProxy (:5000 write)                   HAProxy-DR (:5000 write)
     │                                         │
  pg1 (Leader) ──streaming──────────────► dr-pg1 (standby leader)
  pg2 (Replica)                           dr-pg2 (standby replica)
  pg3 (Replica)                           dr-pg3 (standby replica)
     │                                         │
     └──── pgbackrest ────► S3 (primary) ──S3 replication──► S3 (DR)

DR cluster stream ข้อมูลจาก leader ปัจจุบันของ primary cluster ผ่าน replication slot ที่กันไว้ให้โดยเฉพาะ พอสั่ง activate DR ตัว standby cluster จะขึ้นเป็น primary cluster อิสระได้ภายในไม่กี่นาที


10.2 เตรียม Primary Cluster สำหรับ DR

Primary cluster ต้องมี permanent replication slot ไว้ให้ DR standby cluster ใช้ ให้เพิ่ม slot นี้ใน section bootstrap.dcs ของ patroni.yml บนทุก node ของ primary site แล้ว apply ผ่าน edit-config:

patronictl -c /var/lib/pgsql/patroni.yml edit-config --apply - --force << 'JSON'
{
  "slots": {
    "patroni_standby_leader": {
      "type": "physical"
    }
  }
}
JSON

เช็คว่าบน primary มี slot นี้แล้ว:

psql -U postgres -c "SELECT slot_name, slot_type, active FROM pg_replication_slots;"

Monitor slot นี้

Replication slot ที่ไม่มีใครดึงข้อมูลไปใช้จะทำให้ WAL กองอยู่บน primary ถ้า DR cluster หลุดไปนาน ๆ disk ของ primary จะเต็มเพราะ WAL ที่ค้างไว้ คอย monitor pg_replication_slots.wal_status ไว้ ถ้าขึ้น lost ให้ reinitialize DR cluster จาก pgbackrest backup


10.3 DR Site: ตั้งค่า Node

Provision node ใหม่ 3 ตัวใน DR site ตั้งค่าเหมือนฝั่ง primary ทุกอย่าง ต่างกันแค่ IP:

Host IP Role
dr-pg1 172.32.47.229 Standby leader (stream จาก primary)
dr-pg2 172.32.34.169 Standby replica
dr-pg3 172.32.39.118 Standby replica
dr-haproxy 172.32.10.50 HAProxy (ช่วงที่เป็น standby รับเฉพาะ read)

รัน Part 1 ถึง Part 4 ของไกด์นี้บน DR node (ปรับ OS, etcd, PostgreSQL, ติดตั้ง Patroni) ที่ต่างมีแค่ไฟล์ configuration ของ Patroni


10.4 DR Patroni Configuration

patroni.yml ของ DR cluster เหมือนฝั่ง primary ทุกอย่าง ยกเว้น block standby_cluster และ section bootstrap.dcs ตัว standby_cluster นี่แหละที่บอก Patroni ว่า cluster นี้ต้องตาม primary ห้ามเลือก leader เอง

/var/lib/pgsql/patroni.yml บน dr-pg1:

scope: dr_cluster          # different scope name from primary
name: dr-pg1

restapi:
  listen: '172.32.47.229:8008'
  connect_address: '172.32.47.229:8008'

etcd3:
  hosts: 'dr-pg1:2379,dr-pg2:2379,dr-pg3:2379'   # DR-site etcd cluster
  protocol: http

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576

    # This block declares the cluster is a standby of another cluster
    standby_cluster:
      host: 172.31.10.50             # primary site HAProxy write port
      port: 5000
      primary_slot_name: patroni_standby_leader   # slot created in step 10.2
      create_replica_methods:
        - pgbackrest
        - basebackup

    postgresql:
      use_pg_rewind: true
      use_slots: true
      parameters:
        hot_standby: 'on'
        wal_keep_size: 256MB
        max_wal_senders: 10
        max_replication_slots: 10
        wal_level: replica
        archive_command: 'pgbackrest --stanza=pg_cluster archive-push %p'
        archive_mode: 'on'

  pg_hba:
    - local all all trust
    - host all postgres 0.0.0.0/0 trust
    - host replication replicator 172.32.47.229/32 scram-sha-256
    - host replication replicator 172.32.34.169/32 scram-sha-256
    - host replication replicator 172.32.39.118/32 scram-sha-256
    - host all all 0.0.0.0/0 scram-sha-256

postgresql:
  listen: '172.32.47.229:5432'
  connect_address: '172.32.47.229:5432'
  bin_dir: /usr/pgsql-17/bin
  data_dir: /var/lib/pgsql/17/data
  pgpass: /tmp/pgpass0

  authentication:
    replication:
      username: replicator
      password: 'Rep-Pass-2026!'      # must match primary cluster
    superuser:
      username: postgres
      password: 'PgSuperPass2026!'
    rewind:
      username: rewind_user
      password: 'Rewind-Pass-2026!'

  create_replica_methods:
    - pgbackrest
    - basebackup

  pgbackrest:
    command: 'pgbackrest --stanza=pg_cluster --delta restore'
    keep_data: true
    no_params: true

  basebackup:
    checkpoint: fast

Start Patroni บนทุก DR node แล้ว DR cluster จะ bootstrap จาก primary ผ่าน pgbackrest ก่อน จากนั้นค่อยเปลี่ยนไปใช้ streaming replication


10.5 ตรวจสอบ Standby Cluster

บน DR site:

patronictl -c /var/lib/pgsql/patroni.yml list

ที่ควรเห็น (สังเกต role standby_leader):

+ Cluster: dr_cluster ─────────────────+─────────+────────────+
| Member  | Host            | Role            | State   | Lag |
+---------+-----------------+-----------------+---------+-----+
| dr-pg1  | 172.32.47.229   | Standby Leader  | running |   0 |
| dr-pg2  | 172.32.34.169   | Replica         | running |   0 |
| dr-pg3  | 172.32.39.118   | Replica         | running |   0 |
+---------+-----------------+-----------------+---------+-----+

ทุก node อยู่ในโหมด standby แบบ read-only ถ้าลอง write จะ fail ตรงนี้ถูกต้องแล้ว ไม่ใช่ bug

ดู replication lag ได้จากฝั่ง primary site:

psql -U postgres -c "
  SELECT application_name, state, sent_lsn, replay_lsn,
         (sent_lsn - replay_lsn) AS lag_bytes
  FROM pg_stat_replication
  WHERE application_name LIKE 'dr%';
"

10.6 pgbackrest ใน DR Site

ตั้งค่า pgbackrest บน DR node ให้ชี้ไปที่ S3 bucket เดียวกัน (หรือ DR bucket ที่ replicate มา) แล้วเพิ่ม repository ตัวที่สองที่ชี้ไป DR region:

/etc/pgbackrest/pgbackrest.conf บน DR node:

[pg_cluster]
pg1-path=/var/lib/pgsql/17/data
pg1-port=5432
pg1-user=postgres

[global]
start-fast=y
process-max=4
archive-timeout=300
compress-type=lz4

# Primary S3 repo (cross-region accessible)
repo1-type=s3
repo1-path=/pgbackrest/pg_cluster
repo1-retention-full=4
repo1-s3-bucket=your-pgbackrest-bucket
repo1-s3-endpoint=s3.ap-southeast-1.amazonaws.com
repo1-s3-key=YOUR_ACCESS_KEY
repo1-s3-key-secret=YOUR_SECRET_KEY
repo1-s3-region=ap-southeast-1
repo1-s3-uri-style=path

# DR S3 repo (local region — faster restore on DR activation)
repo2-type=s3
repo2-path=/pgbackrest/pg_cluster
repo2-retention-full=4
repo2-s3-bucket=your-pgbackrest-dr-bucket
repo2-s3-endpoint=s3.ap-southeast-2.amazonaws.com
repo2-s3-key=YOUR_DR_ACCESS_KEY
repo2-s3-key-secret=YOUR_DR_SECRET_KEY
repo2-s3-region=ap-southeast-2
repo2-s3-uri-style=path

log-level-console=info
log-level-file=detail
log-path=/var/log/pgbackrest

ใน AWS ให้เปิด S3 cross-region replication จาก primary bucket ไปยัง DR bucket ส่วนนี้ทำที่ storage layer ล้วน ๆ DR repo จะ sync ตามเองโดยไม่ต้องตั้งค่าอะไรใน pgbackrest


10.7 DR Activation Runbook

ถ้า primary site ใช้งานไม่ได้และต้อง promote DR cluster ขึ้นเป็น production ให้ทำตามลำดับนี้:

Step 1 — ยืนยันว่า primary site ล่มจริง

อย่า activate DR เพราะ false alarm เช็คให้ชัวร์ก่อน:

# Try connecting to primary HAProxy
psql -h 172.31.10.50 -p 5000 -U postgres -c "SELECT 1;" --connect-timeout=5

# Check Patroni REST API on primary nodes
curl -s http://172.31.47.229:8008/primary
curl -s http://172.31.34.169:8008/primary
curl -s http://172.31.39.118:8008/primary

ถ้าทุกตัวตอบกลับเป็น error หรือ timeout ค่อยไปขั้นต่อไป

Step 2 — เช็ค lag ของ DR cluster

patronictl -c /var/lib/pgsql/patroni.yml list

ถ้า lag เป็น 0 แปลว่าไม่เสียข้อมูลเลย ถ้าไม่ใช่ 0 แปลว่า DR site ยังได้ transaction จาก primary มาไม่ครบ ให้จดค่า lag ไว้ก่อน promote เพราะนี่คือ RPO ของ incident ครั้งนี้

Step 3 — Promote DR cluster

ลบ block standby_cluster ออกจาก DCS configuration เพื่อให้ DR cluster ออกจากโหมด standby:

patronictl -c /var/lib/pgsql/patroni.yml edit-config --apply - --force << 'JSON'
{"standby_cluster": null}
JSON

ไม่กี่วินาทีต่อมา Patroni จะเห็นว่า configuration เปลี่ยน แล้วเลือก leader ใน DR cluster:

watch -n2 "patronictl -c /var/lib/pgsql/patroni.yml list"

ที่ควรเห็น: dr-pg1 (หรือ node ไหนก็ได้ที่ชนะ election) ขึ้น role Leader

Step 4 — ย้าย traffic ของ application มาที่ DR

แก้ DNS CNAME หรือ load balancer VIP ให้ชี้ไปที่ HAProxy ของ DR:

# Example: update DNS record
# db.example.com → 172.32.10.50 (DR HAProxy)

Application จะ reconnect มาที่ DR เองตอนเชื่อมต่อครั้งถัดไป

Step 5 — เช็คว่า write ได้จริง

psql -h 172.32.10.50 -p 5000 -U postgres -c "
  SELECT pg_is_in_recovery(), now();
  CREATE TABLE IF NOT EXISTS dr_test (ts timestamptz DEFAULT now());
  INSERT INTO dr_test DEFAULT VALUES;
  SELECT * FROM dr_test;
"

pg_is_in_recovery() ต้องได้ false แปลว่าตอนนี้ cluster เป็น primary ที่ write ได้แล้ว


10.8 DR ผ่าน pgbackrest Restore (Cold Standby)

ถ้า standby cluster ก็ใช้ไม่ได้อีก (region ล่มทั้ง region) ให้ restore จาก S3 backup ใน DR region:

# On new DR infrastructure — after installing PostgreSQL and pgbackrest

# List available backups in DR repo
sudo -u postgres pgbackrest --stanza=pg_cluster --repo=2 info

# Restore latest backup
sudo -u postgres pgbackrest --stanza=pg_cluster \
  --repo=2 \
  --delta \
  --target-action=promote \
  restore

# Start PostgreSQL
sudo systemctl start postgresql-17

# Verify recovery completed
psql -U postgres -c "SELECT pg_is_in_recovery(), pg_last_xact_replay_timestamp();"

จากนั้น initialize Patroni บน node ที่ restore เสร็จ ให้เป็น primary cluster ตัวใหม่ (เอา block standby_cluster ออกจาก patroni.yml)

ถ้าต้องการ point-in-time recovery ย้อนไปก่อนจังหวะที่ข้อมูลเสียหาย:

sudo -u postgres pgbackrest --stanza=pg_cluster \
  --repo=2 \
  --delta \
  --type=time \
  --target="2026-05-26 08:45:00 UTC" \
  --target-action=promote \
  restore

10.9 ตารางซ้อม DR

DR plan ที่ไม่เคยทดสอบไม่ใช่ DR plan เป็นแค่ความหวัง ให้ทดสอบตามรอบเหล่านี้เป็นประจำ:

การทดสอบ ความถี่ พิสูจน์อะไร
เช็คว่า standby lag < 5 วินาที ทุกวัน (อัตโนมัติ) Streaming replication ปกติดี
pgbackrest restore ลง environment แยก ทุกเดือน Backup restore ได้จริง
Full DR activation (ใช้ traffic ที่ไม่ใช่ prod) ทุกไตรมาส Runbook ใช้ได้ครบทุกขั้น
ซ้อม DNS/VIP cutover ทุกไตรมาส ทีม application รู้ว่าต้องทำอะไร
จำลองว่า primary site ล่ม ทุกปี มั่นใจใน DR ได้เต็มที่

ตั้งให้เช็ค lag รายวันแบบอัตโนมัติ:

# Add to crontab on monitoring host
*/5 * * * * psql -h 172.31.10.50 -p 5000 -U postgres -t -c \
  "SELECT COALESCE(MAX(write_lag), '0')::text FROM pg_stat_replication \
   WHERE application_name LIKE 'dr%';" | \
  grep -v "^$" | awk '{if ($1 > 5) print "ALERT: DR lag " $1 " seconds"}'

Port ที่ใช้ทั้งหมด

Primary site:

Port Host หน้าที่
2379 pg1/2/3 etcd client
2380 pg1/2/3 etcd peer (คุยกันภายใน cluster)
5432 pg1/2/3 PostgreSQL
8008 pg1/2/3 Patroni REST API (health check)
5000 haproxy Write port → primary
5001 haproxy Read port → replica
7000 haproxy HAProxy stats dashboard

DR site (port เหมือนฝั่ง primary แต่ IP ต่างกัน):

Port Host หน้าที่
2379 dr-pg1/2/3 etcd client
2380 dr-pg1/2/3 etcd peer
5432 dr-pg1/2/3 PostgreSQL (read-only ในโหมด standby)
8008 dr-pg1/2/3 Patroni REST API
5000 dr-haproxy Write port (ใช้ได้หลัง promote DR แล้วเท่านั้น)
5001 dr-haproxy Read port → DR replica

สรุป

แต่ละ layer ทำหน้าที่อะไร:

  1. etcd คือกรรมการกลาง เก็บ cluster state และ leader lock ไม่มี PostgreSQL node ไหน promote ตัวเองได้ ถ้า etcd quorum ไม่เห็นด้วย

  2. Patroni 4.x คือ orchestration layer ดูแล initialization, replication, health check และ automatic failover ทั้งหมด REST API ของ Patroni บอก cluster topology ปัจจุบัน แล้ว HAProxy ก็ใช้ข้อมูลนี้ route traffic

  3. PostgreSQL 17 จาก PGDG ติดตั้งบน RHEL 9 / Rocky Linux ได้ง่าย ๆ ด้วย repo RPM ตัวเดียว และตาม release ของ community ตรง ๆ security patch กับ feature ใหม่มาถึงทันที ไม่ต้องรอ vendor rebuild

  4. pgbackrest 2.58 ทำ point-in-time backup ไป S3 และช่วยให้ Patroni สร้าง replica ได้เร็วขึ้นด้วย เพราะ pg_basebackup จาก primary ที่รันอยู่นั้นช้า ส่วน pgbackrest restore จาก backup repository แบบ parallel ได้

  5. HAProxy ส่ง write ไปที่ primary ปัจจุบัน (port 5000) และส่ง read ไปที่ replica (port 5001) โดยดูจาก health check endpoint ของ Patroni ฝั่ง application เลยได้ read/write splitting โดยไม่ต้องแก้โค้ดสักบรรทัด

  6. Patroni Standby Cluster (Part 10) ขยาย HA ข้าม site DR cluster stream จาก leader ของ primary cluster ผ่าน replication slot ที่กันไว้ให้โดยเฉพาะ ส่วน runbook ห้าขั้นตอนจะ promote DR ขึ้นเป็น primary อิสระได้ภายใน 5 นาที โดยไม่ต้องแตะ etcd หรือ Patroni configuration ฝั่ง primary site เลย

  7. pgbackrest PITR Restore คือตาข่ายชั้นสุดท้าย รองรับอยู่หลัง standby cluster อีกที ถ้า standby ก็ใช้ไม่ได้อีก restore จาก S3 bucket ใน DR region ก็พา database กลับไปยังจุดเวลาไหนก็ได้ รวมถึงก่อนจังหวะที่ข้อมูลเสียหายจะลามไปทุก replica

setup นี้รอดจากเหตุอะไรได้บ้าง:

เหตุการณ์ กู้ด้วยอะไร RTO
Node ล่มตัวเดียว Patroni automatic failover < 30 วินาที
ทุก node ใน primary site ล่ม Promote DR standby cluster 2–5 นาที
ข้อมูลเสียหาย (replicate ไปแล้ว) pgbackrest PITR restore 30–120 นาที
เสียทั้ง region pgbackrest restore จาก DR S3 30–120 นาที

สุดท้ายคุณจะได้ database stack ที่จัดการ node ล่มได้เอง รอดแม้เสียทั้ง site มี point-in-time backup เก็บไว้นอก site และไม่เสียค่า license เลย ซ้อม DR runbook ทุกไตรมาส เพราะแผนที่ไม่เคยลงมือทำจริงไม่ใช่แผน


มีคำถามหรืออยากคุยต่อ? ทักมาได้ทาง LinkedIn, X หรือ email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.