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, inventory | Social media, analytics |
BASE — ทางเลือกของ NoSQL แทน ACID
| ตัวอักษร | ความหมาย |
|---|---|
| Basically Available | ระบบพร้อมใช้งานเสมอ (แม้ค่าอาจไม่ล่าสุด) |
| Soft state | State ของระบบเปลี่ยนได้ตลอดเวลา (ไม่ต้อง consistent ตลอด) |
| Eventual consistency | สุดท้ายทุก node จะเห็นค่าเดียวกัน (แต่ไม่รับประกันว่าเมื่อไหร่) |
Consistency ใน CAP ≠ Consistency ใน ACID
| ACID Consistency | CAP Consistency | |
|---|---|---|
| ความหมาย | Data ไม่ขัด rules (FK, constraints) | ทุก node เห็นค่าเดียวกัน |
| ขอบเขต | 1 DB instance | Distributed 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
Related
- 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