Skip to content

CAP Theorem & Consistency Models


Definition

CAP Theorem


CP vs AP Systems

CP vs AP Systems


Consistency Models

Consistency Models


PACELC Theorem

PACELC Theorem


Tunable Consistency

// Many distributed databases let you tune consistency per operation

// QUORUM-BASED CONSISTENCY
// N = Total replicas
// W = Write acknowledgments required
// R = Read acknowledgments required

// Strong consistency: W + R > N
// Example: N=3, W=2, R=2
// Any read overlaps with any write

// CASSANDRA CONSISTENCY LEVELS
// Write consistency
INSERT INTO users (id, name) VALUES (1, 'John')
  USING CONSISTENCY QUORUM;

// Read consistency
SELECT * FROM users WHERE id = 1
  USING CONSISTENCY LOCAL_QUORUM;

// Levels:
// ONE: Single replica (fast, weak)
// QUORUM: Majority (N/2 + 1)
// ALL: All replicas (slow, strong)
// LOCAL_QUORUM: Majority in local datacenter

// DYNAMO-STYLE (DynamoDB)
// Eventually consistent read: Fast, may be stale
// Strongly consistent read: Current, slower

// Java SDK example
GetItemRequest request = GetItemRequest.builder()
    .tableName("users")
    .key(key)
    .consistentRead(true)  // Strong consistency
    .build();

// MONGODB READ CONCERN
db.users.find({}).readConcern("majority")  // Committed to majority
db.users.find({}).readConcern("local")     // Local data (may rollback)
db.users.find({}).readConcern("linearizable")  // Linearizable (slow)

Practical Trade-offs

Practical Trade-offs


Tips & Tricks

Tips and Tricks