Back to Data Management & Consistency
Q8Question 8 of 12

What are consistency models and how do you choose the right one

Answer: Consistency models define the rules about when a write by one node becomes visible to reads on other nodes, and choosing the right model means balancing correctness, availability, and latency for each use case in your system.

Key Concepts
  • Strong consistency guarantees that every read returns the most recent write, which is required for account balance checks.
  • Eventual consistency guarantees that all replicas converge to the same value given enough time, which is acceptable for notification delivery status.
  • Causal consistency preserves the order of causally related operations while allowing unrelated operations to be seen in any order.
  • The CAP theorem states that a distributed system can provide at most two of three guarantees: consistency, availability, and partition tolerance.
  • Banking systems typically choose strong consistency for financial transactions and eventual consistency for read-heavy, non-critical data.
  • Distributed consensus protocols like Raft and Paxos implement strong consistency across multiple nodes.
  • The PACELC theorem extends CAP by considering latency tradeoffs even when there is no network partition.

Definition

Consistency models define the rules about when a write by one node becomes visible to reads on other nodes, and choosing the right model means balancing correctness, availability, and latency for each use case in your system.
  • Strong consistency means every read returns the result of the most recent write, as if there is only one copy of the data.
  • Eventual consistency means that if no new writes happen, all replicas will eventually return the same value, but a read might return stale data in the meantime.
  • Causal consistency means that if operation A causes operation B, every node sees A before B, but operations that are not causally related may appear in any order.
  • CAP theorem states that when a network partition happens, a distributed system must choose between consistency (every read sees the latest write) and availability (every request gets a response).
  • Linearizability is the strongest form of strong consistency where operations appear to execute atomically in some global order consistent with real time.

Think of the National Bank of India with three branch offices in Mumbai, Delhi, and Chennai. Rajesh has 75,000 rupees in his account. With strong consistency, if Priya deposits 10,000 at the Mumbai branch, every branch immediately shows 85,000 when Rajesh checks. With eventual consistency, the Delhi branch might still show 75,000 for a few seconds until the update propagates. With causal consistency, if Rajesh deposits money and then checks his balance, he always sees the updated balance, but another customer at a different branch might not see the update yet.

Understanding the Concepts

What is strong consistency?

Strong consistency (also called linearizability) guarantees that once a write completes, every subsequent read from any node returns that value. It behaves as if there is a single copy of the data, even though multiple replicas exist.

In a banking system, strong consistency is critical for account balance reads after a write. If Rajesh withdraws 10,000 rupees, every subsequent balance check must reflect the withdrawal.

The cost of strong consistency is higher latency and lower availability. The system must coordinate across replicas before confirming a write.

JAVA
package com.bank.consistency;

import java.math.BigDecimal;
import java.util.concurrent.locks.ReentrantLock;

public class StrongConsistencyDemo {

    private BigDecimal balance = new BigDecimal("75000.00");
    private final ReentrantLock lock = new ReentrantLock();

    // Strong consistency: lock ensures every read after write
    // sees the updated value
    public void withdraw(String accountId, BigDecimal amount) {
        lock.lock();
        try {
            balance = balance.subtract(amount);
            System.out.println("[WRITE] " + accountId
                + " withdrew " + amount + ", new balance: " + balance);
        } finally {
            lock.unlock();
        }
    }

    public BigDecimal readBalance(String reader) {
        lock.lock();
        try {
            System.out.println("[READ] " + reader + " sees balance: " + balance);
            return balance;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        StrongConsistencyDemo account = new StrongConsistencyDemo();

        account.withdraw("SAV2001", new BigDecimal("10000.00"));
        // Every read after the write sees the updated balance
        account.readBalance("Mumbai-Branch");
        account.readBalance("Delhi-Branch");
        account.readBalance("Chennai-Branch");
    }
}
TEXT
[WRITE] SAV2001 withdrew 10000.00, new balance: 65000.00
[READ] Mumbai-Branch sees balance: 65000.00
[READ] Delhi-Branch sees balance: 65000.00
[READ] Chennai-Branch sees balance: 65000.00

What is eventual consistency?

Eventual consistency guarantees that if no new writes happen, all replicas will eventually converge to the same value. There is no guarantee about when. A read on a stale replica may return an old value.

Eventual consistency is acceptable for data where temporary staleness does not cause financial harm: notification delivery status, promotional offers, customer profile display names.

The benefit is high availability and low latency. Writes succeed immediately on one replica and propagate asynchronously to others.

JAVA
package com.bank.consistency;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EventualConsistencyDemo {

    // Three replicas hold their own copy
    private final Map<String, BigDecimal> replicas = new ConcurrentHashMap<>();

    public EventualConsistencyDemo() {
        replicas.put("Mumbai", new BigDecimal("75000.00"));
        replicas.put("Delhi", new BigDecimal("75000.00"));
        replicas.put("Chennai", new BigDecimal("75000.00"));
    }

    // Write hits one replica immediately
    public void writeToReplica(String replica, BigDecimal newBalance) {
        replicas.put(replica, newBalance);
        System.out.println("[WRITE] " + replica + " updated to " + newBalance);
    }

    // Read from any replica (may be stale)
    public void readAll() {
        replicas.forEach((name, balance) ->
            System.out.println("[READ] " + name + " shows: " + balance));
    }

    // Replication propagates the update asynchronously
    public void replicateFrom(String source) {
        BigDecimal value = replicas.get(source);
        replicas.replaceAll((name, old) -> value);
        System.out.println("[REPLICATED] All replicas now: " + value);
    }

    public static void main(String[] args) {
        EventualConsistencyDemo bank = new EventualConsistencyDemo();

        // Rajesh withdraws at Mumbai
        bank.writeToReplica("Mumbai", new BigDecimal("65000.00"));

        // Before replication, Delhi and Chennai are stale
        System.out.println("\nBefore replication:");
        bank.readAll();

        // After replication completes
        bank.replicateFrom("Mumbai");
        System.out.println("\nAfter replication:");
        bank.readAll();
    }
}
TEXT
[WRITE] Mumbai updated to 65000.00

Before replication:
[READ] Mumbai shows: 65000.00
[READ] Delhi shows: 75000.00
[READ] Chennai shows: 75000.00
[REPLICATED] All replicas now: 65000.00

After replication:
[READ] Mumbai shows: 65000.00
[READ] Delhi shows: 65000.00
[READ] Chennai shows: 65000.00

What is causal consistency?

Causal consistency sits between strong and eventual. It preserves the order of causally related operations. If operation A happens before operation B, and B depends on A, then every replica sees A before B.

Operations that are not causally related can be seen in any order. This gives better performance than strong consistency while preventing the most confusing anomalies.

In banking: if Rajesh deposits money (operation A) and then checks his balance (operation B), causal consistency guarantees B sees the result of A. But Priya, who does not know about the deposit, might still see the old balance until replication catches up.

JAVA
package com.bank.consistency;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CausalConsistencyDemo {

    private BigDecimal balance = new BigDecimal("75000.00");
    private final List<String> causalLog = new ArrayList<>();
    private int version = 0;

    // Each write records a causal dependency (version)
    public void deposit(String actor, BigDecimal amount) {
        version++;
        balance = balance.add(amount);
        causalLog.add("v" + version + ":" + actor + " deposited " + amount);
        System.out.println("[WRITE v" + version + "] "
            + actor + " deposited " + amount + ", balance: " + balance);
    }

    // Read with causal dependency: must see at least version N
    public void readAfter(String reader, int afterVersion) {
        if (version >= afterVersion) {
            System.out.println("[READ] " + reader
                + " sees balance: " + balance
                + " (version " + version + " >= required " + afterVersion + ")");
        } else {
            System.out.println("[WAIT] " + reader
                + " must wait for version " + afterVersion);
        }
    }

    public static void main(String[] args) {
        CausalConsistencyDemo account = new CausalConsistencyDemo();

        // Rajesh deposits (creates version 1)
        account.deposit("Rajesh", new BigDecimal("10000.00"));

        // Rajesh reads after his deposit: causally related, must see v1
        account.readAfter("Rajesh", 1);

        // Priya reads without causal dependency: can see any version
        account.readAfter("Priya", 0);
    }
}
TEXT
[WRITE v1] Rajesh deposited 10000.00, balance: 85000.00
[READ] Rajesh sees balance: 85000.00 (version 1 >= required 1)
[READ] Priya sees balance: 85000.00 (version 1 >= required 0)

How do the three models compare?

AspectStrongEventualCausal
GuaranteeEvery read sees latest writeReads converge over timeCausally related reads see correct order
LatencyHigh (coordination required)Low (local writes)Medium
AvailabilityLower during partitionsHighMedium
Use caseAccount balance, transfersNotifications, analyticsSocial feeds, collaborative edits
Banking exampleBalance after withdrawalEmail delivery statusCustomer reads own deposit
ImplementationRaft, Paxos, 2PCGossip, anti-entropyVersion vectors, causal clocks
Trade-offSpeed for correctnessCorrectness for speedBalanced
JAVA
package com.bank.consistency;

public class ConsistencyComparisonDemo {
    public static void main(String[] args) {
        System.out.println("=== Strong Consistency ===");
        System.out.println("Rajesh withdraws 10000 from SAV2001");
        System.out.println("ALL branches immediately show 65000");
        System.out.println("Latency: ~50ms (waits for majority ack)");
        System.out.println();

        System.out.println("=== Eventual Consistency ===");
        System.out.println("Rajesh updates his display name to 'Rajesh K'");
        System.out.println("Mumbai: 'Rajesh K' (immediate)");
        System.out.println("Delhi: 'Rajesh' (stale for ~200ms)");
        System.out.println("Chennai: 'Rajesh' (stale for ~500ms)");
        System.out.println("After convergence: all show 'Rajesh K'");
        System.out.println();

        System.out.println("=== Causal Consistency ===");
        System.out.println("Rajesh deposits 10000 then checks balance");
        System.out.println("Rajesh: always sees 85000 (causal order)");
        System.out.println("Priya: might see 75000 until replication");
    }
}
TEXT
=== Strong Consistency ===
Rajesh withdraws 10000 from SAV2001
ALL branches immediately show 65000
Latency: ~50ms (waits for majority ack)

=== Eventual Consistency ===
Rajesh updates his display name to 'Rajesh K'
Mumbai: 'Rajesh K' (immediate)
Delhi: 'Rajesh' (stale for ~200ms)
Chennai: 'Rajesh' (stale for ~500ms)
After convergence: all show 'Rajesh K'

=== Causal Consistency ===
Rajesh deposits 10000 then checks balance
Rajesh: always sees 85000 (causal order)
Priya: might see 75000 until replication

What is the CAP theorem?

The CAP theorem says a distributed system can guarantee at most two of three properties during a network partition:

  • Consistency (C): Every read sees the latest write.
  • Availability (A): Every request gets a response (not an error).
  • Partition tolerance (P): The system continues operating when network messages between nodes are lost.

Since network partitions are unavoidable in distributed systems, the real choice is between C and A during a partition.

  • CP system: Refuses to respond rather than return stale data. Example: a banking transfer service that rejects requests when it cannot reach the database replica.
  • AP system: Always responds, but might return stale data. Example: a product catalog that shows cached prices when the primary is unreachable.
JAVA
package com.bank.consistency;

public class CAPTheoremDemo {

    static boolean networkPartitionActive = true;

    // CP behavior: reject if we cannot guarantee consistency
    static String cpBalanceCheck(String accountId) {
        if (networkPartitionActive) {
            return "ERROR: Cannot guarantee consistent balance. Try again later.";
        }
        return "Balance: 75000.00";
    }

    // AP behavior: return cached/stale value to stay available
    static String apBalanceCheck(String accountId) {
        if (networkPartitionActive) {
            return "Balance: 75000.00 (cached, may be stale)";
        }
        return "Balance: 75000.00";
    }

    public static void main(String[] args) {
        System.out.println("Network partition is active");
        System.out.println();

        System.out.println("CP system (Transfer Service):");
        System.out.println("  " + cpBalanceCheck("SAV2001"));
        System.out.println();

        System.out.println("AP system (Statement Cache):");
        System.out.println("  " + apBalanceCheck("SAV2001"));
    }
}
TEXT
Network partition is active

CP system (Transfer Service):
  ERROR: Cannot guarantee consistent balance. Try again later.

AP system (Statement Cache):
  Balance: 75000.00 (cached, may be stale)

How do you choose the right consistency model for banking?

Different parts of a banking system need different consistency levels. Applying strong consistency everywhere kills performance. Applying eventual consistency everywhere risks financial errors.

Banking use caseConsistency modelReason
Account balance after transferStrongFinancial accuracy, regulatory compliance
Transfer between accountsStrong (2PC or Saga)Money cannot be lost or duplicated
Transaction history displayEventual (read replica)Slight delay is acceptable
Notification delivery statusEventualMissing an update for 2 seconds is harmless
Customer profile editsCausal (read-your-writes)Customer must see their own changes
Fraud detection alertsEventualSlight delay is acceptable, high throughput needed
Interest rate updatesEventualPropagated during batch processing
JAVA
package com.bank.consistency;

import java.math.BigDecimal;

public class ConsistencyChoiceDemo {

    public static void main(String[] args) {
        // STRONG: Rajesh transfers money
        System.out.println("[STRONG] Transfer 25000 from SAV2001 to SAV3002");
        System.out.println("  -> Wait for both debits and credits to commit");
        System.out.println("  -> Both accounts reflect correct balance immediately");
        System.out.println("  -> If any step fails, entire transfer rolls back");
        System.out.println();

        // EVENTUAL: Transaction history on read replica
        System.out.println("[EVENTUAL] Rajesh views last 10 transactions");
        System.out.println("  -> Read from nearest replica (fast, <5ms)");
        System.out.println("  -> Most recent transaction may appear after 1-2 sec delay");
        System.out.println("  -> Acceptable: customer refreshes and sees it");
        System.out.println();

        // CAUSAL: Priya updates her phone number
        System.out.println("[CAUSAL] Priya updates phone number in profile");
        System.out.println("  -> Priya always sees her updated phone number");
        System.out.println("  -> Other branch staff might see old number briefly");
        System.out.println("  -> Converges within seconds");
    }
}
TEXT
[STRONG] Transfer 25000 from SAV2001 to SAV3002
  -> Wait for both debits and credits to commit
  -> Both accounts reflect correct balance immediately
  -> If any step fails, entire transfer rolls back

[EVENTUAL] Rajesh views last 10 transactions
  -> Read from nearest replica (fast, <5ms)
  -> Most recent transaction may appear after 1-2 sec delay
  -> Acceptable: customer refreshes and sees it

[CAUSAL] Priya updates phone number in profile
  -> Priya always sees her updated phone number
  -> Other branch staff might see old number briefly
  -> Converges within seconds

What are common mistakes with consistency in distributed systems?

Mistake 1: Assuming strong consistency from a read replica

Wrong: reading the balance from a read replica right after a write and expecting the latest value.

JAVA
package com.bank.consistency;

import java.math.BigDecimal;

public class ReplicaLagMistake {
    public static void main(String[] args) {
        BigDecimal primaryBalance = new BigDecimal("65000.00");
        BigDecimal replicaBalance = new BigDecimal("75000.00"); // stale

        // WRONG: Read from replica right after write to primary
        System.out.println("WRONG: Primary balance: " + primaryBalance);
        System.out.println("WRONG: Replica balance: " + replicaBalance);
        System.out.println("WRONG: Customer sees 75000 after withdrawing 10000!");
        System.out.println();

        // CORRECT: Read from primary for critical reads,
        // or use "read-your-writes" consistency
        System.out.println("CORRECT: Read balance from primary after write");
        System.out.println("CORRECT: Primary balance: " + primaryBalance);
        System.out.println("CORRECT: Customer sees 65000 (accurate)");
    }
}
TEXT
WRONG: Primary balance: 65000.00
WRONG: Replica balance: 75000.00
WRONG: Customer sees 75000 after withdrawing 10000!

CORRECT: Read balance from primary after write
CORRECT: Primary balance: 65000.00
CORRECT: Customer sees 65000 (accurate)

Mistake 2: Using eventual consistency for financial transactions

Wrong: allowing two withdrawals to process concurrently on different replicas without coordination.

JAVA
package com.bank.consistency;

import java.math.BigDecimal;

public class ConcurrentWithdrawalMistake {
    public static void main(String[] args) {
        BigDecimal balance = new BigDecimal("20000.00");

        // WRONG: Two replicas process withdrawals independently
        // Both see balance = 20000 and approve
        BigDecimal replica1 = balance.subtract(new BigDecimal("15000.00"));
        BigDecimal replica2 = balance.subtract(new BigDecimal("12000.00"));

        System.out.println("WRONG: Both withdrawals approved");
        System.out.println("  Replica 1: 20000 - 15000 = " + replica1);
        System.out.println("  Replica 2: 20000 - 12000 = " + replica2);
        System.out.println("  Total withdrawn: 27000 from 20000 balance!");
        System.out.println();

        // CORRECT: Coordinate through primary with strong consistency
        balance = new BigDecimal("20000.00");
        BigDecimal first = balance.subtract(new BigDecimal("15000.00"));
        System.out.println("CORRECT: First withdrawal approved: " + first);
        if (first.subtract(new BigDecimal("12000.00"))
                .compareTo(BigDecimal.ZERO) < 0) {
            System.out.println("CORRECT: Second withdrawal rejected (insufficient funds)");
        }
    }
}
TEXT
WRONG: Both withdrawals approved
  Replica 1: 20000 - 15000 = 5000.00
  Replica 2: 20000 - 12000 = 8000.00
  Total withdrawn: 27000 from 20000 balance!

CORRECT: First withdrawal approved: 5000.00
CORRECT: Second withdrawal rejected (insufficient funds)

What is the PACELC theorem?

The PACELC theorem extends CAP. It says:

  • During a Partition (P): choose between Availability (A) and Consistency (C).
  • Else (E) (normal operation, no partition): choose between Latency (L) and Consistency (C).

This is important because most of the time there is no partition. The real daily trade-off is between low latency and strong consistency.

A banking transfer service is PC/EC: it chooses consistency over both availability (during partitions) and latency (during normal operation). A notification service is PA/EL: it chooses availability during partitions and low latency during normal operation.

JAVA
package com.bank.consistency;

public class PACELCDemo {
    public static void main(String[] args) {
        System.out.println("PACELC examples in banking:");
        System.out.println();
        System.out.println("Transfer Service (PC/EC):");
        System.out.println("  Partition -> reject request (Consistency over Availability)");
        System.out.println("  Normal   -> wait for replica sync (Consistency over Latency)");
        System.out.println();
        System.out.println("Statement Service (PA/EL):");
        System.out.println("  Partition -> serve cached data (Availability over Consistency)");
        System.out.println("  Normal   -> read from nearest replica (Latency over Consistency)");
    }
}
TEXT
PACELC examples in banking:

Transfer Service (PC/EC):
  Partition -> reject request (Consistency over Availability)
  Normal   -> wait for replica sync (Consistency over Latency)

Statement Service (PA/EL):
  Partition -> serve cached data (Availability over Consistency)
  Normal   -> read from nearest replica (Latency over Consistency)

What should a senior engineer know?

- Raft consensus. Raft is a consensus algorithm used by etcd, CockroachDB, and TiKV. A leader accepts writes and replicates to followers. A write is committed when a majority acknowledges. This gives strong consistency with automatic leader election on failure.

- Read-your-writes consistency. A practical middle ground where a user always sees their own writes, even if other users see stale data. Implement by routing reads to the primary for a short window after a write, or by tracking a session token that includes the write timestamp.

- Conflict resolution in eventual consistency. When two replicas accept conflicting writes, you need a resolution strategy: last-writer-wins (LWW) based on timestamps, merge using CRDTs (Conflict-free Replicated Data Types), or application-level resolution.

- Quorum reads and writes. In a system with N replicas, require W replicas to acknowledge a write and R replicas to respond to a read. If W + R > N, you get strong consistency. Common configuration: N=3, W=2, R=2.

- Saga pattern for distributed consistency. In microservices, you cannot use a distributed transaction across services easily. The Saga pattern coordinates local transactions: each service commits locally and publishes an event. If a step fails, compensating transactions undo previous steps.

What are common interview follow-up questions?

  • What is the difference between linearizability and serializability?
  • How does a quorum-based system handle network partitions?
  • What is a vector clock and how does it track causality?
  • How does CockroachDB provide strong consistency across data centers?
  • When is eventual consistency dangerous in a banking system?
  • What is the difference between read-after-write and monotonic read consistency?

Visual Overview

DIAGRAM
  Consistency Models Spectrum
  ============================

  Strong ─────────── Causal ─────────── Eventual
  (all reads see    (causally related  (reads converge
   latest write)     ops are ordered)   over time)

  Latency:  HIGH          MEDIUM           LOW
  Availability: LOW       MEDIUM           HIGH
  Banking use: Transfers  Profile edits    Notifications


  CAP Theorem During Network Partition
  =====================================

  ┌──────────────────────┐
  │    Network Partition  │
  │    (P is unavoidable) │
  └──────────┬───────────┘
             │
     ┌───────┴───────┐
     │               │
     ▼               ▼
  ┌──────┐       ┌──────┐
  │  CP  │       │  AP  │
  │      │       │      │
  │Reject│       │Serve │
  │ stale│       │cached│
  │reads │       │data  │
  └──────┘       └──────┘
  Transfer       Statement
  Service        Service


  Quorum: W + R > N  (Strong Consistency)
  =========================================

  N = 3 replicas
  W = 2 (write to 2 before confirming)
  R = 2 (read from 2 and pick latest)

  Write: ──> Replica-1 (ACK)
         ──> Replica-2 (ACK)     W=2 met, write confirmed
         ──> Replica-3 (pending)

  Read:  <── Replica-1 (v2)     R=2 met, return v2
         <── Replica-3 (v1)     overlap with write set

Key Takeaway

Consistency models answer one question: when does a write become visible to reads? In the National Bank of India system, the answer depends on what you are reading. If Rajesh just withdrew money, his balance check must see the withdrawal immediately. That is strong consistency. If the notification service has not yet sent the SMS confirming the withdrawal, a two-second delay is acceptable. That is eventual consistency.

The CAP theorem frames the trade-off during network partitions. Since partitions happen in every distributed system, you must choose: reject requests to stay consistent (CP), or serve potentially stale data to stay available (AP). The PACELC theorem adds the daily trade-off: even without partitions, strong consistency costs latency because writes must coordinate across replicas.

The practical approach in banking is to apply strong consistency only where financial accuracy demands it: account balances, transfer processing, and loan disbursement. Everything else, like transaction history display, notification status, and analytics dashboards, can use eventual consistency for better performance and availability.

Causal consistency is the useful middle ground for user-facing operations. When Priya updates her phone number and immediately views her profile, she must see the updated number. Other users might see the old number for a moment. Read-your-writes consistency achieves this without the full cost of linearizability.

One sentence to remember: use strong consistency for money, eventual consistency for everything else, and causal consistency when a user must see their own writes.

---

Share
Use ← → arrow keys to navigate