The CAP Theorem
The CAP theorem is a rule about the choice a system must make when the link between its copies breaks. Such a break is called a partition, and the choice is between consistency and availability.
Two data centers and a healthy link
Each data center holds a copy of the same name. A write in the first data center reaches the second one while the link is up.
east = "Ada"
west = "Ada"
link_up = True
east = "Grace"
if link_up:
west = east
print("East data center:", east)
print("West data center:", west)
print("Copies agree:", east == west)A partition cuts the link
A flag now marks the link as down, and this break is the partition. The same write stays on its own side, so the copies disagree.
east = "Ada"
west = "Ada"
link_up = False
east = "Grace"
if link_up:
west = east
print("East data center:", east)
print("West data center:", west)
print("Copies agree:", east == west)The two choices during a partition
The west side holds the old value while the partition lasts. One choice refuses the read, and the other choice answers with that old value.
west_value = "Ada"
link_up = False
def read_for_consistency(link_is_up, value):
if link_is_up:
return value
return "refused"
def read_for_availability(link_is_up, value):
return value
print("Consistency choice:", read_for_consistency(link_up, west_value))
print("Availability choice:", read_for_availability(link_up, west_value))Example
east = "Ada"
west = "Ada"
link_up = False
east = "Grace"
print("During the partition, east:", east)
print("During the partition, west:", west)
print("Copies agree:", east == west)
link_up = True
if link_up:
west = east
print("After the link heals, west:", west)
print("Copies agree:", east == west)Key points
- CAP theorem: during a partition, a system can keep consistency or availability, but not both.
- Partition: a break in the network link between machines that hold copies.
- Partition tolerance: the system keeps running even while a partition splits its copies.
- Consistency choice: refuse requests until the link heals, so no stale value is served.
- Availability choice: keep answering with the value on hand, even when that value may be stale.
In this example, the write cannot cross during the partition, so the west copy keeps the old value. Once the link heals, the new value crosses and the copies agree again.
Note
when the link is healthy, a system can have consistency and availability together.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A partition splits two data centers. What does the availability choice do?