🏗️ Architecture

Eventual Consistency

Eventual Consistency

A consistency model in a distributed system in which, if updates stop, all replicas eventually converge to the same value. A trade-off strategy that relaxes Strong Consistency to gain Availability and Scalability.

📐 CAP Theorem (CAP Theorem)

In a distributed system, during a network partition (Partition), you must choose between consistency (C) and availability (A).

C - Consistency
All nodes hold the same data
A - Availability
Always able to respond
P - Partition Tolerance
Tolerates network partitions
Only 2 of 3
can be guaranteed at the same time
CP System
MongoDB, HBase
Consistency first, availability sacrificed
AP System
DynamoDB, Cassandra
Availability first, eventual consistency
CA System
Single-node RDBMS
Not distributed (unrealistic)

⚖️ ACID vs BASE

ACID (Traditional RDBMS)

A - Atomicity All succeed or all fail
C - Consistency Always maintains a valid state
I - Isolation Isolation between Transactions
D - Durability Committed data is permanently preserved
Suited to strong consistency, vertical scaling, and single nodes

BASE (NoSQL/Distributed Systems)

BA - Basically Available Basic availability is guaranteed
S - Soft State State may change over time
E - Eventually Consistent Consistency is eventually achieved
Suited to eventual consistency, horizontal scaling, and large-scale distribution

📊 Consistency Spectrum

Consistency is not binary. Various levels exist between strong consistency and eventual consistency.

Strong Consistency (Strong) Causal Consistency (Causal) Eventual Consistency (Eventual)
Linearizability

The strongest. Every read reflects the latest write. Behaves like a single copy.

Read-your-writes

You can read your own writes immediately. Other users may see a delay.

Monotonic Reads

Never reads an older value than one already read. Time does not go backward.

✅ Deciding When to Apply Eventual Consistency

✅ Suitable cases
  • Social media likes/view counts
  • Product reviews/ratings
  • User profile updates
  • Search index updates
  • Log/analytics data collection
  • CDN cache invalidation
  • DNS record propagation
❌ Unsuitable cases
  • Bank account balances
  • Inventory quantity (risk of double selling)
  • Reservations/seat selection
  • Auction bidding
  • Authentication/permission changes
  • Payment/remittance Transactions
  • Medical record updates

💻 Actual Implementation Code

# AWS DynamoDB: 읽기 일관성 옵션
import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')

# 1. Eventually Consistent Read (기본값)
# - 빠름 (리전 내 아무 복제본에서 읽기)
# - 최신 쓰기가 반영 안 될 수 있음 (보통 1초 이내 동기화)
# - 읽기 용량 유닛: 1 RCU = 4KB
response = table.get_item(
    Key={'user_id': 'user-123'},
    ConsistentRead=False  # 기본값
)
user = response.get('Item')
print(f"Eventually Consistent: {user}")

# 2. Strongly Consistent Read
# - 느림 (Primary 노드에서만 읽기)
# - 최신 쓰기가 항상 반영됨
# - 읽기 용량 유닛: 2배 소비 (1 RCU = 2KB)
# - Global Secondary Index에서는 사용 불가
response = table.get_item(
    Key={'user_id': 'user-123'},
    ConsistentRead=True  # 강한 일관성
)
user = response.get('Item')
print(f"Strongly Consistent: {user}")

# 3. 실제 사용 예시: 쓰기 후 읽기
def update_and_read_profile(user_id, new_name):
    # 프로필 업데이트
    table.update_item(
        Key={'user_id': user_id},
        UpdateExpression='SET #name = :name',
        ExpressionAttributeNames={'#name': 'name'},
        ExpressionAttributeValues={':name': new_name}
    )

    # 방금 쓴 데이터를 바로 읽어야 하므로 Strong Consistency 사용
    response = table.get_item(
        Key={'user_id': user_id},
        ConsistentRead=True  # 중요: 자신이 쓴 값 즉시 확인
    )
    return response.get('Item')

# 4. Query에서의 일관성
response = table.query(
    KeyConditionExpression='user_id = :uid',
    ExpressionAttributeValues={':uid': 'user-123'},
    ConsistentRead=True  # Query도 강한 일관성 가능
)
# 최종 일관성 시스템에서의 충돌 해결 전략
from datetime import datetime
from dataclasses import dataclass
from typing import List, Any
import hashlib

# 1. Last-Write-Wins (LWW) - 가장 간단
@dataclass
class LWWValue:
    value: Any
    timestamp: datetime

    def merge(self, other: 'LWWValue') -> 'LWWValue':
        """타임스탬프가 더 최신인 값을 선택"""
        return self if self.timestamp > other.timestamp else other

# 사용 예시
replica1 = LWWValue("value_A", datetime(2024, 1, 1, 10, 0))
replica2 = LWWValue("value_B", datetime(2024, 1, 1, 10, 5))
resolved = replica1.merge(replica2)  # "value_B" 선택


# 2. G-Counter CRDT (Conflict-free Replicated Data Type)
# 증가만 가능한 카운터 - 최종 일관성에서도 충돌 없이 병합
class GCounter:
    def __init__(self, node_id: str):
        self.node_id = node_id
        self.counts = {}  # {node_id: count}

    def increment(self, amount: int = 1):
        # 자신의 노드 카운트만 증가
        self.counts[self.node_id] = self.counts.get(self.node_id, 0) + amount

    def value(self) -> int:
        # 모든 노드 카운트의 합
        return sum(self.counts.values())

    def merge(self, other: 'GCounter') -> 'GCounter':
        """각 노드의 max 값을 취해 병합 - 충돌 없음"""
        merged = GCounter(self.node_id)
        all_nodes = set(self.counts.keys()) | set(other.counts.keys())
        for node in all_nodes:
            merged.counts[node] = max(
                self.counts.get(node, 0),
                other.counts.get(node, 0)
            )
        return merged

# 사용 예시: 좋아요 카운터
node_a = GCounter("node-a")
node_b = GCounter("node-b")

node_a.increment(5)   # 노드 A에서 5번 클릭
node_b.increment(3)   # 노드 B에서 3번 클릭

# 네트워크 복구 후 병합 - 순서 무관, 멱등성 보장
merged = node_a.merge(node_b)
print(f"총 좋아요: {merged.value()}")  # 8


# 3. Vector Clock - 인과관계 추적
class VectorClock:
    def __init__(self, node_id: str):
        self.node_id = node_id
        self.clock = {}

    def tick(self):
        self.clock[self.node_id] = self.clock.get(self.node_id, 0) + 1

    def compare(self, other: 'VectorClock') -> str:
        """인과관계 판단: 'before', 'after', 'concurrent'"""
        less = equal = greater = False
        all_keys = set(self.clock.keys()) | set(other.clock.keys())
        for key in all_keys:
            v1 = self.clock.get(key, 0)
            v2 = other.clock.get(key, 0)
            if v1 < v2: less = True
            elif v1 > v2: greater = True
            else: equal = True

        if less and not greater: return 'before'
        if greater and not less: return 'after'
        return 'concurrent'  # 충돌 발생!
# Saga 패턴: 분산 트랜잭션에서의 최종 일관성
# 각 서비스는 로컬 트랜잭션 + 보상 트랜잭션으로 일관성 유지
from enum import Enum
from dataclasses import dataclass
from typing import Callable, List
import asyncio

class SagaState(Enum):
    PENDING = "pending"
    COMPLETED = "completed"
    COMPENSATING = "compensating"
    FAILED = "failed"

@dataclass
class SagaStep:
    name: str
    action: Callable           # 실행할 작업
    compensation: Callable     # 롤백 작업

class OrderSaga:
    """주문 처리 Saga 예시"""

    def __init__(self, order_id: str):
        self.order_id = order_id
        self.state = SagaState.PENDING
        self.completed_steps: List[SagaStep] = []

    async def execute(self):
        steps = [
            SagaStep(
                name="재고 확보",
                action=lambda: self._reserve_inventory(),
                compensation=lambda: self._release_inventory()
            ),
            SagaStep(
                name="결제 처리",
                action=lambda: self._process_payment(),
                compensation=lambda: self._refund_payment()
            ),
            SagaStep(
                name="배송 예약",
                action=lambda: self._schedule_delivery(),
                compensation=lambda: self._cancel_delivery()
            ),
        ]

        try:
            for step in steps:
                print(f"[Saga] 실행: {step.name}")
                await step.action()
                self.completed_steps.append(step)

            self.state = SagaState.COMPLETED
            print(f"[Saga] 완료: 주문 {self.order_id}")

        except Exception as e:
            print(f"[Saga] 실패: {e}")
            await self._compensate()

    async def _compensate(self):
        """완료된 단계를 역순으로 롤백"""
        self.state = SagaState.COMPENSATING
        for step in reversed(self.completed_steps):
            try:
                print(f"[Saga] 보상: {step.name} 롤백")
                await step.compensation()
            except Exception as e:
                print(f"[Saga] 보상 실패: {e}")
        self.state = SagaState.FAILED

    # 각 단계 구현 (실제로는 마이크로서비스 호출)
    async def _reserve_inventory(self):
        # 재고 서비스에 재고 확보 요청
        await asyncio.sleep(0.1)  # 시뮬레이션

    async def _release_inventory(self):
        # 재고 서비스에 재고 해제 요청
        await asyncio.sleep(0.1)

    async def _process_payment(self):
        # 결제 서비스에 결제 요청
        await asyncio.sleep(0.1)
        # raise Exception("결제 실패")  # 테스트용

    async def _refund_payment(self):
        # 결제 서비스에 환불 요청
        await asyncio.sleep(0.1)

    async def _schedule_delivery(self):
        # 배송 서비스에 배송 예약
        await asyncio.sleep(0.1)

    async def _cancel_delivery(self):
        # 배송 서비스에 배송 취소
        await asyncio.sleep(0.1)

# 실행
async def main():
    saga = OrderSaga("order-12345")
    await saga.execute()

asyncio.run(main())

💬 Learning Through Conversation

👤
Junior Developer
We manage product inventory in an online store, and if we use DynamoDB, couldn't eventual consistency cause inventory to go negative?
🏗️
Senior Architect
That's right. In cases like inventory where oversellingis fatal, eventual consistency is unsuitable. There are two solutions: (1) use DynamoDB's ConsistentRead=Trueand conditional updates, (2) separate inventory into a distinct system that provides strong consistency (Redis, PostgreSQL).
👤
Junior Developer
Then when is eventual consistency used? It looks risky.
🏗️
Senior Architect
It's used "when showing a slightly stale value causes no problem for the business." For example, if an Instagram like count shows 100 but the actual number is 103? Users don't care. But availability and scalability improve enormously. Trade-offsUnderstanding them and using them in the right place is the key.

⚠️ Cautions

💰

Do not use for financial transactions

If you apply eventual consistency to data where accuracy is essential, such as bank balances, remittances, and payments, serious problems such as double withdrawals and negative balances occur. Use strong consistency or distributed Transactions.

📖

Read-after-Write Problem

Reading right after writing data may show the previous value. It is a UX problem where a user edits their profile and, on refresh, sees the old value. Resolve it with ConsistentRead or client-side caching.

⚔️

Conflict Resolution Strategy Required

Modifying the same data at the same time causes conflicts. You must design a clear conflict resolution strategy such as Last-Write-Wins, Vector Clock, or CRDT. Assuming "it will resolve itself" leads to data loss.

📋 Real-World Use Cases

Amazon DynamoDB
E-commerce

Background: Amazon's shopping cart service must handle millions of requests per second. Even in peak seasons like Black Friday, if adding to the cart fails, it directly leads to lost sales.

Application: Adopted an eventual consistency model, replicating across multiple data centers. Adding a cart item "always succeeds," and conflicts (the same product added at the same time) are merged later. "Add failed" is worse than showing the user a slightly stale cart.

Key point:

Cases where availability > consistency. Even if the cart item count is briefly wrong, it is fine as long as it is correct at the time of purchase.

DNS (Domain Name System)
Infrastructure

Background: DNS is a global distributed system that translates domain names into IP addresses. Billions of DNS queries occur every day, and strong consistency is impossible.

Application: Eventual consistency based on TTL (Time-To-Live). When a DNS record changes, it does not propagate immediately; it is updated after the TTL expires on each cache server. Propagation generally completes within 24-48 hours.

Key point:

This is why DNS changes are not reflected immediately. During migrations, a technique of lowering the TTL in advance is used.

Twitter Like/Retweet Counters
Social Media

Background: Popular tweets receive thousands of likes per second. Aggregating every like accurately in real time creates enormous load.

Application: Counters in each region are aggregated asynchronously to maintain eventual consistency. Different users may see different numbers, but they eventually converge. Differences are hidden by displaying approximations such as "1.2M likes."

Key point:

Cases where the exact number does not matter. What matters is the sense that there are "many"; whether it is 1,234,567 or 1,234,568 is irrelevant.

🧠 Comprehension Quiz

Q. Which is a use case where Eventual Consistency is suitable?
A. Checking a bank account balance
B. Booking an airline seat
C. Social media post view counts
D. Decreasing inventory quantity
Answer: C

For social media view counts, availability matters more than accuracy. Whether the view count is 1,234,567 or 1,234,570 does not affect the user experience.

By contrast:
• Bank balance: must be accurate (risk of double withdrawal)
• Seat reservation: duplicate bookings must be prevented
• Inventory quantity: overselling must be prevented

🔗 Related Terms

📚 Learning Resources