Sitemap

Database Replication Patterns

12 min readDec 23, 2025

--

This guide covers the fundamental replication patterns.

Replication means keeping a copy of the same data on multiple machines that are connected via a network. The major reasons for replication are:

  • High Availability: Keeping the system running even when one machine (node) goes down.
  • Latency: Placing data geographically closer to users.
  • Scalability: Increasing read throughput by handling more read requests than a single machine can.

1. Overview of Frameworks

There are three main approaches to replication:

  1. Single-Leader: One node accepts writes; all others replicate.
  2. Multi-Leader: Multiple nodes accept writes; they replicate to each other.
  3. Leaderless: No central leader; writes are sent to multiple nodes directly.
Press enter or click to view image in full size

2. Single-Leader Replication

In this pattern (also known as active-passive or master-slave), one replica is designated as the leader (master/primary). The others are followers (read replicas/slaves/secondaries).

How It Works

  1. Clients send all writes to the leader.
  2. The leader writes the change to its Write-Ahead Log (WAL) first (on disk, for durability).
  3. The leader applies the change to its in-memory data structures (and eventually to the data files).
  4. The leader sends the WAL entries to all followers.
  5. Followers write to their own WAL, then apply the changes in the same order as the leader.
  6. Reads can be served by the leader or any follower.

Replication Methods

Different databases implement replication in different ways:

  1. Statement-Based Replication: The leader logs every SQL statement (INSERT, UPDATE, DELETE) and sends it to followers.

Pros: Compact (SQL statements are usually smaller than the data they modify), simple to understand.

Cons:

  • Nondeterministic functions (NOW(), RAND(), UUID()) produce different values on each replica
  • Statements with auto-incrementing columns or those that depend on existing data can produce different results
  • Statements with side effects (triggers, stored procedures, UDFs) may behave differently on each replica
  • Requires followers to execute the same statements in the exact same order

Used by: MySQL (before 5.1), older versions of PostgreSQL

2. Write-Ahead Log (WAL) Shipping: The leader sends the exact sequence of bytes written to the WAL (physical replication).

Pros:

  • Exact replica — followers guaranteed to have identical data structures
  • No ambiguity about what should be replicated
  • Efficient for high write throughput

Cons:

  • Very low-level (describes data at the level of disk blocks and byte offsets)
  • Tightly coupled to the storage engine — different storage engine versions may not be compatible
  • Zero-downtime upgrades are difficult (can’t replicate between different database versions)
  • Can’t replicate between different database systems

Used by: PostgreSQL (physical replication), Oracle (physical standby)

3. Logical (Row-Based) Replication: Uses a logical log format describing inserts, updates, and deletes at the row/document granularity (logical replication).

Pros:

  • Decoupled from storage engine internals — leaders and followers can run different database versions
  • Can replicate between different storage engines or even different database systems
  • Easier to parse by external applications (for change data capture, data warehousing, custom indexes)
  • Allows selective replication (e.g., only certain tables or certain types of changes)

Cons:

  • May be larger in size compared to physical WAL (especially for operations that modify many rows)
  • Slightly more CPU overhead to produce logical log entries

Used by: MySQL binlog (row-based mode), PostgreSQL (logical replication), MongoDB (oplog), Oracle (logical standby)

Key Concepts

Synchronous vs. Asynchronous Replication

  • Synchronous Replica: The leader waits for the replica’s acknowledgment (ACK ✓) before reporting success to the client. This provides strong consistency between the leader and synchronous replica, guaranteeing durability. However, writes block if the replica is slow or down.
  • Asynchronous Replica: The leader reports success immediately without waiting for acknowledgment. This is fast but provides only eventual consistency. Data can be lost if the leader fails before replicating.
  • Semi-Synchronous: One replica is synchronous (for durability), while others are asynchronous (for availability). This is the most common production setup.

Handling Failures

  • Follower Failure: Catch-up recovery. Each follower keeps a log of data changes received from the leader. If a follower crashes or the network is interrupted, it can recover by connecting to the leader and requesting all changes that occurred during disconnection (using the last processed position in the log).
  • Leader Failure: Failover (the trickiest case). The process involves:
  1. Detecting leader failure: Most systems use timeout-based detection (if the leader doesn’t respond for 30 seconds, it’s assumed dead). But timeout-based detection is problematic because there’s no foolproof way to detect a failure — network issues can look like node failures.
  2. Choosing a new leader: Election via consensus algorithm or appointed by a previously elected controller node. The best candidate is usually the replica with the most up-to-date data changes.
  3. Reconfiguring the system: Clients must send writes to the new leader. The old leader must recognize that it’s no longer the leader when it comes back (to prevent split-brain scenarios).

Replication Lag Issues

  • With asynchronous replication, followers may be seconds or even minutes behind the leader. This leads to several consistency problems:
  • Read-After-Write Consistency (also called read-your-writes): Users should always see their own updates immediately after writing. Solutions include:
  • Reading user’s own profile from the leader, other users’ profiles from followers
  • Tracking the timestamp of the last update and ensuring reads from replicas sufficiently up-to-date
  • Client remembering the timestamp of its most recent write and ensuring the replica has processed updates at least until that timestamp
  • Monotonic Reads: If a user makes several reads, they should not see time go backward (seeing data, then refreshing and not seeing it). This can happen if different reads are routed to different replicas. Solution: Each user always reads from the same replica (e.g., hash user ID to choose replica).
  • Consistent Prefix Reads: Users should see causality preserved (questions before answers, cause before effect). This is a problem in partitioned databases where different partitions operate independently. If writes happen in a certain order, anyone reading should see them in that same order.

Pros & Cons

Press enter or click to view image in full size

When to Choose

✅ Choose Single-Leader when:

  • You have a read-heavy workload (can scale reads by adding followers).
  • Your application requires simple, strong consistency guarantees.
  • You are using standard relational databases (PostgreSQL, MySQL, SQL Server) which default to this mode.
Press enter or click to view image in full size

3. Multi-Leader Replication

Also known as master-master or active-active replication. Multiple nodes are allowed to accept writes. Each node that accepts writes must forward that data change to all other nodes.

How It Works

  • Typically used in multi-datacenter setups (e.g., Datacenter 1 in US East, Datacenter 2 in EU West, Datacenter 3 in Asia).
  • Each datacenter has its own “leader” that accepts writes locally from nearby clients.
  • Within each datacenter, the leader replicates to local followers.
  • Cross-DC Replication: Leaders replicate to each other asynchronously across datacenters, forming a mesh topology.

Key Concepts

  • Write Conflicts: ⚠️ The biggest challenge. Since multiple leaders can update the same record concurrently, conflicts will happen. In single-leader systems, the leader determines the order of writes, so there are no conflicts. But in multi-leader, concurrent writes can conflict.
  • Detecting Conflicts: A conflict exists when two operations are concurrent (neither happened before the other in the causal order). To detect this, we need version vectors (or vector clocks) — each replica keeps track of version numbers for itself and other replicas.
  • Conflict Resolution Strategies:
  • Last Write Wins (LWW): Assign each write a timestamp or unique ID, and the highest timestamp wins. Simple but prone to data loss because concurrent writes are not truly concurrent in wall-clock time. Used by Cassandra and Riak.
  • Merge Conflicts On Read: Store all conflicting versions (siblings) and present them to the application/user to resolve. The application merges the values and writes back the result. Used by Riak, CouchDB (revision trees).
  • Custom Merge Logic: Application code automatically merges values using domain-specific rules. For example, merging shopping cart items or collaborative text editing.
  • Conflict-Free Replicated Data Types (CRDTs): Data structures that automatically resolve conflicts in sensible ways (e.g., sets, counters, registers). CRDTs can be merged without any conflict resolution logic.
  • Operational Transformation: Conflict resolution algorithm for concurrent edits to ordered lists (used in Google Docs, Figma).
  • Topologies:
  • All-to-all: Every leader talks to every other leader (shown in diagram). Most general but can result in some writes overtaking others due to different network delays.
  • Circular: Each node forwards writes to the next node in the ring. If one node fails, it can break the circle.
  • Star: One designated root node forwards writes to all other leaders. If the root fails, it breaks replication.

Pros & Cons

Press enter or click to view image in full size

When to Choose

✅ Choose Multi-Leader when:

  • You have a multi-datacenter deployment and need to tolerate entire datacenter failures.
  • Your users are geographically distributed and need low write latency.
  • Your application needs to work offline (e.g., mobile apps syncing when online).
  • You are using databases suited for this, such as CouchDB or MongoDB (in multi-master mode).
  • You are willing to implement complex conflict resolution logic.
Press enter or click to view image in full size

4. Leaderless Replication

Also known as Dynamo-style replication (used by Amazon Dynamo, Cassandra, Riak, Voldemort). No Single Leader! All nodes are equal. The client sends writes to multiple replicas concurrently.

How It Works

  1. Quorums: To ensure consistency, we use the formula W + R > N (Write quorum + Read quorum > Total replicas).

Example: With N=5 total nodes, W=3 write quorum, R=3 read quorum:

  • Client sends PUT to all 5 nodes in parallel.
  • Write succeeds when 3 nodes acknowledge (W=3 satisfied).
  • Client reads from 3 nodes (R=3). Since 3 + 3 = 6 > 5, at least one node is guaranteed to have the latest version.
  • Why W + R > N works: If W + R > N, the write and read quorums must overlap (have at least one node in common). This guarantees that at least one of the nodes you read from must have seen the most recent write.
  • Tuning quorums: You can vary W and R to make reads or writes faster. For example, W=N, R=1 makes reads very fast (only need to read from one node) but writes slow. W=1, R=N makes writes fast but reads slow. Common choices: W=R=(N+1)/2 (rounded up).

2. Sloppy Quorum & Hinted Handoff:

Get Saahid’s stories in your inbox

Join Medium for free to get updates from this writer.

Traditional quorums are not fault-tolerant — if too many nodes are unavailable, you can’t reach a quorum. Sloppy quorums relax the requirement: writes and reads still require W and R successful responses, but they may be from nodes that are not among the designated N “home” nodes for a value. When a temporarily unavailable node comes back online, any writes that were sent to a substitute node are sent back to the original “home” nodes (hinted handoff). This improves write availability at the cost of consistency — you may read stale data even if W + R > N because the values may have been written to different nodes than you’re reading from.

3. Detecting Concurrent Writes:

Even with quorums, you can get conflicts. If two clients concurrently write to the same key (or if the write is handled by different nodes that then replicate), you need to determine which write happened first. This requires version vectors (generalizing version numbers to multiple replicas). Each replica increments its own version number when processing a write, and keeps track of the version numbers it has seen from every other replica.

4. Repairing Data:

  • Read Repair: When a client reads from multiple nodes and detects stale data (e.g., version v1 vs v2), it writes the newer version back to the stale nodes immediately. Works well for frequently read values.
  • Anti-Entropy: A background process (often using a Gossip protocol) constantly compares data between nodes and syncs missing data. Uses Merkle trees (hash trees) to efficiently detect differences between replicas. Essential for values that are rarely read.

Pros & Cons

Press enter or click to view image in full size

When to Choose

✅ Choose Leaderless when:

  • High Availability is your #1 priority (system must never reject a write).
  • You can tolerate eventual consistency.
  • You need to withstand chaotic network conditions or high node failure rates.
  • Common in big data / NoSQL stores (Cassandra, DynamoDB).
Press enter or click to view image in full size

Quorum Operations in Detail

The diagram below shows a complete write and read cycle with read repair:

  1. Write Operation (W=3): Client sends PUT key=user:123, value=data, version=v2 to all 5 nodes. Three nodes (N1, N2, N3) acknowledge, satisfying the write quorum.
  2. Read Operation (R=3): Client sends GET key=user:123 to nodes N1, N3, N4. N1 and N3 return v2 (latest), but N4 returns v1 (stale).
  3. Read Repair: Client detects the version conflict, returns v2 to the application, and triggers an update to N4 to repair the stale data.
Press enter or click to view image in full size

5. Other Architectures

Chain Replication

Arranges nodes in a chain. Writes go to the Head, propagate through Middle nodes, and end at the Tail. Reads always come from the Tail.

Write Flow:

  1. Write Client sends PUT to the Head Node.
  2. Head processes the write and forwards to Middle Node 1.
  3. Middle nodes apply updates and forward down the chain.
  4. Tail Node applies the update and sends ACK back to the client.
  5. Only when the Tail acknowledges is the write considered committed.

Read Flow:

  • Read Client always queries the Tail Node.
  • The Tail always has the latest committed data, providing strong consistency guarantee.

How Chain Replication Ensures Consistency:

  • Writes propagate from head to tail in order. The tail sends acknowledgment only after all nodes in the chain have applied the write.
  • Since all reads go to the tail, and the tail only acknowledges writes that have been applied everywhere, reads are always linearizable (clients always read the latest committed value).
  • If a node fails in the middle of the chain, the system can reconfigure: remove the failed node from the chain and let updates flow around it.

CRAQ (Chain Replication with Apportioned Queries):

An enhancement that allows reads from any node in the chain (not just the tail), improving read throughput while maintaining strong consistency. Nodes in the chain maintain both “clean” (committed) and “dirty” (uncommitted) versions. A read from a non-tail node can return a clean version if it has one; otherwise, it queries the tail for the latest committed version.

Trade-offs:

  • Pros: Strong consistency (linearizable reads), high read throughput (CRAQ allows reading from any node), simple consistency model, good for write-once-read-many workloads.
  • Cons: Higher write latency (must traverse entire chain), head and tail are critical points (failure requires reconfiguration).
  • Use Case: Object storage systems (e.g., Azure Storage, CRAQ), blob stores, immutable data storage.
Press enter or click to view image in full size

Consensus-Based (Raft/Paxos)

Uses a consensus algorithm (like Raft) to agree on a sequence of values (the replicated log). Provides strong consistency with automatic failover.

Normal Operation (Raft Consensus):

  1. Client sends PUT to the Leader.
  2. Leader appends the entry to its local log.
  3. Leader sends AppendEntries RPC to all followers.
  4. Followers append to their logs and send ACK.
  5. When a majority acknowledges (e.g., 3/5 nodes), the entry is committed.
  6. Leader responds to the client and notifies followers of the commit.

Leader Failure Scenario:

  1. Leader fails 💥.
  2. Election timeout triggers on followers.
  3. A follower becomes a candidate and sends RequestVote RPC to all nodes.
  4. If it receives a majority of votes (e.g., 3/5), it becomes the new leader.
  5. System continues with the new leader.

Key Mechanisms in Raft:

  • Terms (Epochs): Logical clocks that divide time into numbered periods. Each term has at most one leader. When a leader fails, a new term begins with a new election. This prevents split-brain scenarios where two leaders exist simultaneously.
  • Log Matching Property: If two logs contain an entry with the same index and term, then they are identical in all preceding entries. This is enforced by the AppendEntries RPC consistency check.
  • Leader Completeness: If a log entry is committed in a given term, then that entry will be present in the logs of the leaders for all higher-numbered terms. This ensures no committed data is lost.
  • State Machine Safety: If a server has applied a log entry at a given index to its state machine, no other server will ever apply a different log entry for the same index.

Why Consensus is Expensive:

  • Every write requires at least two network round-trips: one to propose, one to commit.
  • Cannot make progress if a majority of nodes are unavailable. In a 5-node cluster, losing 3 nodes means the cluster cannot accept writes (it can still serve reads from remaining nodes).
  • More complex than primary-backup replication (single-leader).

Trade-offs:

  • Pros: Strong consistency (linearizable), automatic leader election with safety guarantees, proven safety (formal verification), fault-tolerant (survives minority failures).
  • Cons: Performance overhead (consensus rounds, at least 2 RTTs per write), complexity, requires majority for progress (cannot tolerate majority failures — 5 nodes can only tolerate 2 failures).
  • Use Case: Configuration stores (etcd, ZooKeeper, Consul), coordination services, distributed locks, leader election, metadata storage. Not suitable for high-throughput data storage due to performance overhead.
Press enter or click to view image in full size

Summary: Which one should I choose?

Press enter or click to view image in full size

--

--