Course outline · 0% complete

0/29 lessons0%

Course overview →

Read replicas and replication lag

lesson 4-3 · ~10 min · 13/29

Followers can earn their keep

Followers exist for safety, but they hold a full copy of the data, so why not let them answer read queries? Used this way a follower is called a read replica.

Most apps read far more than they write. A social feed might see 100 reads per write. Send all writes to the leader and spread reads across three replicas, and you have roughly quadrupled read capacity without touching your schema.

The catch: the replication log takes time to ship and replay, typically milliseconds, sometimes seconds under load. That delay is replication lag, and it means a replica is always slightly behind the leader. A read from a replica can return data that is a moment out of date. Whether that matters depends entirely on the query, and the next simulation makes the problem concrete.

Code exercise · python

Run this replication lag simulation. The leader has applied 3 writes, the follower only 2. Compare what each returns for the latest balance.

Read your own writes

The classic lag bug: Ada posts a comment (a write, to the leader), the page reloads and fetches comments (a read, from a lagging replica), and her comment is missing. She assumes the site ate it and posts again. Now it is there twice.

The standard fix is read-your-own-writes routing: for a short window after a user writes, send that user's reads to the leader, where the write definitely exists. Everyone else can keep reading replicas, because they never knew the comment existed and cannot miss it.

This is your first taste of a theme unit 7 makes precise: replicas that receive changes with a delay are eventually consistent, and systems are designed around who can tolerate how much staleness.

Code exercise · python

Your turn: implement read-your-own-writes routing. Complete read(where) so that "leader" returns the newest entry of leader_log and anything else returns what the follower has applied (entry at index follower_applied - 1). The two prints then show the stale and fresh reads.

Quiz

Which query is safe to send to a read replica that lags the leader by up to 2 seconds?