Skip to lesson

Replication and read replicas

ShopLite's pages are read far more often than orders are placed, yet one database server answers everything and sits at 90% CPU. Extra copies can share the reads, but a copy can be a little out of date.

Your turn: too many reads

ShopLite shows product and order pages about 50 times for every order placed, and one MySQL server is at 90% CPU. Only one server may accept writes. Think about three questions:

  • How can extra servers help the reads if they may not accept writes?
  • A customer places an order and the next page reads from a copy that has not caught up. What does the customer see?
  • The main server dies at 2 a.m. What must happen next, and what could be lost?

Primary for writes, replicas for reads

A replica is a copy of the primary database that applies the primary's changes in the same order and serves read queries, while all writes still go to the primary.

The app writes to the primary; replicas copy its log and answer reads. This program sends one write and nine reads.

The app sends writes to the primary, which saves them and records each change in its binary log. Two replicas copy the log and apply the changes. The app sends reads to the replicas. A label shows that replicas are a little behind, called replication lag.

Example 1 · One primary, two replicas, spread reads

ReplicationBasicsDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class Node {    final String name;    final Map<String, String> data = new HashMap<>();    int reads = 0;    int writes = 0;
    Node(String name) {        this.name = name;    }}
public class ReplicationBasicsDemo {    public static void main(String[] args) {        Node primary = new Node("primary");        List<Node> replicas = List.of(new Node("replica-1"), new Node("replica-2"));        List<String[]> binlog = new ArrayList<>();
        primary.data.put("product:1:stock", "40");        primary.writes++;        binlog.add(new String[] {"product:1:stock", "40"});
        for (Node r : replicas) {            for (String[] change : binlog) {                r.data.put(change[0], change[1]);                r.writes++;            }        }
        for (int i = 0; i < 9; i++) {            Node r = replicas.get(i % replicas.size());            r.data.get("product:1:stock");            r.reads++;        }
        for (Node n : List.of(primary, replicas.get(0), replicas.get(1))) {            System.out.printf("%-9s stock=%s  app writes=%d  reads=%d%n", n.name, n.data.get("product:1:stock"),                    n == primary ? n.writes : 0, n.reads);        }        System.out.println("Replicas applied the change from the log: " + replicas.get(0).writes + " each");    }}
Output
primary   stock=40  app writes=1  reads=0
replica-1 stock=40  app writes=0  reads=5
replica-2 stock=40  app writes=0  reads=4
Replicas applied the change from the log: 1 each

What this code does

  • The app writes only to the primary, which records the change in its log; each replica applies the same change from the log.
  • Nine reads are spread 5 and 4 over the replicas, and the primary handles none of them, leaving it free for writes.

The primary records every change in its binary log (binlog), an ordered list of changes. Each replica fetches that log and applies the same changes in the same order, so after a short delay it holds the same data. The app sends INSERT, UPDATE and DELETE to the primary and spreads SELECTs over the replicas.

This scales reads, not writes: every replica still applies every write. It fits ShopLite, where product and order pages are read far more often than orders are placed. Replicas also give a ready copy if the primary fails, and a place to run heavy reports without slowing checkout.

Synchronous vs asynchronous replication, and lag

Replication lag is how far a replica is behind the primary: the time between a write being confirmed on the primary and appearing on the replica.

Asynchronous replication confirms first and copies later. This program shows a replica with 500 ms lag, then the synchronous alternative.

Example 2 · Replication lag with asynchronous replication

ReplicationLagDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
record Change(long at, String key, String value) { }
class Replica {    final String name;    final long lagMs;    final Map<String, String> data = new HashMap<>();    int applied = 0;
    Replica(String name, long lagMs) {        this.name = name;        this.lagMs = lagMs;    }
    void catchUp(List<Change> log, long now) {        while (applied < log.size() && log.get(applied).at() + lagMs <= now) {            Change c = log.get(applied++);            data.put(c.key(), c.value());        }    }}
public class ReplicationLagDemo {    public static void main(String[] args) {        List<Change> log = new ArrayList<>();        Replica async = new Replica("async replica", 500);
        log.add(new Change(1_000, "order:501:status", "PLACED"));        System.out.println("Async write: confirmed to the user after 5 ms");        for (long t : new long[] {1_100, 1_400, 1_500, 2_000}) {            async.catchUp(log, t);            System.out.printf("  t=%d ms  replica sees status=%s%n", t, async.data.get("order:501:status"));        }
        long networkRoundTripMs = 2;        long applyMs = 3;        System.out.println("Sync write: confirmed after " + (5 + networkRoundTripMs + applyMs)                + " ms, and every replica already has it");    }}
Output
Async write: confirmed to the user after 5 ms
  t=1100 ms  replica sees status=null
  t=1400 ms  replica sees status=null
  t=1500 ms  replica sees status=PLACED
  t=2000 ms  replica sees status=PLACED
Sync write: confirmed after 10 ms, and every replica already has it

What this code does

  • The order is written at t=1000 ms and confirmed to the user at once. A replica with 500 ms lag shows nothing until t=1500 ms.
  • Synchronous replication confirms later (10 ms instead of 5 ms in this simplified model) but no replica is ever behind a confirmed write.

With asynchronous replication (MySQL's default), the primary confirms a write as soon as it is saved locally and ships it to replicas afterwards. Writes are fast, but replicas are a little behind: usually milliseconds, but seconds or minutes when a replica is overloaded or a huge update runs. SHOW REPLICA STATUS reports it as Seconds_Behind_Source.

With synchronous replication, the primary waits for replicas to confirm before it answers, so no confirmed write can be missing on them, at the cost of slower writes and a stall if a replica is slow. MySQL's semi-synchronous mode sits in between: the primary waits until at least one replica has received the change.

Predict the output

What does the replica show?

The replica lags 500 ms behind. What does the customer see?

Round 1 of 3

t=1000 ms primary saves order 501 (asynchronous)
t=1300 ms customer opens My orders -> read goes to the replica

The read-your-own-writes problem

Read-your-own-writes means a user always sees their own changes right away, even when the data is read from a replica that may be behind.

Asha's new order is missing from "My orders". The fix below reads from the primary for 2 seconds after a user's own write.

Example 3 · Asha's missing order, and the sticky-to-primary fix

ReadYourWritesDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class ReadYourWritesDemo {    static final long LAG_MS = 800;    static final long STICKY_MS = 2_000;
    static final List<long[]> log = new ArrayList<>();    static final Map<String, Long> lastWriteAt = new HashMap<>();
    static List<Long> ordersOnPrimary() {        List<Long> ids = new ArrayList<>();        log.forEach(e -> ids.add(e[1]));        return ids;    }
    static List<Long> ordersOnReplica(long now) {        List<Long> ids = new ArrayList<>();        log.stream().filter(e -> e[0] + LAG_MS <= now).forEach(e -> ids.add(e[1]));        return ids;    }
    static void placeOrder(String user, long orderId, long now) {        log.add(new long[] {now, orderId});        lastWriteAt.put(user, now);    }
    static String myOrders(String user, long now, boolean stickyToPrimary) {        Long last = lastWriteAt.get(user);        boolean recentWrite = last != null && now - last < STICKY_MS;        if (stickyToPrimary && recentWrite) {            return "primary " + ordersOnPrimary();        }        return "replica " + ordersOnReplica(now);    }
    public static void main(String[] args) {        log.add(new long[] {0, 498});        placeOrder("Asha", 501, 10_000);
        System.out.println("Always read from a replica:");        System.out.println("  t=10.1 s  My orders -> " + myOrders("Asha", 10_100, false) + "   <- where is order 501?");        System.out.println("  t=11.0 s  My orders -> " + myOrders("Asha", 11_000, false));
        System.out.println("Read from the primary for 2 s after the user's own write:");        System.out.println("  t=10.1 s  My orders -> " + myOrders("Asha", 10_100, true));        System.out.println("  t=13.0 s  My orders -> " + myOrders("Asha", 13_000, true));    }}
Output
Always read from a replica:
  t=10.1 s  My orders -> replica [498]   <- where is order 501?
  t=11.0 s  My orders -> replica [498, 501]
Read from the primary for 2 s after the user's own write:
  t=10.1 s  My orders -> primary [498, 501]
  t=13.0 s  My orders -> replica [498, 501]

What this code does

  • Reading "My orders" from a replica 100 ms after the order shows only order 498; order 501 appears once the 800 ms lag has passed.
  • With the fix, reads by the user who just wrote go to the primary for 2 seconds and include order 501 at once. After that the replica has caught up.

Without the fix, Asha places order 501, the app redirects her to "My orders", and that read goes to a replica 800 ms behind. Her new order is missing, and she may place it again.

Common fixes:

  • Send a user's reads to the primary for a short time (say 2 seconds) after that user writes.
  • Always read data the user just changed (their orders, profile, cart) from the primary; use replicas for catalogue pages and reports.
  • Remember the log position of the user's write and read only from replicas that have reached it.
  • Show the result of the write directly from the write's response instead of reading it back.

Order of execution

Route Asha's request

Put the steps in the order they happen.

A read/write router

A read/write router is the code that picks a database for each statement: writes and transactions go to the primary, and plain reads go to a replica, usually in turn (round robin).

This simulation has two replicas with different lag. Watch what one product price looks like across five reads.

Example 4 · A read/write router with two lagging replicas

ReadWriteRouterDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.atomic.AtomicInteger;
record Change(long at, String key, String value) { }
class Db {    final String name;    final long lagMs;    final Map<String, String> data = new HashMap<>();    int applied = 0;    int queries = 0;
    Db(String name, long lagMs) {        this.name = name;        this.lagMs = lagMs;    }
    void catchUp(List<Change> log, long now) {        while (applied < log.size() && log.get(applied).at() + lagMs <= now) {            Change c = log.get(applied++);            data.put(c.key(), c.value());        }    }}
class ReadWriteRouter {    private final Db primary;    private final List<Db> replicas;    private final List<Change> log = new ArrayList<>();    private final AtomicInteger next = new AtomicInteger();
    ReadWriteRouter(Db primary, List<Db> replicas) {        this.primary = primary;        this.replicas = replicas;    }
    void write(long now, String key, String value) {        primary.data.put(key, value);        primary.queries++;        log.add(new Change(now, key, value));        System.out.printf("t=%4d  WRITE %s=%s -> %s%n", now, key, value, primary.name);    }
    String read(long now, String key) {        Db r = replicas.get(Math.floorMod(next.getAndIncrement(), replicas.size()));   // round robin        r.catchUp(log, now);        r.queries++;        String v = r.data.get(key);        System.out.printf("t=%4d  READ  %s -> %s sees %s%n", now, key, r.name, v);        return v;    }}
public class ReadWriteRouterDemo {    public static void main(String[] args) {        Db primary = new Db("primary", 0);        Db fast = new Db("replica-1 (lag 200 ms)", 200);        Db slow = new Db("replica-2 (lag 800 ms)", 800);        ReadWriteRouter router = new ReadWriteRouter(primary, List.of(fast, slow));
        router.write(0, "price:1", "17999");        router.read(1000, "price:1");        router.read(1100, "price:1");        router.write(1200, "price:1", "16999");      // sale price        router.read(1500, "price:1");        router.read(1600, "price:1");                // the slow replica is still behind        router.read(2100, "price:1");        router.read(2200, "price:1");        System.out.println("queries: primary=" + primary.queries + " replica-1=" + fast.queries + " replica-2=" + slow.queries);    }}
Output
t=   0  WRITE price:1=17999 -> primary
t=1000  READ  price:1 -> replica-1 (lag 200 ms) sees 17999
t=1100  READ  price:1 -> replica-2 (lag 800 ms) sees 17999
t=1200  WRITE price:1=16999 -> primary
t=1500  READ  price:1 -> replica-1 (lag 200 ms) sees 16999
t=1600  READ  price:1 -> replica-2 (lag 800 ms) sees 17999
t=2100  READ  price:1 -> replica-1 (lag 200 ms) sees 16999
t=2200  READ  price:1 -> replica-2 (lag 800 ms) sees 16999
queries: primary=2 replica-1=3 replica-2=3

What this code does

  • Writes go to the primary and are added to the log; reads alternate between replica-1 (lag 200 ms) and replica-2 (lag 800 ms).
  • At t=1500 the fast replica shows the sale price 16999, but at t=1600 the slow one still shows 17999: one user can see the price go back up.

In Spring this is often an AbstractRoutingDataSource that checks whether the current transaction is @Transactional(readOnly = true); managed proxies such as ProxySQL can do the same outside the app.

With replicas that lag by different amounts, two reads a moment apart can return different values, even an older value after a newer one. A good router skips replicas whose lag is above a limit and falls back to the primary when none is fresh enough.

Find the bug

Find the routing bug

Tap the line that routes the statement to the wrong place.

Pick the next replica in turn, forever.

Round 1 of 3

Failover: promoting a replica

Failover is replacing a failed primary with a replica: the replica is promoted to accept writes, and the app is pointed at it.

Failover promotes the replica that has applied the most changes. This program picks it from log positions and counts the lost writes.

Example 5 · Failover: promote the most up-to-date replica

FailoverDemo.javaJava
import java.util.Comparator;import java.util.List;
public class FailoverDemo {    record ReplicaState(String name, int appliedPosition) { }
    public static void main(String[] args) {        int primaryPosition = 1_050;                      // changes the primary had written        List<ReplicaState> replicas = List.of(                new ReplicaState("replica-1", 1_048),                new ReplicaState("replica-2", 1_031));
        System.out.println("Primary stops answering health checks at log position " + primaryPosition);
        // Promote the replica that has applied the most changes        ReplicaState best = replicas.stream()                .max(Comparator.comparingInt(ReplicaState::appliedPosition)).orElseThrow();        System.out.println("Promote " + best.name() + " (position " + best.appliedPosition() + ") to primary");
        for (ReplicaState r : replicas) {            if (r != best) {                System.out.println(r.name() + " now copies from " + best.name()                        + " and first catches up " + (best.appliedPosition() - r.appliedPosition()) + " changes");            }        }        int lost = primaryPosition - best.appliedPosition();        System.out.println("Writes confirmed by the old primary but never copied: " + lost                + " (lost with async replication)");        System.out.println("App config: writes now go to " + best.name());    }}
Output
Primary stops answering health checks at log position 1050
Promote replica-1 (position 1048) to primary
replica-2 now copies from replica-1 and first catches up 17 changes
Writes confirmed by the old primary but never copied: 2 (lost with async replication)
App config: writes now go to replica-1

What this code does

  • replica-1 has applied 1,048 of the primary's 1,050 changes, more than replica-2, so it becomes the new primary.
  • replica-2 copies from the new primary and catches up 17 changes. The last 2 writes existed only on the dead primary and are lost.

A tool or the cloud provider detects that the primary is down, picks the replica that has applied the most of the log, makes it writable (promotes it), points the other replicas at it and switches the app's write address.

With asynchronous replication, writes the old primary confirmed but had not shipped are lost: a few orders the customers believe were placed. Managed databases (for example Amazon RDS Multi-AZ) automate failover in about a minute or two, and apps must retry the failed requests.

Predict the output

Choose and count

The primary wrote up to log position 1,050 and then died.

Round 1 of 2

replica-1 has applied up to 1,048
replica-2 has applied up to 1,031
Which replica do you promote?

Next step

Check your understanding

11 quick questions