[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+262 -57
View File
@@ -1,91 +1,296 @@
---
id: wiki-2026-0508-cap-theorem
title: CAP Theorem
title: CAP Theorem & PACELC
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CAP-001]
aliases: [CAP, Brewer's theorem, PACELC, eventual consistency, distributed consensus, BASE]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, Distributed-Systems, infrastructure, database, Scalability]
confidence_score: 0.95
verification_status: applied
tags: [distributed-systems, cap-theorem, pacelc, consistency, availability, partition-tolerance, database, raft, paxos]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: distributed systems theory
framework: any
---
# CAP Theorem (CAP 정리)
# CAP Theorem & PACELC
## 📌 한 줄 통찰 (The Karpathy Summary)
> "분산 시스템에서 완벽한 데이터 일치와 24시간 가동, 네트워크 오류 방지를 모두 가질 수는 없다" — 분산 컴퓨팅 환경에서 일관성, 가용성, 분단 허용성 중 두 가지만 동시에 만족할 수 있다는 에릭 브루어의 정리.
## 📌 한 줄 통찰
> **"매 distributed 의 매 3 중 매 2 만"** — Eric Brewer (2000). Consistency + Availability + Partition tolerance — 매 partition 가 inevitable → 매 CP / AP 의 trade-off. 매 modern 의 PACELC 의 보완 — 매 partition 외 의 latency-consistency.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 시스템의 규모가 커지고 노드가 분산될 때 발생하는 네트워크 지연 및 단절 상황에서, 데이터의 정확성과 시스템의 응답성 사이의 우선순위를 결정하는 아키텍처 선택 패턴.
- **세 가지 핵심 속성:**
- **Consistency (일관성):** 모든 노드에서 동시에 같은 데이터를 조회할 수 있어야 함. (정확성 중시)
- **Availability (가용성):** 일부 노드에 장애가 생겨도 시스템은 항상 응답해야 함. (연결성 중시)
- **Partition Tolerance (분단 허용성):** 노드 간 네트워크가 끊겨도 시스템이 계속 작동해야 함. (분산 시스템의 필수 요건)
- **주요 선택 전략:**
- **CP (Consistency + Partition Tolerance):** 데이터 정확성이 중요할 때 (예: 금융 시스템, 분산 락).
- **AP (Availability + Partition Tolerance):** 서비스 중단이 치명적일 때 (예: SNS 피드, 쇼핑몰 장바구니).
## 📖 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 '모든 것을 만족하는 DB'를 찾던 시기에서, 비즈니스 요구사항에 따라 일관성을 희생(Eventual Consistency)하더라도 가용성을 챙기는 유연한 설계 시대로 전환.
- **정책 변화:** Antigravity 프로젝트의 분산 지식 그래프 시스템은 지식의 전파 속도보다 정확성이 중요하므로 CP 전략을 기본으로 하되, 사용자 읽기 요청에 대해서는 AP적 요소를 도입하여 응답성을 확보함.
### 매 3 property
1. **Consistency (C)**: 매 모든 node 의 같은 data.
2. **Availability (A)**: 매 모든 request 의 매 response.
3. **Partition tolerance (P)**: 매 network split 시 매 동작.
## 🔗 지식 연결 (Graph)
-[[_system|system]]-Design-for-AI-Scale, [[Distributed-Computing|Distributed-Computing]], Vector-Database-Selection, Microservices
- **Raw Source:** 10_Wiki/Topics/AI/CAP-Theorem.md
### Brewer's theorem
- 매 distributed system 의 매 partition 의 inevitable.
- 매 P 의 force.
- 매 실제 선택 = CP or AP.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### CP vs AP
**언제 이 지식을 쓰는가:**
- *(TODO)*
#### CP (Consistency + Partition tolerance)
- 매 partition 시 매 일부 의 unavailable.
- 매 stale data 의 reject.
- 매 financial / lock / counter.
- 예: HBase, MongoDB (default), Etcd, Zookeeper, Postgres.
**언제 쓰면 안 되는가:**
- *(TODO)*
#### AP (Availability + Partition tolerance)
- 매 partition 시 매 stale OK.
- 매 eventual consistency.
- 매 social feed / cart / cache.
- 예: Cassandra, DynamoDB, CouchDB.
## 🧪 검증 상태 (Validation)
### 매 PACELC (Daniel Abadi 2010)
> Partition → A or C; Else → L (latency) or C (consistency).
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
| System | PA / PC | EL / EC |
|---|---|---|
| MongoDB | PC (default) | EL |
| DynamoDB | PA | EL |
| Cassandra | PA | EL |
| HBase | PC | EC |
| Spanner | PC | EC |
| Postgres (sync replica) | PC | EC |
| Postgres (async) | PA | EL |
## 🧬 중복 검사 (Duplicate Check)
### Consistency level
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
#### Strict / Linearizability
- 매 like 매 single machine.
- 매 expensive (cross-region 의 round trip).
## 🕓 변경 이력 (Changelog)
#### Sequential
- 매 program order.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
#### Causal
- 매 cause-effect 만.
## 💻 코드 패턴 (Code Patterns)
#### Read-your-writes
- 매 own write 의 read OK.
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
#### Eventual
- 매 결국 의 converge.
- 매 weakest 가 매 fastest.
```text
# TODO
### 매 BASE (vs ACID)
- **BASE** = Basically Available, Soft state, Eventual consistency.
- 매 NoSQL 의 paradigm.
- 매 ACID 의 strong vs BASE 의 loose.
### 매 modern reality
- 매 hybrid: 매 region 별 의 다른 model.
- 매 Spanner: 매 global linearizable (TrueTime API).
- 매 CRDTs: 매 commutative 의 eventual consistency 의 conflict-free.
- 매 Raft / Paxos: 매 majority quorum 의 CP.
### 매 응용 의 결정
#### CP 선호
- 매 financial transaction.
- 매 distributed lock.
- 매 counter (unique).
- 매 schema migration.
#### AP 선호
- 매 social feed.
- 매 product catalog (cache).
- 매 shopping cart.
- 매 click tracking.
### 매 misconception
- "CP = always consistent": 매 partition 시 의 unavailable.
- "AP = always available": 매 partition 시 만 의 stale.
- "Eventual = OK": 매 conflict resolution 의 critical.
- "P 의 optional": 매 X — 매 distributed 의 P 의 inevitable.
## 💻 패턴
### Eventual consistency (Cassandra)
```python
from cassandra.cluster import Cluster
from cassandra import ConsistencyLevel
session = Cluster(['127.0.0.1']).connect('mykeyspace')
# 매 write — 매 ANY (가장 weak)
write_stmt = session.prepare("INSERT INTO users (id, name) VALUES (?, ?)")
write_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE
session.execute(write_stmt, [user_id, name])
# 매 read — 매 strong consistency 가 필요 시 의 QUORUM
read_stmt = session.prepare("SELECT * FROM users WHERE id = ?")
read_stmt.consistency_level = ConsistencyLevel.LOCAL_QUORUM
result = session.execute(read_stmt, [user_id])
# 매 quorum write + quorum read = 매 strong consistency.
```
## 🤔 의사결정 기준 (Decision Criteria)
### Raft consensus (etcd)
```python
import etcd3
**선택 A를 써야 할 때:**
- *(TODO)*
client = etcd3.client(host='localhost', port=2379)
**선택 B를 써야 할 때:**
- *(TODO)*
# 매 strong consistency 의 write
client.put('/config/feature_flag', 'true')
**기본값:**
> *(TODO)*
# 매 read (sequential)
value, _ = client.get('/config/feature_flag')
## ❌ 안티패턴 (Anti-Patterns)
# 매 distributed lock (CP)
lock = client.lock('my-resource', ttl=10)
if lock.acquire():
try: do_critical_section()
finally: lock.release()
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CRDT (eventual + conflict-free)
```python
class LWWRegister:
"""매 Last-Write-Wins Register."""
def __init__(self):
self.value = None
self.timestamp = 0
def set(self, value, timestamp):
if timestamp > self.timestamp:
self.value = value
self.timestamp = timestamp
def merge(self, other):
if other.timestamp > self.timestamp:
self.value = other.value
self.timestamp = other.timestamp
class GCounter:
"""매 Grow-only counter."""
def __init__(self, node_id):
self.node_id = node_id
self.counts = {}
def increment(self):
self.counts[self.node_id] = self.counts.get(self.node_id, 0) + 1
def value(self):
return sum(self.counts.values())
def merge(self, other):
for nid, cnt in other.counts.items():
self.counts[nid] = max(self.counts.get(nid, 0), cnt)
```
### Read-your-writes (sticky session)
```python
class StickyClient:
def __init__(self, replica_pool):
self.pool = replica_pool
self.last_write_replica = None
def write(self, key, value):
# 매 write 의 leader
leader = self.pool.leader()
leader.write(key, value)
self.last_write_replica = leader
def read(self, key):
# 매 own write 의 read 시 matched replica
if self.last_write_replica:
return self.last_write_replica.read(key)
# 매 else any
return self.pool.any().read(key)
```
### Quorum (Cassandra 식)
```python
# 매 R + W > N → 매 strong consistency
N = 3 # 매 replica
W = 2 # 매 write quorum
R = 2 # 매 read quorum
# 매 R + W = 4 > N = 3 → 매 latest 의 read 보장.
```
### Multi-region with Spanner-like
```sql
-- 매 Spanner: 매 global strong consistency
BEGIN TRANSACTION;
INSERT INTO orders (id, user_id, total) VALUES (uuid(), 123, 100);
UPDATE inventory SET count = count - 1 WHERE id = 'item-456';
COMMIT;
-- 매 TrueTime 의 timestamp 의 ordering 의 보장.
```
### Hybrid: CP critical + AP rest
```python
class HybridStore:
def __init__(self):
self.cp_store = etcd3.client() # 매 CP
self.ap_store = redis.Redis() # 매 AP cache
def get(self, key, strict=False):
if strict: return self.cp_store.get(key)[0]
cached = self.ap_store.get(key)
if cached: return cached
value = self.cp_store.get(key)[0]
self.ap_store.set(key, value, ex=60)
return value
def set(self, key, value):
self.cp_store.put(key, value)
self.ap_store.delete(key) # 매 invalidate
```
## 🤔 결정 기준
| 상황 | Choice |
|---|---|
| Money / lock | CP (Spanner, etcd, Postgres) |
| Social feed | AP (Cassandra, DynamoDB) |
| Cart | AP + CRDT |
| Counter | CP (Spanner) or CRDT |
| Search | AP + eventual |
| Config | CP (etcd, Zookeeper) |
| Cache | AP + TTL |
| Multi-region linear | Spanner / FoundationDB |
**기본값**: CP for state-of-record, AP for derived / cache.
## 🔗 Graph
- 부모: [[Distributed-Systems]] · [[Database-Theory]]
- 변형: [[PACELC]] · [[BASE]] · [[ACID]]
- 응용: [[Raft]] · [[Paxos]] · [[CRDT]] · [[Quorum]] · [[Spanner]]
- DB: [[Cassandra]] · [[DynamoDB]] · [[MongoDB]] · [[Postgres]] · [[Etcd]]
- Adjacent: [[Availability-and-Persistence]] · [[Eventual-Consistency]] · [[Linearizability]]
## 🤖 LLM 활용
**언제**: 매 distributed system design. 매 database choice. 매 multi-region architecture. 매 consistency model decision.
**언제 X**: 매 single-server (no partition).
## ❌ 안티패턴
- **"매 모든 의 want"**: 매 impossible — 매 trade-off 의 필요.
- **AP 의 financial**: 매 lost update / double spend.
- **CP 의 social feed**: 매 partition 시 의 user-facing fail.
- **Strict 의 default**: 매 unnecessary expensive.
- **No conflict resolution (eventual)**: 매 silent loss.
- **PACELC 무시**: 매 happy path latency 의 ignore.
- **Cross-region sync replication**: 매 latency 의 disaster.
## 🧪 검증 / 중복
- Verified (Brewer 2000, Gilbert-Lynch 2002 proof, Abadi PACELC).
- 신뢰도 A.
- Related: [[Availability-and-Persistence]] · [[Database-Theory]] · [[Raft]] · [[CRDT]] · [[Architecture-Styles]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — CP/AP + PACELC + 매 Cassandra / etcd / CRDT / hybrid code |