Replication là sao chép dữ liệu từ một primary sang một hay nhiều replica — để chia tải đọc và tăng độ sẵn sàng (primary chết thì có replica thay).
PostgreSQL: primary stream liên tục bản ghi WAL sang replica (streaming replication), độ trễ thường dưới 1 giây. Logical replication thì chỉ chép một số bảng/thay đổi cụ thể — hợp nâng cấp version không downtime hoặc chép sang schema khác.
Đồng bộ vs bất đồng bộ — đây là đánh đổi cốt lõi:
- Sync: commit chỉ xác nhận sau khi replica đã nhận → không mất dữ liệu, nhưng ghi chậm hơn (cần replica online).
- Async: xác nhận ngay, replica trễ vài giây → nhanh, nhưng rủi ro mất dữ liệu nếu primary crash.
Failover tự động: Patroni (dùng etcd/Consul để đồng thuận) tự nâng replica lên primary khi primary chết.
Bẫy hay bị hỏi — read-after-write: vừa ghi vào primary, đọc ngay từ replica có thể chưa thấy do trễ replica. Khắc phục: định tuyến các đọc-sau-ghi về primary, hoặc routing có nhận biết độ trễ.
Replication copies data from one primary to one or more replicas — to spread read load and improve availability (if the primary dies, a replica takes over).
PostgreSQL: the primary continuously streams WAL records to replicas (streaming replication), with lag usually under a second. Logical replication copies only specific tables/changes — good for zero-downtime version upgrades or replicating to a different schema.
Sync vs async — the core trade-off:
- Sync: commit is confirmed only after a replica has received it → no data loss, but slower writes (needs a replica online).
- Async: confirms immediately, replicas lag a few seconds → fast, but risk of data loss if the primary crashes.
Automatic failover: Patroni (using etcd/Consul for consensus) auto-promotes a replica to primary when the primary dies.
Frequently-asked trap — read-after-write: right after writing to the primary, an immediate read from a replica may not see it yet due to lag. Fix: route reads-after-writes to the primary, or use lag-aware routing.