CAP Theorem & Consistency
CAP Theorem কেন শিখতে হবে?
আপনি একটা distributed system design করছো। Interview এ জিজ্ঞেস করলো — "আপনার system এ network failure হলে কী হবে? User কি wrong data দেখবেন নাকি error পাবেন?" — এই question এর answer হলো CAP Theorem।
Cassandra vs MongoDB vs PostgreSQL কোনটা choose করবেন — এই decision এর পেছনে CAP আছে। Senior engineer হতে হলে এই trade-off বুঝতেই হবে।
DEFINITION
CAP Theorem বলে: একটা distributed system এ সর্বোচ্চ দুটো guarantee দেওয়া সম্ভব — Consistency, Availability, Partition Tolerance এর মধ্যে। তিনটা একসাথে impossible। Eric Brewer 2000 সালে propose করেন, 2002 সালে formally prove হয়।
C, A, P — তিনটা কি মানে?
C — Consistency
A — Availability
P — Partition Tolerance
💡 Real Choice
🎯 Interview এ এটা বলুন
"CAP এ P সবসময় থাকবেন কারণ network failure real world এ inevitable। তাই practical choice হলো CP বা AP। Financial systems এ CP — wrong data catastrophic। Social media তে AP — stale data কয়েক seconds acceptable।"
Network Partition হলে কি হয়?
| Use Case | CP নাকি AP? | কারণ |
|---|---|---|
| Bank balance | CP | Wrong balance দেখালে double-spending হবে |
| Facebook likes | AP | কয়েক seconds stale count দেখানো acceptable |
| Online booking | CP | Double-booking prevent করতে হবে |
| DNS records | AP | Always available, propagation delay acceptable |
| Shopping cart | AP | Cart lock হলে sale হারাবে, stale cart acceptable |
| Leader election | CP | Split-brain হলে catastrophic |
CP Systems — Consistency Priority
Partition হলে কিছু requests reject করে। Wrong data দেবে না। Banking, coordination (Zookeeper), configuration management এর জন্য।
AP Systems — Availability Priority
Partition হলেও respond করে, কিন্তু stale data দিতে পারে। Eventually consistent। Social feeds, caching, DNS, shopping cart এর জন্য।
Consistency — Strong থেকে Eventual
| Level | মানে কি | Real Example |
|---|---|---|
| Strong | Write এর পর সব nodes এ latest value। Slowest | Bank balance, Stock inventory |
| Linearizable | Real-time order maintain। Operations globally ordered | Zookeeper, etcd |
| Causal | Causally related operations ordered। Reply এর আগে post দেখা যাবেন | Chat apps, Comments |
| Read-your-writes | আপনি নিজের write সবসময় দেখবেন। অন্যরা হয়তো দেখবেন না | Instagram — নিজের post দেখা |
| Eventual | Eventually সব nodes same data। কখন হবে guarantee নেই | DNS, YouTube view count, Likes |
💡 Eventual Consistency Example
DNS update করলেন সারা বিশ্বে propagate হতে ২৪-৪৮ ঘণ্টা লাগতে পারে। এই সময় কেউ old IP দেখছে, কেউ new IP। এটাই Eventual Consistency।
-- Cassandra তে per-query consistency level configure করা যায়!
-- এটাই practical CAP flexibility
-- QUORUM: majority nodes (N/2+1) agree করলেন success
-- 3 nodes থাকলে QUORUM = 2 nodes agree করতে হবে
INSERT INTO accounts (id, balance)
VALUES (uuid(), 10000)
USING CONSISTENCY QUORUM; -- Strong-ish, balanced
-- ONE: শুধু একটা node respond করলেনই success (fastest)
SELECT * FROM user_activity WHERE user_id = 101
CONSISTENCY ONE; -- Fast, eventually consistent
-- ALL: সব nodes confirm করতে হবে (strongest, slowest)
UPDATE accounts SET balance = balance - 5000
WHERE account_id = 101
CONSISTENCY ALL; -- Critical financial opPACELC — CAP এর Extension
CAP শুধু partition সময়ের কথা বলে। কিন্তু normal operation এও trade-off আছে। Daniel Abadi 2012 সালে PACELC propose করেন।
📌 PACELC মানে
Partition থাকলে Availability vs Consistency; Else (normal এ) Latency vs Consistency। যত বেশি nodes এ replicate করবেন, তত বেশি consistent কিন্তু তত বেশি latency।
| Database | Partition Time | Normal Operation | সহজ কথায় |
|---|---|---|---|
| DynamoDB | PA (available) | EL (low latency) | Fast, eventual consistency |
| Cassandra | PA (available) | EL (configurable) | Tunable, default fast |
| MongoDB | PC (consistent) | EC (some latency) | Strong consistency |
| PostgreSQL | PC (consistent) | EC (ACID overhead) | Full ACID, slower |
বড় কোম্পানিগুলো কীভাবে করেছেনে
📦 Amazon DynamoDB — AP by Design
Amazonconsciously AP choose করেছেনে। "Always available" guarantee। Werner Vogels (Amazon CTO): "Network partition হলে আপনাকে পুরোনো cart দেখাবো কিন্তু cart lock করবো না।" Availability থেকে Consistency বেশি important — cart lock হলে sale হারাবে। তবে checkout এ CP enforce হয়।
🔒 Apache Zookeeper — CP by Design
Distributed coordination service — CP choice। Leader election, distributed locks, config management। Wrong value এখানে catastrophic — দুটো nodes যদি একসাথে leader মনে করে, split-brain problem হয়। Partition এ কিছু clients reject হলেও correct data দেওয়া জরুরি। Kafka broker coordination, HDFS এ Zookeeper use হয়।
💡 Split-brain কি?
Network partition এ দুটো partition নিজেকেই primary মনে করে — conflicting states তৈরি হয়। Solution: Quorum (majority voting) — ছোট partition writes accept করে না। Zookeeper, etcd এভাবে handle করে।
import asyncio, time, random
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.data = {} # Local state
self.peers = []
async def write(self, key, value):
# AP: Local write, async sync — fire and forget
self.data[key] = {'value': value, 'ts': time.time()}
print(f"[{self.node_id}] Wrote {key}={value} (local)")
asyncio.create_task(self._propagate(key)) # Async!
async def read(self, key):
# May return stale data!
entry = self.data.get(key)
val = entry['value'] if entry else None
print(f"[{self.node_id}] Read {key}={val}")
return val
async def _propagate(self, key):
# Simulate network delay (0.5-3 seconds)
await asyncio.sleep(random.uniform(0.5, 3.0))
for peer in self.peers:
await peer._sync(key, self.data[key])
async def _sync(self, key, entry):
# Last-Write-Wins conflict resolution
existing = self.data.get(key)
if not existing or existing['ts'] < entry['ts']:
self.data[key] = entry
print(f"[{self.node_id}] Synced {key}={entry['value']}")
async def demo():
a, b = Node("A"), Node("B")
a.peers = [b]; b.peers = [a]
await a.write("likes", 100)
await b.read("likes") # None! Not synced yet
await asyncio.sleep(4) # Wait for propagation
await b.read("likes") # 100 — eventually consistent!
asyncio.run(demo())Database CAP Classification
| Database | CAP Type | Consistency | Availability | Best For |
|---|---|---|---|---|
| Zookeeper | CP | Strong | Partition = reject | Leader election, locks |
| HBase | CP | Strong | Partition = reject | Big data analytics |
| MongoDB | CP | Strong (default) | Primary must respond | Content, catalogs |
| Cassandra | AP (tunable) | Tunable ONE→ALL | Always responds | Social, IoT, logging |
| DynamoDB | AP (default) | Eventually/Strong | 99.999% SLA | E-commerce, gaming |
| CouchDB | AP | Eventual | Always available | Offline-first apps |
| PostgreSQL | CP | Strong (ACID) | Single-node limit | Finance, e-commerce |
SUMMARY — আজকে যা শিখলাম
| Concept | এক লাইনে |
|---|---|
| CAP Theorem | C + A + P একসাথে impossible। P সবসময় থাকে, তাই CP বা AP choose করুন |
| CP Systems | Consistency priority — Banking, Zookeeper |
| AP Systems | Availability priority — Social, DNS, Cache |
| Eventual Consistency | Eventually সব nodes same, latency কম |
| PACELC | Normal operation এ Latency vs Consistency trade-off |
| QUORUM | Majority (N/2+1) nodes agreement |
| Split-brain | Partition এ দুটো leaders — Quorum দিয়ে prevent করুন |
Phase 1 — Foundations Complete!
আপনি System Design Mastery Course এর Phase 1 সম্পূর্ণ করেছেনো। চারটি fundamental topic এ solid foundation তৈরি হয়েছে।
PHASE 2 — Next Topics:
Caching Strategies · Message Queues · API Design · Microservices · Rate Limiting · System Design Case Studies