CAP nói: trong hệ phân tán, khi có network partition (các node mất liên lạc với nhau) bạn chỉ giữ được 1 trong 2 — Consistency hoặc Availability. Vì partition là điều không tránh khỏi (P luôn phải có), lựa chọn thực sự là CP hay AP.
Ba chữ:
- C (Consistency): mọi node thấy cùng dữ liệu tại mọi thời điểm.
- A (Availability): mọi request đều có phản hồi, không lỗi/timeout.
- P (Partition tolerance): vẫn chạy khi mạng giữa các node bị đứt.
Khi có partition:
- CP (PostgreSQL, MySQL, ZooKeeper): từ chối bớt request để dữ liệu luôn đúng, tránh "split-brain".
- AP (Cassandra, DynamoDB, CouchDB): vẫn phục vụ nhưng có thể trả dữ liệu cũ, hòa giải sau (eventual consistency).
(MongoDB tùy cấu hình: mặc định nghiêng AP; đặt writeConcern: majority + readConcern: majority thì thành CP nhưng trễ hơn.)
Mở rộng PACELC: ngay cả khi KHÔNG có partition (Else), vẫn phải đánh đổi Latency vs Consistency — DynamoDB chọn độ trễ thấp, Spanner chọn nhất quán.
Chọn thế nào: CP cho dữ liệu tài chính, tồn kho, hồ sơ y tế (đúng quan trọng hơn sẵn sàng); AP cho feed mạng xã hội, giỏ hàng, bảng xếp hạng (sẵn sàng + hiệu năng quan trọng hơn, dữ liệu hơi cũ chấp nhận được).
CAP says: in a distributed system, when a network partition happens (nodes lose contact with each other) you can keep only 1 of 2 — Consistency or Availability. Since partitions are unavoidable (P is always required), the real choice is CP or AP.
The three letters:
- C (Consistency): every node sees the same data at every moment.
- A (Availability): every request gets a response, no errors/timeouts.
- P (Partition tolerance): keeps running when the network between nodes breaks.
During a partition:
- CP (PostgreSQL, MySQL, ZooKeeper): rejects some requests so data stays correct, avoiding "split-brain".
- AP (Cassandra, DynamoDB, CouchDB): keeps serving but may return stale data, reconciling later (eventual consistency).
(MongoDB depends on config: defaults lean AP; set writeConcern: majority + readConcern: majority to be CP, but with higher latency.)
The PACELC extension: even with NO partition (Else), you still trade Latency vs Consistency — DynamoDB picks low latency, Spanner picks consistency.
How to choose: CP for financial data, inventory, medical records (correctness over availability); AP for social feeds, shopping carts, leaderboards (availability + performance matter more, slightly stale data is acceptable).