Managing Data Consistency

1. Strong Consistency Pattern

AspectDetail
GuaranteeAll readers see latest write immediately
MechanismSingle primary, synchronous replication, distributed consensus
CostReduced availability under partition (CAP)
StoresSingle-node RDBMS, Spanner, CockroachDB, etcd

2. Eventual Consistency Pattern

AspectDetail
GuaranteeReplicas converge to same value over time, absent new writes
WindowInconsistency window (ms-seconds typical)
UX MitigationShow optimistic UI, "saved, syncing" indicators
StoresDynamoDB (default), Cassandra, S3

3. Causal Consistency Pattern

AspectDetail
GuaranteeOperations causally related observed in same order by all
MechanismVector clocks, version vectors
Use CaseSocial feeds (reply must follow original), chat

4. Read-Your-Writes Consistency Pattern

AspectDetail
GuaranteeClient always reads its own writes immediately
ImplementationSticky session to primary; pass write timestamp on reads
Use Case"My profile" updates appear instantly to user

5. Monotonic Reads Pattern

AspectDetail
GuaranteeSubsequent reads never go backwards in time
MechanismPin client to single replica or track read versions
Anti-SymptomPage refresh shows older data than previous load

6. Monotonic Writes Pattern

AspectDetail
GuaranteeWrites from same client applied in submission order
MechanismSame-session affinity; per-session sequence numbers

7. Optimistic Locking Pattern

AspectDetail
MechanismRead with version; write with WHERE version = read_version
Conflict0 rows affected → another writer won; retry/merge
Best ForLow-contention scenarios
JPA@Version annotation auto-handles

Example: Optimistic UPDATE

UPDATE accounts SET balance = $1, version = version + 1
WHERE id = $2 AND version = $3;
-- if rowcount = 0 → throw OptimisticLockException

8. Pessimistic Locking Pattern

AspectDetail
MechanismSELECT ... FOR UPDATE acquires row lock
Holds UntilTransaction commits/rolls back
Best ForHigh-contention, short-tx workloads
RiskDeadlocks; long transactions block others

9. Conflict-Free Replicated Data Type Pattern

CRDT TypeUse Case
G-CounterIncrement-only counter (page views)
PN-CounterIncrement + decrement counter
G-SetAdd-only set
OR-SetAdd/remove set with tags
LWW-RegisterLast-writer-wins value
RGA / YjsCollaborative text editing
Note: CRDTs guarantee strong eventual consistency without coordination — replicas converge automatically.

10. Version Vector Pattern

AspectDetail
DefinitionMap of [node → counter] tracking causal history
CompareDetermines: equal, descendant, or concurrent
Conflict ResolutionConcurrent → app-level merge or LWW
Used InDynamo, Riak, Cassandra (timestamps)