LLM.coPrivate, self-hosted LLM deployments
Legal AI infrastructure for firms
AI RFP discovery and response drafting
Automatic.coBusiness process automation
Secure AI virtual data rooms
How to Set Up PostgreSQL Logical Replication for Multi-Region Systems (Architecture, Tuning, and Failover)
Stretching a database across continents used to feel like juggling chainsaws in a wind tunnel, but PostgreSQL logical replication turns that circus into a planned routine. This guide shows how to design a multi-region layout that keeps reads local, keeps writes consistent, and behaves when the network gets grumpy.
We will map the moving parts, the order of operations, and the drills that keep on call teams calm. Expect practical detail with a light touch that keeps the topic friendly for software development teams.
What Logical Replication Actually Does
Logical replication ships row changes, not disk pages. Inserts, updates, and deletes are decoded from the write-ahead log and applied on subscribers as regular SQL. Because it is row aware, you can choose specific tables, filter columns, and even transform data with triggers on the destination. That precision is ideal for multi-region designs where only the hot slice must travel. It also side steps hazards in physical replication, such as dependence on storage layout and the inability to filter by table.
Architecture in a Nutshell
You run a publisher in the primary region and one or more subscribers elsewhere. The publisher defines a publication that lists the tables to replicate. Each subscriber defines a subscription that connects back to the publisher and streams changes.
First comes an initial copy of table contents, then a continuous apply of new changes. Lag should be small and steady. Because publications are table scoped, you can expand or contract the footprint with confidence. In practice, you will iterate, observe, and tune.
Publisher And Subscriber Roles
The publisher is the authority for the replicated tables and keeps a replication slot for each subscription so needed WAL is retained until the subscriber confirms receipt. The subscriber is a PostgreSQL cluster that replays the feed. You can pause and resume a subscription, refresh it to include new tables, or drop and recreate it cleanly. Since replication is table scoped, you can expand or contract the footprint without drama.
LSNs, Slots, and Lag
Every change has a log sequence number, and the subscriber tracks the last one applied. Replication slots on the publisher control WAL retention so the stream cannot outrun the slowest destination. Lag appears in two flavors. Byte lag shows how much WAL remains. Time lag shows the delay between commit and apply. Watch both. A subscriber can look calm while quietly drowning in megabytes.
Prerequisites and Version Notes
Use a recent PostgreSQL release for mature features and sturdier monitoring. Keep publisher and subscribers within the major version family to avoid oddities in types and behavior. Align extensions, collations, encodings, and time zones across regions.
If you rely on custom types, install them everywhere before you flip any switches. Size disk on the publisher to retain WAL for the longest subscriber outage you will tolerate. A slot that falls behind and forces a base backup at noon will not make friends.
Step-by-Step Setup
Begin with the network. Connect regions over private links or a secure VPN, and measure round trip time during busy hours. Prepare roles and schemas next. Create a dedicated role for replication with only the privileges it needs. Ensure target tables exist on subscribers with identical schemas, including indexes and constraints. The fewer differences you allow, the fewer surprises appear.
Configure the Publisher
Set the WAL level to logical. Size max replication slots and max wal senders for all subscribers plus a spare. Tune checkpoint and background writer settings to smooth bursts. Create a publication that lists only the tables that matter. Start small, validate behavior, then widen the scope after the graphs look boring. Boring is success.
Configure the Subscriber
Provision a cluster in the target region with the same major version and extensions. Verify that schemas and privileges match. Decide whether the initial copy should run automatically or if you prefer to load snapshots during a quiet window. The first sync can be heavy on IOPS and bandwidth, so plan capacity and confirm that autovacuum is awake.
Create Publication and Subscription
On the publisher, create the publication. On the subscriber, create the subscription that uses the replication role connection string. The subscriber will copy tables, then switch to streaming changes. Watch the system views that report current LSN, remaining bytes, and replication state. If you add a table later, update the publication and refresh the subscription so the new table joins the parade.
| Step | Goal | Do this | Validate / watch |
|---|---|---|---|
| 1) Network Region connectivity | Ensure regions can talk securely and predictably before you touch Postgres knobs. | Use private links or VPN; restrict paths to known subscriber IPs Measure RTT during peak hours (expect “weather”) Enable TLS in transit and plan credential rotation VPN / PrivateLink TLS RTT baseline | Stable latency + no intermittent drops Firewall rules only allow expected ports/hosts |
| 2) Roles + schemas Reduce surprises | Make publisher/subscriber schemas match so apply doesn’t fail in weird, late ways. | Create a dedicated replication role with least-privilege Ensure tables exist on subscribers with identical schemas Match indexes, constraints, extensions, encodings, collations, time zones Install custom types everywhere before enabling replication least privilege schema parity extensions/types | No DDL drift; migrations apply cleanly in all regions Permissions allow apply without elevated roles |
| 3) Configure publisher Enable logical WAL | Turn on logical replication and ensure capacity for slots, senders, and WAL retention. | Set WAL level to logical Size max_replication_slots and max_wal_senders (subs + spare) Tune checkpoints/background writer to smooth bursts Provision disk to retain WAL for the longest tolerated subscriber outage wal_level=logical slots/senders WAL retention | Slots aren’t forcing runaway WAL growth Checkpoint spikes aren’t crushing write latency |
| 4) Configure subscriber Ready to apply | Build a compatible target cluster that can absorb initial copy + steady apply. | Use the same major Postgres version and aligned extensions Decide initial copy approach (auto vs controlled snapshot window) Plan IOPS + bandwidth for initial sync; ensure autovacuum is healthy Set timeouts conservatively for cross-ocean links version match initial copy autovacuum | Initial copy doesn’t starve production workload Apply stays steady without “stale in bursts” behavior |
| 5) Create pub/sub Start the stream | Publish only what you need, subscribe cleanly, then monitor LSN/lag until it’s boring. | Create a publication with only the tables that matter (start small) Create the subscription using the replication role connection string After adding tables later: update publication + refresh subscription Pause/resume subscriptions when performing planned maintenance publication scope subscription refresh pause/resume | Monitor byte lag + time lag (both matter) Watch replication state, retries, apply rate, and slot retention Alert if lag exceeds an agreed “lag budget” |
Conflict Handling and Write Ownership
Logical replication is happiest when each row has one writer. The simplest pattern is to keep writes centralized in the primary and treat subscribers as read only. If you must accept writes in multiple regions, divide ownership cleanly. Route tenants or customer groups to specific regions and keep their related rows pinned there.
Foreign keys should follow that choice so you do not create cross region write dependencies. Sequences need care. Global sequences avoid collisions but can add latency. Region scoped sequences reduce chatter and keep inserts fast.
Network, Latency, and Tuning
Transoceanic links behave like weather. Some days are sunny, others feel like sailing through soup. Keep timeouts conservative and avoid overly chatty application patterns. On subscribers, tune apply batch size so throughput is strong while jitter stays low. Oversized batches can make replicas feel stale in bursts. Autovacuum needs attention so it does not starve the apply process during heavy churn. Schedule freeze operations when traffic is light.
Observability and Routine Care
Good replication is dull to watch. Track byte lag and time lag, the oldest retained WAL on the publisher, and the rate of conflicts on subscribers. Alert early when lag exceeds a budget you can defend. Expose metrics that show throughput and retries, and keep enough history to spot weekly patterns. Run periodic audits that count rows and validate checksums on key tables across regions.
Failover and Switchover Plans
Practice turning a subscriber into a publisher before you need to do it live. A controlled switchover promotes the subscriber, updates client routing for that region, and recreates downstream publications so other regions keep receiving updates. When the original publisher returns, decide whether to reverse the flow or rebuild subscriptions from scratch. For real disasters, have a document that explains who pushes which button and in what order.
Common Pitfalls to Avoid
Do not replicate every table just to feel complete. Focus on hot paths that users touch. Keep schemas aligned and avoid surprise type changes. A tiny difference in collation can grow into a large headache. Limit migrations that rewrite huge tables during peak season. Remember that unlogged tables do not replicate, and that some sequence behaviors can produce collisions.
Security Considerations
Treat replication with the same respect as client traffic. Use TLS in transit, bind roles to the minimum they need, and restrict network paths to the subscriber addresses you expect. Rotate credentials on a schedule you can sustain. Keep secrets out of logs. Backups must cover both publisher and subscribers, since replication will faithfully distribute mistakes as well as valid changes.
Conclusion
Logical replication gives you a careful way to stretch PostgreSQL across regions without stretching your luck. Design for single writers per row, keep schemas aligned, and watch lag like a hawk. Practice failovers until they feel boring.
Measure what matters and tune what you measure. Do that, and your global users will feel close to the data, your on call engineers will keep their weekends, and your database will act like the dependable teammate it was meant to be.
