16. Consistency and CAP
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. Strong, read-your-writes, causal or eventual? One line each.
- The number of likes on a review.
- Whether a seat on a flight is still free at the moment of booking.
- A user's own profile page right after they edit it.
- A chat where replies must never appear before the message they answer.
- "Customers who bought this also bought."
B. True or false? Explain.
- "Our database is CA, so we don't need to worry about partitions."
- "CAP means you must give up consistency all the time."
- "With W + R > N, every read is guaranteed to be linearizable."
Level 2: Calculate
- The wallet is strongly consistent across Mumbai and Frankfurt, which are 120 ms apart (round trip). A local write takes 2 ms. Roughly how long does each wallet write take now? A user makes 3 wallet writes in a row; how long in total?
- A 5-node coordination cluster needs a majority. How many nodes can fail before it refuses writes? A 6-node cluster?
- A replicated store uses N = 3. Which (W, R) pairs give W + R > N? Which of those still accepts writes with one replica down?
- A partition lasts 30 minutes. A CP wallet refuses spends on the minority side, which normally handles 20 spends a minute. How many spends are refused?
Level 3: Build
In Python, build a Pair of two replicas (Mumbai and Frankfurt) with a partitioned flag and a mode of "CP" or "AP":
- While connected, writes copy to both replicas.
- While partitioned, CP mode raises
Unavailableon reads and writes; AP mode serves from the local copy. heal_last_write_wins()reconciles by keeping the latest write.- A
GCounterCRDT that merges increments from both sides.
Check that: CP refuses during a partition; AP lets both sides diverge; last-write-wins keeps only one of two concurrent edits; the counter CRDT ends with the sum of both sides' increments.
Level 4: Debug
During a 20-minute network problem between regions, finance found gift cards that were spent more than their balance. The spend code runs in whichever region the user is in:
- Find the bug. Walk through how ₹800 is spent from a ₹500 card.
- Fix it, and say what users see during the next partition.
Level 5: Design
Choose the consistency for each bookstore feature and say how it's implemented, given replicas in Mumbai and Frankfurt:
- Gift-card wallet.
- Book stock: the "only 3 left" label, and the final check at checkout.
- User profile and cart.
- Review comments and replies.
- Book view counters and "trending".
- What users in Frankfurt experience during a 10-minute partition, feature by feature.