CAP theorem: network ขาดแล้วจะตอบหรือจะถูก
เก็บข้อมูลไว้หลาย copy บนหลายเครื่อง วันหนึ่ง network ระหว่างเครื่องจะขาด copy ที่ติดต่อตัวอื่นไม่ได้มีสองทาง: ตอบจากที่ตัวเองมี หรือปฏิเสธจนกว่าจะเช็กได้ ที่นั่งเหลือหนึ่งที่ สาม copy สองคนซื้อ
สิ่งที่จะได้
- อธิบายได้ว่า copy ที่ติดต่อตัวอื่นไม่ได้ต้องเลือก ตอบจากของที่ตัวเองมี หรือปฏิเสธไปก่อน
- รู้ว่าทำไมการเล่าแบบเลือกสองในสามชวนเข้าใจผิด และทำไมต้องเลือกทีละ operation
- ใช้ R + W > N บอกได้ว่าเมื่อไหร่การอ่านจะเจอค่าที่เขียนล่าสุดแน่ ๆ
- ชั่งทางเลือกของ PACELC ได้ ตอน network ปกติ รอหลาย copy ถูกกว่าแต่ช้ากว่า
สรุป 1 นาที
กดข้อไหน ภาพข้างล่างจะเล่นขั้นนั้นให้ดู
ลองทั้งสามแบบตอน network ปกติ แล้วตอนขาด: แบบไหนขายเกิน แบบไหนปฏิเสธ และแบบไหนขายเกินทั้งที่ network ไม่ได้ขาด
ข้อมูลมีสาม copy แล้ว network ขาด C อยู่ฝั่งเดียวคนเดียว ลูกค้าถาม C ว่าที่นั่งยังเหลือไหม C ทำอะไรได้บ้าง
ในภาพ ที่นั่งสุดท้ายหนึ่งที่ เก็บไว้สาม copy ศูนย์ข้อมูล A กับ B อยู่ฝั่งซ้าย C อยู่อีกฝั่งของถนนยาว มือถือของพลอยอยู่ข้าง A ของต้นอยู่ข้าง C แผ่นสีฟ้าบนหลังคาคือที่นั่งที่ยังว่าง กรอบทองว่างคือขายแล้ว ป้ายของแต่ละตึกบอกว่า copy นั้นถือค่าอะไร (v คือ version และขึ้นว่า "เก่า" เมื่อมีตัวที่ใหม่กว่า) วงที่วิ่งออกไปคือการอ่าน ไฟที่วิ่งกลับคือคำตอบ (ฟ้าคือเหลือ 1 ทองคือ 0) ก้อนสีทองคือการเขียน พอ network ขาด ถนนไป C จะขาดระหว่างแผงกั้นสีแดงสองอัน และไม่มีอะไรข้ามไปได้ เป็นเวลาในแบบจำลอง ไม่ใช่ค่าที่วัดจริง
เทียบทุกแบบ: CAP: ตอบ หรือ ถูก
พลอยซื้อที่ A แล้วต้นซื้อที่ C ทีละแบบ บน network ปกติ ตอน C ถูกตัดขาด และตอนต่อกลับ กล่องคือตั๋วที่ขายได้ (ที่นั่งมีที่เดียว กล่องแดงคือขายเกิน) ข้างหลังคือคำตอบที่ต้นได้
ใช้เมื่อ ของที่เก่าไปนิดไม่เสียหาย: จำนวน like, feed, ตะกร้าสินค้า, cache ระบบที่ต้องตอบเร็วและตอบได้แม้ network ขาด
ไม่ควรใช้เมื่อ ของที่มีชิ้นเดียว: ที่นั่ง สต็อกชิ้นสุดท้าย ยอดเงิน สองฝั่งตัดสินใจจากข้อมูลเก่าได้พร้อมกัน
ผลจากแบบจำลองเดียวกับโค้ด quorum.ts ที่รันจริงด้านล่าง · กดช่องไหนก็ได้ ภาพใหญ่ด้านบนจะเปลี่ยนเป็นแบบนั้น พร้อมบอกว่าเหมาะกับงานแบบไหน
อ่านและเขียนสาม copy ได้สามแบบ
| อ่าน · เขียน | network ปกติ | C ถูกตัดขาด | เหมาะกับ |
|---|---|---|---|
| ONE · ONE | เร็วสุด อ่านได้ค่าเก่าจนกว่าการเขียนจะมาถึง | ทุกฝั่งตอบ ที่นั่งเดียวขายสองครั้ง | จำนวน like, feed, ตะกร้า, cache |
| QUORUM · QUORUM | ทุก request รอ copy ที่สอง | ฝั่งที่มี 2 ใน 3 ทำงานต่อ C ปฏิเสธ | การจอง สต็อก ยอดเงิน ชื่อที่ห้ามซ้ำ |
| ONE · ALL | อ่านเร็ว เขียนแต่ละครั้งรอ copy ที่ช้าที่สุด | ทุกคนอ่านได้ ไม่มีใครเขียนได้ | อ่านบ่อย เขียนนาน ๆ ครั้ง: config, ราคา |
ไม่ใช่ “สองในสาม”
Gilbert กับ Lynch ผู้พิสูจน์ theorem นี้ เขียนไว้สำหรับ network ที่ทำข้อความหายได้: ไม่มี service ไหนตอบทุก request ได้และทำตัวเป็น copy เดียวที่ใหม่เสมอได้พร้อมกัน (Perspectives on the CAP Theorem) network ขาดไม่ใช่เรื่องที่เลือกไม่รับได้ ตัวเลือกจึงมีแค่ C หรือ A และเฉพาะตอนที่ขาดอยู่ Brewer เขียนในปี 2012 ว่าการเล่าแบบสองในสามชวนเข้าใจผิด network ขาดไม่บ่อย และระบบเลือกได้หลายครั้ง ทีละ operation (CAP Twelve Years Later)
R + W > N
มี N copy การอ่านที่รอ R ตัวกับการเขียนที่รอ W ตัว จะซ้อนกันอย่างน้อยหนึ่ง copy เมื่อ R + W > N การอ่านจึงเจอการเขียนล่าสุด Cassandra ส่งการเขียนไปทุก replica เสมอ แล้วให้แต่ละ query กำหนดว่าจะรอกี่คำตอบ: ONE, QUORUM (เสียงข้างมาก), ALL (Cassandra: Dynamo) DynamoDB อ่านแบบ eventual เป็นค่าเริ่มต้น ConsistentRead ขอข้อมูลล่าสุดได้ในราคาสองเท่า และ global secondary index กับ stream เป็น eventual อย่างเดียว (DynamoDB: read consistency) Abadi ชี้ว่า R + W > N อย่างเดียวยังไม่ได้ consistency เต็มแบบที่ theorem หมายถึง
PACELC: ไม่ขาดก็ยังต้องเลือก
ถ้ามี Partition เลือก Availability หรือ Consistency, Else (ไม่ขาด) เลือก Latency หรือ Consistency การรอ copy มากขึ้นใช้เวลาแม้ network ปกติ (ในแบบจำลอง เขียนแล้วอ่าน: ONE 1 ms ได้ค่าเก่า QUORUM 61 ms ได้ค่าใหม่) ปี 2012 Abadi จัดค่าเริ่มต้นของ Dynamo, Cassandra และ Riak เป็น PA/EL, VoltDB/H-Store, Megastore และ BigTable/HBase เป็น PC/EC และ MongoDB เป็น PA/EC (Consistency Tradeoffs in Modern Distributed Database System Design)
Redis ที่รันจริง
Redis ทำ replication แบบ asynchronous โดยค่าเริ่มต้น replica ที่หลุดจาก primary ยังตอบด้วยข้อมูลที่อาจเก่า เว้นแต่ตั้ง replica-serve-stale-data no ซึ่งจะตอบ MASTERDOWN แทน min-replicas-to-write คู่กับ min-replicas-max-lag ทำให้ primary ปฏิเสธการเขียน (NOREPLICAS) เมื่อ replica ที่ ping มาเมื่อเร็ว ๆ นี้มีไม่พอ Redis เรียกสิ่งนี้ว่ากลไกป้องกันแบบ best effort และบอกว่า WAIT ก็ไม่ได้ทำให้เป็นระบบ CP (Redis replication)
ในโค้ดจริง
// Three copies of one value (seats left on a flight: 1) on three nodes, A, B and C, talking over real TCP links that
// hold every chunk for a set delay. Any node can take a request and coordinate it: it asks the copies and waits for
// R answers to a read, W to a write (ONE = 1, QUORUM = 2 of 3, ALL = 3), and a read returns the newest version it
// got. Cutting a link makes it swallow everything, as a partition does: no error, just silence.
import { createServer as httpServer } from "node:http";
import { createConnection, createServer, type AddressInfo, type Socket } from "node:net";
import { setTimeout as sleep } from "node:timers/promises";
const NODES = ["A", "B", "C"] as const;
type Node = (typeof NODES)[number];
type Copy = { seats: number; version: number };
const LEVEL = { ONE: 1, QUORUM: 2, ALL: 3 } as const;
type Level = keyof typeof LEVEL;
// one-way delay of each link, set here (a model of three sites, not a measurement of any real one)
const DELAY: Record<string, number> = { AB: 15, AC: 40, BC: 30 };
const TIMEOUT = 250; // a request with no answer by then counts as none: a cut link and a slow one look the same
// ---- the copies: a tiny HTTP server per node ----
const copies = new Map<Node, Copy>();
const replicaPort = new Map<Node, number>();
const servers: { close(): void }[] = [];
for (const node of NODES) {
const server = httpServer((req, res) => {
let body = "";
req.on("data", (c: Buffer) => (body += c));
req.on("end", () => {
if (req.method === "POST") {
const next = JSON.parse(body) as Copy;
if (next.version > copies.get(node)!.version) copies.set(node, next); // a newer version replaces an older one
}
res.end(JSON.stringify(copies.get(node)));
});
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
replicaPort.set(node, (server.address() as AddressInfo).port);
servers.push(server);
}
// ---- the links: a TCP proxy per pair of nodes, each way delayed, cut on demand ----
const cut = new Set<string>();
const linkPort = new Map<string, number>();
const sockets = new Set<Socket>();
for (const from of NODES) for (const to of NODES) {
if (from === to) continue;
const key = [from, to].sort().join("");
const proxy = createServer((client) => {
const server = createConnection(replicaPort.get(to)!, "127.0.0.1");
for (const s of [client, server]) { sockets.add(s); s.on("error", () => s.destroy()); s.on("close", () => sockets.delete(s)); }
const relay = (a: Socket, b: Socket) => a.on("data", (chunk: Buffer) => {
if (!cut.has(key)) setTimeout(() => cut.has(key) || b.write(chunk), DELAY[key]);
});
relay(client, server);
relay(server, client);
});
await new Promise<void>((ok) => proxy.listen(0, "127.0.0.1", ok));
linkPort.set(from + to, (proxy.address() as AddressInfo).port);
servers.push(proxy);
}
async function ask(from: Node, to: Node, write?: Copy): Promise<Copy | null> {
const port = from === to ? replicaPort.get(to) : linkPort.get(from + to);
try {
const res = await fetch(`http://127.0.0.1:${port}/seats`, { method: write ? "POST" : "GET", body: write && JSON.stringify(write), signal: AbortSignal.timeout(TIMEOUT) });
return (await res.json()) as Copy;
} catch {
return null;
}
}
// ---- who each node can hear: a ping to the others every 50 ms (a small failure detector) ----
const heard = new Map<string, number>();
const pings = setInterval(() => {
for (const from of NODES) for (const to of NODES) if (from !== to) void ask(from, to).then((c) => c && heard.set(from + to, Date.now()));
}, 50);
const reachable = (at: Node) => NODES.filter((to) => to === at || Date.now() - (heard.get(at + to) ?? 0) < 200);
type Answer = { ok: true; copy: Copy; ms: number } | { ok: false; why: string };
/** Asks every copy it can reach and settles at the need-th answer. Too few reachable: refused before anything is sent. */
async function quorum(at: Node, level: Level, write?: Copy): Promise<Answer> {
const need = LEVEL[level];
const near = reachable(at);
if (near.length < need) return { ok: false, why: `reaches ${near.length} of the ${need} copies it needs` };
const start = performance.now();
const answers: Copy[] = [];
return new Promise((done) => {
let pending = near.length;
for (const to of near) void ask(at, to, write).then((copy) => {
if (copy) answers.push(copy);
if (answers.length === need) {
const newest = answers.reduce((a, b) => (b.version > a.version ? b : a));
done({ ok: true, copy: newest, ms: Math.round(performance.now() - start) });
} else if (--pending === 0 && answers.length < need) done({ ok: false, why: `only ${answers.length} answered in time` });
});
});
}
async function buy(at: Node, read: Level, write: Level): Promise<"ticket" | "sold out" | "refused"> {
const seen = await quorum(at, read);
if (!seen.ok) return "refused";
if (seen.copy.seats < 1) return "sold out";
const wrote = await quorum(at, write, { seats: seen.copy.seats - 1, version: seen.copy.version + 1 });
return wrote.ok ? "ticket" : "refused";
}
async function reset(partition: boolean) {
await sleep(300); // whatever is still on the wire lands first
cut.clear();
for (const node of NODES) copies.set(node, { seats: 1, version: 1 });
if (partition) { cut.add("AC"); cut.add("BC"); } // C is cut off from A and B; A and B still talk
await sleep(300); // long enough for every node to notice who it can hear
}
// 1. No partition. A takes a write, and a read at C follows at once.
const fresh: string[] = [];
for (const level of ["ONE", "QUORUM"] as const) {
await reset(false);
await quorum("A", level, { seats: 0, version: 2 });
const read = await quorum("C", level);
if (read.ok) fresh.push(`${level} ${read.copy.seats === 0 ? "new" : "OLD"} value in ${read.ms} ms`);
}
await reset(false);
const times: string[] = [];
for (const level of ["ONE", "QUORUM", "ALL"] as const) {
const read = await quorum("A", level);
if (read.ok) times.push(`${level} ${read.ms} ms`);
}
// 2. Ploy buys the last seat at A; then Ton, at C, tries to buy it too: with the network whole, then with C cut off.
const PICKS = [["ONE", "ONE"], ["QUORUM", "QUORUM"], ["ONE", "ALL"]] as const;
async function sell(partition: boolean): Promise<string> {
const sold: string[] = [];
for (const [read, write] of PICKS) {
await reset(partition);
const ploy = await buy("A", read, write);
const ton = await buy("C", read, write);
const tickets = [ploy, ton].filter((r) => r === "ticket").length;
sold.push(`R=${read} W=${write}: ${tickets} ticket${tickets === 1 ? "" : "s"} (A ${ploy}, C ${ton})`);
}
return sold.join(" · ");
}
const whole = await sell(false);
const split = await sell(true);
const why = await quorum("C", "QUORUM"); // still cut off
const refusedWhy = why.ok ? "answered" : why.why;
// 3. The link comes back. Nothing here copies a missed write over later (real systems do: read repair, resync), so
// each copy shows what it was sent.
const healed: string[] = [];
for (const level of ["ONE", "QUORUM"] as const) {
await reset(true);
const tickets = [await buy("A", level, level), await buy("C", level, level)].filter((r) => r === "ticket").length;
cut.clear();
await sleep(300);
const read = await quorum("C", "QUORUM");
if (!read.ok || read.copy.seats !== 0) throw new Error("the healed read missed the sale");
const each = NODES.map((n) => `${n} ${copies.get(n)!.seats}`).join(", ");
healed.push(`${level}: copies ${each}, ${tickets} ticket${tickets === 1 ? "" : "s"} out, a QUORUM read at C says ${read.copy.seats}`);
}
clearInterval(pings);
for (const s of sockets) s.destroy();
for (const s of servers) s.close();
console.log(`no partition, a write at A then a read at C: ${fresh.join(", ")} · reads at A: ${times.join(", ")}`);
console.log(`no partition, Ploy buys at A, then Ton at C: ${whole}`);
console.log(`C cut off: ${split} · C at QUORUM ${refusedWhy}`);
console.log(`healed: ${healed.join(" · ")}`);
node quorum.ts (Node 23.6+ · Node 22 ใส่ --experimental-strip-types)ผลที่พิมพ์ออกมา:no partition, a write at A then a read at C: ONE OLD value in 1 ms, QUORUM new value in 63 ms · reads at A: ONE 1 ms, QUORUM 32 ms, ALL 81 ms no partition, Ploy buys at A, then Ton at C: R=ONE W=ONE: 2 tickets (A ticket, C ticket) · R=QUORUM W=QUORUM: 1 ticket (A ticket, C sold out) · R=ONE W=ALL: 1 ticket (A ticket, C sold out) C cut off: R=ONE W=ONE: 2 tickets (A ticket, C ticket) · R=QUORUM W=QUORUM: 1 ticket (A ticket, C refused) · R=ONE W=ALL: 0 tickets (A refused, C refused) · C at QUORUM reaches 1 of the 2 copies it needs healed: ONE: copies A 0, B 0, C 0, 2 tickets out, a QUORUM read at C says 0 · QUORUM: copies A 0, B 0, C 1, 1 ticket out, a QUORUM read at C says 0
สาม node บน TCP link จริงที่หน่วงทุกก้อนข้อมูลตามเวลาที่ตั้งไว้ (เป็นแบบจำลองของสามที่ ไม่ใช่ค่าที่วัดจากที่ไหน) node ไหนก็รับอ่านหรือเขียนแบบ ONE, QUORUM หรือ ALL ได้ ขายที่นั่งสุดท้ายตอน network ปกติ ตอน C ถูกตัดขาด และหลังต่อกลับ ใช้แค่ standard library ของ Node รันจริง ด้านล่างคือสิ่งที่มันพิมพ์
คำถามที่เจอบ่อย
CAP theorem คืออะไร
ถ้า network ทำข้อความระหว่าง copy หายได้ ระบบไม่สามารถทั้งตอบทุก request และคืนค่าที่เขียนล่าสุดเสมอได้พร้อมกัน ระหว่างที่ network ขาด copy แต่ละตัวต้องเลือก: ตอบไปก่อน (A) หรือถูกเสมอแต่บางครั้งปฏิเสธ (C)
เลือกได้สองในสามจริงไหม
ไม่ Brewer ผู้ตั้งข้อนี้เขียนเองในปี 2012 ว่าการเล่าแบบสองในสามชวนเข้าใจผิดมาตลอด network ขาดไม่ใช่เรื่องที่เลือกได้ ตอนไม่ขาดระบบได้ทั้ง C และ A ต้องเลือกเฉพาะตอนขาด และเลือกต่างกันได้ในแต่ละงาน
ระบบแบบ CA มีไหม
CAP พูดถึง copy ที่อยู่บน network เครื่องเดียวตัดขาดจากตัวเองไม่ได้ CAP จึงไม่มีอะไรจะบอก ถ้าเครื่องล่มก็แค่ไม่มีใครตอบ เมื่อไรที่ copy อยู่คนละเครื่อง วันหนึ่ง network จะขาด และต้องบอกได้ว่าตอนนั้นจะทำอะไร
Cassandra หรือ DynamoDB เป็น CP หรือ AP
เลือกได้ทีละ request Cassandra ให้กำหนด consistency level ต่อ query เช่น ONE หรือ QUORUM ส่วน DynamoDB อ่านแบบ eventual เป็นค่าเริ่มต้น และขออ่านแบบ strong ได้ด้วย ConsistentRead ป้ายเดียวทั้งระบบจึงบอกได้ไม่ครบ
eventual consistency คืออะไร
copy อาจไม่ตรงกันอยู่พักหนึ่ง แต่ถ้าไม่มีการเขียนใหม่ สุดท้ายจะตรงกัน ข้อควรรู้คือการตามกันทันไม่ได้ย้อนสิ่งที่ตัดสินใจไปแล้วจากข้อมูลเก่า ตั๋วสองใบยังอยู่ ต้องมีขั้นแก้ เช่นคืนเงินหรือขอโทษลูกค้า
PACELC คืออะไร
ส่วนต่อของ CAP โดย Daniel Abadi: ถ้ามี Partition เลือก Availability หรือ Consistency Else (ไม่ขาด) เลือก Latency หรือ Consistency เพราะรอ copy หลายตัวต้องใช้เวลาแม้ network ปกติ เขาจัด Dynamo และ Cassandra ค่าเริ่มต้นเป็น PA/EL
quorum ช่วยไม่ให้อ่านค่าเก่าได้ยังไง
ถ้า copy ที่อ่าน (R) รวมกับ copy ที่เขียน (W) มากกว่าจำนวน copy (N) ชุดที่อ่านกับชุดที่เขียนต้องซ้อนกันอย่างน้อยหนึ่งตัวเสมอ การอ่านจึงเจอค่าใหม่ ราคาคือรอนานขึ้น และฝั่งที่ได้ไม่ครบต้องปฏิเสธ
Redis ทำอะไรตอน network ขาด
replication ของ Redis เป็นแบบ asynchronous โดยค่าเริ่มต้น replica ที่หลุดยังตอบด้วยข้อมูลที่อาจเก่า ตั้ง replica-serve-stale-data no ให้ปฏิเสธได้ และ min-replicas-to-write ให้ primary ไม่รับเขียน แต่เอกสารเรียกว่า best effort ไม่ใช่ CP
บทต่อไป
Circuit breaker, retry และ timeoutระดับ: ลึก
copy ที่ติดต่อตัวอื่นไม่ได้ต้องเลือก ผู้เรียก service ที่ไม่ตอบก็ต้องเลือกเหมือนกัน จะรอ ลองใหม่ หรือใช้ fallback