Database Replication Models
What you will learn
- What replication is and why it is used
- Primary-replica replication and the ordered change log
- Synchronous versus asynchronous copying
- Replication lag and stale reads
- What can be lost at failover
- Why multi-primary designs create conflicts
All code in this lesson is a simulation that imitates an idea. It is not a real database. You can run each block on its own.
1. What replication is
Replication means keeping a copy of the same data on more than one machine. A copy is called a replica. Replication is used for:
- availability: if one machine fails, another has the data (lesson 14.1)
- read capacity: many replicas can answer reads at the same time
- closeness: a replica near the users answers faster
- backups and analysis: a replica can feed reports without slowing the main system (it is not a replacement for backups, see chapter 8: a mistaken delete is copied to every replica too)
The hard part is that the copies must be kept the same while data keeps changing, and the network between them is slow and can fail.
2. Primary and replicas
The most common design has one primary (also called leader or master in older material) and one or more replicas (followers). The rules:
- All writes go to the primary.
- The primary records every change in an ordered log (the same idea as the log behind transactions in chapter 6).
- Each replica reads the log and applies the changes in the same order.
- Reads can go to the primary or to replicas.
Because every replica applies the same changes in the same order, they end with the same data. The question is when.
3. Synchronous and asynchronous
| Synchronous | Asynchronous | |
|---|---|---|
| The primary tells the client "done" | after the replica has also stored the change | right after the primary stored it |
| Data loss if the primary dies | none for confirmed writes (the replica has them) | recent confirmed writes may be lost |
| Speed | slower: waits for the network | faster |
| If the replica is down or slow | writes can stall | writes continue |
A common compromise is semi-synchronous: wait for one replica to confirm, and let the others catch up in the background.
4. Replication lag and stale reads
With asynchronous copying, a replica is always a little behind the primary. The delay is the replication lag. A read from a replica can therefore return old data (a stale read). This simulation has a primary and two replicas, one quick and one slow:
class Node:
def __init__(self, name):
self.name = name
self.data = {}
self.applied = 0 # how many changes from the primary's log this node has applied
primary = Node("primary")
replicas = [Node("replica-1"), Node("replica-2")]
log = [] # the primary's ordered log of changes
def write(key, value):
primary.data[key] = value # the primary changes first
log.append((key, value))
primary.applied = len(log)
def replicate(replica, how_many):
"""Let a replica catch up by applying up to how_many new changes (its speed is its 'lag')."""
for key, value in log[replica.applied:replica.applied + how_many]:
replica.data[key] = value
replica.applied += 1
def show(title):
print(title)
for node in [primary] + replicas:
print(f" {node.name:10} applied {node.applied}/{len(log)} name = {node.data.get('name')}")
write("name", "Rina")
write("name", "Rina Akter")
write("name", "Rina A. Khan")
replicate(replicas[0], 3) # replica-1 is quick
replicate(replicas[1], 1) # replica-2 is slow
show("After three writes (a simulation of asynchronous replication):")
print("\nA read from replica-2 returns:", replicas[1].data["name"], "(stale)")
replicate(replicas[1], 2)
print("A moment later it returns: ", replicas[1].data["name"], "(caught up)")
print("\nNow the primary fails right after one more write, before any replica gets it:")
write("name", "Rina A. Khan-Rahman")
failed = primary
promoted = replicas[0] # replica-1 becomes the new primary
print(" the write is on the failed primary only:", failed.data["name"])
print(" the new primary has: ", promoted.data["name"])
print(" changes lost by failover:", len(log) - promoted.applied)
After three writes (a simulation of asynchronous replication):
primary applied 3/3 name = Rina A. Khan
replica-1 applied 3/3 name = Rina A. Khan
replica-2 applied 1/3 name = Rina
A read from replica-2 returns: Rina (stale)
A moment later it returns: Rina A. Khan (caught up)
Now the primary fails right after one more write, before any replica gets it:
the write is on the failed primary only: Rina A. Khan-Rahman
the new primary has: Rina A. Khan
changes lost by failover: 1
The same replicas in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The primary's log is a table with an order number, and each replica is just a number: how many log entries it has applied. A replica's data is whatever the log says up to that number. The tables are small ones of their own; Reset data removes them.
CREATE TABLE repl_log (seq INTEGER PRIMARY KEY, key TEXT, value TEXT);
CREATE TABLE replicas (node TEXT PRIMARY KEY, applied INTEGER);
INSERT INTO repl_log VALUES (1, 'name', 'Rina'), (2, 'name', 'Rina Akter'), (3, 'name', 'Rina A. Khan');
INSERT INTO replicas VALUES ('primary', 3), ('replica-1', 3), ('replica-2', 1);
SELECT r.node, r.applied || '/' || (SELECT MAX(seq) FROM repl_log) AS applied,
(SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r ORDER BY r.node;
node applied name
--------- ------- ------------
primary 3/3 Rina A. Khan
replica-1 3/3 Rina A. Khan
replica-2 1/3 Rina
(3 rows)
Replica-2 returns the stale name Rina. A moment later it has applied two more entries:
UPDATE replicas SET applied = 3 WHERE node = 'replica-2';
SELECT node, (SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r WHERE node = 'replica-2';
node name
--------- ------------
replica-2 Rina A. Khan
(1 row)
Now one more write reaches only the primary, which then fails. Replica-1 is promoted, and the entries it never received are the changes lost by the failover:
INSERT INTO repl_log VALUES (4, 'name', 'Rina A. Khan-Rahman');
UPDATE replicas SET applied = 4 WHERE node = 'primary';
SELECT (SELECT MAX(seq) FROM repl_log) - (SELECT applied FROM replicas WHERE node = 'replica-1') AS changes_lost_by_failover;
changes_lost_by_failover
------------------------
1
(1 row)
CREATE TABLE repl_log (seq INTEGER PRIMARY KEY, key TEXT, value TEXT);
CREATE TABLE replicas (node TEXT PRIMARY KEY, applied INTEGER);
INSERT INTO repl_log VALUES (1, 'name', 'Rina'), (2, 'name', 'Rina Akter'), (3, 'name', 'Rina A. Khan');
INSERT INTO replicas VALUES ('primary', 3), ('replica-1', 3), ('replica-2', 1);
SELECT r.node, r.applied || '/' || (SELECT MAX(seq) FROM repl_log) AS applied,
(SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r ORDER BY r.node;
node applied name
--------- ------- ------------
primary 3/3 Rina A. Khan
replica-1 3/3 Rina A. Khan
replica-2 1/3 Rina
(3 rows)
Replica-2 returns the stale name Rina. A moment later it has applied two more entries:
UPDATE replicas SET applied = 3 WHERE node = 'replica-2';
SELECT node, (SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r WHERE node = 'replica-2';
node name
--------- ------------
replica-2 Rina A. Khan
(1 row)
Now one more write reaches only the primary, which then fails. Replica-1 is promoted, and the entries it never received are the changes lost by the failover:
INSERT INTO repl_log VALUES (4, 'name', 'Rina A. Khan-Rahman');
UPDATE replicas SET applied = 4 WHERE node = 'primary';
SELECT (SELECT MAX(seq) FROM repl_log) - (SELECT applied FROM replicas WHERE node = 'replica-1') AS changes_lost_by_failover;
changes_lost_by_failover
------------------------
1
(1 row)
CREATE TABLE repl_log (seq INTEGER PRIMARY KEY, key TEXT, value TEXT);
CREATE TABLE replicas (node TEXT PRIMARY KEY, applied INTEGER);
INSERT INTO repl_log VALUES (1, 'name', 'Rina'), (2, 'name', 'Rina Akter'), (3, 'name', 'Rina A. Khan');
INSERT INTO replicas VALUES ('primary', 3), ('replica-1', 3), ('replica-2', 1);
SELECT r.node, r.applied || '/' || (SELECT MAX(seq) FROM repl_log) AS applied,
(SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r ORDER BY r.node;
node applied name
--------- ------- ------------
primary 3/3 Rina A. Khan
replica-1 3/3 Rina A. Khan
replica-2 1/3 Rina
(3 rows)
Replica-2 returns the stale name Rina. A moment later it has applied two more entries:
UPDATE replicas SET applied = 3 WHERE node = 'replica-2';
SELECT node, (SELECT value FROM repl_log l WHERE l.key = 'name' AND l.seq <= r.applied ORDER BY l.seq DESC LIMIT 1) AS name
FROM replicas r WHERE node = 'replica-2';
node name
--------- ------------
replica-2 Rina A. Khan
(1 row)
Now one more write reaches only the primary, which then fails. Replica-1 is promoted, and the entries it never received are the changes lost by the failover:
INSERT INTO repl_log VALUES (4, 'name', 'Rina A. Khan-Rahman');
UPDATE replicas SET applied = 4 WHERE node = 'primary';
SELECT (SELECT MAX(seq) FROM repl_log) - (SELECT applied FROM replicas WHERE node = 'replica-1') AS changes_lost_by_failover;
changes_lost_by_failover
------------------------
1
(1 row)
Read the output from top to bottom:
- After three writes, the quick replica has all three changes but the slow one has applied only the first. A read from the slow replica returns
Rina, which is stale. A moment later it catches up. Nothing was wrong; it was just behind. - Then the primary fails right after one more write that no replica had received. When replica-1 is promoted to be the new primary (a failover), that last change exists only on the failed machine. One confirmed write was lost. This is the price of asynchronous copying. Synchronous or semi-synchronous copying avoids it at the cost of slower writes.
Two related effects appear in applications:
- Read your own writes. A user saves a change and the next page, read from a lagging replica, shows the old value, so the user thinks the save failed. A common fix is to read from the primary for a short time after a write.
- Failover is a decision. Choosing which replica to promote, and being sure the old primary is really out of action, needs agreement between machines (lesson 14.7).
Quick check: a user changes their name and the profile page still shows the old name. Which replication property is the likely cause?
Replication lag: the page was read from a replica that had not yet applied the change.
5. More than one primary
In multi-primary (multi-leader) replication, several machines accept writes, for example one in each office or region. This helps when a region must keep working even if it cannot reach the others. The cost is that two primaries may change the same data at the same time, and when their changes meet, they conflict.
# Two primaries accept writes at the same time (a simulation of multi-primary replication).
# Each change carries a timestamp. "Last write wins" keeps the newest timestamp.
site_a = {}
site_b = {}
def write(site, key, value, timestamp):
site[key] = (value, timestamp)
write(site_a, "phone", "01711-000000", timestamp=100) # a customer edits their phone in Dhaka
write(site_b, "phone", "01811-111111", timestamp=101) # a support agent edits it elsewhere a moment later
write(site_a, "city", "Dhaka", timestamp=105) # a different field, edited only on site A
print("Before they sync:")
print(" A:", site_a)
print(" B:", site_b)
def merge_last_write_wins(x, y):
merged = dict(x)
for key, (value, ts) in y.items():
if key not in merged or ts > merged[key][1]:
merged[key] = (value, ts)
return merged
merged = merge_last_write_wins(site_a, site_b)
print("\nAfter 'last write wins':")
print(" ", merged)
print("The phone edit made at time 100 is silently gone.")
Before they sync:
A: {'phone': ('01711-000000', 100), 'city': ('Dhaka', 105)}
B: {'phone': ('01811-111111', 101)}
After 'last write wins':
{'phone': ('01811-111111', 101), 'city': ('Dhaka', 105)}
The phone edit made at time 100 is silently gone.
Last write wins in SQL. The merge is an upsert: insert the incoming value, and when the key already exists replace it only if the incoming timestamp is newer. The tables are small ones of their own; Reset data removes them.
CREATE TABLE site_a (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
CREATE TABLE site_b (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
INSERT INTO site_a VALUES ('phone', '01711-000000', 100), ('city', 'Dhaka', 105);
INSERT INTO site_b VALUES ('phone', '01811-111111', 101);
INSERT INTO site_a
SELECT key, value, ts FROM site_b WHERE true
ON CONFLICT (key) DO UPDATE SET value = excluded.value, ts = excluded.ts WHERE excluded.ts > site_a.ts;
SELECT * FROM site_a ORDER BY key;
key value ts
----- ------------ ---
city Dhaka 105
phone 01811-111111 101
(2 rows)
CREATE TABLE site_a (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
CREATE TABLE site_b (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
INSERT INTO site_a VALUES ('phone', '01711-000000', 100), ('city', 'Dhaka', 105);
INSERT INTO site_b VALUES ('phone', '01811-111111', 101);
INSERT INTO site_a
SELECT key, value, ts FROM site_b WHERE true
ON CONFLICT (key) DO UPDATE SET value = excluded.value, ts = excluded.ts WHERE excluded.ts > site_a.ts;
SELECT * FROM site_a ORDER BY key;
key value ts
----- ------------ ---
city Dhaka 105
phone 01811-111111 101
(2 rows)
CREATE TABLE site_a (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
CREATE TABLE site_b (key TEXT PRIMARY KEY, value TEXT, ts INTEGER);
INSERT INTO site_a VALUES ('phone', '01711-000000', 100), ('city', 'Dhaka', 105);
INSERT INTO site_b VALUES ('phone', '01811-111111', 101);
INSERT INTO site_a
SELECT key, value, ts FROM site_b WHERE true
ON CONFLICT (key) DO UPDATE SET value = excluded.value, ts = excluded.ts WHERE excluded.ts > site_a.ts;
SELECT * FROM site_a ORDER BY key;
key value ts
----- ------------ ---
city Dhaka 105
phone 01811-111111 101
(2 rows)
The phone edit made at time 100 is silently gone: the upsert kept the newer one.
Both sites changed the phone number, and the system has to choose. The rule used here, last write wins, keeps the change with the later timestamp. It is simple, but it throws away the other edit without anyone noticing. Other approaches are to keep both versions and ask a person, to merge by rules for each kind of data, or to design the data so that conflicts cannot happen (for example, by adding a new row for each event instead of changing a value). Timestamps from different machines are also not perfectly in step, which makes "last" less clear than it looks.
Single-primary replication avoids this class of problem by giving every piece of data exactly one place where writes are decided.
Worked example: choosing a replication setup for a shop
An online shop (made-up) has one database in a main city. Reports and a busy product search slow it down at lunchtime, and the owner fears losing orders if the machine breaks.
| Need | Choice | Why |
|---|---|---|
| Do not lose paid orders | one replica with semi-synchronous copying | an order is acknowledged only after two machines hold it |
| Faster product search and reports | two more asynchronous replicas used only for reads | a few seconds of lag is fine for search and reports |
| Customer sees their own new order | after placing an order, read the order page from the primary | avoids stale reads right after a write |
| One office abroad edits stock too | do not start with multi-primary | keep one primary; conflicts need a plan first |
The shop gets safety for payments, speed for reading, and no conflict handling at all.
Common mistakes
- Treating replicas as backups. A bad delete or a bug is copied to every replica within moments.
- Reading just-written data from a lagging replica. Users see their own changes disappear.
- Assuming failover loses nothing. With asynchronous copying, recent writes can be lost.
- Choosing multi-primary without a conflict rule. Last-write-wins quietly discards edits.
- Promoting a replica without making sure the old primary stopped. Two machines then both believe they are the primary (lesson 14.7).
Key takeaways
- Replication keeps copies of data on several machines for availability, read capacity and closeness.
- In primary-replica replication, all writes go to the primary, which sends an ordered log to the replicas.
- Synchronous copying is safer and slower; asynchronous is faster and can lose recent writes at failover.
- Replicas lag behind, so reads from them can be stale.
- Multi-primary lets several places accept writes but creates conflicts that need a rule.
- Replication is not a backup.
Practice
1. What is replication lag?
Show answer
The delay between a change being made on the primary and the same change being applied on a replica.
2. In the simulation, why did replica-2 return Rina after three writes?
Show answer
It had applied only the first change from the log so far, so it was behind. Its answer was stale, not wrong in the sense of corrupted.
3. Why was one write lost at failover in the simulation, and how could it be avoided?
Show answer
The primary confirmed the write before any replica had it, and then failed, so the promoted replica never received it. Synchronous or semi-synchronous copying makes the primary wait for at least one replica before confirming.
4. Give two reasons why a replica is not a replacement for a backup.
Show answer
A mistaken delete or a bad update is copied to every replica; and a bug or corruption can spread the same way. A backup keeps an older, separate copy that you can restore from.
5. In the multi-primary simulation, which edit was lost and why?
Show answer
The phone number written at time 100 was lost, because the other site wrote a phone number at time 101 and "last write wins" kept the later one.
6. A user saves a new address and the page immediately shows the old one. Suggest a fix that keeps most reads on replicas.
Show answer
Read from the primary for that user for a short time after they write (or until their replica has caught up), and use replicas for all other reads.