AlgoViz

The CAP theorem

medium 28 min

When the network between copies of your data breaks, each copy must either refuse some requests or risk answers that disagree.

See it run

Cut the network between three replicas and watch what a CP and an AP store do, then look at normal days.

Operations

CP: ask a majority

Every write needs 2 of 3 nodes. The side without them refuses.

Step 1 of 6

Normal operation

Our systemsyncsyncClient AClient BNode 1v1Node 2v1Node 3v1

All nodes are connected and hold v1.

Step 1: Normal operation

def write(node, key, value):    peers = reachable(node)    if len(peers) < N // 2 + 1:        raise Unavailable    for p in peers:        p.store(key, value)    return "ok"
In a partition
Minority refuses
Price
Errors for some
AP
answers everywhere

Two sides can never both hold a majority. That is the whole trick.

In the real world

The same the cap theorem doing real jobs. Pick one and step through it.

Two regions sell tickets for one concert. One seat is left when the link drops.

Step 1 of 4

One seat left

Our systemsyncsyncClient AClient BNode 11 seatNode 21 seatNode 31 seat

Both regions know it.

Step 1: One seat left

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Saying pick two of three

    major

    You do not pick whether cables break. CA is not a design for several machines.

    Wrong
    design = choose(["CA", "CP", "AP"])
    Right
    if partitioned:    refuse() or answer_and_repair()
  • Counting only live nodes

    critical

    If each side counts only the nodes it sees, both sides have a majority.

    Wrong
    if acks > len(alive) / 2:
    Right
    if acks >= total_members // 2 + 1:
  • Last write wins on money

    critical

    One of two accepted payments vanishes without an error.

    Wrong
    balance = max(a, b, key=timestamp)
    Right
    balance = start + sum(all_transfers)
  • One letter for the whole product

    minor

    Browsing and paying have different needs.

    Wrong
    DATABASE_MODE = "CP"
    Right
    read_catalog(level="local")place_order(level="majority")

Interview tips

  • How to explain it

    • Copies that cannot talk must refuse or risk it.
    • C is one copy, A is every node answers.
    • Choose for each operation.
  • Memory trick

    • C: same data everywhere.
    • A: always responds.
    • P: survives splits, and it is given.
  • Choose CP for

    • Money and stock.
    • Locks and leaders.
    • Anything that cannot be undone.
  • Choose AP for

    • Feeds and carts.
    • Metrics and logs.
    • Anything that merges.