System Design Part 4 Distributed data

CAP and PACELC: Consistency or Availability During a Partition, Latency or Consistency Otherwise

Bill.Lin 17 min read

System Design series Part 4-5 | Previous: Distributed IDs | Next: Consensus and Raft | Series map

Read first: Part 4-1 Replication and Replication Lag.

Scenario and problem

The talk platform expands to Japan and opens a second data center in Tokyo, with data replicated between Taipei and Tokyo. Reads get faster for users in Japan, and if the whole Taipei data center fails, Tokyo can take over. But the team runs into two problems right away:

  1. The network between Taipei and Tokyo goes down (a fiber cable gets dug up, the international link is congested). Both sides are still alive; they just cannot reach each other. Now users in Tokyo sign up for the same seat, edit their profile bio, and report their watch progress. How should the system respond?
  2. When the network is fine, should every write wait for the other data center to confirm? If it waits, every write takes 30 ms longer; if it does not, the other data center may read old data
Two data centers, Taipei and Tokyo1 / 4
Two data centers, Taipei and TokyoTokyo usersTokyo DCTaipei DCTaiwan usersTokyo usersTokyo DCTaiwan usersTaipei DCnearby readnearby readreplicateTokyo DCTaipei DCunreachablestill alivealso still aliveTokyo usersTokyo DCTaipei DCclaim same seatunreachableAccept or reject?Tokyo usersTokyo DCTaipei DCTaiwan userswritewait for ack?waiting adds 30 msmay read stale
  1. Data in both placesYou open a second data center in Tokyo and replicate data between Taipei and Tokyo. Users in Japan get faster reads, and if Taipei fails entirely, Tokyo can take over.
  2. The network breaks, both sides aliveA fiber cable gets dug up, or the international link is congested. Both data centers are still alive; they just cannot reach each other.
  3. Then Tokyo gets a sign-upUsers in Tokyo sign up for the same seat and edit their profile bios. Accept that, and it may conflict with an edit in Taipei; reject it, and users in Tokyo cannot use the service.
  4. A choice even when the network is fineWhen the network is fine, should every write wait for the other data center to confirm? Waiting adds 30 ms to every write; not waiting means Taipei may read old data.

The simplest approach and its limits

The version you hear most often is “CAP, pick two of three: consistency, availability, partition tolerance, you can only have two”, followed by sorting databases into CA, CP, and AP. This version has two problems:

  • A partition is not something you can choose to do without: as long as data lives on two or more machines connected by a network, the network can break. The real choice only appears while a partition is happening: consistency or availability
  • There is a trade-off even without a partition: and every single request faces it; it is problem 2 above. CAP does not talk about it at all

Core mechanism

What CAP actually says

The three terms in the CAP theorem (proved by Gilbert and Lynch in 2002) have precise definitions:

  • C (consistency) means linearizability: every operation appears to complete instantaneously at some point in time, and once a write completes, any read that starts afterwards sees it or a newer value
  • A (availability): every non-failing node that receives a request must eventually return a non-error response
  • P (partition tolerance): any number of messages between nodes may be lost

The proof is intuitive:

sequenceDiagram
    participant U1 as User in Taipei
    participant T as Taipei node
    participant J as Tokyo node
    participant U2 as User in Tokyo
    Note over T,J: Network partition
    U1->>T: Seat 12 goes to member A
    T-->>U1: Success
    U2->>J: Is seat 12 still free?
    Note over J: Cannot reach Taipei, only two choices
    J-->>U2: Reply "free" (stale data, gives up C)
    J--xU2: Reject or keep waiting (gives up A)

The Tokyo node does not know what happened in Taipei. It can only reply with data that may be stale, or not reply at all.

Two details people often miss:

  • The C in CAP is linearizability, which is very strict. Most databases are not linearizable in their default configuration to begin with, such as the asynchronous replicas in Replication and Replication Lag. They did not “choose A”; they fully provide neither
  • The A in CAP has no time limit: a reply that takes 10 minutes still counts as available. In practice what matters is “replying within an acceptable latency”, and that is exactly the part PACELC adds

PACELC

Daniel Abadi proposed PACELC in 2012:

  • During a Partition: choose between Availability and Consistency
  • Else (when there is no partition): choose between Latency and Consistency

For strong consistency you wait for several replicas to confirm, so latency goes up; for low latency you wait only for the nearest replica, and the others may not be updated yet. This trade-off happens every day, while a partition may happen only a few times a year.

System During a partition Normally Notes
Dynamo, Cassandra (default) A L The consistency level can be tuned per query
Spanner C C The minority side stops accepting writes; every commit needs a majority
MySQL async replication + automatic failover A L A failover can lose acknowledged writes

The spectrum of consistency models

Model Guarantee Examples
Linearizability Once a write completes, everyone can see it Seats, seat counts, account balances, uniqueness checks
Causal consistency Operations with a causal relationship are seen in the same order by everyone You see the question before you see the reply
Session guarantees Read-your-writes and monotonic reads for the same user Profile bio, your own sign-up list
Eventual consistency Once writes stop, all replicas end up the same View counts, like counts, watch progress

The higher up, the stronger, but also the slower, and the more likely to stop serving during a partition. When you design, decide item by item which level each kind of data needs, instead of choosing one for the whole system.

Quorum: trading numbers for consistency

The data has N replicas. A write waits for W replicas to confirm; a read asks R replicas and takes the value with the newest version. As long as W + R > N, the replicas a read asks and the replicas that confirmed the write overlap in at least one, so the read is guaranteed to see the acknowledged write. Cassandra’s QUORUM is a majority (2 of 3 replicas), and LOCAL_QUORUM is a majority within the local data center.

Measured: a quorum across data centers

3 replicas, 2 in Taipei and 1 in Tokyo, with the client in Taipei. One way takes about 0.7 ms within the Taipei data center and about 16 ms from Taipei to Tokyo. Each replica has a 2% chance of being busy (GC, compaction), and then the write takes another 5 to 50 ms to take effect. Within 1 ms after a write completes, another client reads the same record:

Simulation code (java QuorumSimulation.java)
java
import java.util.Arrays;
import java.util.Random;

/**
 * 3 replicas: 2 in Taipei, 1 in Tokyo, client in Taipei. A write goes to all 3 and waits for W acks; a read asks all 3, waits for the fastest R replies, and takes the newest version.
 * Each replica has a 2% chance of being busy (GC, compaction); the write then takes another 5 to 50 ms to apply, and the ack goes out only after it is applied.
 * Within 0 to 1 ms after the write completes, another client reads the same record.
 */
public class QuorumSimulation {

    static final int TRIALS = 200_000;
    static final Random RANDOM = new Random(42);

    /** One-way latency (ms): about 0.7 ms within the Taipei data center, about 16 ms from Taipei to Tokyo. */
    static double oneWay(int replica) {
        double jitter = Math.exp(0.5 * RANDOM.nextGaussian());
        return replica < 2 ? 0.3 + 0.4 * jitter : 15 + jitter;
    }

    public static void main(String[] args) {
        int[][] levels = {{1, 1}, {2, 1}, {1, 2}, {2, 2}, {3, 1}, {1, 3}};
        System.out.println("W R  W+R>N     stale  write p50/p99 ms  read p50/p99 ms");
        for (int[] level : levels) {
            run(level[0], level[1], new boolean[] {true, true, true}, true);
        }
        System.out.println("\nOne Taipei replica down (one in Taipei and the one in Tokyo left):");
        for (int[] level : levels) {
            run(level[0], level[1], new boolean[] {true, false, true}, false);
        }
        System.out.println("\nTaipei-Tokyo link down (only the two in Taipei left):");
        for (int[] level : levels) {
            run(level[0], level[1], new boolean[] {true, true, false}, false);
        }
    }

    static void run(int w, int r, boolean[] reachable, boolean showStale) {
        int up = 0;
        for (boolean b : reachable) {
            up += b ? 1 : 0;
        }
        if (w > up || r > up) {
            System.out.printf("%d %d  %-5s  %s%n", w, r, w + r > 3 ? "yes" : "no",
                    (w > up ? "write failed" : "") + (w > up && r > up ? ", " : "") + (r > up ? "read failed" : ""));
            return;
        }
        double[] writeLatency = new double[TRIALS];
        double[] readLatency = new double[TRIALS];
        long stale = 0;
        for (int t = 0; t < TRIALS; t++) {
            double[] applied = new double[3];                       // when the write takes effect on each replica
            double[] ack = new double[3];
            for (int i = 0; i < 3; i++) {
                double busy = RANDOM.nextDouble() < 0.02 ? 5 + RANDOM.nextDouble() * 45 : 0;
                applied[i] = reachable[i] ? oneWay(i) + busy : Double.POSITIVE_INFINITY;
                ack[i] = applied[i] + (reachable[i] ? oneWay(i) : 0);
            }
            double writeDone = kth(ack, w);
            double readAt = writeDone + RANDOM.nextDouble();
            double[] response = new double[3];
            boolean[] fresh = new boolean[3];
            for (int i = 0; i < 3; i++) {
                double requestArrives = readAt + (reachable[i] ? oneWay(i) : Double.POSITIVE_INFINITY);
                fresh[i] = requestArrives >= applied[i];
                response[i] = requestArrives + (reachable[i] ? oneWay(i) : 0);
            }
            double readDone = kth(response, r);
            boolean anyFresh = false;
            for (int i = 0; i < 3; i++) {
                anyFresh |= response[i] <= readDone && fresh[i];   // only the R replicas that replied before the read completed
            }
            stale += anyFresh ? 0 : 1;
            writeLatency[t] = writeDone;
            readLatency[t] = readDone - readAt;
        }
        Arrays.sort(writeLatency);
        Arrays.sort(readLatency);
        System.out.printf("%d %d  %-5s  %s  %6.1f / %6.1f   %6.1f / %6.1f%n", w, r, w + r > 3 ? "yes" : "no",
                showStale ? String.format("%7.2f%%", 100.0 * stale / TRIALS) : "        ",
                writeLatency[TRIALS / 2], writeLatency[TRIALS * 99 / 100],
                readLatency[TRIALS / 2], readLatency[TRIALS * 99 / 100]);
    }

    static double kth(double[] values, int k) {
        double[] sorted = values.clone();
        Arrays.sort(sorted);
        return sorted[k - 1];
    }
}
text
W R  W+R>N     stale  write p50/p99 ms  read p50/p99 ms
1 1  no        2.03%     1.3 /    2.0      1.3 /    2.0
2 1  no        0.75%     1.6 /   32.0      1.3 /    1.9
1 2  no        0.00%     1.3 /    2.0      1.6 /    2.8
2 2  yes       0.00%     1.6 /   32.0      1.6 /    2.8
3 1  yes       0.00%    32.2 /   59.4      1.3 /    1.9
1 3  yes       0.00%     1.3 /    2.0     32.1 /   35.0

One Taipei replica down (one in Taipei and the one in Tokyo left):
1 1  no                  1.5 /   28.9      1.4 /    2.6
2 1  no                 32.1 /   58.4      1.4 /    2.6
1 2  no                  1.5 /   28.3     32.1 /   35.0
2 2  yes                32.2 /   60.0     32.1 /   35.0
3 1  yes    write failed
1 3  yes    read failed

Taipei-Tokyo link down (only the two in Taipei left):
1 1  no                  1.3 /    2.0      1.3 /    1.9
2 1  no                  1.6 /   40.0      1.3 /    2.0
1 2  no                  1.3 /    2.0      1.6 /    2.8
2 2  yes                 1.6 /   39.8      1.6 /    2.8
3 1  yes    write failed
1 3  yes    read failed
  • W=1, R=1 is the fastest, but 2% of reads see old data: the read happened to ask the replica that was still busy
  • W=2, R=2 (equivalent to QUORUM) never read old data, and is normally almost as fast as W=1: the two Taipei replicas alone make a majority. But the write p99 becomes 32 ms: when one Taipei replica is busy, the second ack has to come from Tokyo
  • W=3 or R=3: every request waits for Tokyo, so latency is always above 30 ms
  • With one Taipei replica down, W=2, R=2 is still consistent and still available, but every request waits for Tokyo, and latency goes from 1.6 ms to 32 ms. That is the “E” in PACELC: the system is not partitioned, it has only lost one machine, and the trade-off between latency and consistency shows up
  • When Taipei and Tokyo are cut off from each other, W=2, R=2 on the Taipei side is not affected at all, because the majority of replicas are in Taipei; every combination that needs 3 replicas fails. On the other side, Tokyo has only 1 replica and cannot form a majority, so requests with W=2 or R=2 fail there. CP does not mean the whole system stops; it means the minority side stops serving

The stale rate of 0 for W=1, R=2 is only a coincidence of this topology: the first ack of a write always comes from Taipei, and R=2 happens to ask the two replicas in Taipei. When W + R is not greater than N, there is no guarantee.

Note that W + R > N does not mean linearizability either: two writes running at the same time, or a write that times out after succeeding on only some replicas, can both make different reads see different results. When you need linearizability, Cassandra requires a lightweight transaction (Paxos).

Comparing options

The talk platform makes a separate choice for each kind of data:

Data During a partition Normally How
Seats, seat counts C: the minority side rejects sign-ups C: wait for a majority Cassandra LWT with SERIAL, or decrement seat counts only on the MySQL primary in the main data center
Permissions, account status C: better to reject C The primary in the main data center
Profile bio A: each side accepts edits, merged later Majority within the local data center LOCAL_QUORUM
Watch progress A L: ask only one replica LOCAL_ONE, last write wins
Like counts, view counts A L Each data center counts on its own, summed periodically (CRDT counter)

In Java

The keyspace replication settings match the simulation, 2 copies in Taipei and 1 in Tokyo:

sql
CREATE KEYSPACE learning WITH replication =
    {'class': 'NetworkTopologyStrategy', 'taipei': 2, 'tokyo': 1};

CREATE TABLE learning.lecture_progress (member_id uuid, lecture_id bigint, seconds int,
                                        PRIMARY KEY (member_id, lecture_id));
CREATE TABLE learning.member_bio (member_id uuid PRIMARY KEY, bio text);
CREATE TABLE learning.seat_claim (lecture_id bigint, seat_no int, member_id uuid,
                                  PRIMARY KEY (lecture_id, seat_no));

The default load balancing policy of the Apache Cassandra Java driver connects only to the local data center, which you have to name when you build the session:

java
CqlSession session = CqlSession.builder()
        .withLocalDatacenter("taipei")
        .withKeyspace("learning")
        .build();

With the same session, set the consistency level on each query according to the nature of the data:

java
package cap;

import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.DefaultConsistencyLevel;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import java.util.Optional;
import java.util.UUID;

/** One cluster, one driver: a different consistency level for each kind of data. */
public class LearningRepository {

    private final CqlSession session;

    public LearningRepository(CqlSession session) {
        this.session = session;
    }

    /** Watch progress: ask only one replica in the local data center. Reading progress from a few seconds ago now and then is fine; what matters is speed, and that writes still go through during a partition. */
    public void saveProgress(UUID memberId, long lectureId, int seconds) {
        session.execute(SimpleStatement.newInstance(
                        "UPDATE lecture_progress SET seconds = ? WHERE member_id = ? AND lecture_id = ?",
                        seconds, memberId, lectureId)
                .setConsistencyLevel(DefaultConsistencyLevel.LOCAL_ONE));
    }

    /** Profile bio: quorum writes and quorum reads in the local data center, so you can read your own writes within the same data center. */
    public void updateBio(UUID memberId, String bio) {
        session.execute(SimpleStatement.newInstance(
                        "UPDATE member_bio SET bio = ? WHERE member_id = ?", bio, memberId)
                .setConsistencyLevel(DefaultConsistencyLevel.LOCAL_QUORUM));
    }

    public Optional<String> findBio(UUID memberId) {
        Row row = session.execute(SimpleStatement.newInstance(
                        "SELECT bio FROM member_bio WHERE member_id = ?", memberId)
                .setConsistencyLevel(DefaultConsistencyLevel.LOCAL_QUORUM)).one();
        return Optional.ofNullable(row).map(r -> r.getString("bio"));
    }

    /** Seats: Paxos across data centers (SERIAL). During a partition the minority side fails, instead of giving the same seat to two people. */
    public boolean claimSeat(long lectureId, int seatNo, UUID memberId) {
        return session.execute(SimpleStatement.newInstance(
                        "INSERT INTO seat_claim (lecture_id, seat_no, member_id) VALUES (?, ?, ?) IF NOT EXISTS",
                        lectureId, seatNo, memberId)
                .setConsistencyLevel(DefaultConsistencyLevel.QUORUM)
                .setSerialConsistencyLevel(DefaultConsistencyLevel.SERIAL)).wasApplied();
    }
}

This code was compiled against java-driver-core 4.19.4 but never connected to a real Cassandra cluster; the semantics of the consistency levels follow the Cassandra 5.0 documentation.

  • The SERIAL in claimSeat is Paxos across data centers and needs a majority of all replicas (2 of 3). During a partition Taipei can still take sign-ups, while Tokyo fails
  • A standing consistency level can go into an execution profile in the driver configuration (basic.request.consistency), so a query only has to name the profile

Pitfalls and gotchas

  • Claiming seats with LOCAL_SERIAL: it runs Paxos only within the local data center. If Taipei and Tokyo each use LOCAL_SERIAL to claim the same seat, both can succeed; the two are later merged by timestamp, and one of them is silently overwritten
  • An LWT timeout does not mean failure: when a write times out (WriteTimeoutException with write type CAS), Paxos may already have completed. Read again with SERIAL to find out whose seat it actually is. For every write across a network, the result of a timeout is “unknown”, and retries must be idempotent
  • Using QUORUM instead of LOCAL_QUORUM with multiple data centers: QUORUM counts the replicas in all data centers, so sometimes it has to wait for the other data center, and latency jumps up and down
  • Last write wins (LWW) and clock skew: when two machines’ clocks are 50 ms apart, an edit sent 30 ms later can carry an earlier timestamp and get overwritten by the one sent first. When you need to keep every edit, use version vectors or CRDTs
  • Systems that call themselves “CA”: this usually means their behavior during a partition was never explicitly designed; ask exactly what happens when the network breaks
  • Testing only the normal case: rehearse the partition behavior for real: cut the links between data centers with firewall rules and watch how each feature reacts

Security

  • Client-controlled timestamps: CQL lets you set the timestamp of a write with USING TIMESTAMP. If that value comes from the client, an attacker can send a time far in the future, and their write will never be overwritten, not even by an admin. Always let the server decide the timestamp
  • Choose C for revoking permissions: an admin disables an account in Taipei, Tokyo does not find out during the partition, and the account still works in Tokyo. For data like permissions, account status, and token revocation, fail closed during a partition: if you cannot reach the main data center, reject sensitive operations instead of letting them through based on local data that may be stale
  • Double redemption across data centers: if a coupon’s “already used” flag lives in an eventually consistent database, an attacker can redeem it in Taipei and in Tokyo separately during a partition, and both succeed. Keep this kind of data in a linearizable store, or require each user to redeem only in their own home data center
  • Audit logs during a partition: when both sides accept operations on their own during a partition and are merged afterwards, the audit log must keep the events from both sides in full, and must not lose any of them to last write wins

When to use it, and when not to

  • Choose C: money, seats, uniqueness, permissions; data where a temporary rejection is better than a mistake
  • Choose A: counts, progress, preferences; data that can be merged afterwards
  • Choose L: read-heavy data that can tolerate brief staleness, where users are sensitive to latency
  • Do not put one label on the whole system: within the same system, different data should get different choices

References

Comments