Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 05 · Distributed Systems & ConsensusChapter 26 of 33
25.
Phase 05Read time ~23 minDifficulty advanced

Consistency Models

In this chapter
  • 01Chapter Overview
  • 02Why Do We Need Consistency Models?
  • 03Banking
  • 04Social media likes
  • 05Search
  • 06Recommendations
  • 07A Simple Mental Model
  • 08Strong Consistency
  • 09Linearizability
  • 10Real-Time Ordering
  • 11Why Linearizability Is Expensive
  • 12Sequential Consistency
  • 13Example: Sequential vs Linearizable
  • 14Causal Consistency
  • 15Causality
  • 16Why Causal Consistency Is Useful
  • 17Eventual Consistency
  • 18Eventual Consistency Does Not Mean Randomness
  • 19Eventual Consistency Example
  • 20Read-Your-Writes Consistency
  • 21Read-Your-Writes Architecture
  • 22Monotonic Reads
  • 23Why Monotonic Reads Matter
  • 24Monotonic Writes
  • 25Session Consistency
  • 26Writes Follow Reads
  • 27Consistency Spectrum
  • 28Strong vs Eventual Consistency
  • 29Choosing a Consistency Model
  • 30Payment
  • 31Inventory reservation
  • 32Product catalog
  • 33Search index
  • 34Recommendations
  • 35Social likes
  • 36Not Every Database Operation Needs the Same Model
  • 37Leader-Based Consistency
  • 38Read From Leader
  • 39Read From Replicas
  • 40Quorum-Based Consistency
  • 41Version Numbers
  • 42Optimistic Concurrency
  • 43Last-Write-Wins
  • 44Vector Clocks
  • 45CRDTs
  • 46Consistency in Collaborative Editing
  • 47Search Systems
  • 48Cache Consistency
  • 49Cache-Aside Example
  • 50Consistency and Messaging
  • 51Consistency and Event-Driven Architecture
  • 52Consistency and Microservices
  • 53The Business Requirement Comes First
  • 54Payment
  • 55Inventory
  • 56Email
  • 57Analytics
  • 58Consistency Budget
  • 59Latency vs Consistency
  • 60Availability vs Consistency
  • 61A Consistency Decision Matrix
  • 62Common Misconception #1
  • 63Wrong
  • 64Correct
  • 65Common Misconception #2
  • 66Wrong
  • 67Common Misconception #3
  • 68Wrong
  • 69Common Misconception #4
  • 70Wrong
  • 71Common Misconception #5
  • 72Wrong
  • 73Interview Question: Linearizability
  • 74Question
  • 75Answer
  • 76Interview Question: Eventual Consistency
  • 77Question
  • 78Answer
  • 79Interview Question: Causal Consistency
  • 80Question
  • 81Answer
  • 82Interview Question: Read-Your-Writes
  • 83Question
  • 84Answer
  • 85Interview Question: Monotonic Reads
  • 86Question
  • 87Answer
  • 88Interview Question: Strong vs Eventual
  • 89Question
  • 90Answer
  • 91Interview Question: One Model for Everything?
  • 92Question
  • 93Answer
  • 94Mini Project
  • 95Design a Globally Distributed User Profile System
  • 96Practical Design Example
  • 97Production Checklist
  • 98Master Mental Model
  • 99Final Summary
  • 100Strong consistency
  • 101Linearizability
  • 102Sequential consistency
  • 103Causal consistency
  • 104Eventual consistency
  • 105Session guarantees
  • 106Practical tools
  • 107Exercises
  • 108Exercise 1
  • 109Exercise 2
  • 110Exercise 3
  • 111Exercise 4
  • 112Exercise 5
  • 113Exercise 6
  • 114Exercise 7
  • 115Interview Challenge
  • 116Next Chapter
  • 117Chapter 25 — Distributed Transactions
In this chapter (117 sections)
01Chapter Overview02Why Do We Need Consistency Models?03Banking04Social media likes05Search06Recommendations07A Simple Mental Model08Strong Consistency09Linearizability10Real-Time Ordering11Why Linearizability Is Expensive12Sequential Consistency13Example: Sequential vs Linearizable14Causal Consistency15Causality16Why Causal Consistency Is Useful17Eventual Consistency18Eventual Consistency Does Not Mean Randomness19Eventual Consistency Example20Read-Your-Writes Consistency21Read-Your-Writes Architecture22Monotonic Reads23Why Monotonic Reads Matter24Monotonic Writes25Session Consistency26Writes Follow Reads27Consistency Spectrum28Strong vs Eventual Consistency29Choosing a Consistency Model30Payment31Inventory reservation32Product catalog33Search index34Recommendations35Social likes36Not Every Database Operation Needs the Same Model37Leader-Based Consistency38Read From Leader39Read From Replicas40Quorum-Based Consistency41Version Numbers42Optimistic Concurrency43Last-Write-Wins44Vector Clocks45CRDTs46Consistency in Collaborative Editing47Search Systems48Cache Consistency49Cache-Aside Example50Consistency and Messaging51Consistency and Event-Driven Architecture52Consistency and Microservices53The Business Requirement Comes First54Payment55Inventory56Email57Analytics58Consistency Budget59Latency vs Consistency60Availability vs Consistency61A Consistency Decision Matrix62Common Misconception #163Wrong64Correct65Common Misconception #266Wrong67Common Misconception #368Wrong69Common Misconception #470Wrong71Common Misconception #572Wrong73Interview Question: Linearizability74Question75Answer76Interview Question: Eventual Consistency77Question78Answer79Interview Question: Causal Consistency80Question81Answer82Interview Question: Read-Your-Writes83Question84Answer85Interview Question: Monotonic Reads86Question87Answer88Interview Question: Strong vs Eventual89Question90Answer91Interview Question: One Model for Everything?92Question93Answer94Mini Project95Design a Globally Distributed User Profile System96Practical Design Example97Production Checklist98Master Mental Model99Final Summary100Strong consistency101Linearizability102Sequential consistency103Causal consistency104Eventual consistency105Session guarantees106Practical tools107Exercises108Exercise 1109Exercise 2110Exercise 3111Exercise 4112Exercise 5113Exercise 6114Exercise 7115Interview Challenge116Next Chapter117Chapter 25 — Distributed Transactions

1. Chapter Overview#

In the previous chapter, we learned CAP Theorem and saw that distributed systems face a fundamental trade-off during network partitions.

But one important question remains:

What exactly does "consistency" mean?

A distributed system can provide many different consistency guarantees.

For example:

Strong consistency
        ↓
Linearizability
        ↓
Sequential consistency
        ↓
Causal consistency
        ↓
Eventual consistency

These are not simply "good" and "bad" versions of consistency.

They represent different guarantees with different costs.

This chapter teaches you how to reason about them and, more importantly, how to choose an appropriate consistency model during system design.


2. Why Do We Need Consistency Models?#

Imagine a database with three replicas:

             ┌───────────┐
             │ Application│
             └─────┬─────┘
                   │
          ┌────────┼────────┐
          │        │        │
       ┌──▼──┐  ┌──▼──┐  ┌──▼──┐
       │ R1  │  │ R2  │  │ R3  │
       └─────┘  └─────┘  └─────┘

Suppose a write occurs:

Write X = 100

Does every replica need to immediately return:

X = 100

?

Not necessarily.

Different applications have different requirements.

Banking#

A stale balance can be dangerous.

Social media likes#

A temporarily stale count may be acceptable.

Search#

A newly created document may take a short time to appear.

Recommendations#

A recommendation generated from slightly stale data may be completely acceptable.

Therefore we need different consistency guarantees.


3. A Simple Mental Model#

Think of consistency as answering:

If multiple clients interact with a distributed system, what values are they allowed to observe?

The stronger the guarantee:

More predictable behavior
        ↓
More coordination
        ↓
Higher latency / lower availability in some failure cases

The weaker the guarantee:

More freedom for replicas
        ↓
Less coordination
        ↓
Potentially better latency and availability

There is no universally correct consistency model.


4. Strong Consistency#

A common beginner-friendly definition is:

Once a write succeeds, subsequent reads see the latest value.

Example:

Initial:
X = 10
 
Client A:
WRITE X = 20
 
WRITE succeeds
 
Client B:
READ X
 
Result:
20

The system does not allow Client B to observe the old value if the consistency contract requires a strongly consistent read.

Strong consistency usually requires coordination between replicas.


5. Linearizability#

One of the most important strong consistency models is linearizability.

Linearizability makes operations appear as if they happen atomically at a single point between their invocation and completion.

Consider:

Client A:
WRITE X = 20
 
         completes
 
Client B:
READ X

The read should return:

20

because the write completed before the read began.


6. Real-Time Ordering#

Linearizability respects real-time ordering.

Suppose:

t1             t2             t3
 
WRITE X=20 ──────────────►
                              READ X

Because the write completed before the read started:

READ X → 20

A result of:

READ X → 10

would violate linearizability.


7. Why Linearizability Is Expensive#

Suppose there are replicas:

A
B
C

A write arrives at A.

To provide a strong guarantee, the system may need coordination.

Possible architecture:

Client
  │
  ▼
Leader A
  │
  ├────► B
  │
  └────► C

The system may need acknowledgements before confirming the operation.

This can increase:

  • network round trips
  • latency
  • coordination cost
  • failure sensitivity

During a partition, strong consistency may require refusing operations that cannot be safely coordinated.


8. Sequential Consistency#

Sequential consistency is different from linearizability.

A sequentially consistent system guarantees that:

The result is equivalent to some sequential ordering of operations that preserves the order of operations issued by each individual process.

The key difference is:

Linearizability
→ preserves real-time ordering
 
Sequential consistency
→ does not necessarily preserve global real-time ordering

This distinction is important in advanced distributed systems.


9. Example: Sequential vs Linearizable#

Suppose:

Client A:
WRITE X = 1
 
Client B:
WRITE X = 2

If these operations overlap, a sequentially consistent system may choose a valid ordering such as:

WRITE X=1
WRITE X=2

or:

WRITE X=2
WRITE X=1

as long as the ordering is consistent with each client's own operation order.

Linearizability additionally requires the ordering to respect real-time relationships between non-overlapping operations.


10. Causal Consistency#

Causal consistency focuses on cause-and-effect relationships.

Suppose:

User creates post
        ↓
User comments on post

The comment causally depends on the post.

A causally consistent system should not expose:

Comment

before exposing the corresponding:

Post

to a client that observes the causal chain.


11. Causality#

Consider:

A writes:
"New product launched"
 
Then B writes:
"Congratulations!"

The second operation depends on the first.

Therefore:

Event A
  ↓
causes
  ↓
Event B

A system preserving causal consistency maintains this ordering.


12. Why Causal Consistency Is Useful#

Causal consistency is useful for systems such as:

  • social networks
  • collaborative applications
  • messaging
  • distributed collaboration
  • comment/reply systems

For example:

Post
 ↓
Comment
 ↓
Reply

Users should not observe the reply without the causal context that makes it meaningful.


13. Eventual Consistency#

Eventual consistency is weaker.

A simplified definition:

If no new updates occur and communication continues, replicas eventually converge to the same value.

Example:

t1:
A = 10
B = 10
 
t2:
A = 20
B = 10
 
t3:
A = 20
B = 20

At t2:

A ≠ B

At t3:

A = B

The system eventually converges.


14. Eventual Consistency Does Not Mean Randomness#

A common misconception is:

Eventual consistency means anything can happen.

No.

An eventually consistent system can still define rules for:

  • conflict resolution
  • version ordering
  • retries
  • convergence
  • session guarantees

The guarantee is simply weaker than strong consistency.


15. Eventual Consistency Example#

Imagine a global social-media follower count.

Region US:
followers = 10,000
 
Region EU:
followers = 10,015

A user in Europe might temporarily see:

10,015

while a user in the US sees:

10,000

After replication catches up:

Both → 10,015

If the product can tolerate temporary differences, eventual consistency can be appropriate.


16. Read-Your-Writes Consistency#

A very useful session guarantee is:

After a user successfully writes a value, that same user should be able to read their own write.

Example:

User updates profile:
 
name = "Anubhav"
 
Write succeeds
 
User refreshes page
 
Expected:
name = "Anubhav"

Without read-your-writes:

Write succeeds
     ↓
Read hits stale replica
     ↓
Old name appears

This creates a confusing user experience.


17. Read-Your-Writes Architecture#

One solution is routing the user to a replica known to contain their latest write.

Example:

             Load Balancer
                  │
          ┌───────┴───────┐
          │               │
        Replica A       Replica B
          │
       user's latest write

Other approaches include:

  • session affinity
  • version tokens
  • waiting for replication
  • reading from a leader
  • tracking replication positions

18. Monotonic Reads#

Monotonic reads guarantee:

Once a client has observed a value, later reads should not return an older value.

Example:

First read:
X = 20
 
Later read:
X = 10

This can be surprising.

A monotonic-read system prevents the client from moving backward:

20
↓
20
↓
25

but not:

20
↓
10

19. Why Monotonic Reads Matter#

Imagine checking a message application:

First refresh:
5 messages
 
Second refresh:
3 messages

Even if technically possible due to replica lag, users perceive this as broken behavior.

Monotonic reads prevent this kind of backward movement.


20. Monotonic Writes#

Monotonic writes guarantee that a client's writes are applied in the order the client issued them.

Suppose:

Write A:
status = "processing"
 
Write B:
status = "completed"

The system should not apply:

B before A

if the consistency contract requires monotonic writes.

This is particularly useful when operations depend on previous operations.


21. Session Consistency#

Session consistency combines useful guarantees for a particular client session.

Common session guarantees include:

Read Your Writes
Monotonic Reads
Monotonic Writes
Writes Follow Reads

These guarantees can provide a much better user experience without requiring every operation in the entire system to be globally linearizable.


22. Writes Follow Reads#

Suppose:

Client reads version 10
        ↓
Client writes version 11

The write should be based on a state at least as recent as what the client observed.

This prevents causality from going backward.


23. Consistency Spectrum#

A useful conceptual spectrum is:

Stronger
   │
   │  Linearizability
   │
   │  Sequential consistency
   │
   │  Causal consistency
   │
   │  Session guarantees
   │
   │  Eventual consistency
   │
Weaker

This is a conceptual model, not a universal strict ordering of every possible consistency protocol.

Different models guarantee different properties.


24. Strong vs Eventual Consistency#

Property Strong / Linearizable Eventual
Latest value immediately visible Yes, under contract Not necessarily
Replica divergence Minimized/controlled Expected temporarily
Coordination Usually higher Often lower
Availability during partition May decrease Can be prioritized
Latency Can be higher Often lower
Complexity Coordination complexity Conflict/reconciliation complexity
Typical use Critical state Feeds, counters, indexes

25. Choosing a Consistency Model#

Do not ask:

"Which consistency model is best?"

Ask:

"What consistency guarantee does this operation actually require?"

For example:

Payment#

Strong consistency

Inventory reservation#

Strong coordination

Product catalog#

Moderate / eventual consistency may be sufficient

Search index#

Eventual consistency is often acceptable

Recommendations#

Eventual consistency is usually acceptable

Social likes#

Eventual consistency can often work

26. Not Every Database Operation Needs the Same Model#

A major system-design insight is:

Consistency can be chosen per workload or operation.

Suppose an e-commerce system has:

                    E-commerce
                        │
        ┌───────────────┼────────────────┐
        │               │                │
     Payments       Inventory         Search
        │               │                │
     Strong          Strong           Eventual

This allows the system to optimize each subsystem independently.


27. Leader-Based Consistency#

A common architecture is:

          Writes
             │
             ▼
          Leader
          /    \
         /      \
      Follower Follower

Writes go through the leader.

Followers replicate the state.

This can simplify ordering.

However, reads from followers may be stale.

For example:

Write → Leader
Read  → Follower

If replication has not completed:

Write = 20
Follower = 10

The read may return:

10

depending on the consistency contract.


28. Read From Leader#

One simple approach for stronger reads:

Writes ──► Leader
Reads  ──► Leader

Advantages:

  • simpler consistency model
  • no follower staleness

Disadvantages:

  • leader becomes a bottleneck
  • higher latency for distant users
  • limited read scalability

29. Read From Replicas#

Another architecture:

Writes ──► Leader
 
Reads ──► Replicas

Advantages:

  • higher read scalability
  • potentially lower latency
  • better geographic distribution

Disadvantage:

Replication lag
      ↓
Stale reads

This is where consistency requirements become an architectural decision.


30. Quorum-Based Consistency#

Suppose:

N = 3

with:

W = 2
R = 2

Then:

W + R > N

because:

2 + 2 > 3

The read and write sets must overlap.

This can help ensure a read encounters information from a recent write.

But remember:

Quorum overlap alone does not automatically provide every strong consistency guarantee.

The protocol matters.


31. Version Numbers#

Distributed systems often attach versions to data.

Example:

value = "A"
version = 10

After an update:

value = "B"
version = 11

A replica receiving:

version 10

after:

version 11

can identify that it is stale.

Versioning helps with:

  • conflict detection
  • replication
  • stale reads
  • synchronization
  • conditional updates

32. Optimistic Concurrency#

Suppose:

Product:
stock = 10
version = 5

Client reads:

stock = 10
version = 5

Client attempts:

UPDATE
SET stock = 9,
    version = 6
WHERE version = 5

If another client already changed version 5 to 6:

WHERE version = 5

fails.

The application can retry using the latest state.

This is a common way to prevent lost updates.


33. Last-Write-Wins#

A simple conflict-resolution strategy is:

The update with the greatest timestamp/version wins.

Example:

Replica A:
X = A
timestamp = 100
 
Replica B:
X = B
timestamp = 105

Result:

X = B

But last-write-wins has limitations.

Clock differences can make timestamps unreliable if not handled carefully.

It can also discard valid concurrent updates.

Therefore it should not automatically be used for business-critical conflicts.


34. Vector Clocks#

Vector clocks track causal history.

For replicas:

A
B
C

a vector can represent:

[A: 3, B: 2, C: 5]

This helps determine whether one version happened-before another or whether two versions are concurrent.

Conceptually:

Version 1
   ↓
Version 2

means causally related.

But:

Version A
   ↘
     concurrent
   ↗
Version B

indicates concurrent updates.

Vector clocks are more sophisticated than simply comparing timestamps.


35. CRDTs#

CRDT stands for:

Conflict-Free Replicated Data Type

CRDTs are data structures designed so that replicas can independently update state and still converge under defined conditions.

They are useful for some:

  • collaborative applications
  • counters
  • sets
  • replicated state

For example, an increment-only counter can often merge independent increments safely.

CRDTs are powerful, but they are not a universal solution for every business transaction.


36. Consistency in Collaborative Editing#

Imagine two users edit a shared document.

User A → add text
User B → add text

The system should allow concurrent work without requiring every edit to synchronously coordinate globally.

Techniques such as:

  • CRDTs
  • Operational Transformation
  • causal ordering

can help.

The correct approach depends on the application.


37. Search Systems#

Consider:

Primary Database
       │
       ▼
Search Index

A user creates a product:

Product created

Immediately searching may return:

No result

because indexing happens asynchronously.

This is usually acceptable if the system documents or designs around:

Eventual consistency

The database remains the source of truth.


38. Cache Consistency#

Caches introduce another consistency problem.

Suppose:

Database:
price = ₹1,000
 
Cache:
price = ₹900

The database is updated:

price = ₹1,100

But cache still contains:

₹900

The system must define:

  • TTL
  • invalidation
  • write-through
  • write-back
  • cache-aside behavior
  • version validation

Consistency is therefore not only a database problem.


39. Cache-Aside Example#

Common pattern:

Application
    │
    ▼
Cache
    │
    ├── hit → return
    │
    └── miss
          │
          ▼
       Database
          │
          ▼
       Cache

After a database update, the cache must eventually be invalidated or updated.

Otherwise users can see stale data.


40. Consistency and Messaging#

Asynchronous messaging introduces another consistency challenge.

Suppose:

Order DB
   │
   └──► Message Queue
            │
            ▼
      Notification Service

The order may be committed before the notification is processed.

Therefore:

Order exists
Notification not yet sent

This is normal eventual behavior.

Patterns such as Transactional Outbox can make database-to-message publication more reliable.


41. Consistency and Event-Driven Architecture#

Consider:

Order Service
      │
      ▼
Order Created Event
      │
 ┌────┼───────────┐
 ▼    ▼           ▼
Email Search   Analytics

Different consumers process the event at different times.

Therefore the system naturally becomes:

Eventually consistent

across many derived views.

The order service remains the source of truth.


42. Consistency and Microservices#

In a monolith:

One database
One transaction

can make consistency easier.

In microservices:

Service A → DB A
Service B → DB B
Service C → DB C

a single ACID transaction across everything may be expensive or undesirable.

Therefore architectures often use:

  • eventual consistency
  • Saga
  • Outbox
  • idempotency
  • compensating actions
  • asynchronous events

43. The Business Requirement Comes First#

Consider an order workflow:

Order
 ↓
Payment
 ↓
Inventory
 ↓
Shipment

You should ask:

Payment#

Can payment be duplicated?

Usually no.

Inventory#

Can stock become negative?

Usually no.

Email#

Can email arrive slightly later?

Usually yes.

Analytics#

Can analytics lag by a few seconds?

Usually yes.

This leads to different consistency choices.


44. Consistency Budget#

A useful architectural concept is to define a consistency budget.

Ask:

How stale can this data safely be?

For example:

Payment:
0 seconds
 
Inventory:
very small / tightly controlled
 
Product catalog:
seconds may be acceptable
 
Search:
seconds or minutes may be acceptable
 
Analytics:
minutes may be acceptable

The exact values depend on the business.

This makes consistency an explicit engineering requirement rather than an accidental property.


45. Latency vs Consistency#

Suppose a read needs confirmation from multiple regions:

India
  │
  ▼
Singapore
  │
  ▼
Europe

Cross-region coordination can add significant latency.

If the business accepts slightly stale data:

Read local replica

can be much faster.

Therefore:

Strong consistency
        ↕
Latency

is often a practical architectural trade-off.

This relationship is one of the ideas expanded by PACELC.


46. Availability vs Consistency#

During a partition:

Partition
    │
    ├── Strong consistency
    │       ↓
    │   reject/wait
    │
    └── Availability
            ↓
       keep serving

The correct decision depends on what the operation means.

For example:

Payment authorization
→ safer to reject than incorrectly authorize
 
Social feed
→ may be better to serve slightly stale content

47. A Consistency Decision Matrix#

Workload Typical Requirement Possible Model
Payment balance Very strong Linearizable / transactional
Inventory reservation Strong Strong coordination
User profile Moderate to strong Session/strong depending on needs
Product catalog Moderate Eventual can be acceptable
Search index Eventual Eventual
Analytics Eventual Eventual
Social feed Eventual / causal Causal + eventual
Like counter Eventual Eventual
Collaborative editing Causal/convergent CRDT/OT-based
Distributed lock Strong Linearizable coordination

These are typical patterns, not universal rules.


48. Common Misconception #1#

Wrong#

Eventual consistency means the user always sees stale data.

Correct#

Stale data is possible temporarily.

If updates stop and replication succeeds, replicas should converge under the eventual-consistency contract.


49. Common Misconception #2#

Wrong#

Strong consistency means every replica is physically updated before every read.

Not necessarily.

The implementation can use:

  • leaders
  • quorums
  • consensus
  • replication protocols
  • leases
  • versioning

What matters is the externally observable guarantee.


50. Common Misconception #3#

Wrong#

Eventual consistency is always faster.

Not necessarily.

Conflict resolution, retries, reconciliation, and application complexity can introduce significant costs.

The trade-off is not simply:

strong = slow
eventual = fast

It depends on the architecture.


51. Common Misconception #4#

Wrong#

Every microservice should use eventual consistency.

No.

Some operations require strong consistency.

A microservice architecture should choose consistency based on business requirements.


52. Common Misconception #5#

Wrong#

A read from a replica is always eventually consistent.

Not necessarily.

A system can provide stronger read guarantees through:

  • synchronous replication
  • quorum reads
  • leader reads
  • version checks
  • read-after-write mechanisms

The exact contract matters.


53. Interview Question: Linearizability#

Question#

What is linearizability?

Answer#

Linearizability makes each operation appear to occur atomically at a single point between invocation and completion while respecting real-time ordering between non-overlapping operations.


54. Interview Question: Eventual Consistency#

Question#

What is eventual consistency?

Answer#

If updates stop and communication continues successfully, replicas eventually converge to the same state.

It allows temporary divergence.


55. Interview Question: Causal Consistency#

Question#

What is causal consistency?

Answer#

Operations that have a causal relationship must be observed in an order consistent with that relationship.

For example:

Post
 ↓
Comment

A system should not expose the comment without respecting the causal dependency.


56. Interview Question: Read-Your-Writes#

Question#

What problem does read-your-writes solve?

Answer#

It prevents a user from seeing an older state after successfully writing a newer state.

Example:

Update profile
     ↓
Read profile
     ↓
Must see own update

57. Interview Question: Monotonic Reads#

Question#

What are monotonic reads?

Answer#

Once a client observes a particular version of data, later reads should not return an older version.

Example:

20 → 20 → 25

is valid.

20 → 10

violates monotonic reads.


58. Interview Question: Strong vs Eventual#

Question#

When would you use eventual consistency?

Answer#

When temporary stale data is acceptable and the system benefits from reduced coordination, lower latency, higher availability, or easier geographic distribution.

Examples include:

  • search indexes
  • recommendations
  • feeds
  • analytics
  • many counters

59. Interview Question: One Model for Everything?#

Question#

Should every operation in a distributed system use the same consistency level?

Answer#

No.

Different operations can have different requirements.

For example:

Payment → strong
 
Search → eventual
 
Analytics → eventual
 
User session → session guarantees

This is often a more scalable architectural approach.


60. Mini Project#

Design a Globally Distributed User Profile System#

Requirements:

  • Users exist globally.
  • Users can update their profile.
  • Profile reads should be fast.
  • Users should immediately see their own changes.
  • Other regions can tolerate short replication delays.
  • Concurrent updates must be handled safely.
  • The system must survive regional communication failures.

Design:

                    Global Users
                         │
          ┌──────────────┼──────────────┐
          │              │              │
       Region A       Region B       Region C
          │              │              │
       Replica A      Replica B      Replica C

Define:

  1. Write routing
  2. Read routing
  3. Replication
  4. Versioning
  5. Read-your-writes
  6. Conflict resolution
  7. Partition behavior
  8. Recovery
  9. Cache strategy
  10. Observability

The important part is to explicitly document the consistency contract.


61. Practical Design Example#

A possible design:

                Client
                  │
                  ▼
              API Layer
                  │
             ┌────┴────┐
             │         │
           Cache      Profile DB
                       │
              ┌────────┼────────┐
              ▼        ▼        ▼
             R1       R2       R3

Write:

Client
  ↓
API
  ↓
Primary
  ↓
Version = 42
  ↓
Replicate

Read-your-writes can be supported by:

Client receives version 42
             ↓
Later read requires version >= 42

A replica that has only:

version = 40

cannot satisfy the read.

The system can:

  • route to a fresher replica
  • wait for replication
  • read from the primary

62. Production Checklist#

Before selecting a consistency model, answer:

  • What data is the source of truth?
  • How stale can data be?
  • Does the user need to see their own writes?
  • Must reads be monotonic?
  • Do writes have causal dependencies?
  • Can conflicting writes happen?
  • How are conflicts resolved?
  • What happens during a partition?
  • What happens during replication lag?
  • Can the system read from followers?
  • What quorum is required?
  • What happens if quorum cannot be reached?
  • What is the latency budget?
  • What is the availability requirement?
  • Which operations require strong guarantees?

63. Master Mental Model#

When approaching consistency in system design, use this sequence:

Business requirement
        ↓
What can go wrong?
        ↓
How stale can data be?
        ↓
Do writes require coordination?
        ↓
Do reads require latest state?
        ↓
What happens during partition?
        ↓
Choose consistency model
        ↓
Choose replication strategy
        ↓
Choose read/write routing
        ↓
Design recovery

Do not start with:

"Should I use CP or AP?"

Start with:

"What guarantee does the business operation require?"

64. Final Summary#

You now understand the major consistency models used in distributed systems.

The most important concepts are:

Strong consistency#

Readers observe the latest committed state according to the system's guarantee.

Linearizability#

Operations appear atomic and respect real-time ordering.

Sequential consistency#

Operations appear in a valid sequential order while preserving each client's program order.

Causal consistency#

Causally related operations are observed in causal order.

Eventual consistency#

Replicas may temporarily diverge but eventually converge when updates stop and communication succeeds.

Session guarantees#

Useful client-oriented guarantees include:

  • Read-your-writes
  • Monotonic reads
  • Monotonic writes
  • Writes-follow-reads

Practical tools#

Distributed systems may use:

  • leaders
  • replicas
  • quorums
  • version numbers
  • optimistic concurrency
  • vector clocks
  • CRDTs
  • conflict resolution
  • session routing

The biggest system-design lesson is:

Consistency is a business requirement translated into a distributed-systems guarantee.


65. Exercises#

Exercise 1#

Explain linearizability using a bank account example.

Exercise 2#

Explain the difference between:

Linearizability
vs
Sequential consistency

Exercise 3#

Explain causal consistency using:

Post → Comment → Reply

Exercise 4#

Design read-your-writes for a multi-region profile service.

Exercise 5#

Explain monotonic reads with a social-media example.

Exercise 6#

A search index can be 10 seconds behind the database.

Which consistency model could be appropriate and why?

Exercise 7#

A payment service must never expose an incorrect successful balance.

What consistency requirements would you consider?


66. Interview Challenge#

Design a globally distributed social-media feed.

Requirements:

  • 100 million users
  • Users can post globally
  • Feed reads must be fast
  • Posts can appear slightly later in some regions
  • Users should see their own posts immediately
  • Comments must respect causal relationships
  • Likes can tolerate temporary count differences

Identify the consistency model for:

Posts
Feed
Comments
Likes
User's own writes

Then explain:

Replication
Caching
Partition behavior
Conflict resolution

This exercise combines CAP and consistency models.


67. Next Chapter#

Chapter 25 — Distributed Transactions#

In the next chapter, we will learn how systems perform operations that span multiple machines or services.

We will cover:

  • What is a distributed transaction?
  • Why distributed transactions are difficult
  • ACID across services
  • Two-Phase Commit (2PC)
  • Coordinator and participants
  • Prepare and commit phases
  • Failure scenarios
  • Blocking problems
  • Three-Phase Commit
  • Distributed locks
  • Sagas
  • Compensating transactions
  • Transactional Outbox
  • Idempotency
  • Exactly-once misconceptions
  • Real-world payment/order workflows
  • Choosing between 2PC and Saga
  • Interview questions
  • Distributed transaction design exercise

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 23 — CAP TheoremNext ChapterChapter 25 — Distributed Transactions
PrevNext