Part 4 of 7 · 2 min read
Monotonic reads
Preventing time from running backward when reads hit different followers.
Think of two clocks on the wall in two rooms, one correct and one 10 minutes slow. Walking from the first room to the second makes it look as though time ran backward.
If a user refreshes a page and each request goes to a random follower, the first read may hit a follower with little lag and the second a follower with more lag. The book's example: user 2345 reads a comment added moments before by user 1234 from the fresh follower, then reloads and the lagging follower does not have it. The comment appears and then disappears. The second query sees the system at an earlier time than the first.
Monotonic reads
Monotonic reads is the guarantee that if a user makes several reads in a row, they will not see older data after having seen newer data. It is weaker than strong consistency and stronger than eventual consistency.
Example: once a user has seen a comment, every later read of the same page by that user shows the comment too.
The book gives one way to get it: let each user always read from the same replica. Different users can use different replicas. The replica can be chosen by a hash of the user id, not randomly. If that replica fails, the user's queries must be rerouted to another replica, and then the guarantee can break for a moment.
A worked example. A site has 4 followers and 100,000 users.
- Random routing: two refreshes land on different followers with probability 3/4, so in 75 percent of refreshes the user may see an older state.
- Routing by hash of the user id: user 7 always reads from follower (7 mod 4) = 3. Two refreshes always use follower 3. The user never sees time going backward, though the data may be old. Each follower serves about 25,000 users.
- If follower 3 dies, its 25,000 users move to the others. For a moment, a user may see older data after newer, if the new follower is behind.
Monotonic reads is not read-your-writes. A user can have monotonic reads and still not see their own latest write, if the chosen replica is slow. The two guarantees are often combined.
Check yourself:
- How does routing by user id give monotonic reads?
- With 6 followers and random routing, what is the chance that two reads land on different followers?