Mafiree logo
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
Schedule a Call
Menu
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
  • Schedule a Call
Database
Database Managed Database Services
MySQL MySQL
MySQL Consulting
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB MongoDB
MongoDB Consulting
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL PostgreSQL
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
SQL Server MSSQL
MSSQL Consulting
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Aerospike
Aerospike Consulting
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
Clickhouse Clickhouse
ClickHouse Consulting
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB TiDB
TiDB Consulting
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB ScyllaDB
ScyllaDB Consulting
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
DevOps
DevOps DevOps Services
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Networking
Networking Networking Services
Basic Basic
Advanced Advanced
MySQL MySQL
MongoDB MongoDB
PostgreSQL PostgreSQL
MSSQL MSSQL
Aerospike Aerospike
Clickhouse Clickhouse
TiDB TiDB
ScyllaDB ScyllaDB
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Basic Basic
Advanced Advanced
MySQL Consulting
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB Consulting
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
MSSQL Consulting
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Consulting
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
ClickHouse Consulting
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB Consulting
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB Consulting
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
  1. Home
  2. > Blogs
  3. > PostgreSQL
  4. > PostgreSQL Replication Setup: Step-by-Step Guide for Streaming Replication and Failover

PostgreSQL Replication Setup: Step-by-Step Guide for Streaming Replication and Failover

Understand how PostgreSQL streaming replication works, deploy a primary server and replica node, implement failover for high availability, and optimize your replication setup with Mafiree's expert DBA services. Ensuring high availability and data protection in PostgreSQL environments is critical for modern applications. One of the most effective ways to achieve this is through PostgreSQL replication setup, particularly using streaming replication with failover capabilities. This guide walks you through configuring a robust PostgreSQL replication system, covering everything from basic setup to handling failover scenarios.

Jethish September 16, 2026

Subscribe for email updates

Summarize with AI: ChatGPT Google AI Perplexity Claude Grok

Understanding PostgreSQL Replication

PostgreSQL supports several types of replication, but streaming replication is the most commonly used for high availability. It allows a standby server to receive changes from a primary server in real time, ensuring data consistency and enabling failover capabilities.

With streaming replication, PostgreSQL uses the Write-Ahead Log (WAL) mechanism to stream transaction logs from the primary to the replica. This ensures that all committed transactions are replicated to the standby node with minimal delay. For background on how this mechanism works under the hood, see PostgreSQL's official Write-Ahead Logging documentation.

Why Streaming Replication?

  • Real-time data synchronization
  • Minimal lag between primary and replica
  • Supports automatic failover with tools like Patroni
  • Enables read scaling by offloading queries to replicas

Not sure if streaming replication is the right choice for your environment? Explore our guide on Choosing the Right Replication Type in PostgreSQL to compare streaming, logical, and other replication methods before implementing your architecture.

Prerequisites for PostgreSQL Replication Setup

Before starting the replication setup, ensure you have:

  • Two PostgreSQL servers (primary and replica)
  • Network connectivity between them
  • Same PostgreSQL version on both nodes
  • SSH access to both servers

Mafiree's database experts can assist with setting up and optimizing your replication infrastructure, ensuring seamless integration with your existing systems.

Planning a production PostgreSQL replication setup? Let Mafiree's experienced DBAs help you implement a secure, scalable, and highly available replication architecture tailored to your environment.

Talk to Our PostgreSQL DBA Team

Step-by-Step PostgreSQL Replication Setup

Step 1: Configure the Primary Server

Update the following parameters in postgresql.conf:

postgresql.conf
listen_addresses='*'
wal_level=replica
max_wal_senders=10
max_replication_slots=10
wal_keep_size=2GB
archive_mode=on
hot_standby=on

These settings enable WAL streaming and allow standby servers to connect.

Next, update pg_hba.conf to allow replication connections:

pg_hba.conf
host replication replicator <standby_ip>/32 scram-sha-256

Create a dedicated replication user:

psql
CREATE ROLE replicator
WITH REPLICATION
LOGIN
PASSWORD 'StrongPassword';

Restart PostgreSQL to apply the configuration changes.

Step 2: Create a Replication Slot

Replication slots prevent WAL files from being deleted before the standby server has received them.

psql
SELECT pg_create_physical_replication_slot('standby1');

Although optional, replication slots are highly recommended for production environments.

Step 3: Initialize the Standby Server

Stop PostgreSQL on the standby server and remove any existing data directory.

Use pg_basebackup to clone the primary database:

bash
pg_basebackup \
  -h <primary_ip> \
  -U replicator \
  -D $PGDATA \
  -P \
  -R \
  -X stream \
  -C \
  -S standby1

The -R option automatically creates the required replication configuration.

Full flag reference: pg_basebackup documentation.

Step 4: Start the Standby Server

Start PostgreSQL on the standby server.

Verify the standby status:

psql
SELECT pg_is_in_recovery();
Expected output: true

This confirms the server is operating as a standby.

Need a hand with this setup? Talk to a Mafiree DBA Expert.

Step 5: Verify Streaming Replication

On the primary server, verify the standby connection using the pg_stat_replication view:

psql
SELECT application_name,
       client_addr,
       state,
       sync_state
FROM pg_stat_replication;
See the full column reference in the official pg_stat_replication documentation.

A healthy streaming replication setup should show:

  • State: streaming
  • Sync State: async (or sync if synchronous replication is configured)

Step 6: Test Replication

Create a test table on the primary server:

psql
CREATE TABLE replication_test(id INT);
INSERT INTO replication_test
VALUES (1);

Query the standby server:

psql
SELECT *
FROM replication_test;

If the inserted row is visible, streaming replication is functioning correctly.

Step 7: Monitor Replication Health

Regular monitoring is essential for maintaining a healthy replication environment.

Useful monitoring queries include:

psql
SELECT *
FROM pg_stat_replication;

Replication lag:

psql
SELECT now() - pg_last_xact_replay_timestamp();

These queries help identify delays, disconnected replicas, and synchronization issues before they impact production.

Under normal conditions, replication lag should remain low. Persistent or increasing lag may indicate network bottlenecks, insufficient resources, or long-running transactions on the primary server.

With streaming replication configured, verified, and continuously monitored, the final step is to prepare your PostgreSQL environment for primary server failures by implementing a reliable failover strategy.

Step 8: Configure PostgreSQL Failover for High Availability

After streaming replication is configured and verified, the next step is to implement a failover strategy. Failover ensures that if the primary server becomes unavailable, a standby server can be promoted to primary, minimizing downtime and maintaining service availability.

Best Practices for PostgreSQL Failover

  • Use high-availability tools such as Patroni to automate failover and cluster management.
  • Test failover and failback procedures regularly to ensure they work as expected.
  • Maintain regular backups of both primary and standby servers to protect against data loss.
  • Continuously monitor replication lag, server health, and connectivity, and configure alerts for anomalies.
  • Document your failover process and recovery procedures to enable quick response during outages.

Manual Failover (When Required)

If automatic failover is not configured, you can manually promote the standby server:

psql
SELECT pg_promote();

Verify that the promoted server is no longer in recovery mode:

psql
SELECT pg_is_in_recovery();
Expected output: false

This confirms that the standby has been promoted and is now acting as the primary server.

For organizations requiring high availability, Mafiree offers expert PostgreSQL DBA services to manage replication setups, monitor performance, and ensure seamless failover processes.

Mafiree's PostgreSQL Replication Services

Mafiree provides comprehensive database administration and optimization services tailored to your PostgreSQL environment. Our experts can help you:

  • Design and implement robust replication strategies
  • Monitor replication health and performance
  • Implement automated failover solutions
  • Ensure compliance with data protection standards

PostgreSQL streaming replication provides a reliable foundation for high availability, disaster recovery, and read scalability. By following the steps in this guide — from configuring the primary server and standby node to monitoring replication health and implementing failover — you can build a resilient PostgreSQL environment that minimizes downtime and protects critical data.

If you're looking to deploy, optimize, or troubleshoot PostgreSQL replication in production, Mafiree's PostgreSQL DBA experts can help you design, implement, and manage a highly available database infrastructure tailored to your business needs.

Conclusion

Setting up a reliable PostgreSQL replication system is crucial for maintaining data integrity and ensuring business continuity. With streaming replication, you can achieve near real-time synchronization between your primary and standby servers. Proper configuration, monitoring, and failover procedures are essential to maximize uptime and minimize risk.

Mafiree's database experts specialize in optimizing PostgreSQL replication setups, offering scalable solutions for high availability and disaster recovery. Whether you're planning a new deployment or looking to enhance an existing system, our team can help streamline your infrastructure with best practices and industry-leading tools.

Ready to secure your PostgreSQL environment?

Contact Mafiree for Expert PostgreSQL Replication Setup

FAQ

PostgreSQL streaming replication is a method where the primary server streams Write-Ahead Log (WAL) records to standby servers in real time. This ensures that all committed transactions are replicated with minimal delay, enabling high availability and read scaling.
To set up PostgreSQL replication, configure the primary server with appropriate WAL settings, create a replication user, initialize the replica node using pg_basebackup, and configure recovery parameters on the standby. Finally, start the replica to begin syncing.
Benefits include high availability, data protection against failures, read scaling, disaster recovery capabilities, and improved performance through load distribution across multiple nodes.
Yes, tools like Patroni can automate failover processes. These tools monitor the primary node and automatically promote a standby to primary if the main server becomes unavailable.
Physical replication replicates all data changes byte-by-byte, maintaining exact copies of the database. Logical replication allows selective replication of tables or schemas, enabling more flexible setups but with additional complexity.

Author Bio

Jethish

Jethish is a PostgreSQL DBA at Mafiree with expertise in building scalable, reliable, and high-performance database infrastructures. He focuses on PostgreSQL architecture, replication strategies, performance tuning, and high availability for mission-critical systems. Through his technical writing, he shares clear, practical insights on database internals, replication choices, load balancing, and cross-database integrations that help engineers and DBAs tackle real-world data challenges.

Leave a Comment

Related Blogs

REPACK in PostgreSQL 19: Finally, Online Table Bloat Removal in Core

PostgreSQL 19 introduces REPACK, a native command that unifies the functionality of VACUUM FULL and CLUSTER while adding support for CONCURRENTLY to minimize downtime. Unlike traditional table rewrites that require long ACCESS EXCLUSIVE locks, REPACK can reclaim table bloat online by copying live data, rebuilding indexes, and applying concurrent changes before a final metadata swap. This article explores how REPACK works internally, compares it with VACUUM FULL and pg_repack, demonstrates a hands-on performance test, explains the new pg_stat_progress_repack monitoring view, and covers current limitations and best practices for production environments.

  13177 views
ProxySQL vs HAProxy for MySQL High Availability: Complete Comparison 2026

ProxySQL excels in MySQL-specific query routing, read/write splitting, and performance tuning. HAProxy offers robust load balancing across multiple protocols and is ideal for general-purpose proxying. Choose ProxySQL if your focus is on MySQL optimization; select HAProxy for broader application-level load balancing. Both tools support failover mechanisms but with different levels of database-specific integration.

  337 views
Tracking PostgreSQL Operations in Real Time: A Deep Dive into PostgreSQL Progress Reporting

This blog explores PostgreSQL’s progress reporting system views that provide real-time visibility into long-running operations like VACUUM, ANALYZE, CREATE INDEX, COPY, and base backups. It explains how DBAs can monitor execution phases, estimate completion, detect bottlenecks, and improve operational efficiency using these built-in views. Real-world examples and use cases demonstrate how progress tracking enhances performance tuning, automation, and maintenance planning.

  13136 views
Key Differences Between MySQL and PostgreSQL: Architecture, Performance & Use Cases

Understanding the difference between MySQL and PostgreSQL is critical when choosing a database for production workloads. While both are powerful open-source relational databases, they are built with fundamentally different philosophies. This comprehensive guide compares MySQL vs PostgreSQL across architecture, performance behavior under concurrent loads, replication strategies, and real-world use cases — backed by Mafiree's 17+ years of hands-on production experience across India, APAC, and the Middle East.

  1251 views
AWS Database Storage Optimization: How We Reclaimed 3.6 TB and Cut Costs in Half

A client came to us with a classic AWS database storage optimization problem: 15.2 TB allocated, less than a third actually in use — and a bill that kept growing regardless. Within one week, Mafiree had reclaimed 3.6 TB, validated a safe path to cut allocation nearly in half, and executed a zero-downtime migration. Here's the full story.

  911 views
PostgreSQL Connection Pooling: PgBouncer vs Odyssey – Performance & Configuration

PostgreSQL uses a process-per-connection model, which can limit scalability in high-traffic environments. Connection poolers help manage this challenge by reusing database connections efficiently. This blog compares PgBouncer and Odyssey, two popular PostgreSQL connection poolers, highlighting their architecture, performance characteristics, configuration differences, and ideal use cases. It helps organizations choose the right pooling solution based on workload scale, complexity, and operational requirements.

  7464 views
8 Enhancing Features in PostgreSQL 18

PostgreSQL 18: Efficiency, security, and reliability, all in one upgrade

  13121 views
Optimizing PostgreSQL Queries with Functional Indexes – A Real-World Case Study

Cutting Query Time from 10 Minutes to Under 1 Second – How Functional Indexes Helped Us Optimize Aurora PostgreSQL and Stabilize CPU Performance.

  4431 views
Mastering PostgreSQL Meta-Commands: The Ultimate psql Cheat Sheet

Why memorize SQL queries when \d, \l, and \dx do the heavy lifting? Learn the power of PostgreSQL’s psql meta-commands today.

  5064 views
Choosing the Right Replication Type in PostgreSQL

Choosing the Right Replication Type in PostgreSQL – Understand the key differences between Streaming and Logical Replication, their best use cases, and how to implement them effectively for high availability, scalability, and disaster recovery.

  3753 views
PostgreSQL Schema Changes pg_osc: Zero-Downtime Migrations for Production Systems

Altering large tables in PostgreSQL can cause locks, performance issues, and downtime in production environments. This blog explains how pg_osc (PostgreSQL Online Schema Change) enables safe schema modifications using a shadow table approach, allowing applications to continue operating during migrations. The article covers how pg_osc works, compares it with alternatives like pg_repack, explores real-world use cases, and provides practical steps for implementing online schema changes in production. It also highlights best practices used by Mafiree to perform reliable zero-downtime PostgreSQL schema migrations in high-traffic environments.

  3127 views
Connecting MySQL to PostgreSQL Using mysql_fdw for Cross-DB Queries

This illustration represents the power of mysql_fdw in enabling smooth data exchange and real-time connectivity between MySQL and PostgreSQL. A perfect solution for cross-database operations and data integration!

  4599 views
Incremental Backup In PostgreSQL 17

Revolutionize your database management with PostgreSQL 17! Experience faster, smarter, and more efficient backups with the power of incremental backup. Reduce storage, save time, and ensure seamless recovery – the future of PostgreSQL backup starts here!

  1271 views
A Practical Guide to PostgreSQL Load Balancing

Load balancing in PostgreSQL distributes client connections across multiple database servers to improve performance, scalability, and availability. This guide compares Pgpool-II, ProxySQL, and HAProxy, covering their key features, advantages, limitations, and suitability for PostgreSQL workloads.

  13128 views
7 Enhancing Features In PostgreSQL 17

PostgreSQL 17 is here to revolutionize your database experience! Packed with enhanced performance, cutting-edge features, and improved scalability, this release is designed to meet the evolving demands of modern applications. Whether you're handling complex queries or scaling to new heights, PostgreSQL 17 brings unparalleled reliability and efficiency to your data management solutions.

  3639 views
6 Interesting Features in PostgreSQL 16

Recently Postgres 16 has launched and I have picked the most interesting feature in this blog.

  5567 views
PostgreSQL Autovacuum Explained in Detail

This blog explains how PostgreSQL Autovacuum works — covering the launcher/worker process model, the exact formula that decides when a table becomes eligible, and the key differences between VACUUM, Autovacuum, and VACUUM FULL. It includes an interactive eligibility calculator, tunable parameters, monitoring queries, and best practices to help DBAs prevent table bloat and transaction ID wraparound.

  1748 views

Subscribe for email updates

Get in touch with us

Highlights

More than 6000 Servers Monitored

Happy Clients

Certified DBAs

24 x 7 x 365 Support

PCI

Database Services

MySQL MongoDB PostgreSQL SQL Server Aerospike Clickhouse TiDB ScyllaDB

Quick Links

Careers Blog Contact Privacy Policy Disclaimer Policy

Contacts

Linkedin Mafiree Facebook Mafiree Twitter Mafiree

Nagercoil Office

Miru IT Park, Vallankumaranvillai,

Nagercoil, Tamilnadu - 629 002.

Bangalore Office

Unit 303, Vanguard Rise,

5th Main, Konena Agrahara,

Old Airport Road, Bangalore - 560 017.

Call: +91 6383016411

Email: sales@mafiree.com


Copyright © - All Rights Reserved - Mafiree