What Is Database Replication?

By Oleksandr Andrushchenko — Published on
0 Likes
0 Dislikes
What Is Database Replication?
What Is Database Replication?

Database replication is the process of maintaining copies of the same data across multiple database servers. Changes made on one database are propagated to one or more replicas so the system can improve availability, read scalability, disaster recovery, or geographic distribution.

Replication sounds simple—copy data from one server to another—but production systems must decide where writes are accepted, how quickly changes reach replicas, what happens during failures, and how applications handle replicas that temporarily contain older data.

Table of Contents

Why Database Replication Exists

A database running on a single server creates several limitations. All reads and writes compete for the same resources, and a server failure can make the entire database unavailable.

Replication introduces additional database instances containing copies of the data:

Database Replication
Database Replication

These copies can serve different purposes.

  • High availability: another database can take over when the primary fails.
  • Read scaling: read-only queries can be distributed across replicas.
  • Disaster recovery: copies can exist in another availability zone or region.
  • Workload isolation: reporting or analytics queries can run against replicas instead of competing with transactional traffic.
  • Geographic distribution: applications can read data from a database closer to users.

Replication does not automatically provide all of these benefits. The replication topology and consistency model determine what the replicas can safely be used for.

How Database Replication Works

Database engines usually replicate changes rather than repeatedly copying the entire database.

A simplified sequence is:

Client Write
    ↓
Primary Database
    ↓
Replication Log
    ↓
Replica
    ↓
Apply Change

The primary records modifications in an ordered change log. Depending on the database, this might be a write-ahead log, binary log, oplog, or another replication stream.

A replica consumes those changes and applies them to its local copy.

For example:

UPDATE products
SET price = 109.00
WHERE id = 8472;

The replication mechanism transfers the corresponding database changes to replicas, which eventually reach the same logical state.

The exact implementation differs between PostgreSQL, MySQL, MongoDB, and other databases, but the fundamental problem is similar: propagate an ordered sequence of changes while preserving the required consistency and durability guarantees.

Database Replication Patterns
Database Replication Patterns

Primary-Replica Replication

One of the most common topologies has one writable primary and multiple replicas.

                 ┌→ Replica 1
Writes → Primary ├→ Replica 2
                 └→ Replica 3

The primary is responsible for accepting changes. Replicas continuously receive those changes.

This architecture is covered in more depth in Replication and Read Replicas in Distributed Databases.

Write Path

Writes normally go to the primary:

Application → Primary → Commit
                  |
                  └→ Replication Stream → Replicas

This provides a clear authority for ordering conflicting updates.

For example, two clients changing the same account record ultimately submit their transactions to the same writable database, where locking, isolation, and transaction semantics determine the final result.

Read Path

Reads can either continue using the primary or be distributed to replicas.

Writes → Primary

Reads ──┬→ Primary
        ├→ Replica 1
        └→ Replica 2

Moving reads to replicas can substantially reduce primary load, especially for read-heavy applications.

However, replicas may not contain the newest committed data yet. Read scaling therefore introduces a consistency trade-off.

Synchronous vs Asynchronous Replication

The most important replication decision is often whether the primary waits for replicas before confirming a write.

With synchronous replication, the write path waits for confirmation from another database node according to the configured durability policy:

Client → Primary → Replica
                    ↓
                 Confirm
                    ↓
Client ← Success ← Primary

This reduces the amount of acknowledged data that can be lost if the primary suddenly fails.

The cost is write latency and availability. A slow or unreachable replica can delay writes unless the replication policy allows another replica or a degraded mode.

With asynchronous replication, the primary can acknowledge the transaction before replicas receive it:

Client → Primary → Success
             |
             └→ Replica later

This keeps write latency lower and isolates the primary from some replica delays, but creates a window where acknowledged changes exist only on the primary.

Property Synchronous Asynchronous
Write latency Higher Lower
Replica freshness Stronger guarantees May lag
Potential data loss during failover Lower under the configured acknowledgment policy Possible for changes not yet replicated
Sensitivity to replica/network latency Higher Lower on the client write path

Some systems use intermediate policies rather than choosing a purely synchronous or asynchronous model. For example, a transaction may wait for one nearby replica while other replicas receive the change asynchronously.

Replication Lag

Replication lag is the delay between a change being committed on the primary and becoming available on a replica.

Consider this sequence:

12:00:00.000 → Primary commits price=$109
12:00:00.150 → Replica applies price=$109

For approximately 150 milliseconds, the primary and replica contain different visible states.

Lag can increase because of:

  • heavy write traffic;
  • slow network links;
  • large transactions;
  • replica CPU or disk saturation;
  • long-running queries on replicas;
  • replication worker bottlenecks;
  • cross-region network latency;
  • maintenance or recovery activity.

A replica can remain healthy while still being too stale for a particular application request.

This is why replication health should not be represented only as an up/down status.

Read-After-Write Consistency

Replication lag becomes visible when an application writes to the primary and immediately reads from a replica.

For example:

1. User changes display name to "Alex"
2. Primary commits the update
3. Application reads profile from Replica 2
4. Replica 2 still contains the old name

From the user's perspective, the successful update appears to have disappeared.

A common solution is to route consistency-sensitive reads to the primary:

Normal read      → Replica
Read after write → Primary

Applications can apply this policy for a short period after a write or only for specific operations.

Another strategy is to track a replication position associated with the write and avoid serving the subsequent read from a replica until that replica has reached the required position.

Different business operations need different guarantees. A product catalog may tolerate a few seconds of staleness, while reading a newly changed password, account permission, or financial state may require much stronger consistency.

These trade-offs are part of the broader consistency models described in Consistency Models in Distributed Systems.

Failover and Replica Promotion

Replication can support high availability when a replica is capable of becoming the new primary.

Normal operation:

        ┌→ Replica A
Primary ├→ Replica B
        └→ Replica C

If the primary fails, the system selects an appropriate replica and promotes it:

Old Primary → unavailable

Replica A → promoted to Primary
Replica B → follows new Primary
Replica C → follows new Primary

Failover requires more than simply changing a label.

The system needs to determine:

  • whether the old primary is actually unavailable;
  • which replica has the most complete data;
  • whether acknowledged transactions might be missing;
  • how applications discover the new primary;
  • how remaining replicas switch replication sources;
  • how the old primary is prevented from accepting writes if it returns.

Automatic failover reduces recovery time but makes coordination correctness critical.

Split-Brain and Stale Primary Problems

A dangerous failure occurs when two database nodes both believe they are allowed to accept writes.

Suppose the primary loses connectivity to the rest of the cluster:

Primary A     X     Replicas B, C

The cluster may promote B because A appears unavailable.

If A is still running and applications can still reach it, the system can temporarily have two writable nodes:

Client 1 → Primary A → Write X

Client 2 → Primary B → Write Y

The two histories can diverge.

Production replication systems therefore need coordination mechanisms such as quorum decisions, terms or epochs, fencing, leases, or external consensus mechanisms to ensure that an obsolete primary cannot continue accepting authoritative writes.

Leader Election and Distributed Coordination explains the underlying coordination problem in more detail.

Multi-Primary Replication

Some architectures allow multiple database nodes to accept writes.

Application A → Primary A
                    ↕
               Replication
                    ↕
Application B → Primary B

This can reduce write latency across geographic regions and improve write availability, but concurrent updates introduce conflicts.

Suppose two regions update the same record before receiving each other's changes:

Region A → status="approved"
Region B → status="cancelled"

The replication system needs a conflict policy.

Possible strategies include:

  • last-write-wins rules;
  • application-level conflict resolution;
  • ownership of specific records by specific regions;
  • conflict-free data structures for suitable workloads;
  • coordination before accepting conflicting writes.

Multi-primary replication should therefore be chosen because the workload requires it, not simply because more writable nodes sound more scalable.

Replication and Read Scaling

Read replicas are especially useful when an application has far more reads than writes.

Suppose the primary can comfortably handle:

Writes: 5,000 operations/s
Reads:  20,000 operations/s

Application demand grows to 60,000 reads per second.

Adding replicas can distribute the workload:

              ┌→ Replica 1 → 20k reads/s
Application ──┼→ Replica 2 → 20k reads/s
              └→ Replica 3 → 20k reads/s

Writes ─────────→ Primary

This reduces read pressure on the primary.

But replication does not scale writes in the same way. Every primary write still needs to be replicated, and replicas ultimately apply the same changes.

When a single writable database can no longer support the write workload, other techniques such as partitioning or sharding may be required. Database Sharding Strategies and Trade-Offs covers that different scaling problem.

Replication Across Regions

Replicas can be placed in different geographic regions.

A simplified topology might be:

US Region
Primary
   |
   ├→ US Replica
   |
   └────────→ EU Replica

Users in Europe can potentially read from the nearby replica instead of sending every query across the Atlantic.

Cross-region replication introduces additional trade-offs:

  • higher replication latency;
  • larger replication-lag windows;
  • network partitions between regions;
  • cross-region data transfer cost;
  • data residency requirements;
  • more complicated failover decisions.

Synchronous replication across distant regions can significantly increase write latency because network round trips become part of the commit path.

Asynchronous replication avoids that latency on normal writes but increases the amount of recent data potentially unavailable in another region during a sudden primary-region failure.

Multi-region architecture therefore needs explicit recovery point and recovery time requirements rather than assuming replication alone solves disaster recovery.

Replication Is Not a Backup

Replication protects against some infrastructure failures, but it should not be confused with backup.

If an application accidentally executes:

DELETE FROM customers;

a healthy replication system may quickly reproduce that deletion on every replica.

Primary → DELETE
   |
   ├→ Replica A → DELETE
   ├→ Replica B → DELETE
   └→ Replica C → DELETE

The replicas are consistent—and the data is still gone.

The same issue applies to corrupted writes, application bugs, and many administrative mistakes.

Backups, snapshots, and point-in-time recovery preserve historical states that can be restored after logical corruption or deletion.

Capability Replication Backup
Fast failover Yes Usually no
Read scaling Possible No
Protect against server failure Yes Yes, with restore time
Recover deleted historical data Usually no Yes
Point-in-time recovery Not by replication alone Possible with appropriate backup/log strategy

For a broader comparison, see Replication, Snapshots, and Backup Strategies.

Production Design Example

Consider an e-commerce application using PostgreSQL.

The workload is:

Writes:  3,000/s
Reads:  45,000/s

Critical writes:
- orders
- payments
- inventory reservations

Read-heavy data:
- products
- order history
- account information

The database topology uses one primary and two read replicas:

                    ┌→ Replica A
Application → Primary
                    └→ Replica B

All writes go to the primary.

Ordinary read-only requests can use replicas:

Product listing → Replica
Order history   → Replica
Reporting       → Replica

Consistency-sensitive operations remain on the primary:

Create order            → Primary
Read order after create → Primary
Reserve inventory       → Primary
Verify latest balance   → Primary

The application does not randomly distribute every read across every database. Routing depends on the consistency requirements of the operation.

Suppose Replica A develops 20 seconds of replication lag.

It may still be technically reachable, but serving recent order history from it could create visible inconsistencies. The routing layer can temporarily remove that replica from consistency-sensitive read traffic until lag returns below the configured threshold.

If the primary fails, the database management layer promotes the most appropriate replica. Application connections move to the new primary through a stable database endpoint or updated service discovery.

During failover, the system verifies that the old primary cannot continue accepting writes before normal write traffic resumes.

The architecture also maintains independent backups and point-in-time recovery because replication cannot protect against accidental data deletion.

This design uses replication for three separate goals: read scalability, high availability, and infrastructure-failure recovery, while handling logical data recovery through a separate backup strategy.

Monitoring Database Replication

Replication should be monitored as a data pipeline rather than simply checking whether replicas respond to connections.

Important signals include:

Metric What It Reveals
Replication lag How far replicas are behind the primary
Replication byte backlog How much change data remains unapplied
Replica apply rate Whether replicas can keep up with writes
Primary write rate Incoming replication workload
Replica CPU and disk usage Potential apply bottlenecks
Replication connection status Broken or interrupted replication streams
Failover events Changes in database leadership
Replica query latency Whether replicas remain useful for serving reads

Alerting should consider workload requirements.

Five seconds of lag might be irrelevant for an analytics dashboard and unacceptable for an authorization workflow.

Monitoring therefore needs both infrastructure thresholds and application-level expectations.

Common Database Replication Mistakes

  • Assuming replicas are always current. Asynchronous replicas can return stale data.
  • Sending every read to replicas. Read-after-write and other consistency-sensitive operations may require the primary.
  • Treating replication as backup. Accidental deletions and bad writes can propagate to every replica.
  • Monitoring only whether replicas are online. A reachable replica can still be minutes behind.
  • Ignoring replica capacity. Replicas need enough CPU, memory, disk, and I/O capacity to apply changes while serving queries.
  • Assuming replicas scale writes. Primary-replica architectures primarily improve read capacity and availability.
  • Promoting an arbitrary replica during failure. Different replicas may contain different amounts of recent data.
  • Allowing an old primary to rejoin as writable. This can create divergent histories or split-brain behavior.
  • Using synchronous cross-region replication without considering latency. Geographic round trips can become part of every transaction.
  • Adding multi-primary replication without a conflict model. Concurrent writes need explicit resolution semantics.

Replication architecture should start from concrete requirements for availability, acceptable data loss, read freshness, write latency, geographic distribution, and recovery behavior.

Conclusion

Database replication maintains copies of data across multiple database nodes. It can improve read scalability, availability, disaster recovery, workload isolation, and geographic performance.

The important engineering decisions are not simply how many replicas exist. Systems must define how writes propagate, whether replication is synchronous or asynchronous, how much lag is acceptable, which reads can tolerate stale data, how failover works, and how obsolete primaries are fenced.

The core principle is: replication creates additional copies of current database state, but the consistency, durability, and availability guarantees depend on when those copies are updated and how the system behaves when nodes or networks fail.

Comments (0)