14. Replication
Practice: five levels
Assignments
Five levels. Do them in order. Answers are in "Solutions" at the end, so try first.
Level 1: Think (no code)
A. Which problem is this, and what's the fix?
- A user posts a review, refreshes the page, and their review is missing; a second later it appears.
- Scrolling through order history, a user sees an order, then on the next page load it's gone, then it's back.
- After the database leader crashed and a replica took over, three customers who were told "order confirmed" have no order.
- During a network glitch, two database nodes both accepted writes; now some seats are double-booked.
B. Synchronous or asynchronous replication, and why?
- The bookstore's payments table.
- Page-view counters.
- A replica in another continent used for reports.
Level 2: Calculate
- The leader takes 1,000 writes a second; a follower applies 900. How far behind is it after 10 minutes? If writes drop to 500 a second, how long until it catches up?
- Replication is asynchronous and a follower is typically 2 seconds behind at 1,000 writes a second. Roughly how many confirmed writes could be lost in a failover?
- Each replica handles 5,000 reads a second at full load; you run them at 70%. How many replicas for 20,000 reads a second?
- With N = 5: which W and R give W + R > N with both reads and writes surviving 2 nodes down?
Level 3: Build
In Python:
- A
Leaderwith a list of(key, value)log entries andwrite()that returns the entry's log position, and areplicate(follower, max_entries)that ships entries asynchronously. read_your_writes(user_last_lsn, leader, follower, key)that reads from the follower only if it has applied the user's last write.quorum_write(replicas, key, value, version, w)andquorum_read(replicas, key, r)that returns the highest version.
Check that: a read on a lagging follower is stale but read-your-writes returns the new value from the leader; once the follower catches up, it serves the read; promoting a follower that applied 7 of 10 writes loses 3; with N = 3, W = 2, R = 2 always returns the latest; R = 1 can be stale.
Level 4: Debug
Users report: "I changed my delivery address, the page still shows the old one, so I changed it again. Now I have two support tickets."
- Find the bug. Explain step by step.
- Fix it. Give two fixes.
Level 5: Design
The bookstore's database must survive a machine failure with no lost orders, handle 4 times today's browsing reads, and serve users in India and Europe.
Deliver:
- The replication layout (leader, followers, regions) and sync vs async choices.
- How reads are routed, including read-your-writes for carts and orders.
- How failover works, and how you avoid split brain.
- What happens to European users' writes, and why.
- What you monitor.