Lesson 13 of 17
16. Consistency and CAP

Practice: five levels

3 min read+10 XP

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.

  1. The number of likes on a review.
  2. Whether a seat on a flight is still free at the moment of booking.
  3. A user's own profile page right after they edit it.
  4. A chat where replies must never appear before the message they answer.
  5. "Customers who bought this also bought."

B. True or false? Explain.

  1. "Our database is CA, so we don't need to worry about partitions."
  2. "CAP means you must give up consistency all the time."
  3. "With W + R > N, every read is guaranteed to be linearizable."

Level 2: Calculate

  1. 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?
  2. A 5-node coordination cluster needs a majority. How many nodes can fail before it refuses writes? A 6-node cluster?
  3. A replicated store uses N = 3. Which (W, R) pairs give W + R > N? Which of those still accepts writes with one replica down?
  4. 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":

  1. While connected, writes copy to both replicas.
  2. While partitioned, CP mode raises Unavailable on reads and writes; AP mode serves from the local copy.
  3. heal_last_write_wins() reconciles by keeping the latest write.
  4. A GCounter CRDT 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:

python
  1. Find the bug. Walk through how ₹800 is spent from a ₹500 card.
  2. 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:

  1. Gift-card wallet.
  2. Book stock: the "only 3 left" label, and the final check at checkout.
  3. User profile and cart.
  4. Review comments and replies.
  5. Book view counters and "trending".
  6. What users in Frankfurt experience during a 10-minute partition, feature by feature.