🏗️ Architecture

BASE

Basically Available, Soft state, Eventually consistent

A data consistency model for distributed systems. As an alternative to ACID, it chooses eventual consistency over immediate strong consistency for high availability and scalability.

📖 Detailed Explanation

Basically Available means that the system always returns a response. Even if some nodes fail, the entire system continues to operate and always provides a response, although the data may not be the latest. The key is prioritizing availability over consistency.

Soft state means that the state of the system can change over time even without external input. While synchronization between data replicas is in progress, the system state may be temporarily inconsistent, and this is considered a normal condition.

Eventually consistent guarantees that all replicas will hold the same value after enough time has passed. Immediate consistency is given up, but in the end all nodes will have the same data. The time this "eventually" takes varies from milliseconds to several seconds.

BASE was inspired by the CAP Theorem. When a network partition (Partition) occurs, an ACID system chooses consistency (Consistency) and gives up availability, whereas a BASE system chooses availability (Availability) and relaxes consistency.

Most large-scale distributed NoSQL databases, such as Amazon DynamoDB, Apache Cassandra, MongoDB (default settings), and Redis clusters, adopt the BASE model. It is well suited to scenarios where slight inconsistency is tolerable, such as social media feeds, like counts, and shopping carts.

💻 Code Example

# BASE 모델 - Python + DynamoDB 예제
import boto3
from botocore.config import Config
from decimal import Decimal
import time

class EventuallyConsistentCart:
    """
    BASE 원칙을 따르는 장바구니 서비스
    - 최종 일관성 읽기로 빠른 응답
    - 강한 일관성 읽기는 필요할 때만 사용
    """

    def __init__(self, table_name: str):
        self.dynamodb = boto3.resource('dynamodb')
        self.table = self.dynamodb.Table(table_name)

    def add_item(self, user_id: str, product_id: str, quantity: int):
        """
        장바구니에 상품 추가
        DynamoDB는 자동으로 여러 리전에 복제 (최종 일관성)
        """
        self.table.update_item(
            Key={'user_id': user_id},
            UpdateExpression='SET items.#pid = if_not_exists(items.#pid, :zero) + :qty',
            ExpressionAttributeNames={'#pid': product_id},
            ExpressionAttributeValues={
                ':qty': quantity,
                ':zero': 0
            }
        )
        # 쓰기는 즉시 반환되지만, 읽기에 반영되기까지 시간 필요
        print(f"✅ 상품 추가됨 (최종 일관성으로 전파 중)")

    def get_cart_eventually_consistent(self, user_id: str) -> dict:
        """
        최종 일관성 읽기 - 빠르지만 최신 데이터 아닐 수 있음
        대부분의 경우 충분 (밀리초 내 동기화)
        """
        response = self.table.get_item(
            Key={'user_id': user_id},
            ConsistentRead=False  # 기본값, 최종 일관성
        )
        return response.get('Item', {})

    def get_cart_strongly_consistent(self, user_id: str) -> dict:
        """
        강한 일관성 읽기 - 결제 직전 등 정확성이 중요할 때
        약간 느리고 비용 2배, 하지만 최신 데이터 보장
        """
        response = self.table.get_item(
            Key={'user_id': user_id},
            ConsistentRead=True  # 강한 일관성
        )
        return response.get('Item', {})


# BASE 원칙을 활용한 좋아요 카운터
class EventuallyConsistentCounter:
    """
    SNS 좋아요 수처럼 정확한 일관성보다 가용성이 중요한 경우
    """

    def __init__(self, table_name: str):
        self.dynamodb = boto3.resource('dynamodb')
        self.table = self.dynamodb.Table(table_name)

    def increment_like(self, post_id: str):
        """
        좋아요 증가 - 원자적 카운터 업데이트
        여러 리전에서 동시 증가해도 결국 합쳐짐
        """
        self.table.update_item(
            Key={'post_id': post_id},
            UpdateExpression='SET like_count = if_not_exists(like_count, :zero) + :inc',
            ExpressionAttributeValues={
                ':inc': 1,
                ':zero': 0
            }
        )

    def get_approximate_count(self, post_id: str) -> int:
        """
        대략적인 좋아요 수 - UI 표시용
        "약 1.2K 좋아요" 처럼 표시하면 정확성 불필요
        """
        response = self.table.get_item(
            Key={'post_id': post_id},
            ConsistentRead=False,
            ProjectionExpression='like_count'
        )
        return response.get('Item', {}).get('like_count', 0)


# 사용 예시
if __name__ == "__main__":
    cart = EventuallyConsistentCart('shopping-carts')

    # 상품 추가 (빠른 쓰기)
    cart.add_item('user123', 'product-abc', 2)

    # 최종 일관성 읽기 (일반 조회)
    cart_data = cart.get_cart_eventually_consistent('user123')
    print(f"장바구니 (최종 일관성): {cart_data}")

    # 결제 전 강한 일관성 읽기 (정확성 필요)
    cart_data = cart.get_cart_strongly_consistent('user123')
    print(f"장바구니 (강한 일관성): {cart_data}")
// BASE 모델 - Node.js + Cassandra 예제
const cassandra = require('cassandra-driver');

class EventuallyConsistentUserService {
    constructor() {
        // Cassandra는 분산 설계로 BASE 모델 기본 지원
        this.client = new cassandra.Client({
            contactPoints: ['node1', 'node2', 'node3'],
            localDataCenter: 'datacenter1',
            keyspace: 'users_ks'
        });
    }

    /**
     * 사용자 프로필 업데이트
     * Cassandra는 "Last Write Wins" 전략 사용
     */
    async updateProfile(userId, profileData) {
        const query = `
            UPDATE users
            SET name = ?, bio = ?, updated_at = toTimestamp(now())
            WHERE user_id = ?
        `;

        // 일관성 수준 선택
        await this.client.execute(query,
            [profileData.name, profileData.bio, userId],
            {
                // ONE: 한 노드 확인 후 반환 (빠름, 낮은 일관성)
                // QUORUM: 과반수 노드 확인 (균형)
                // ALL: 모든 노드 확인 (느림, 높은 일관성)
                consistency: cassandra.types.consistencies.one
            }
        );

        console.log('✅ 프로필 업데이트됨 (최종 일관성으로 전파 중)');
    }

    /**
     * 프로필 조회 - 일관성 수준 선택 가능
     */
    async getProfile(userId, strongConsistency = false) {
        const query = 'SELECT * FROM users WHERE user_id = ?';

        const result = await this.client.execute(query, [userId], {
            consistency: strongConsistency
                ? cassandra.types.consistencies.quorum
                : cassandra.types.consistencies.one
        });

        return result.rows[0];
    }

    /**
     * 팔로워 수 카운터 - 분산 카운터 사용
     * Cassandra Counter는 최종 일관성으로 동작
     */
    async incrementFollowers(userId) {
        const query = `
            UPDATE user_stats
            SET follower_count = follower_count + 1
            WHERE user_id = ?
        `;

        await this.client.execute(query, [userId], {
            consistency: cassandra.types.consistencies.one
        });
    }
}

// 읽기 복구 (Read Repair) 시뮬레이션
class ReadRepairExample {
    /**
     * Cassandra의 Read Repair 동작 원리
     * 읽기 시 불일치 발견하면 자동으로 복구
     */
    async readWithRepair(client, userId) {
        // QUORUM 읽기: 여러 복제본 비교
        const query = 'SELECT * FROM users WHERE user_id = ?';

        const result = await client.execute(query, [userId], {
            consistency: cassandra.types.consistencies.quorum
        });

        // 내부적으로:
        // 1. 여러 노드에서 데이터 읽기
        // 2. 타임스탬프 비교
        // 3. 오래된 데이터 가진 노드에 최신 데이터 전파
        // => "최종 일관성"이 실현되는 메커니즘

        return result.rows[0];
    }
}

// 사용 예시
async function main() {
    const userService = new EventuallyConsistentUserService();

    // 프로필 업데이트 (빠른 쓰기)
    await userService.updateProfile('user123', {
        name: '홍길동',
        bio: '소프트웨어 개발자'
    });

    // 일반 조회 (최종 일관성, 빠름)
    const profile = await userService.getProfile('user123', false);
    console.log('프로필:', profile);

    // 중요한 조회 (강한 일관성, 느림)
    const accurateProfile = await userService.getProfile('user123', true);
    console.log('정확한 프로필:', accurateProfile);
}
┌─────────────────────────────────────────────────────────────────────┐
│                     ACID vs BASE 비교                                │
├─────────────────────────────────────────────────────────────────────┤

    ACID (관계형 DB)                    BASE (NoSQL/분산 시스템)
    ═══════════════                    ═══════════════════════

    ┌─────────────┐                    ┌─────────────┐
    │  Atomicity  │                    │  Basically  │
    │   원자성    │                    │  Available  │
    │ 전부/전무   │                    │  기본가용성  │
    └─────────────┘                    └─────────────┘
          ↓                                  ↓
    트랜잭션 전체 성공                   장애 시에도 응답 반환
    또는 전체 롤백                      (오래된 데이터일 수 있음)

    ┌─────────────┐                    ┌─────────────┐
    │ Consistency │                    │ Soft State  │
    │   일관성    │                    │  유연한상태  │
    │ 즉각적 반영 │                    │ 중간상태허용 │
    └─────────────┘                    └─────────────┘
          ↓                                  ↓
    쓰기 후 읽기는                      복제 중 일시적
    항상 최신 데이터                    불일치 허용

    ┌─────────────┐                    ┌─────────────┐
    │  Isolation  │                    │ Eventually  │
    │   격리성    │                    │ Consistent  │
    │ 동시성제어  │                    │ 최종일관성  │
    └─────────────┘                    └─────────────┘
          ↓                                  ↓
    트랜잭션 간                         시간이 지나면
    간섭 없음                          모든 노드 동기화

    ┌─────────────┐
    │ Durability  │
    │   지속성    │
    │ 영구 저장   │
    └─────────────┘


    ═══════════════════════════════════════════════════════════════

    적합한 사용 사례
    ───────────────

    ACID 선택                          BASE 선택
    ──────────                         ──────────
    • 금융 거래                        • 소셜 미디어 피드
    • 결제 시스템                      • 좋아요/조회수 카운터
    • 재고 관리 (정확성 중요)          • 쇼핑 카트 (결제 전)
    • 예약 시스템                      • 로그/분석 데이터
    • 사용자 인증                      • 추천 시스템


    ═══════════════════════════════════════════════════════════════

    최종 일관성의 시간 흐름
    ─────────────────────

    T=0ms (쓰기)          T=50ms              T=200ms (최종 일관성 달성)
    ┌─────────┐          ┌─────────┐          ┌─────────┐
    │ Node A  │          │ Node A  │          │ Node A  │
    │ v=100 ✓ │  ──→     │ v=100   │  ──→     │ v=100   │
    └─────────┘          └─────────┘          └─────────┘
    ┌─────────┐          ┌─────────┐          ┌─────────┐
    │ Node B  │          │ Node B  │          │ Node B  │
    │ v=99    │  ──→     │ v=100 ✓ │  ──→     │ v=100   │
    └─────────┘          └─────────┘          └─────────┘
    ┌─────────┐          ┌─────────┐          ┌─────────┐
    │ Node C  │          │ Node C  │          │ Node C  │
    │ v=99    │  ──→     │ v=99    │  ──→     │ v=100 ✓ │
    └─────────┘          └─────────┘          └─────────┘

    불일치 상태             복제 진행 중          모든 노드 동기화!
    (Soft State)          (Soft State)        (Eventually Consistent)

└─────────────────────────────────────────────────────────────────────┘

🗣️ Say It Like This in Practice

💬 In a System Design Meeting
"A BASE model is suitable for the social media feed. It's no big problem for the user experience if a friend's new post shows up 0.5 seconds late. In return, it can respond quickly to millions of concurrent users. On the other hand, ACID is essential for the payment feature."
💬 In an incident response meeting
"The like count briefly looking different is a characteristic of BASE. Because it's eventually consistent, there can be replication lag. It will be synchronized after 1-2 seconds. It's not a serious bug but designed behavior."
💬 In a Technology Selection Discussion
"With Cassandra, you can adjust the consistency level. For regular reads, use ONE for speed, and for critical operations, raise consistency with QUORUM. Even a BASE system can have its consistency tuned depending on the situation."

⚠️ Cautions & Best Practices

❌
Do not use BASE for financial transactions

For operations where accuracy is essential, such as payments, transfers, and inventory deduction, use ACID transactions. Even a difference of 1 won is not acceptable.

❌
Be careful when Read-Your-Write guarantees are needed

Users get confused when a post they just wrote does not show up when they view it right after. After a write, use strongly consistent reads for the user's own data.

❌
A conflict resolution strategy is essential

When multiple nodes modify the same data at the same time, conflicts occur. Decide on a conflict resolution strategy in advance, such as Last-Write-Wins or version vectors.

✅
A hybrid approach is recommended

Even within a single system, distinguish ACID/BASE by feature. Separating cart viewing as BASE and payment processing as ACID lets you gain the advantages of both.

🔗 Related Terms

📚 Learn More