Introduction to data replication
easy 25 minReplication keeps the same data on several machines and keeps the copies up to date.
Video lesson · Chapter 1 of 5
Can a nearby catalog answer the lunch rush
Why we copy databases, in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Data replication means keeping a copy of the same data on more than one machine, and keeping every copy up to date as the data changes. Each copy is called a replica.
Making a copy once is easy. Replication is the second part: data changes all day, so every change made on one copy must reach all the others, in an order that makes sense.
Replication is different from partitioning. Replicas hold the same rows. Partitions, also called shards, hold different rows. Large systems use both, and sharding covers the second one.
Why it exists
A single database server is a single point of failure: when it stops, so does everything that needs the data. A second copy means a failure becomes a short interruption instead of a long outage.
Copies also do useful work while nothing is broken. Read queries can be spread over them, reports can run on one without slowing customers down, and a copy in another region answers the people there without a trip across an ocean.
The price is that copies can disagree for a while. Almost every hard question about replication is about what users see during that while.
A short history
1979
David Gifford publishes weighted voting for replicated data: give every copy a vote, and require enough votes to read or write.
1996
Jim Gray and others publish The Dangers of Replication and a Solution. They show that letting every copy accept transactional updates becomes unstable as the number of nodes grows.
2007
Amazon describes Dynamo, a store in which any of several nodes can accept a write and conflicting versions are reconciled later.
2010
PostgreSQL 9.0 ships built-in streaming replication and hot standby, so a standby server can also answer read-only queries.
Words to know
- Primary (leader)
- The copy that accepts writes. The source of truth in single-leader replication.
- Replica (follower)
- A copy that receives changes from a leader. It normally serves reads only.
- Replication lag
- The delay between a write on the primary and the moment it can be seen on a replica.
- Failover
- Making a replica the new primary after the old one fails.
- Write conflict
- Two copies accepted different changes to the same record at about the same time.
- Quorum
- The number of copies that must answer before an operation counts as done.
- Convergence
- All copies end up with the same value once changes stop.
How it works
Step through the idea, or press Play.
Copy. Start a new server from a full copy of the data
Understand it
Start here
The treasure map
Some friends own one treasure map. If rain ruins it, the treasure is lost. So they make copies, agree that one friend adds new marks first, and everyone else copies those marks.
Everything on this page is a detail of this picture: who may draw, how marks travel, and what a friend sees before the mark arrives.
The idea
The basic architecture
Writes to one, reads from many
Four words you need
Primary, or leader
Accepts all the writes. The source of truth.
Replica, or follower
A read-only copy that follows the primary.
Replication lag
How far behind the primary a replica is.
Failover
A replica becomes the primary when the original fails.
One write and two reads
Why
Three reasons to replicate
Before and after
| Question | One server | Replicated |
|---|---|---|
| Who does the work? | One server handles everything | Several servers share the reads |
| The server crashes | Total outage | Failover to a copy, if it is set up and tested |
| More read traffic | Limited by one machine | Add replicas |
| Users far away | Every read crosses the distance | Reads come from a replica in the region |
| Maintenance | Downtime | Patch replicas in turn, then switch over |
High availability. A replica can take over. How long that takes depends on detection and promotion, which implementing replication covers step by step. Read scaling. Many applications read far more often than they write. Geography. A nearby copy removes the distance from each read.
How much does read scaling give?
Why distance costs time
Type 1
Single-leader replication
One primary accepts all writes and sends them to its replicas. Older texts call it master-slave. PostgreSQL streaming replication, MySQL replication, MongoDB replica sets and Redis replication all work this way.
Good
- Simple to understand and run
- No write conflicts between leaders
- Strong reads are possible: read from the primary
Costs
- Writes stop until failover if the primary dies
- Write throughput is one machine's throughput
- Reads from replicas can be old
Single leader
Type 2
Multi-leader replication
Several nodes accept writes and send changes to each other. It is common to put one leader in each region, so local users write locally and a region keeps working when the link between regions is cut. CouchDB databases that replicate both ways are an example, and so is an app that lets you edit offline: each device is a small leader.
Good
- Local writes in each region are fast
- A region survives losing another region or the link
- Offline editing becomes possible
Costs
- Two leaders can change the same row: a write conflict
- Conflict resolution is complex
- Unique and foreign-key checks are hard across leaders
How to resolve a write conflict
| Method | How it works | What you lose |
|---|---|---|
| Avoid it | Each record has a home region that takes its writes | Writes travel when the user moves |
| Last write wins | Keep the change with the newest timestamp | The other change disappears, and clocks must agree |
| Keep both | Store both versions and let the application choose | Extra code, and users may have to decide |
| Merge | Use a data type that merges safely, such as a counter or a set | Only some data has a sensible merge |
Type 3
Leaderless replication
Any replica of a record can take a read or a write. The client, or a coordinator node, sends each operation to several replicas and waits for enough answers. With N copies, writing to W and reading from R overlaps when R + W > N. The proof, and what it does not promise, live in implementing replication. Apache Cassandra is the best-known example, and Amazon's Dynamo paper describes the idea.
Good
- No leader whose loss stops writes
- Stays available while some nodes are down
- Consistency can be tuned per request
Costs
- Often eventually consistent
- Copies that missed a write need repair
- Concurrent writes conflict and need a rule
Leaderless with three copies
Compare
The three side by side
| Aspect | Single leader | Multi-leader | Leaderless |
|---|---|---|---|
| Write conflicts | None between leaders | Possible | Possible |
| Consistency | Strong if you read from the primary | Eventual between leaders | Tunable |
| Complexity | Low | High | Medium |
| Write availability | Lowest: waits for failover | Higher | Highest while a quorum answers |
| Fits | Most applications | Regions that must write alone, offline apps | Very large, always-on key lookups |
Which type do I need?
Speed or safety
Wait for the copies, or not?
A primary can wait for a replica before it tells the client the write is done (synchronous), or answer immediately and send the change afterwards (asynchronous). Waiting protects the last writes when the primary dies. Not waiting is faster, and a slow replica cannot hold up customers.
When to use what
| Wait (synchronous) | Do not wait (asynchronous) |
|---|---|
| Money movements | High write throughput |
| Data that must not be lost | Copies far away |
| The business accepts extra latency | Low latency is critical |
| A standby nearby, in the same region | Slightly old reads are acceptable |
Using replicas
Route reads and writes
Read/write splitting sends every write to the primary and most reads to replicas. It can live in the application, in the database driver or in a proxy between them.
- 1
Classify
Is this a write, a read that must be current, or a read that may be old?
- 2
Send writes to the primary
A read inside a transaction that writes goes there too.
- 3
Send current reads to the primary
For example an account balance before a payment.
- 4
Send the rest to a healthy replica
Take turns, skip replicas that are down or too far behind.
- 5
Fall back
If no replica is healthy, use the primary only if it has the spare capacity. Otherwise shed the least important reads.
A primary at home, replicas near users
Three patterns that hide the lag
| Pattern | What you do | What the user notices |
|---|---|---|
| Read your writes | After a write, send that user's reads to the primary for a short time | Their own change is always there |
| Sticky sessions | Keep sending a user to the same replica | Data does not jump back in time, until that replica is lost |
| Causal order | Remember what a user has seen, and only read from copies that have it | Never an answer before its question |
Not the same
A replica is not a backup
A replica copies everything, quickly, including the mistakes. Delete a table by accident and every replica deletes it moments later. Backups keep older versions that nothing overwrites. You need both, and you need to practise restoring.
Do
- Pool connections to each node
- Route writes to the primary only
- Monitor replication lag
- Test failover regularly
- Health-check replicas and retry safely
Do not
- Read everything from the primary
- Ignore the lag
- Skip retry logic
- Write to a replica directly
- Forget that the network between copies can break
Examples
What to pick for four systems
Worked choices, with reasons
| System | Choice | Reason |
|---|---|---|
| Bank ledger | Single leader, synchronous standby in the same region | Losing a confirmed payment is worse than a slower one |
| Social feed | Single leader per shard, asynchronous read replicas | A like that appears a second late harms nobody |
| Shop | Primary for stock and orders, replicas for the catalogue | Product pages are read far more than they change |
| Viewing history in several regions | Leaderless, eventual | It must accept writes everywhere, and an old position is easy to live with |
How it sounds in an interview
Interviewer
Your recipe site has 1,000 reads a second on average and 20 writes. What does the data layer look like?
You
Peak is about 3 times average, so 3,000 reads and 60 writes a second. I assume one node serves 2,000 simple reads a second, so I need two nodes for the load and a third so that losing one is fine: a primary and two replicas. Writes are tiny, so one leader is enough.
Interviewer
A cook saves a recipe and does not see it.
You
That read hit a replica that was behind. I send a user's reads to the primary for a few seconds after they save. Everyone else can wait a second.
Summary
The whole topic in one minute.
Replication keeps copies of the same data on several machines. You gain survival, read capacity and nearness to users, and you pay in storage, in extra work for every write, and in copies that briefly disagree.
Choose who may write first. One leader is the simplest and is right for most systems. Several leaders help when regions must keep writing on their own, and cost you conflicts. Leaderless stores ask several nodes on each operation. A replica is never a backup, because it copies your mistakes too.
- Replication is the same data on several machines, kept up to date.
- It buys availability, read capacity and nearness to users. It does not add write capacity.
- Single leader first. Several leaders or no leader only when a requirement forces it, with a conflict rule.
- Route writes to the primary, current reads to the primary, the rest to healthy replicas.
- A replica is not a backup.