Skip to content

Eventual Consistency

A consistency model where updates eventually propagate to all replicas, prioritizing availability over immediate consistency in distributed systems

TL;DR

Eventual consistency is a consistency model where, in the absence of new updates, all replicas will eventually converge to the same value. It favors availability and partition tolerance over strong consistency (CAP theorem tradeoff), powering systems like DynamoDB, Cassandra, and DNS at massive scale.

Visual Overview

Strong vs Eventual Consistency

Core Explanation

What is Eventual Consistency?

Eventual consistency is a consistency model used in distributed databases where updates propagate to all replicas asynchronously. The system guarantees that:

  1. Eventually: Given enough time without new updates
  2. All replicas converge: To the same final value
  3. No guarantee on timing: Could take milliseconds or seconds

This is in contrast to strong consistency, where all replicas are updated synchronously before acknowledging a write.

Real-World Analogy:

Think of eventual consistency like Wikipedia edits:

  • Someone updates an article (write to primary)
  • The change is visible immediately on their screen
  • Other users see the change after their browser cache expires (eventual propagation)
  • Eventually, everyone sees the same updated article

The CAP Theorem Trade-off

Eventual consistency is a choice made in the CAP theorem:

CAP Theorem Trade-off

When Network Partition Happens:

Network Partition Scenarios

Consistency Levels

Most eventually consistent systems offer tunable consistency:

1. Read-Your-Writes Consistency

Read-Your-Writes Consistency

2. Monotonic Reads

Monotonic Reads

3. Monotonic Writes

Monotonic Writes

Conflict Resolution

When replicas diverge, how do we resolve conflicts?

1. Last-Write-Wins (LWW)

Last-Write-Wins (LWW)

2. Vector Clocks

Vector Clocks

3. CRDTs (Conflict-Free Replicated Data Types)

CRDTs (Conflict-Free Replicated Data Types)

Real Systems Using Eventual Consistency

SystemConsistency ModelConflict ResolutionUse Case
DynamoDBEventual (default)Last-Write-Wins or Vector ClocksHigh-availability key-value store
CassandraTunable (eventual default)Last-Write-Wins with timestampsMulti-datacenter database
DNSEventual (TTL-based)Authoritative server winsGlobal name resolution
S3Eventual (new objects immediate)Latest timestamp winsObject storage
RiakEventual (with siblings)Vector clocks + application mergeShopping carts

Case Study: DynamoDB

DynamoDB Read Levels

When to Use Eventual Consistency

✓ Perfect Use Cases

High Availability Requirements

High Availability Requirements

Multi-Region Systems

Multi-Region Systems

High Write Throughput

High Write Throughput

Tolerates Temporary Inconsistency

Tolerates Temporary Inconsistency

✕ When NOT to Use

Financial Transactions

Financial Transactions

Inventory Management

Inventory Management

Strong Ordering Requirements

Strong Ordering Requirements

Interview Application

Common Interview Question

Q: “Design a shopping cart for an e-commerce site. Should you use eventual or strong consistency?”

Strong Answer:

“I’d use eventual consistency for the shopping cart. Here’s my reasoning:

Why Eventual Consistency:

  1. Availability matters: Users should always be able to add items, even during network issues
  2. Temporary inconsistency is acceptable: If a user adds an item and it takes 200ms to propagate to all replicas, that’s fine
  3. Multi-region performance: Low latency in all geographic regions
  4. Conflict resolution is straightforward: Cart operations are mostly additive

Conflict Resolution Strategy:

  • Use Last-Write-Wins for item quantities
  • Alternatively, use CRDT (addition-based counter) to merge carts
  • If two regions add the same item concurrently, merge by summing quantities

Strong Consistency for Checkout:

  • Switch to strong consistency during payment
  • Verify inventory availability with strong read
  • Deduct inventory with ACID transaction

Real-World Example:

  • Amazon uses eventual consistency for carts (famously described in Dynamo paper)
  • Better to show users an item briefly, then say ‘out of stock’ at checkout, than to have site downtime”

Why This Answer Works:

  • Identifies appropriate consistency model with reasoning
  • Explains trade-offs clearly
  • Discusses conflict resolution strategy
  • Mentions when to switch to strong consistency (checkout)
  • References real-world implementation (Amazon)

Code Example

Eventually Consistent Read in DynamoDB (Node.js)

const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB.DocumentClient();

// Eventually Consistent Read (default, faster, cheaper)
async function getEventuallyConsistent(userId) {
  const params = {
    TableName: "Users",
    Key: { userId: userId },
    ConsistentRead: false, // Eventually consistent (default)
  };

  const result = await dynamodb.get(params).promise();

  // May return stale data if recent write occurred
  // Typical lag: 10-50ms
  // Use case: Display user profile, product listings

  return result.Item;
}

// Strongly Consistent Read (slower, more expensive)
async function getStronglyConsistent(userId) {
  const params = {
    TableName: "Users",
    Key: { userId: userId },
    ConsistentRead: true, // Strongly consistent
  };

  const result = await dynamodb.get(params).promise();

  // Always returns latest data
  // Typical lag: 0ms
  // Use case: Bank balance, inventory checks before purchase

  return result.Item;
}

// Example: Shopping cart with eventual consistency
async function addToCart(userId, itemId, quantity) {
  // Write is always strongly consistent in DynamoDB
  // (single-item writes are ACID)
  await dynamodb
    .put({
      TableName: "ShoppingCarts",
      Item: {
        userId: userId,
        itemId: itemId,
        quantity: quantity,
        updatedAt: Date.now(),
      },
    })
    .promise();

  // Subsequent reads may be eventually consistent
  // Read-your-writes: Route user to same replica or use consistent read

  // Read cart (eventually consistent, faster)
  const cart = await dynamodb
    .query({
      TableName: "ShoppingCarts",
      KeyConditionExpression: "userId = :userId",
      ExpressionAttributeValues: { ":userId": userId },
      ConsistentRead: false, // Allow stale reads (< 1 second lag)
    })
    .promise();

  return cart.Items;
}

// At checkout: Switch to strong consistency
async function checkout(userId) {
  // Critical operation: Need accurate inventory and cart

  const cart = await dynamodb
    .query({
      TableName: "ShoppingCarts",
      KeyConditionExpression: "userId = :userId",
      ExpressionAttributeValues: { ":userId": userId },
      ConsistentRead: true, // Strong consistency required!
    })
    .promise();

  // Check inventory with strong consistency
  for (const item of cart.Items) {
    const product = await dynamodb
      .get({
        TableName: "Inventory",
        Key: { productId: item.itemId },
        ConsistentRead: true, // Must be accurate!
      })
      .promise();

    if (product.Item.stock < item.quantity) {
      throw new Error(`Insufficient stock for ${item.itemId}`);
    }
  }

  // Proceed with payment (ACID transaction)
  // ...
}

See It In Action:

Prerequisites:

Related Concepts:

Used In Systems:

  • Shopping cart systems (Amazon, e-commerce)
  • Social media feeds (Twitter, Facebook)
  • CDN and caching (Cloudflare, Akamai)

Explained In Detail:

  • Distributed Systems Deep Dive - Consistency models in depth

Quick Self-Check

  • Can explain eventual consistency in 60 seconds?
  • Can draw timeline showing write propagation delay?
  • Understand CAP theorem trade-off (AP vs CP)?
  • Can name 3 real systems using eventual consistency?
  • Know when to choose eventual vs strong consistency?
  • Understand conflict resolution strategies (LWW, vector clocks, CRDTs)?
Interview Notes
💼75% of distributed systems interviews
Interview Relevance
75% of distributed systems interviews
🏭Amazon, Netflix, LinkedIn
Production Impact
Powers systems at Amazon, Netflix, LinkedIn
Billions of requests
Performance
Billions of requests query improvement
📈CAP theorem (AP systems)
Scalability
CAP theorem (AP systems)