NewCode CLOUD — 20% off your first month on all cloud VPSClaim

PostgreSQL High Availability on Hong Kong VPS: Patroni Cluster (2026)

· 4 min read

A single-node PostgreSQL server is a single point of failure — when the VPS reboots or the disk fills up, your application goes down. Patroni is the most widely deployed PostgreSQL HA solution: it manages streaming replication between a primary and replicas, detects failure automatically, and promotes a replica to primary within 30–60 seconds with no manual intervention. This guide sets up a Patroni cluster across two or three Hong Kong VPS instances for production-grade database availability.


Architecture

<code">
           Applications (PgBouncer)
                    │
            ┌───────┴────────┐
            │                │
       HK VPS 1          HK VPS 2
    [Primary PG]      [Replica PG]
    [Patroni]         [Patroni]
            │                │
            └───────┬────────┘
                    │
              HK VPS 3 (or use etcd cloud)
              [etcd — distributed consensus]
              [HAProxy — connection routing]

Step 1: Install on All Nodes

<code"># Run on ALL three VPS nodes
apt update && apt install -y postgresql-16 python3-pip python3-venv etcd
pip3 install patroni[etcd] psycopg2-binary --break-system-packages

# Stop PostgreSQL (Patroni will manage it)
systemctl stop postgresql
systemctl disable postgresql

Step 2: Configure etcd (Consensus Store)

<code"># On the etcd node (VPS 3) — or install etcd on all three nodes for 3-node etcd cluster
cat > /etc/etcd/etcd.conf.yml << 'EOF'
name: hk-etcd-1
data-dir: /var/lib/etcd

listen-peer-urls: http://ETCD_NODE_IP:2380
listen-client-urls: http://ETCD_NODE_IP:2379,http://127.0.0.1:2379

initial-advertise-peer-urls: http://ETCD_NODE_IP:2380
advertise-client-urls: http://ETCD_NODE_IP:2379

initial-cluster: hk-etcd-1=http://ETCD_NODE_IP:2380
initial-cluster-state: new
initial-cluster-token: hk-pg-cluster
EOF

systemctl enable --now etcd
etcdctl endpoint health

Step 3: Configure Patroni on Each PostgreSQL Node

<code"># /etc/patroni/patroni.yml — VPS 1 (adjust name and connect_address per node)
scope: hk-postgres-cluster
namespace: /service/
name: pg-node-1   # Change to pg-node-2 on second node

restapi:
  listen: VPS1_IP:8008
  connect_address: VPS1_IP:8008

etcd:
  hosts: ETCD_NODE_IP:2379

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576   # 1 MB max lag before failover
    postgresql:
      use_pg_rewind: true
      use_slots: true
      parameters:
        wal_level: replica
        hot_standby: on
        max_connections: 100
        max_wal_senders: 5
        max_replication_slots: 5
        wal_log_hints: on
        logging_collector: on

  initdb:
    - encoding: UTF8
    - locale: en_US.UTF-8
    - data-checksums

  pg_hba:
    - host replication replicator 0.0.0.0/0 md5
    - host all all 0.0.0.0/0 md5
    - local all all trust

  users:
    admin:
      password: AdminPass!
      options: [superuser]
    replicator:
      password: ReplPass!
      options: [replication]

postgresql:
  listen: VPS1_IP:5432
  connect_address: VPS1_IP:5432
  data_dir: /var/lib/postgresql/16/patroni
  bin_dir: /usr/lib/postgresql/16/bin
  config_dir: /etc/postgresql/16/main

  authentication:
    replication:
      username: replicator
      password: ReplPass!
    superuser:
      username: postgres
      password: PostgresPass!

  parameters:
    shared_buffers: 256MB
    effective_cache_size: 768MB
    maintenance_work_mem: 64MB
    checkpoint_completion_target: 0.9
    wal_buffers: 16MB

tags:
  nofailover: false
  noloadbalance: false
  clonefrom: false

Patroni Systemd Service

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

[Service]
Type=simple
User=postgres
Environment="PATRONI_POSTGRESQL_DATA_DIR=/var/lib/postgresql/16/patroni"
ExecStart=/usr/local/bin/patroni /etc/patroni/patroni.yml
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# Create data directory
mkdir -p /var/lib/postgresql/16/patroni
chown postgres:postgres /var/lib/postgresql/16/patroni

systemctl enable --now patroni
journalctl -u patroni -f

Step 4: Verify Cluster Status

<code"># Check cluster health
patronictl -c /etc/patroni/patroni.yml list

# Expected output:
# + Cluster: hk-postgres-cluster (7234817251234567890) ---+----+-----------+
# | Member     | Host           | Role    | State   | TL | Lag in MB |
# +-----------+----------------+---------+---------+----+-----------+
# | pg-node-1 | VPS1_IP:5432   | Leader  | running |  1 |           |
# | pg-node-2 | VPS2_IP:5432   | Replica | running |  1 |         0 |
# +-----------+----------------+---------+---------+----+-----------+

# Initiate manual failover test
patronictl -c /etc/patroni/patroni.yml failover hk-postgres-cluster --master pg-node-1
# New leader elected within 30-60 seconds

# Switchback
patronictl -c /etc/patroni/patroni.yml switchover hk-postgres-cluster --master pg-node-2

Step 5: HAProxy for Transparent Routing

<code">apt install -y haproxy

cat > /etc/haproxy/haproxy.cfg << 'EOF'
global
    maxconn 4000

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

# Stats page
listen stats
    bind *:7000
    stats enable
    stats uri /
    stats refresh 10s

# Primary — write traffic (always routes to Patroni leader)
listen postgres-primary
    bind *:5000
    option httpchk GET /master
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server pg-node-1 VPS1_IP:5432 check port 8008
    server pg-node-2 VPS2_IP:5432 check port 8008

# Replica — read traffic
listen postgres-replica
    bind *:5001
    option httpchk GET /replica
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server pg-node-1 VPS1_IP:5432 check port 8008 weight 1
    server pg-node-2 VPS2_IP:5432 check port 8008 weight 1
EOF

systemctl enable --now haproxy

Patroni’s REST API at port 8008 returns HTTP 200 for /master on the current leader and HTTP 200 for /replica on replicas — HAProxy uses these health checks to route automatically.


Step 6: Application Connection via HAProxy

<code"># Applications connect to HAProxy, not directly to PostgreSQL
DATABASE_URL=postgresql://app_user:Pass!@HAPROXY_IP:5000/mydb   # Writes → primary
DATABASE_URL_RO=postgresql://app_user:Pass!@HAPROXY_IP:5001/mydb # Reads → replica

# After failover:
# HAProxy detects old primary is down (health check fails)
# Patroni promotes replica to new leader
# HAProxy starts routing port 5000 to new leader
# Applications reconnect automatically (next connection attempt)
# Total downtime: 30–60 seconds (Patroni election) + reconnect time

Failover Timeline

Event Time
Primary VPS goes down T+0
Patroni detects missed heartbeat T+10s (loop_wait)
Consensus reached in etcd T+15s
Replica promoted to leader T+20s
HAProxy health check confirms new leader T+25s
New connections route to new leader T+30s
Application fully recovered T+35–60s

Conclusion

Patroni on two or three Hong Kong VPS instances transforms single-node PostgreSQL into a self-healing HA cluster — automatic failover in under 60 seconds, streaming replication with zero data loss (synchronous mode), and HAProxy routing that applications never need to reconfigure. For Asia-Pacific applications where database downtime directly costs revenue, a three-VPS Patroni cluster (two PostgreSQL nodes + one etcd/HAProxy) is the minimum viable HA architecture at a fraction of managed HA database service pricing.

Build an HA database cluster: Browse Server.HK Hong Kong VPS plans — deploy two or three VPS instances in the same HK data centre for Patroni clustering with minimal replication lag.

Related articles

More in VPS & ServersServer setup guides