Databases & Storage
Data Replication Explained: Keep Copies of Your Database in Sync
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيData replication means keeping the same data on more than one server and continuously copying changes from one to the others. It is how databases survive a failed server, how read-heavy applications spread load, and how teams run reports without slowing down production. It is also widely misunderstood: replication is not a backup, and adding a replica does not automatically make your application highly available. This guide explains the core concepts and walks through a basic PostgreSQL streaming replication setup on two Linux servers.
Why replicate?
- Redundancy. If the primary server fails, a replica already holds nearly all the data and can take over.
- Read scaling. Replicas can answer read-only queries, such as reports, search pages or dashboards.
- Maintenance. You can run heavy analytics or take backups from a replica instead of the primary.
- Geographic reach. A replica in another region can serve local reads, though writes still go to the primary.
Core concepts
Primary and replicas
In the most common setup, one primary accepts writes and one or more replicas (also called standbys or secondaries) receive a stream of changes and apply them. Applications send writes to the primary and may send some reads to replicas.
Synchronous vs asynchronous
| Mode | How it works | Trade-off |
|---|---|---|
| Asynchronous | Primary confirms the commit immediately; replicas catch up shortly after | Fast writes, but the newest transactions can be lost if the primary dies |
| Synchronous | Primary waits until at least one replica confirms it has the change | No loss of confirmed commits, but each write pays the network round trip |
Asynchronous replication is the usual default. Synchronous replication makes sense when losing even a few seconds of committed data is unacceptable, and it works best when replicas are close to the primary, because latency is added to every commit.
Replication lag
With asynchronous replication, a replica is always slightly behind. Usually that is a fraction of a second, but heavy writes, a slow network or long-running queries on the replica can make it grow. Lag matters because a user who saves a form and then reads from a replica might not see their own change. Common fixes are to read from the primary right after a write, or to route a user's requests to the primary for a short time after they modify data.
Physical vs logical replication
Physical replication copies low-level changes to data files, producing an exact copy of the whole database cluster. Logical replication sends row-level changes for selected tables, which allows replicating between different major versions or only part of the data. Physical replication is simpler for high availability; logical replication is more flexible for migrations and integrations.
Replication is not a backup
If someone runs DROP TABLE orders; on the primary, every replica faithfully drops the table a moment later. Corruption caused by a bug is replicated too. You still need point-in-time backups stored separately. See our guide to incremental backups for strategies that pair well with replication.
Setting up PostgreSQL streaming replication
The steps below outline asynchronous physical replication between two servers on the same PostgreSQL major version. Paths shown are for Debian/Ubuntu with PostgreSQL 16; adjust them for your version and distribution. Use a private network between the servers if available, and restrict access with your firewall.
On the primary
- Create a replication role:
``sql CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'choose-a-strong-password'; ``
- In
/etc/postgresql/16/main/postgresql.conf, make sure these are set:
`` listen_addresses = 'localhost,10.0.0.2' wal_level = replica max_wal_senders = 10 ``
wal_level = replica and max_wal_senders = 10 are already the defaults in recent versions, but check them.
- Allow the replica in
/etc/postgresql/16/main/pg_hba.conf:
`` host replication replicator 10.0.0.3/32 scram-sha-256 ``
- Restart PostgreSQL:
sudo systemctl restart postgresql.
On the replica
- Stop PostgreSQL and move the empty data directory aside:
``bash sudo systemctl stop postgresql sudo mv /var/lib/postgresql/16/main /var/lib/postgresql/16/main.old ``
- Copy the primary's data with
pg_basebackup. The-Rflag writes the connection settings and createsstandby.signalso the server starts as a replica;-C -Screates a replication slot:
``bash sudo -u postgres pg_basebackup -h 10.0.0.2 -U replicator \ -D /var/lib/postgresql/16/main -R -X stream -C -S replica1 -P ``
- Start it:
sudo systemctl start postgresql.
Verify
On the primary:
SELECT client_addr, state, sent_lsn, replay_lsn FROM pg_stat_replication;On the replica:
SELECT pg_is_in_recovery();
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;pg_is_in_recovery() should return true. Note that replay_delay also grows when the primary is simply idle, so compare LSN positions for an accurate picture.
A word on replication slots: they guarantee the primary keeps WAL until the replica has received it, but if a replica disappears, WAL accumulates and can fill the primary's disk. Monitor pg_replication_slots and drop slots you no longer use.
Failover
Promoting a replica is one command:
SELECT pg_promote();The hard parts are around it: making sure the old primary does not come back and accept writes (split brain), pointing applications to the new primary, and rebuilding a replica afterwards. Tools such as Patroni automate this with a consensus store. For small projects, a documented manual failover procedure that you have actually rehearsed is often enough.
Planning on a VPS
Run the replica on a separate server, ideally in the same location for low lag, or in a second location if you want protection against a full data center outage. You can launch a second server from deploy and pick its location there.
FAQ
Does a replica double my database's write capacity?
No. Every write still goes to the primary and is then repeated on each replica. Replication scales reads and improves availability; scaling writes needs other techniques such as sharding.
Can I read from a replica safely?
Yes, for queries that can tolerate slightly stale data. For reads that must reflect a change the user just made, read from the primary.
Do I still need backups if I have a replica?
Yes. Replicas copy mistakes and deletions instantly. Keep separate backups that let you restore to a point in time before the problem.