Monday, 14 April 2025

"consistency" in CAP vs ACID

 

🧱 1. ACID Consistency (Database Transactions)

Context: ACID is a set of properties that ensure reliable processing of database transactions (especially in traditional relational databases).

  • ACID stands for:

    • Atomicity – All or nothing.

    • Consistency – Maintains database rules.

    • Isolation – Transactions don’t interfere.

    • Durability – Once committed, it stays.

✅ What "Consistency" Means in ACID:

The database must start and end in a valid state, following all integrity rules (e.g., constraints, triggers, foreign keys, etc.).

For example:

  • If you transfer $100 from Account A to B, the total balance should remain the same.

  • If a transaction leaves the database in an invalid state (like negative balance when it’s not allowed), it violates consistency.

🔁 If any step fails, the transaction is rolled back, preserving data integrity.


🌐 2. CAP Consistency (Distributed Systems)

Context: CAP theorem (also called Brewer’s theorem) applies to distributed systems and says you can only guarantee two out of the three:

  • Consistency

  • Availability

  • Partition Tolerance

✅ What "Consistency" Means in CAP:

All nodes see the same data at the same time – like a single, up-to-date view of the data, regardless of which node you query.

Imagine a replicated database:

  • If you write a value x = 5 to one node,

  • A read from any node immediately after should return x = 5.

This is often called "linearizability" or strong consistency.


🔍 Key Differences Between ACID and CAP Consistency:

FeatureACID ConsistencyCAP Consistency
📚 ContextDatabases / TransactionsDistributed systems / networks
🎯 GoalEnsure valid data by enforcing rules (e.g., constraints, referential integrity)Ensure all replicas have the same data at the same time
🧠 Focuses onCorrectness of state before and after transactionSame view of data across nodes
💥 ViolationHappens when data violates rules after a transaction (e.g., null in a NOT NULL column)Happens when nodes return different results after a write
🔄 Rollback?Yes, rollback restores consistencyNo rollback; focus is on how to sync nodes or handle divergence

🧠 Example to Compare:

Imagine a banking app:

ACID Consistency:

  • You must not allow transferring money from an account with insufficient balance.

  • If this happens, the system rolls back.

CAP Consistency:

  • You made a transaction to transfer money.

  • You check balance on one server and it shows updated balance.

  • Your phone (connected to another replica) still shows the old balance.

  • This is a CAP consistency problem, because both replicas are not in sync.


🚨 Common Confusion:

  • ACID consistency is about valid states, often on a single node or database.

  • CAP consistency is about same view of data across multiple nodes in a network.