Synchronous vs Asynchronous Replication
Replication can be asynchronous or synchronous depending on how it waits for confirmation.
Asynchronous
- The primary doesn’t wait for the replica.
- Faster writes, but risk of data loss if the primary crashes.
Synchronous
- The primary waits until the replica confirms it received the data.
- No data loss, but slightly slower writes.
Example:
synchronous_standby_names = 'replica1'
Master–Replica Internals
A typical master–replica setup has:
- One primary server (handles all writes)
- One or more replicas (read-only)
flowchart TB
A[Clients] --> B[Primary - Writable]
B -- WAL Stream --> C[Replica 1 - Read-only]
B -- WAL Stream --> D[Replica 2 - Standby]
D -. Failover .-> B
The replica has a background process called WAL receiver, and the primary has WAL sender. They communicate continuously to keep data in sync.
You can check replication status:
SELECT application_name, state, write_lag, replay_lag FROM pg_stat_replication;
Multi-Master Architecture (Active–Active)
Sometimes, you want multiple servers that can all accept writes, for example, a global application with servers in different regions. This setup is called multi-master replication or active–active replication.
PostgreSQL doesn’t support multi-master by default, but it can be achieved using BDR (Bi-Directional Replication) or other tools like pglogical.
How BDR Works
- Each node is both a publisher and a subscriber.
- WAL is decoded logically and sent both ways.
- Conflict resolution rules are applied to avoid data clashes.
Example:
Node A (Asia) ←→ Node B (Europe)
If both nodes insert the same primary key, BDR resolves the conflict using:
- last-update-wins
- origin priority
- or custom conflict handlers.
Advantages:
- Writes possible on multiple nodes
- Geographical redundancy
Challenges:
- Conflict management
- Higher latency
- Complex setup
