Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Database › Scaling and distribution

Replication lag and CAP

I just saved it, but the query shows the old value

Why it exists — If one DB server receives all reads and writes, in a read-heavy service that one server's processing capacity becomes the limit of the whole service, and if that server stops, there is nowhere left to read data. Replication reapplies changes made on the source, in order, to other DB servers, so that several servers holding the same data can be kept.

Where it's used today — It is used to spread reads across several replicas in a service where reads far outnumber writes, such as product lists or posts, and the replicas are also kept as standby servers to take over when the source fails. In Spring, the data sources are sometimes configured separately so that read-only transactions go to a replica. Reads that must be current right away, such as a confirmation screen just after saving or a balance, are read from the source.

If you send writes to the source (primary) database and reads to a replica, you can spread out the read load. But it takes time for a change on the source to be delivered to the replica and applied there. This time difference is called replication lag. The CAP theorem says that when the network is partitioned, a system has to choose between continuing to respond (availability) and refusing to respond with data that may be stale (consistency), and this lab shows both cases.

Checked against real execution · The 18 replication-lag cases were run with asynchronous replication between two MySQL 8.4.11 servers and the service code on Spring Boot 4.1.1, and the 2 network-partition cases with MySQL and Redis 8.10.2 replicas. The replication time was created with a row lock on the replica

Concepts in this lab

Replication
Continuously copying the changes of an original database (the source, also called the primary) to another database (a replica) so that both keep the same data. It reduces load by spreading read requests across replicas, and if the source fails, a replica can be promoted to take its place and keep the service running. There is a small delay in the copying, so data that was just written may not be visible on a replica right away.
Eventual consistency
The guarantee that, although some nodes may show the old value right after data changes, all nodes end up with the same value over time if no further changes are made. It gives up immediate consistency and gains availability and scalability in return. It is commonly adopted in distributed databases and for synchronizing data between microservices.
CAP theorem
The theorem that a distributed data store cannot guarantee all three of the following at the same time: consistency (every node shows the same data), availability (every request gets a response), and partition tolerance (the system keeps working even when communication between nodes is cut). Network partitions cannot be avoided, so the real choice is whether to put consistency or availability first when a partition happens.
Read-only transaction (readOnly)
Why it exists — Even for a method that only reads, if you open a regular transaction, Hibernate keeps a separate copy (snapshot) of the first state of each entity it reads in order to detect changes. If you turn readOnly on, Spring changes the Hibernate session to read-only so that this keeping is skipped.
Where it's used today — A common approach is to put @Transactional(readOnly = true) on a service class to make read-only the default, and to put @Transactional again only on the methods that save.
@Transactional(readOnly = true) is a setting that declares that the transaction does not change data. With JPA (Hibernate), optimizations apply, such as skipping the flush that writes changes to the DB, and when you have separately configured one DB for reads and one for writes, it also serves as the criterion for routing to the DB for reads. Put it on query methods to make the intent clear.

Try these

Running with the default settings

  1. The member's nickname is "Alice", and the source and the replica have the same value.
  2. 0s: The user changes the nickname to "Bob". It is saved on the source database and committed. The user gets a "saved" response. It has not yet been applied on the replica.
  3. 0.3s: The query is sent to the replica. The change has not been applied on the replica yet, so the replica still has the old value "Alice". This time difference is the replication lag. The user sees a screen on which the nickname they just changed is unchanged.
  4. 1s: The change is finally applied, and the replica also becomes "Bob". Later queries see the new value.

Result of this run

Code

// Only the service class body is shown (class declaration, memberRepository field, the example Member entity, and imports omitted)
// A case where the data sources are set up separately so that readOnly transactions go to the replica and everything else goes to the source
@Transactional
public void changeNickname(long id, String name) {     // -> source
    memberRepository.findById(id).orElseThrow().setNickname(name);
}

@Transactional(readOnly = true)
public Member getMember(long id) {                      // -> replica
    return memberRepository.findById(id).orElseThrow();
}

Assumptions of this model

I built real asynchronous replication with one source and one replica, ran every combination, and compared the results. Replication lag was run on two MySQL 8.4.11 servers (GTID-based asynchronous replication). The service code on the screen (changeNickname, getMember) was run as it is with Spring Boot 4.1.1 and Spring Data JPA (Hibernate 7.4.5), and the setup that sends readOnly transactions to the replica was built with AbstractRoutingDataSource and LazyConnectionDataSourceProxy from Spring (that setup class and the switch that sends "a read right after a write to the source" were made up for this example). The replication time is not a value that arose by itself but a value that I created. Before the save, another session locked that row on the replica so that the applier thread of the replica had to wait, and the lock was released at the set time (0.1, 1, or 5 seconds) after the save was committed. So in this run the change record reached the replica right away, and what was delayed was the step that applies it on the replica. In all eighteen runs, the new value became visible on the replica 0.01 to 0.19 seconds after the set time, and the query result, the servers that the write and the query went to, and the values on both servers right after the save and at the end matched the screen. When no delay was created, it took 7 to 45 milliseconds on this computer for a change to become visible on the replica (measured 20 times, with a median of 27 milliseconds; it differs on each run). Replication lag in a real service varies with load, and its size was not measured here. The network partition was created by disconnecting the replica container from the Docker network used for replication. "Keep responding" was run on a MySQL replica and on a Redis 8.10.2 replica (replica-serve-stale-data yes, the default), and both answered "Alice" even after "Bob" was saved on the source. "Refuse to respond" was run by giving the Redis replica replica-serve-stale-data no, and the query got a MASTERDOWN error. However, until the replica noticed that the link was down (3 seconds in this run, given as repl-timeout), it answered with the old value even with the no setting. A MySQL asynchronous replica has no setting that makes it refuse queries when it is disconnected from the source, so "refuse to respond" was not run on MySQL. In all three runs, the replica caught up with the value on the source once the network was restored. The CAP theorem is about the choice to make during a network partition, and real systems mix different choices depending on the kind of data.

Previous lab: Buffer pool and pages · Next lab: Sharding

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these