In revision.
Crisp5 min readGo deeper →

Streaming replication

Postgres streaming replication ships WAL records from primary to replicas as they are produced, giving you read scale-out and crash failover.

Replication in Postgres ships WAL (write-ahead log) records from a primary to one or more replicas. The replica replays the WAL to keep an exact copy of the primary. Two modes:

  • Asynchronous (default): primary does not wait for replica. Fast. Data loss possible on failover.
  • Synchronous: primary waits for replica acknowledgment before commit returns. Slow. No data loss.

How it works

  1. Primary writes WAL on every change.
  2. The walsender process streams WAL records to each replica.
  3. Replica's walreceiver receives, writes to its WAL.
  4. Replica's startup process replays WAL into the database.
Async vs sync commit timing

Use cases

  • Read scale-out: route SELECTs to replicas, writes to primary
  • HA failover: replica promoted on primary crash
  • Backup: take backups on replica, no primary load
  • Geo replicas: read locally in each region

Replica lag

Replicas are behind. Even on fast networks, expect tens of milliseconds. On busy systems or slow replicas, seconds to minutes. Monitor:

SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes
FROM pg_stat_replication;

Sync replication modes

  • on: wait for replica WAL fsync (durable on replica)
  • remote_write: wait for replica OS write (not fsync)
  • remote_apply: wait for replica to apply (visible to readers)

remote_apply gives you true "read your writes" from the replica but slowest.

The interview line

"Postgres uses WAL-based streaming replication. The primary ships WAL records to replicas as they are produced. Async replication is the default for performance, replicas are seconds behind. Synchronous replication waits for replica ack before commit returns, guaranteeing no data loss but adding latency. For HA you run a sync replica plus async replicas for read scale-out."

Learn more