|

PostgreSQL Streaming Replication: Moscow to Saint Petersburg on Russia VPS

PostgreSQL replication Moscow St Petersburg VPS: Technical architecture diagram for enterprise Russia VPS hosting
Quick Answer ✓ Expert Verified
AEO Executive Summary

For robust PostgreSQL replication Moscow St Petersburg VPS architecture, Optical network latency along the Moscow–Peter corridor is only 9ms–11ms across the 650km rail route. Establish high-availability disaster recovery by running PostgreSQL Physical Streaming Replication over a mutual TLS WireGuard overlay joining both servers. Utilizing asynchronous or semi-synchronous Write-Ahead Logging (WAL) guarantees a Recovery Point Objective (RPO) under one second while maintaining strict 152-FZ data sovereignty.

Executive Overview Engineering Context
Deployment Architecture Guide

Safeguarding mission-critical databases against regional disruptions requires continuous physical streaming replication between Moscow and Saint Petersburg. Deploying primary and standby PostgreSQL nodes across dual metropolitan centers achieves geographic fault tolerance and rapid failover.

Replication Model
Streaming WAL
Moscow Master to SPb Standby
Transit Link
Dedicated DWDM
Sub-8ms Inter-City Highway
Recovery Target
Near-Zero RPO / RTO
Sub-Minute Node Promotion
Storage Class
Enterprise NVMe
Max Write-Ahead Log Speed
Data Security
WireGuard Encrypted
Secure Cross-City Sync
Architecture SLA
99.99% Availability
Geo-Distributed Resilience

Key Inter-City Database HA Takeaways

  • Sub-12ms Dual-City Backbone: Direct carrier optical fiber connecting Moscow MSK-IX and Saint Petersburg SPB-IX provides reliable low-latency transit ideal for database replication.
  • Physical vs Logical Replication: Physical WAL streaming ensures 100% byte-for-byte fidelity across all schemas, indexes, sequences, and tables, outperforming logical replication for DR.
  • Replication Slots Prevent Data Loss: Utilizing PostgreSQL physical replication slots ensures the primary never discards WAL segments before the Saint Petersburg standby confirms receipt.
  • Encrypted Inter-DC Tunneling: Streaming raw database transactions over public internet links creates serious compliance risks. establishing WireGuard or IPsec tunnels guarantees end-to-end encryption.

Moscow to Saint Petersburg Fiber Route

The geographic separation between Moscow and Saint Petersburg is approximately 650 kilometers along primary transport arteries (M10/M11 highway corridors). Multiple Tier-1 telecommunications carriers—primarily Rostelecom, MegaFon, MTS, and RETN—operate dense, redundant DWDM optical fiber cables linking the two metropolitan markets.

Light traversing optical fiber travels at approximately 200,000 km/s. Over a physical fiber route of ~700km, the theoretical one-way transit time is ~3.5ms. In real-world telecommunications networks with active DWDM transponders and optical amplification, the round-trip time (RTT) between a Tier-III datacenter in Moscow (such as DataLine NORD) and a Tier-III facility in Saint Petersburg (such as Selectel Tsvetochnaya) measures consistently between 8.8ms and 11.2ms with virtually undetectable jitter (<0.3ms).

99.99% HIGH AVAILABILITY Moscow to SPb 9.8ms Route
Cross-Regional DR Cluster

Continuous PostgreSQL streaming replication across two cities ensures zero data loss and automated failover.

CATASTROPHIC DOWNTIME Local Failure Vulnerable
Single-Datacenter Database

A municipal power grid failure, fiber severance, or cooling incident results in complete corporate application downtime.

Why Geo-Redundancy Requires Cross-City Placement

Deploying two database nodes in two separate datacenters within Moscow provides redundancy against localized facility failures (such as a UPS transformer explosion), but leaves the application vulnerable to regional infrastructure crises, metro fiber severing, or metropolitan power grid instabilities. Saint Petersburg operates on an independent electrical grid (Lenenergo) and distinct telecommunications routing hubs. This provides genuine disaster recovery resilience.

Physical Streaming Replication WAL

PostgreSQL achieves physical high availability through its Write-Ahead Log (WAL) subsystem. Every mutation executed against the database—whether an INSERT, UPDATE, or schema change—is first written sequentially to a WAL segment file on disk before changes are applied to the database data pages in shared memory.

In physical streaming replication:

DEDICATED DWDM
650km Rail Corridor

Direct routing over the Moscow to Saint Petersburg optical transit path delivers predictable 9.8ms round-trip latency.

PHYSICAL WAL SYNC
Streaming Replication

Streams binary write-ahead log records directly from primary WAL sender to standby WAL receiver.

ZERO DATA LOSS
< 1s RPO Metric

Asynchronous or semi-synchronous replication guarantees a recovery point objective under 1 second.

FAILOVER SPEED
< 15s Automatic RTO

Patroni and etcd orchestrate automated health checks and leader election during primary failure.

  1. WAL Sender Process: A dedicated background process (walsender) on the primary Moscow VPS reads newly generated WAL records from disk or shared memory and streams them over a persistent TCP socket.
  2. WAL Receiver Process: On the standby Saint Petersburg VPS, a corresponding walreceiver process receives the raw byte stream and writes it into local WAL segment files.
  3. Startup Process Replay: The standby’s startup process continuously reads these WAL segments and replays the disk block alterations directly into its local database cluster.
  4. Physical Replication Slots: To guarantee that a busy primary node does not recycle or delete older WAL segments before the remote Saint Petersburg node has consumed them, a physical replication slot is maintained. The primary retains all required WAL records on disk until the standby explicitly acknowledges their receipt.

Synchronous vs Asynchronous Commit

The most critical configuration decision in cross-city replication is the synchronous_commit parameter on the primary database node.

Asynchronous Replication (Default: synchronous_commit = on, no sync standby)

In asynchronous mode (defined in the official PostgreSQL streaming replication documentation), the primary commits transactions locally as soon as the WAL is flushed to its local NVMe drive. The primary does not wait for the Saint Petersburg node to acknowledge receipt.

9.8 ms
Inter-City Latency

Deterministic transmission between DataLine NORD (Moscow) and Selectel (SPb).

< 1.0 s
Recovery Point (RPO)

Minimal transaction lag even during heavy accounting batch writes.

100 %
WireGuard Encrypted

End-to-end kernel encryption protects financial records across public carrier lines.

  • Write Latency: Zero network overhead (<0.5ms on NVMe). Transaction throughput is maximized.
  • RPO Risk: If the Moscow datacenter suffers instantaneous destruction, transactions written within the last 10ms to 50ms that have not yet traversed the fiber to SPb may be lost. For 95% of web applications and e-commerce stores, this sub-second RPO is completely acceptable.
Synchronous Replication (synchronous_commit = remote_write / on)

In synchronous mode, every client COMMIT command on the primary blocks until the Saint Petersburg standby confirms that the WAL record has been written to its OS buffer (remote_write) or flushed to disk (on).

  • Write Latency: Every mutating SQL transaction incurs an unavoidable ~10ms latency penalty (the round-trip network transit time between Moscow and SPb).
  • RPO Guarantee: Mathematically zero data loss (RPO = 0). If Moscow goes dark, Saint Petersburg holds 100% of committed transactions.

Encrypted Point-to-Point WireGuard

Replicated transaction rows originate from our fiscalized online payment processing architecture, mandating end-to-end WireGuard tunnel encryption. Exposing PostgreSQL port 5432 directly to the public internet—even with TLS enabled—creates attack surface and violates regulatory standards under FSTEK and 152-FZ.

Deploying a kernel-space WireGuard VPN tunnel provides lightweight, state-of-the-art ChaCha20-Poly1305 encryption with minimal CPU overhead. The Moscow primary communicates with the Saint Petersburg standby via dedicated private virtual IPs (e.g., 10.10.10.1 to 10.10.10.2). Port 5432 is bound exclusively to the WireGuard interface, rendering the database completely invisible and unreachable from the public internet.

PostgreSQL Replication Insight

Using `wal_compression = lz4` in PostgreSQL 16 reduces replication network bandwidth by up to 60%. This allows high-transaction databases to stream over inter-city optical links without latency penalty.

PostgreSQL HA Architecture Matrix

The matrix below details the performance characteristics, recovery metrics, and engineering tradeoffs of various PostgreSQL high-availability topologies:

Replication Scheme RPO (Data Loss) RTO (Recovery Time) Write Latency Overhead
Asynchronous Streaming (WAL) &lt. 50 milliseconds &lt. 30 seconds (Manual/Patroni) Zero overhead (&lt. 0.5ms)
Synchronous (remote_write) Zero (0 lost transactions) &lt. 15 seconds (Automated) ~10ms (Cross-city network RTT)
Logical Replication (Per Table) &lt. 500 milliseconds Minutes to Hours Moderate CPU overhead
Nightly pg_dump Cold Backups Up to 24 hours of data lost 2 to 8 hours restore time Zero daytime overhead

Production PostgreSQL HA CLI Setup

The following production shell script sets up a hardened PostgreSQL primary instance on the Moscow VPS, generates the replication user with SCRAM-SHA-256 password hashing, configures replication slots. In addition, it provides the command to initialize the Saint Petersburg standby node using pg_basebackup.

# /usr/local/bin/setup-postgres-ha.sh Bash Automation Blueprint
root@russia-vps-node26:~ [SSH:22]
PuTTY v0.81 BASH CLI
#!/usr/bin/env bash
set -euo pipefail

# 1. Install PostgreSQL 16 and WireGuard VPN
apt-get update && apt-get install -y postgresql-16 postgresql-client-16 wireguard ufw

# 2. Configure PostgreSQL Primary for Streaming Replication (Moscow Node)
cat <<'EOF' >&gt. /etc/postgresql/16/main/postgresql.conf
# Listen on localhost and private WireGuard HA IP
listen_addresses = 'localhost, 10.10.10.1'

# WAL & Replication Settings
wal_level = replica
max_wal_senders = 10
max_replication_slots = 10
wal_keep_size = 4096MB
hot_standby = on
archive_mode = on
archive_command = '/bin/true'
EOF

# 3. Restrict Replication Access via pg_hba.conf
cat <<'EOF' >&gt. /etc/postgresql/16/main/pg_hba.conf
# Allow replication connections only from Saint Petersburg WireGuard IP
host replication replicator 10.10.10.2/32 scram-sha-256
EOF

systemctl restart postgresql

# 4. Create Replicator User & Physical Replication Slot
sudo -u postgres psql -c "CREATE USER replicator WITH REPLICATION ENCRYPTED PASSWORD 'SecureReplKey2026!';"
sudo -u postgres psql -c "SELECT pg_create_physical_replication_slot('spb_standby_slot');"

echo "=== Moscow Primary Node Configured Successfully ==="
echo "=== Command to run on Saint Petersburg Standby Node: ==="
echo "systemctl stop postgresql"
echo "rm -rf /var/lib/postgresql/16/main/*"
echo "pg_basebackup -h 10.10.10.1 -D /var/lib/postgresql/16/main/ -U replicator -P -R --slot=spb_standby_slot"
echo "chown -R postgres:postgres /var/lib/postgresql/16/main/"
echo "systemctl start postgresql"

Automated Failover with Patroni & etcd

While streaming replication ensures that database records exist on both nodes, managing **failover** requires high-availability orchestration. In a manual failover setup, a systems engineer must recognize the primary failure, log into the Saint Petersburg VPS, and execute pg_ctl promote.

High-Availability Clustering with Patroni and etcd

For enterprise environments requiring an RTO under 30 seconds, Patroni provides automated consensus-driven failover. Patroni relies on a Distributed Configuration Store (DCS) like etcd. When the primary node stops updating its heartbeat lease in etcd, the surviving nodes elect a new leader. The Saint Petersburg standby automatically promotes itself to primary, reconfigures replication slots, and notifies HAProxy load balancers or DNS endpoints to redirect database writes seamlessly.

1
Establish Kernel WireGuard Tunnel

Join both Moscow and Saint Petersburg VPS nodes on a private encrypted `10.10.10.0/24` subnet.

2
Configure Primary WAL Sender

Set `wal_level = replica`, `max_wal_senders = 10`, and configure authentication in `pg_hba.conf`.

3
Initialize Standby with pg_basebackup

Execute `pg_basebackup -h 10.10.10.1 -D /var/lib/postgresql/data -Fp -Xs -R` and start standby.

Frequently Asked Questions

Q What is the typical network round-trip latency between Moscow and Saint Petersburg VPS nodes? +

The round-trip optical ping time between datacenters (integrated via Keepalived VRRP active-passive cluster deployment standby nodes) is between 9.8ms and 11.2ms over direct railway DWDM fiber trunks. This sub-12ms latency ensures that database replication lag remains under a few milliseconds even during heavy transactional activity.

Q What happens to the database cluster if the network link between Moscow and Saint Petersburg drops? +

In a cluster managed by Patroni and etcd with a 3-node quorum (or an external witness node in Moscow), the loss of connectivity isolates the Saint Petersburg node. Because Saint Petersburg lacks a quorum majority, it safely transitions to read-only mode. This prevents split-brain data corruption while the Moscow primary continues serving writes.

Q Can the Saint Petersburg standby database node be used to serve read-only SQL queries? +

Yes. PostgreSQL streaming replicas can be configured as ‘Hot Standby’ nodes (`hot_standby = on`). Your web application or connection pooler (PgBouncer) can route analytical, reporting, and read-only catalog queries to the Saint Petersburg instance, offloading CPU and I/O from the Moscow primary write node.

Q Why should database replication traffic between cities be routed through WireGuard? +

Public internet traffic can be intercepted or subjected to routing anomalies. WireGuard provides authenticated, state-of-the-art ChaCha20-Poly1305 encryption running inside the Linux kernel. Replication streams traverse the inter-city link securely with negligible CPU overhead and zero unencrypted exposure.

Q Does Onlive Server provide multi-datacenter VPS instances in both Moscow and Saint Petersburg? +

Yes. Onlive Server operates high-performance KVM infrastructure in both Moscow (DataLine) and Saint Petersburg (SPB-IX peered facilities). You can provision instances in both locations under a unified management account and link them via private high-speed networking for geographic redundancy.

Q How does Patroni automate PostgreSQL failover between Moscow and Saint Petersburg? +

Patroni continuously monitors PostgreSQL health and cluster state stored in a distributed consensus store (etcd). If the primary node fails to renew its leader lease within the heartbeat timeout (typically 10 seconds), Patroni initiates an automated failover, promoting the most up-to-date standby to primary.

Q What WAL replication settings prevent replication lag from accumulating during peak hours? +

In `postgresql.conf`, configure `max_wal_senders = 10`, `wal_keep_size = 4GB`, and `max_slot_wal_keep_size = 16GB`. Utilizing permanent replication slots (`wal_level = replica`) ensures the primary retains necessary WAL segments even if temporary network blips delay standby synchronization.

Q How does physical database replication compare to logical replication for multi-city clusters? +

Physical streaming replication copies byte-for-byte binary WAL changes, supporting identical schema replication, high throughput, and lower CPU overhead. Logical replication replicates specific tables or filtered datasets, making it ideal for selective replication or cross-version database upgrades.

âš¡ Zero-Lag Cross-City Replication

Build Resilient Moscow-SPb Database Clusters

Eliminate single points of failure with geo-replicated PostgreSQL KVM VPS hosting. Featuring sub-12ms optical fiber routes, enterprise NVMe storage, and 99.99% high-availability SLA.

✓ 99.98% Network SLA✓ Pure NVMe RAID-10✓ Instant 2-Minute Deployment
VK

Vipin Kumar

Web Performance & Security Specialist at Onlive Server

Specializing in database high-availability engineering, streaming replication topologies, disaster recovery orchestration, and Linux network virtualization across Eurasian datacenters.