System Design Part 4 Distributed data

Replication and Replication Lag: Why Users Cannot Read What They Just Wrote After Read/Write Splitting

Bill.Lin 22 min read

System Design series Part 4-1 | Previous: Geohash and Geospatial Indexes | Next: Sharding | Series map

Read first: Part 3-4 Transactions and Isolation Levels.

Scenario and problem

The talk platform’s read-to-write ratio is about 50 : 1: at peak it serves 10,000 reads and 200 writes per second, and the primary’s CPU has stayed above 80% for a long time. The team added two read replicas and sent queries to them, and the load on the primary dropped right away. But a week after launch, customer support was getting three kinds of complaints:

  1. “I changed my profile bio, and after a refresh it still shows the old one.”
  2. “After I signed up, the talk was in my ‘My sign-ups’ list. I refreshed and it was gone, refreshed again and it was back.”
  3. After the primary crashed and the system failed over to a replica, the sign-up records from the last few seconds were gone.
After reads go to the replicas11 / 11
After reads go to the replicasUserPrimaryReplica 1Replica 2Edit profile bioSuccessRefreshStill the old bioSign up for a talkMy sign-upsThe talk is thereRefresh againThe talk is goneCrashesPromoted to new primary
  1. Writes always go to the primary. With a 50 : 1 read-to-write ratio, reads go to the two replicas.
  2. The primary replies as soon as the write succeeds, without waiting for the replicas (MySQL's default asynchronous replication).
  3. On refresh, the read is routed to replica 1.
  4. The replica has not applied that change yet, so the user sees old data. The lag is usually only tens of milliseconds, but a large transaction can push it to several seconds.
  5. The user then signs up for a talk.
  6. This time replica 1 has caught up.
  7. The list shows the talk the user just signed up for.
  8. Another refresh lands on replica 2, which is further behind.
  9. The sign-up is gone from the list; one more refresh lands back on replica 1, and it reappears. The two replicas are at different points, so the data seems to travel back in time.
  10. The moment the primary crashes, the last few writes have not reached any replica. With 200 milliseconds of lag and 200 writes per second, that is about 40 transactions already reported as successful.
  11. After the failover to replica 1, the records of users who were already told "you are signed up" are gone.

All three problems come from one thing: the replicas’ data lags behind the primary.

The simplest approach and its limits

The simplest approach is to read everything from the primary. There is no lag problem at all, but read volume is capped by what one machine can handle. Adding replicas scales reads horizontally, and the price is having to answer: which reads can accept stale data, and how stale.

The lag is usually only tens of milliseconds, so it is hard to reproduce in a test environment. But it has a long tail: while a replica applies a large transaction (say, a monthly settlement that updates 3 million rows at once), the transactions after it often have to queue behind it, and the lag keeps building up to several seconds. With asynchronous replication, if the primary crashes at a moment when the lag is 200 milliseconds, then at 200 writes per second about 40 transactions already reported to users as successful have not reached a replica; during an 8-second lag spike it is 1,600.

Core mechanism

What replication copies

  • Statement-based: copies the SQL statement itself. Little data, but NOW(), UUID(), and LIMIT without ORDER BY are re-executed on the replica, and the results may differ
  • Row-based: copies the actual change to each row. The result is always the same, but an UPDATE that changes 3 million rows becomes 3 million row events. MySQL uses row-based by default, and since 8.0 switching the format has been marked deprecated; in the future only row-based will remain
  • Physical replication: PostgreSQL’s streaming replication sends the WAL directly, that is, changes at the data-page level. The replica is a byte-for-byte copy of the primary, and the major versions must be the same

MySQL’s replication flow

sequenceDiagram
    participant A as Application
    participant S as Source (primary)
    participant R as Replica
    A->>S: COMMIT
    S->>S: Write binlog, commit transaction
    S-->>A: OK (async replication does not wait for replicas)
    S->>R: dump thread sends binlog events
    R->>R: receiver thread writes relay log
    R->>R: applier threads apply transactions

Lag can build up at any stage: the network, writing the relay log, or how fast the applier applies. In MySQL 8.4 a replica has 4 applier threads applying in parallel by default, but large transactions, DDL, replica hardware weaker than the primary’s, and resource-hungry report queries on the replica can all leave the applier unable to keep up.

Synchronous, asynchronous, semi-synchronous

Mode What a commit waits for Can a primary crash lose data Write latency
Asynchronous (MySQL default) Does not wait for replicas Yes, the part the replicas have not received Lowest
Semi-synchronous, AFTER_SYNC At least one replica receives it and writes it to the relay log No (except while degraded to asynchronous) One more network round trip
Group Replication A majority of nodes reach consensus on the transaction order No Higher

Semi-synchronous replication waits for a replica to “receive” the transaction, not to “apply” it. So it solves data loss during failover, and does not solve the problem of not being able to read data you just wrote.

PostgreSQL uses synchronous_commit to decide how far a commit waits:

synchronous_commit Waits for Visible on the replica
off Does not wait for the local WAL to reach disk No
local Local WAL written to disk No
remote_write Synchronous standby receives it and writes it to the OS No
on Synchronous standby writes it to disk No
remote_apply Synchronous standby finishes applying it Yes

Only remote_apply guarantees that, after a commit, the data is visible on the synchronous standby. The price is that every commit waits for the standby to finish applying.

Anomalies caused by lag

  • Read-your-writes: you cannot read the data you just wrote. This is complaint 1
  • Monotonic reads: you read new data, then the next read returns old data, as if the data went backward. It happens when two reads land on two replicas with different lag. This is complaint 2
  • Consistent prefix: you see the effect without the cause; for example, in a talk’s Q&A section, the speaker’s answer shows up before the attendee’s question. It happens more easily once the data is spread across multiple shards (see the Sharding post)

Measured: four ways to route reads

The simulation runs one primary and two asynchronous replicas for one hour. The replicas normally lag 5 to 80 milliseconds, and on average every 2 minutes they hit a large transaction that takes 2 to 8 seconds to apply. 200,000 users each write once; 30 to 150 milliseconds after the write they are sent back to a page that reads once, and they refresh once at 2 seconds and once at 5 seconds:

Simulation (java ReplicationLagSimulation.java)
java
import java.util.Random;

/** One primary and two asynchronous replicas, simulated for one hour. Compares four read routings: does a user fail to read what they just wrote, or see the data "go back"? */
public class ReplicationLagSimulation {

    static final int SECONDS = 3600;
    static final int STEP_MS = 10;
    static final int STEPS = SECONDS * 1000 / STEP_MS;
    static final long[][] applied = new long[2][STEPS];             // at each moment, the point in primary time the replica has applied up to

    enum Routing { RANDOM_REPLICA, STICKY_REPLICA, PRIMARY_FOR_1S, POSITION_TOKEN }

    public static void main(String[] args) {
        Random random = new Random(42);
        for (int r = 0; r < 2; r++) {
            simulateReplica(r, random);
        }

        int users = 200_000;
        long[] writeAt = new long[users];
        long[][] readAt = new long[users][3];
        for (int u = 0; u < users; u++) {
            writeAt[u] = 10_000 + (long) (random.nextDouble() * (SECONDS - 20) * 1000);
            readAt[u][0] = writeAt[u] + 30 + random.nextInt(120);  // sent back to the page after the write
            readAt[u][1] = writeAt[u] + 2_000;                      // refresh
            readAt[u][2] = writeAt[u] + 5_000;                      // refresh again
        }

        System.out.println("Routing           first stale later stale went back on primary");
        for (Routing routing : Routing.values()) {
            run(routing, users, writeAt, readAt, new Random(7));
        }
    }

    /** Normal lag 5 to 80 ms; on average every 2 minutes a large transaction of 2 to 8 seconds, during which lag keeps building, then it catches up at 3x speed. */
    static void simulateReplica(int r, Random random) {
        long backlog = 0;
        long busyUntil = -1;
        long over1s = 0;
        long max = 0;
        for (int i = 0; i < STEPS; i++) {
            long t = (long) i * STEP_MS;
            if (t >= busyUntil && random.nextDouble() < STEP_MS / 120_000.0) {
                busyUntil = t + 2_000 + random.nextInt(6_000);
            }
            backlog = t < busyUntil ? backlog + STEP_MS : Math.max(0, backlog - 3 * STEP_MS);
            long lag = 5 + random.nextInt(76) + backlog;
            applied[r][i] = Math.max(i == 0 ? 0 : applied[r][i - 1], t - lag);  // a replica never "un-applies"
            long actual = t - applied[r][i];
            max = Math.max(max, actual);
            over1s += actual > 1_000 ? 1 : 0;
        }
        System.out.printf("replica %d: max lag %.1f s, lag over 1 s %.1f%% of the time%n",
                r + 1, max / 1000.0, 100.0 * over1s / STEPS);
    }

    static long appliedAt(int replica, long t) {
        return applied[replica][(int) (t / STEP_MS)];
    }

    static void run(Routing routing, int users, long[] writeAt, long[][] readAt, Random random) {
        long firstStale = 0;
        long laterStale = 0;
        long wentBack = 0;
        long primaryReads = 0;
        for (int u = 0; u < users; u++) {
            long token = writeAt[u];                                // the position this user must at least see
            long lastSeen = -1;
            for (int k = 0; k < 3; k++) {
                long t = readAt[u][k];
                int replica = switch (routing) {
                    case STICKY_REPLICA -> u % 2;
                    default -> random.nextInt(2);
                };
                boolean primary = switch (routing) {
                    case PRIMARY_FOR_1S -> t - writeAt[u] < 1_000;
                    case POSITION_TOKEN -> appliedAt(replica, t) < token;
                    default -> false;
                };
                long seen = primary ? t : appliedAt(replica, t);
                primaryReads += primary ? 1 : 0;
                if (seen < writeAt[u]) {
                    if (k == 0) {
                        firstStale++;
                    } else {
                        laterStale++;
                    }
                }
                if (seen < lastSeen) {
                    wentBack++;
                }
                lastSeen = Math.max(lastSeen, seen);
                token = Math.max(token, seen);                      // the token also remembers the newest position seen
            }
        }
        System.out.printf("%-16s %11.2f%% %10.2f%% %8.2f%% %9.1f%%%n", routing,
                100.0 * firstStale / users, 100.0 * laterStale / (2L * users),
                100.0 * wentBack / (2L * users), 100.0 * primaryReads / (3L * users));
    }
}
text
replica 1: max lag 7.9 s, lag over 1 s 5.1% of the time
replica 2: max lag 7.6 s, lag over 1 s 3.3% of the time
Routing           first stale later stale went back on primary
RANDOM_REPLICA         11.97%       2.04%     1.44%       0.0%
STICKY_REPLICA         11.95%       2.02%     0.00%       0.0%
PRIMARY_FOR_1S          0.00%       2.04%     2.44%      33.3%
POSITION_TOKEN          0.00%       0.00%     0.00%       5.7%
  • Random replica: on the first read after a write, 12% of users cannot see their own data; later refreshes still miss it 2% of the time, when they hit a lag spike; 1.4% of reads see the data go back
  • Sticky replica (assigned per user): the same person always reads the same replica, so the data never goes back, but the rate of not seeing your own data does not improve at all
  • Read the primary for 1 second after a write: the first read is fine now, but reads 2 and 5 seconds later still hit lag spikes, and data going back actually increases: the first read gets the newest data from the primary, later reads go back to a lagging replica, and it looks as if the data disappeared. Guessing lag from time goes wrong exactly when the lag is largest
  • Position token: remember “the position on the primary this user must at least see”; if the replica has not applied up to that position, read the primary instead, and after the read, store the newest position seen back into the token. All three anomalies are 0, and only 5.7% of the reads by these users who just wrote land on the primary

The “position” in the simulation is a GTID set in MySQL and a WAL LSN in PostgreSQL.

Measuring lag

MySQL’s SHOW REPLICA STATUS has Seconds_Behind_Source, but it measures the gap between the applier and the receiver: when the network is slow or the receiver itself is behind, it often shows 0. It can also be 0 when the network is down but the receiver has not noticed yet; when the applier is stopped it is NULL.

A more reliable approach is a heartbeat table: the primary writes the current time into it once a second; on the replica, read that time and subtract it from now, and you get the end-to-end lag, including the delay from the network and the receiver.

Comparing options

Read strategy Guarantee Cost
Read everything from the primary Strongest Read volume limited by one machine
Random replica None Cheapest; all three anomalies happen
Sticky replica Monotonic reads When a replica fails or replicas are added, users move to another one
Read the primary for N seconds after a write Holds only while lag is under N Simple, but fails during lag spikes
Position token Read-your-writes and monotonic reads One extra position check per read; the token has to follow the user
Synchronous replication (remote_apply) After a write, the data is visible on every synchronous standby Every write waits for the standbys to apply it

A common combination in practice: most reads go to replicas, users who just wrote data get a position token, and reads of money, seats, and permissions always go to the primary.

In Java

1. Read/write splitting: LazyConnectionDataSourceProxy

Since Spring Framework 6.1.2, LazyConnectionDataSourceProxy can be given a read-only DataSource: a transaction marked readOnly gets a connection from the replica only when it runs its first SQL statement, and everything else goes to the primary. Once you define your own DataSource bean, Spring Boot no longer creates one for you:

java
package replication;

import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class DataSourceConfig {

    private final Environment env;

    public DataSourceConfig(Environment env) {
        this.env = env;
    }

    @Bean(destroyMethod = "close")
    public HikariDataSource primaryPool() {
        return pool("primary");
    }

    @Bean(destroyMethod = "close")
    public HikariDataSource replicaPool() {
        HikariDataSource pool = pool("replica");
        pool.setReadOnly(true);             // the proxy does not toggle the read-only flag per transaction; the pool sets it up front
        return pool;
    }

    /** Regular transactions use the primary; a transaction marked readOnly gets a replica connection only when its first SQL statement runs. */
    @Bean
    @Primary
    public DataSource dataSource() {
        LazyConnectionDataSourceProxy proxy = new LazyConnectionDataSourceProxy(primaryPool());
        proxy.setReadOnlyDataSource(replicaPool());
        return proxy;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public JdbcClient jdbcClient() {
        return JdbcClient.create(dataSource());
    }

    private HikariDataSource pool(String name) {
        HikariDataSource pool = new HikariDataSource();
        pool.setPoolName(name);
        pool.setJdbcUrl(env.getRequiredProperty("app.datasource." + name + ".url"));
        pool.setUsername(env.getRequiredProperty("app.datasource." + name + ".username"));
        pool.setPassword(env.getRequiredProperty("app.datasource." + name + ".password"));
        return pool;
    }
}

To confirm how this configuration actually behaves, two H2 databases play the primary and the replica (the replica does not sync on its own; the last step fills it in by hand):

Verification program (RoutingDemo.java)
java
package replication;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/** Two H2 in-memory databases play the primary and the replica. The replica does not sync on its own, which shows where each read and write actually lands. */
public class RoutingDemo {

    public static void main(String[] args) {
        for (String node : new String[] {"primary", "replica"}) {
            String url = "jdbc:h2:mem:" + node + ";DB_CLOSE_DELAY=-1";
            System.setProperty("app.datasource." + node + ".url", url);
            System.setProperty("app.datasource." + node + ".username", "sa");
            System.setProperty("app.datasource." + node + ".password", "");
            JdbcClient direct = JdbcClient.create(new DriverManagerDataSource(url, "sa", ""));
            direct.sql("CREATE TABLE node (name VARCHAR(20))").update();
            direct.sql("INSERT INTO node VALUES ('" + node + "')").update();
            direct.sql("CREATE TABLE member_profile (member_id BIGINT PRIMARY KEY, bio VARCHAR(100))").update();
            direct.sql("INSERT INTO member_profile VALUES (1, 'old bio')").update();
        }

        try (var context = new AnnotationConfigApplicationContext(DataSourceConfig.class)) {
            JdbcClient jdbc = context.getBean(JdbcClient.class);
            PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class);
            TransactionTemplate writeTx = new TransactionTemplate(transactionManager);
            TransactionTemplate readTx = new TransactionTemplate(transactionManager);
            readTx.setReadOnly(true);
            String sql = "SELECT n.name || ', bio: ' || p.bio FROM node n, member_profile p WHERE p.member_id = 1";

            show("regular transaction, read after write", writeTx.execute(status -> {
                jdbc.sql("UPDATE member_profile SET bio = 'new bio' WHERE member_id = 1").update();
                return jdbc.sql(sql).query(String.class).single();
            }));
            show("readOnly transaction", readTx.execute(status -> jdbc.sql(sql).query(String.class).single()));
            show("no transaction", jdbc.sql(sql).query(String.class).single());
            show("readOnly transaction inside a regular transaction", writeTx.execute(outer ->
                    readTx.execute(inner -> jdbc.sql(sql).query(String.class).single())));

            JdbcClient.create(new DriverManagerDataSource("jdbc:h2:mem:replica", "sa", ""))
                    .sql("UPDATE member_profile SET bio = 'new bio' WHERE member_id = 1").update();
            show("readOnly transaction after the replica catches up", readTx.execute(status -> jdbc.sql(sql).query(String.class).single()));
        }
    }

    static void show(String label, String result) {
        System.out.println(result + " | " + label);
    }
}
text
primary, bio: new bio | regular transaction, read after write
replica, bio: old bio | readOnly transaction
primary, bio: new bio | no transaction
primary, bio: new bio | readOnly transaction inside a regular transaction
replica, bio: new bio | readOnly transaction after the replica catches up
  • A readOnly transaction does read the replica, and so it gets the old bio
  • Queries without a transaction go to the primary: only “transactions marked readOnly” switch to the replica. For queries without @Transactional(readOnly = true), all the load is still on the primary
  • A readOnly transaction inside a regular transaction goes to the primary: the default propagation joins the outer transaction, whose connection is already on the primary

2. Read-your-writes: a GTID token

After a write, query the GTID set the primary has executed and use it as a token; on later reads, first run GTID_SUBSET on the replica to confirm that all of those transactions have been applied:

java
package replication;

import java.util.Optional;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/** Read-your-writes: after a write, record the primary's GTID set; later reads first check that the replica has applied it, and read the primary otherwise. */
public class ConsistentReads {

    private static final Pattern GTID_SET = Pattern.compile("[0-9a-fA-F:,\\-\\s]{1,2000}");

    private final JdbcClient jdbc;
    private final TransactionTemplate primaryTx;
    private final TransactionTemplate replicaTx;

    public ConsistentReads(JdbcClient jdbc, PlatformTransactionManager transactionManager) {
        this.jdbc = jdbc;
        this.primaryTx = new TransactionTemplate(transactionManager);
        this.replicaTx = new TransactionTemplate(transactionManager);
        this.replicaTx.setReadOnly(true);
    }

    /** The returned token covers every transaction the primary has executed after the write; the caller keeps it in the session and passes it back on later reads. */
    public String write(Runnable command) {
        primaryTx.executeWithoutResult(status -> command.run());
        return jdbc.sql("SELECT @@GLOBAL.gtid_executed").query(String.class).single();
    }

    /** query must not return null. A null token means this user has not written recently. */
    public <T> T read(String token, Supplier<T> query) {
        if (token != null && !GTID_SET.matcher(token).matches()) {
            throw new IllegalArgumentException("invalid consistency token");
        }
        Optional<T> fromReplica = replicaTx.execute(status ->
                token == null || caughtUp(token) ? Optional.of(query.get()) : Optional.empty());
        return fromReplica.orElseGet(() -> primaryTx.execute(status -> query.get()));
    }

    /** Runs in the same transaction and on the same replica connection as query, so it checks the replica that actually answers the query. */
    private boolean caughtUp(String token) {
        return jdbc.sql("SELECT GTID_SUBSET(:token, @@GLOBAL.gtid_executed)")
                .param("token", token)
                .query(Integer.class)
                .single() == 1;
    }
}

This code was compiled against Spring 7.0.10 but not run against MySQL; the semantics of GTID_SUBSET and @@GLOBAL.gtid_executed follow the MySQL 8.4 documentation.

  • The check and the query must use the same connection: behind a replica connection pool there is often a load-balanced address for several replicas. Split into two transactions, the replica that is checked and the one that answers may not be the same
  • Keep the token in a server-side session: a GTID set contains the server’s UUID and transaction sequence numbers, and how fast those numbers grow reveals the platform’s write volume
  • Give the token an expiry: when a failover with asynchronous replication loses some transactions, those GTIDs never appear on any replica, and users carrying an old token keep getting routed to the primary. Discard it after a few minutes
  • @@GLOBAL.gtid_executed includes every executed transaction, which is stricter than “this user’s transactions” but still correct. MySQL can also return this transaction’s GTID with the response through session_track_gtids, saving a query, provided the driver supports it
  • PostgreSQL works the same way: after a write, get pg_current_wal_lsn() on the primary; before a read, confirm that the replica’s pg_last_wal_replay_lsn() has passed it

3. Taking a replica out when its lag is too high

A position token only protects users who just wrote data. How much lag is acceptable for everyone else’s reads depends on the lag the heartbeat measures: above a threshold (say, 5 seconds), temporarily stop routing reads to that replica. Note that when all replicas fall behind at once, every read goes back to the primary, so the primary needs the capacity to take it, or you return stale data instead and show the update time on screen.

Pitfalls and gotchas

  • Assuming every query goes to a replica: only readOnly transactions do. In the test, queries without a transaction went to the primary
  • readOnly on the class, but write methods inside it: the writes are sent to the replica. Always turn on super_read_only on replicas, so this mistake fails outright instead of quietly writing to the replica and making its data diverge from the primary’s
  • Seconds_Behind_Source at 0 does not mean there is no lag: measure end-to-end lag with a heartbeat
  • Large transactions cause lag spikes: split large UPDATEs and DELETEs into batches of a few thousand rows each
  • Semi-synchronous replication quietly degrades: if no replica responds within rpl_semi_sync_source_timeout (10 seconds by default), the primary switches to asynchronous and keeps committing, while rpl_semi_sync_source_enabled is still 1. Monitor Rpl_semi_sync_source_status
  • Failover with asynchronous replication loses data: after the switch, the transactions the old primary had not sent out are gone. When the old primary comes back, you cannot simply attach it as a replica: its binlog may contain transactions the new primary does not have, so compare and deal with them first, then rebuild it
  • Checking on a replica, writing on the primary: reading “seats still available” on a replica and then decrementing seats is the lost update from the transactions post plus lag. The check and the decrement must happen in the same conditional UPDATE on the primary
  • Running long reports on a replica: they compete with replication for resources and make the lag grow. On a PostgreSQL standby, long queries can also conflict with WAL replay and get canceled. Reports are best run on a dedicated replica

Security

  • Permission and revocation checks must read the primary: an admin disables an account, a speaker’s permissions are revoked, a user changes their password and logs out of all devices; these changes may show up on a replica several seconds later. If permission checks read a replica, the revoked person still passes them during the lag, which is exactly the authorization problem the Part 8 BOLA post deals with. Authorization reads always go to the primary, or require that the replica has applied the revoking transaction
  • Lag amplifies race attacks: if a coupon’s “already used” status is read from a replica, an attacker sends redemption requests back to back during a lag spike, and every request sees “unused”. The check that guards a write must happen inside the write transaction on the primary, with a conditional UPDATE or a unique constraint
  • The replication channel is also a path for data leaks: the binlog contains every row change, personal data included. Give the replication account only the REPLICATION SLAVE privilege, turn on TLS for the replication connection, and encrypt binlog files and set a retention period for them. A replica for analytics is a full copy of the production data; manage its accounts and masking separately
  • Validate tokens that come from the client: ConsistentReads checks the token’s format and length because it goes into a SQL parameter and is parsed by GTID_SUBSET. Keeping it in a server-side session is better still, and also stops users from forging a token that sends all their reads to the primary

When to use it, and when not to

  • Use read replicas: many reads, few writes, and most reads can accept a short lag
  • Do not expect replicas to fix a write bottleneck: every replica has to apply every write; when write volume is too high, you need sharding
  • Always read the primary: money, inventory and seats, permissions and account status
  • Cross-region replicas: they let remote users read faster, but the lag is measured in hundreds of milliseconds, so read-your-writes needs handling all the more

References

Comments