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.

The same partition, seen by a CP store and an AP store

Read it, run it, change a line and run it again.

Loading editor…

A teaching model: the CP store checks for a majority before it writes, so a refused write leaves nothing behind. Real systems need consensus for that.

The same in TypeScript
interface Replica { write(k: string, v: string, version: number): Promise<void>; read(k: string): Promise<{ value: string; version: number }> }class CPClient {  private nodes: Replica[];  constructor(nodes: Replica[]) { this.nodes = nodes; }  private get quorum() { return Math.floor(this.nodes.length / 2) + 1; }  // Note: a failed write may still be stored on some nodes. Real systems use consensus.  async write(key: string, value: string, version: number): Promise<void> {    const done = await Promise.allSettled(this.nodes.map((n) => n.write(key, value, version)));    if (done.filter((d) => d.status === "fulfilled").length < this.quorum) throw new Error("no write quorum");  }  async read(key: string): Promise<string> {    const all = await Promise.allSettled(this.nodes.map((n) => n.read(key)));    const ok = all.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));    if (ok.length < this.quorum) throw new Error("no read quorum");    return ok.reduce((a, b) => (b.version > a.version ? b : a)).value;  }}class APClient {  private local = new Map<string, string>();  private queue: { key: string; value: string }[] = [];  write(key: string, value: string): void {    this.local.set(key, value); // accept at once    this.queue.push({ key, value }); // send to the others later  }  read(key: string): string | undefined {    return this.local.get(key); // may be stale  }  async sync(send: (w: { key: string; value: string }) => Promise<void>): Promise<void> {    while (this.queue.length > 0) {      await send(this.queue[0]); // stops here if the peer is unreachable      this.queue.shift();    }  }}
The same in Go
package capdemoimport (	"context"	"errors"	"sync")type Node interface {	Write(ctx context.Context, key, value string, version int64) error	Read(ctx context.Context, key string) (value string, version int64, err error)}type CP struct{ nodes []Node }func (c CP) quorum() int { return len(c.nodes)/2 + 1 }func (c CP) Write(ctx context.Context, key, value string, version int64) error {	acks := make(chan bool, len(c.nodes))	for _, n := range c.nodes {		go func(n Node) { acks <- n.Write(ctx, key, value, version) == nil }(n)	}	ok := 0	for range c.nodes {		if <-acks {			ok++		}		if ok >= c.quorum() {			return nil // do not wait for the slowest		}	}	return errors.New("no write quorum")}// AP keeps answering; it remembers what the others have not seen.type AP struct {	mu      sync.Mutex	local   map[string]string	pending []string}func NewAP() *AP { return &AP{local: map[string]string{}} }func (a *AP) Write(key, value string) {	a.mu.Lock()	defer a.mu.Unlock()	a.local[key] = value	a.pending = append(a.pending, key)}func (a *AP) Read(key string) (string, bool) {	a.mu.Lock()	defer a.mu.Unlock()	v, ok := a.local[key]	return v, ok}
The same in Java
import java.util.*;import java.util.concurrent.*;public class CapDemo {    record Versioned(String value, long version) {}    interface Node {        boolean write(String key, Versioned v);        Versioned read(String key);    }    static class NoQuorum extends RuntimeException {}    static class CP {        private final List<Node> nodes;        CP(List<Node> nodes) { this.nodes = nodes; }        int quorum() { return nodes.size() / 2 + 1; }        void write(String key, Versioned v) {            long acks = nodes.parallelStream().filter(n -> {                try { return n.write(key, v); } catch (RuntimeException e) { return false; }            }).count();            if (acks < quorum()) throw new NoQuorum();        }        String read(String key) {            List<Versioned> got = nodes.parallelStream().map(n -> {                try { return Optional.ofNullable(n.read(key)); } catch (RuntimeException e) { return Optional.<Versioned>empty(); }            }).flatMap(Optional::stream).toList();            if (got.size() < quorum()) throw new NoQuorum();            return got.stream().max(Comparator.comparingLong(Versioned::version)).orElseThrow().value();        }    }    static class AP {        private final Map<String, String> local = new ConcurrentHashMap<>();        private final Queue<String> pending = new ConcurrentLinkedQueue<>();        void write(String key, String value) { local.put(key, value); pending.add(key); }        Optional<String> read(String key) { return Optional.ofNullable(local.get(key)); }    }}