CAP Theorem

Distributed system เลือกได้แค่ 2 ใน 3: Consistency, Availability, Partition Tolerance — ในโลกจริง P หลีกเลี่ยงไม่ได้ → เลือกระหว่าง CP vs AP

3 คุณสมบัติ

Consistency (C)

ทุก node เห็น data เดียวกัน ณ เวลาเดียว — อ่านจากไหนก็ได้ค่าล่าสุดเสมอ

Availability (A)

ทุก request ได้ response (ไม่ error, ไม่ timeout) — แม้บาง node จะล่ม

Partition Tolerance (P)

ระบบทำงานต่อได้แม้ network แบ่ง (บาง node คุยกันไม่ได้)

CP vs AP

CP (Consistency + Partition)AP (Availability + Partition)
เมื่อ network partitionปฏิเสธ request ที่อาจให้ค่าเก่าตอบ request ด้วยค่าที่อาจเก่า
ตัวอย่างPostgreSQL (sync replication), MongoDB (default)Cassandra, DynamoDB (default)
เหมาะกับBanking, inventorySocial media, analytics

BASE — ทางเลือกของ NoSQL แทน ACID

ตัวอักษรความหมาย
Basically Availableระบบพร้อมใช้งานเสมอ (แม้ค่าอาจไม่ล่าสุด)
Soft stateState ของระบบเปลี่ยนได้ตลอดเวลา (ไม่ต้อง consistent ตลอด)
Eventual consistencyสุดท้ายทุก node จะเห็นค่าเดียวกัน (แต่ไม่รับประกันว่าเมื่อไหร่)

Consistency ใน CAP ≠ Consistency ใน ACID

ACID ConsistencyCAP Consistency
ความหมายData ไม่ขัด rules (FK, constraints)ทุก node เห็นค่าเดียวกัน
ขอบเขต1 DB instanceDistributed system

อย่าสับสน 2 ตัวนี้ — คนละเรื่องกัน!

ทำไมคนย้ายไป NoSQL? (มุมมองประวัติศาสตร์)

ยุค 2000s — Web Scale:

  • Google, Yahoo, Facebook โตเร็ว — RDBMS เดิม scale ไม่ทัน
  • ต้องการ high write throughput + horizontal scale + flexible schema
  • → Bigtable (Google), Dynamo (Amazon), Cassandra (Facebook)

ปัจจุบัน:

  • Postgres + MySQL พัฒนาทัน (logical replication, JSONB, partitioning)
  • Cloud DBs (Aurora, Spanner, CockroachDB) — ได้ทั้ง SQL + horizontal scale
  • เส้นแบ่ง SQL/NoSQL เลือนลาง

Key Points

  • CAP: distributed system เลือก 2 ใน 3 — โลกจริงเลือก CP vs AP
  • CP = consistency สำคัญ (banking) / AP = availability สำคัญ (social media)
  • BASE = ทางเลือก NoSQL — Basically Available, Soft state, Eventual consistency
  • CAP Consistency ≠ ACID Consistency — คนละเรื่อง
  • เส้นแบ่ง SQL/NoSQL เลือนลาง — Cloud DBs ได้ทั้ง SQL + scale
  • ACID — Consistency คนละความหมายกับ CAP
  • Database Replication — async = AP, sync = CP
  • NoSQL — NoSQL มักเป็น AP (Cassandra, DynamoDB)
  • Database Sharding — sharding = distributed → เจอ CAP trade-offs
  • PostgreSQL — CP เมื่อใช้ sync replication