Databases & Storage
Read Replicas Explained: Scaling Database Reads the Right Way
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيMost web applications read far more than they write. Product pages, dashboards, search results and reports all query the database, while only a fraction of requests change data. When a single database server starts to struggle under this read load, a read replica is often the next step. A read replica is a copy of your primary database that stays up to date automatically and answers read-only queries, taking load off the primary. This guide explains how replicas work, what they solve, what they do not, and how to set one up on a VPS.
How a read replica works
All writes still go to one server, the primary. The primary records every change in its log: the write-ahead log in PostgreSQL or the binary log in MySQL and MariaDB. One or more replicas connect to the primary, receive that log stream and apply the same changes to their own copy of the data. Applications then send SELECT queries to the replicas and everything that modifies data to the primary.
If you are not familiar with the log that makes this possible, our article on write-ahead logging explains it.
Asynchronous vs synchronous replication
| Mode | How it works | Benefit | Cost |
|---|---|---|---|
| Asynchronous | Primary commits without waiting for replicas | Fast writes, simple | Replicas can be slightly behind |
| Synchronous | Primary waits for at least one replica to confirm | No committed data lost if the primary fails | Higher write latency; writes stall if the replica is unavailable |
Most read-replica setups use asynchronous replication, because the goal is read capacity rather than zero data loss.
Replication lag: the main thing to design for
With asynchronous replication, a replica is always a little behind the primary, usually by a fraction of a second, but sometimes much more during heavy writes, long-running queries on the replica or network problems. This creates a classic bug: a user saves a profile change, the next page reads from a replica, and the old value appears.
Common ways to handle it:
- Read-your-own-writes: after a user writes, send that user's reads to the primary for a short period.
- Route by consistency need: checkout, balances and anything right after a write go to the primary; listings, reports and search go to replicas.
- Monitor lag and stop sending traffic to a replica that falls too far behind.
Checking lag:
-- PostgreSQL, on the primary
SELECT client_addr, state, replay_lag FROM pg_stat_replication;
-- PostgreSQL, on the replica
SELECT now() - pg_last_xact_replay_timestamp() AS lag;-- MySQL 8.0.22+ (older versions: SHOW SLAVE STATUS)
SHOW REPLICA STATUS\GIn MySQL, look at Seconds_Behind_Source and make sure both replication threads report Yes. Note that the PostgreSQL replica query shows a growing value when the primary is simply idle, so interpret it together with write activity.
Setting up a PostgreSQL replica (outline)
The steps below show the general flow on two servers with private connectivity between them. Adjust versions and paths to your distribution.
- On the primary, create a replication user:
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'choose-a-strong-password';- Make sure
wal_level = replica(the default in current versions) andmax_wal_sendersis high enough inpostgresql.conf. Setlisten_addressesto include the private interface. - Allow the replica in
pg_hba.conf, limited to its address:
host replication replicator 10.0.0.3/32 scram-sha-256- Reload PostgreSQL, and allow port 5432 only from the replica in the firewall.
- On the replica, stop PostgreSQL, empty its data directory, and clone the primary:
sudo -u postgres pg_basebackup -h 10.0.0.2 -U replicator \
-D /var/lib/postgresql/16/main -R -X stream -PThe -R flag writes the connection settings and creates standby.signal, so the server starts as a replica.
- Start PostgreSQL on the replica and confirm it appears in
pg_stat_replicationon the primary. Try a write on the replica: it should be rejected as read-only.
MySQL and MariaDB follow a similar pattern: enable the binary log and a unique server_id, take a consistent copy of the data, then point the replica at the primary with CHANGE REPLICATION SOURCE TO (MySQL 8.0.23+) or CHANGE MASTER TO and start replication. Enabling GTIDs makes later failovers simpler.
Sending queries to the replica
Replicas only help if traffic reaches them. Options include:
- Application-level routing: many frameworks support separate read and write connections; Laravel and Django, for example, let you configure read hosts.
- A proxy: ProxySQL for MySQL, or Pgpool-II and HAProxy for PostgreSQL, can split or balance traffic. See our article on connection pooling for how proxies and poolers fit together.
What read replicas do not solve
- Write bottlenecks. Every replica applies every write, so replicas do not increase write capacity.
- Backups. A mistaken
DROP TABLEis replicated within seconds. Keep real backups. - Automatic high availability. A replica can be promoted (
pg_promote()in PostgreSQL), but automatic failover needs extra tooling such as Patroni or an orchestrator, plus careful testing. - Slow queries. A missing index is slow on every server. Optimise queries first; it is often cheaper than adding servers.
When to add a replica
Consider a replica when the primary's CPU is consistently busy with reads, reports interfere with live traffic, or you need a warm copy in another location. Before that, check caching, indexing and connection limits. Each replica needs resources similar to the primary, since it holds the full dataset.
FAQ
Can I write to a read replica?
No. A standard PostgreSQL standby or a MySQL replica with read_only and super_read_only enabled rejects writes. All changes must go to the primary and flow to replicas through replication.
How many read replicas can one primary have?
There is no fixed small limit, but every replica adds network and processing work on the primary to stream changes. Start with one, measure, and add more only when read load requires it.
Does a replica need the same size server as the primary?
It holds the same data, so it needs similar disk space. CPU and RAM depend on the read load you send to it, but a replica that is much weaker than the primary can fall behind during heavy write periods.