SteelReed

Search

Search posts, questions…

7. System Design

Primary–replica replication and read/write splitting: replication lag, read-your-writes and failover

Primary–replica on MySQL and PostgreSQL: async, semi-sync and sync; replication-lag bugs, four ways to keep read-your-writes, read/write routing in Spring Boot, and failover without split-brain.

19 Nov 20268 min readSenior

–

1. The problem

Two replicas are added and every @Transactional(readOnly = true) goes to them. The next day: a user changes their name and the redirect page shows the old one; two sign-ups with the same email both succeed because the duplicate check read a replica.

2. Key idea

The primary is the teacher writing on the board, replicas are students copying it: reading their notebooks is fast and many can read at once, but a notebook sometimes lags the board by a few lines. Web traffic is 90–95% reads, so two replicas nearly triple read capacity. If writes are the bottleneck it's useless: every replica replays every write.

Mode Commit returns when Data loss on failover Cost
Asynchronous (default) the primary has written its log possible no extra latency
MySQL semi-sync one replica has received it none one extra RTT; reads can still be stale
PG remote_apply the standby has applied it none, reads see it immediately slowest

Lag is usually under a second but reaches minutes with transactions updating millions of rows or large DDL.

2.1 How do you keep read-your-writes?

Approach Use when Don't use when
Read the primary (or return the data just written) right after a write, in the same business flow read-heavy public pages
Pin the user to the primary for a few seconds you don't want to change queries; pick seconds > a few × p99 lag lag often exceeds your choice
Carry the write's LSN/GTID you need precision; only route to replicas that have replayed that far you can't track replica positions

Reading to decide a write (duplicate email, stock, balance) must run inside the write transaction on the primary, with UNIQUE or a lock: a replica is wrong even at zero lag, because two parallel requests both see "not there".

3. In Java

JAVA
public class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
        boolean pinned = PrimaryPin.isPinned();            // ThreadLocal set by a filter from cookie/Redis
        return (readOnly && !pinned) ? "replica" : "primary";
    }
}
 
@Bean @Primary
DataSource dataSource(HikariDataSource primaryDataSource, HikariDataSource replicaDataSource) {
    var routing = new ReadWriteRoutingDataSource();
    routing.setTargetDataSources(Map.of("primary", primaryDataSource, "replica", replicaDataSource));
    routing.setDefaultTargetDataSource(primaryDataSource);
    routing.afterPropertiesSet();
    return new LazyConnectionDataSourceProxy(routing);    // required: defers getting the connection
}
// update(): ... PrimaryPin.pinFor(Duration.ofSeconds(5)); return ProfileView.from(saved);

JpaTransactionManager grabs a connection at the start of the transaction, before the readOnly flag is set; the lazy proxy defers it until the first SQL statement.

Measuring lag, failover, and why a replica isn't a backup
  • Measuring lag in MySQL: SHOW REPLICA STATUS → Seconds_Behind_Source, which reports 0 when the I/O thread is stuck. Safer: a heartbeat table (pt-heartbeat) where the primary writes NOW(6) every second. PostgreSQL: pg_stat_replication on the primary (lag in bytes and time), pg_last_wal_replay_lsn() on the standby.
  • Failover: detect (several components must agree) → pick the candidate with the newest GTID/LSN (async can lose transactions) → fence the old primary's write access first, or you get split-brain → redirect clients (DNS, VIP, proxy; mind the JVM DNS cache) → rebuild the old primary as a replica (pg_rewind). Tools: Patroni, Orchestrator, RDS Multi-AZ, Aurora.
  • A replica isn't a backup: a DELETE without WHERE reaches replicas within milliseconds. A backup is a snapshot plus logs for restoring to a specific second.
  • Routing in a proxy (ProxySQL, Pgpool-II, a cloud reader endpoint) needs no code changes but doesn't know "this user just wrote"; usually the proxy routes coarsely and the app decides when the primary is mandatory.
  • Multi-primary must resolve write conflicts (last-write-wins silently loses data; certification forces retries); most systems choose one primary + replicas.

4. Working with AI

Delegate to AI: the routing DataSource, the primary-pinning filter, Testcontainers tests with a real replica to observe lag.

Check yourself:

  • LazyConnectionDataSourceProxy is in place; logs confirm readOnly really goes to a replica.
  • Screens right after a write read the primary or use the data just written.
  • Every "check then write" runs on the primary in one transaction, with UNIQUE or a lock.
  • Lag alerts use a heartbeat, not just Seconds_Behind_Source.

5. Exercises

Exercise 1: Choose where three screens read from

Primary + 2 replicas, p99 lag 800 ms. (a) "My orders" right after placing an order. (b) The public product list. (c) An API checking a coupon still has uses left before applying it. AI suggests "every GET reads a replica". What do you choose?

Solution to Exercise 1
  • (a) Read-your-writes is mandatory: pin the user to the primary for 3–5 seconds after ordering (a few × p99 lag), or return the order in the place-order response.
  • (b) A replica, even a cache/CDN for tens of seconds.
  • (c) "Reading to decide a write": decrement on the primary in the same transaction: UPDATE coupon SET used = used + 1 WHERE code = ? AND used < max_uses, checking the row count. A replica is wrong even at zero lag.

Exercise 2: Read a minutes-of-lag incident

Every night at 1 a.m. PostgreSQL replica lag climbs to 4 minutes and "transaction history" shows missing data; by morning it's fine. At the same time a job runs UPDATE ledger SET archived = true WHERE created_at < now() - interval '1 year' as one transaction. Separately, reports on the standby are sometimes cancelled with "canceling statement due to conflict with recovery". Diagnose and fix.

Solution to Exercise 2
  • Lag: a transaction updating millions of rows produces a big chunk of WAL that the standby replays as a whole. Fix: batch the job (a few thousand rows per transaction, pauses between batches), watching lag and pausing above a threshold.
  • Cancelled reports: long queries on a hot standby conflict with WAL being applied; the standby waits up to max_standby_streaming_delay (30 seconds) and then cancels. Choose: a dedicated reporting replica with a larger delay, or hot_standby_feedback (at the cost of the primary keeping dead tuples longer, so tables bloat).
  • History page: pin to the primary after new transactions, or show "data as of ..." when lag exceeds a threshold.

Summary

  • Replicas scale reads, not writes; asynchronous by default, so they lag.
  • Read-your-writes: read the primary after writing, pin for a few seconds, or route by LSN/GTID.
  • Reading to decide a write always happens on the primary, in the same transaction.
  • Spring: a routing DataSource + LazyConnectionDataSourceProxy.
  • Failover needs fencing; a replica isn't a backup.

Further reading: Sharding: choosing a shard key and resharding.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All Data Modeling & Scaling questions →All Microservices questions →

Loading comments…
Next on the roadmapSharding in system design: choosing a shard key, four case studies and resharding