[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
+304 -83
View File
@@ -2,118 +2,339 @@
id: wiki-2026-0508-distributed-systems
title: Distributed Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [distributed systems, microservices, consensus, raft, paxos, sharding, replication]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-consolidated, technical-documentation]
confidence_score: 0.95
verification_status: applied
tags: [distributed-systems, scalability, microservices, consensus, replication, sharding, fault-tolerance]
raw_sources: []
last_reinforced: 2026-05-08
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
framework: K8s / Kafka / Cassandra / Redis / etcd
---
# [[Distributed-Systems|Distributed-Systems]]
# Distributed Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> "하나처럼 움직이는 여럿: 여러 대의 컴퓨터가 네트워크로 연결되어 사용자에게는 하나의 시스템처럼 보이지만, 실제로는 작업을 나누어 처리하고 일부가 고장 나도 멈추지 않는 현대 인터넷 제국의 엔진이자 뼈대."
## 한 줄
> **"매 N machine 의 1 system 의 appearance"**. 매 fault tolerance + 매 scale + 매 latency 의 trade-off. 매 CAP / PACELC 의 fundamental. 매 modern: 매 K8s + 매 service mesh + 매 eventual consistency 의 default. 매 edge / multi-region 의 trend.
## 📖 구조화된 지식 (Synthesized Content)
분산 시스템(Distributed-Systems)은 독립된 다수의 컴퓨터(노드)가 서로 협력하여 하나의 공동 목표를 수행하는 하드웨어/소프트웨어 아키텍처입니다.
## 매 핵심 challenges
1. **3대 핵심 난제 (CAP Theorem)**:
* **Consistency (일관성)**: 모든 노드가 항상 같은 데이터를 보여줘야 함.
* **Availability (가용성)**: 일부 노드 장애 시에도 서비스는 계속 되어야 함.
* **Partition Tolerance (분할 내성)**: 노드 간 네트워크 통신이 끊겨도 작동해야 함. (셋 중 둘만 완벽히 가질 수 있다는 이론)
2. **왜 중요한가?**:
* 단일 서버로는 감당할 수 없는 빅데이터와 폭발적 트래픽을 감당하는 유일한 방법임. (Scalability의 근간)
### 8 fallacies of distributed computing (Deutsch / Gosling)
1. 매 network 의 reliable.
2. 매 latency 의 zero.
3. 매 bandwidth 의 infinite.
4. 매 network 의 secure.
5. 매 topology 의 unchanged.
6. 매 1 admin.
7. 매 transport cost 의 zero.
8. 매 network 의 homogeneous.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 관리의 편의를 위해 '거대 단일 서버 정책(Monolithic)'을 선호했으나, 현대 정책은 유연성과 생존력을 위해 작게 쪼개어 분산하는 '클라우드 네이티브 정책(Microservices)'으로 전환됨(RL Update).
- **정책 변화(RL Update)**: AI 학습 정책에서, 수만 개의 GPU가 하나로 묶여 거대 모델을 학습하는 '분산 훈련 정책'이 국가적 경쟁력의 지표가 되고 있음.
→ 매 모두 의 false.
## 🔗 지식 연결 (Graph)
- [[Scalability|Scalability]], [[Blockchain|Blockchain]], Load Balancing, [[Technical-Architecture|Technical-Architecture]], [[Internet of Things (IoT)|Internet of Things (IoT)]]
- **Modern Tech/Tools**: Redis, Kafka, Cassandra, Kubernetes, gRPC.
---
### CAP / PACELC
- 매 [[CAP-Theorem]] 참조.
---
### 매 핵심 problem
- **Consistency**: 매 다른 node 의 같은 view?
- **Coordination**: 매 leader / consensus.
- **Failure**: 매 partial failure.
- **Time**: 매 clock skew (Lamport, vector clock).
- **Network**: 매 partition.
- [[Microservices_Architecture]]: 분산 시스템 사상을 현대적으로 구현한 대표적 아키텍처 스타일.
- [[Event_Driven_Architecture]]: 분산 노드 간의 느슨한 결합을 구현하는 비동기 통신 방식.
- [[Cloud_Native_Patterns]]: 분산 시스템을 효율적으로 관리하기 위한 플랫폼 기술 및 패턴.
## 매 핵심 patterns
### Replication
- 매 same data 의 multiple node.
- 매 sync vs async.
- 매 leader-follower vs multi-leader.
## 1. 개요
분산 시스템 아키텍처는 애플리케이션의 기능을 단일 프로세스가 아닌, 네트워크를 통해 상호작용하는 자율적인 여러 노드(서비스)로 분산하여 구성하는 방식이다. 이는 시스템의 무한한 확장성과 고가용성을 제공하지만, 네트워크 지연, 부분적 장애, 데이터 일관성 유지 등 단일 노드 환경에서는 존재하지 않던 고도의 기술적 복잡성을 수반한다.
### Sharding / Partitioning
- 매 data 의 N piece 의 split.
- 매 hash / range / geographic.
## 2. 분산 환경의 핵심 과제와 해결 패턴
- **장애 대응 및 복원력 (Resilience)**: 네트워크 장애나 특정 노드의 다운은 '발생할 수 있는 일'이 아니라 '반드시 발생하는 일'로 간주한다.
- **회로 차단기 (Circuit Breaker)**: 장애가 발생한 서비스로의 요청을 일시적으로 차단하여 연쇄 장애 전파 방지.
- **재시도 및 타임아웃 (Retries & Timeouts)**: 일시적 네트워크 오류에 대응하고, 무한 대기로 인한 자원 고갈 방지.
- **벌크헤드 (Bulkhead)**: 서비스 내부 자원(스레드 풀 등)을 격리하여 특정 기능의 부하가 전체 서비스에 영향을 주지 않도록 차단.
- **데이터 일관성 (Consistency)**: 분산된 데이터베이스 간의 물리적 정합성을 실시간으로 유지하기 어려우므로, 결과적 일관성(Eventual Consistency)과 사가(Saga) 패턴 등을 활용한 보상 트랜잭션 설계 적용.
- **분산 트레이싱 (Distributed Tracing)**: 여러 서비스를 관통하는 하나의 요청 흐름을 추적하기 위해 상관관계 ID(Correlation ID)를 활용한 전 구간 가시성 확보.
### Consensus
- **Raft** (modern, simpler): 매 etcd, Consul, CockroachDB.
- **Paxos**: 매 classic.
- **Multi-Paxos / EPaxos**.
- **PBFT** (Byzantine).
## 3. 엔지니어링 가치
- **수평적 확장성 (Scalability)**: 트래픽 증가 시 특정 노드를 추가하는 것만으로 시스템 전체의 처리 성능을 선형적으로 증대 가능.
- **지리적 가용성**: 서버를 여러 지역(Region)에 분산 배치하여 사용자에게 낮은 지연 시간을 제공하고 지역적 재난 상황에서도 서비스 유지.
- **기술적 유연성**: 각 노드별로 비즈니스 요구사항에 최적화된 프로그래밍 언어, 프레임워크, 데이터베이스 스토리지 선택 가능.
### Eventual consistency
- 매 some time 매 converge.
- 매 CRDT 의 conflict-free.
## 4. 트레이드오프 및 주의사항
- **관측의 어려움**: 시스템의 논리가 여러 저장소와 프로세스에 파편화되어 있어, 전체적인 실행 흐름을 파악하기 위한 인지적 부하와 모니터링 인프라 구축 비용이 매우 높음.
- **테스팅 복잡도**: 단일 노드에서의 단위 테스트만으로는 부족하며, 서비스 간의 상호작용과 네트워크 실패 시나리오를 포함한 정교한 통합 테스트 및 카오스 엔지니어링(Chaos Engineering) 요구됨.
- **네트워크 오버헤드**: 내부 함수 호출에 비해 네트워크를 통한 통신은 수백~수천 배의 지연 시간을 발생시키므로, 빈번한 통신을 최소화하는 조립성(Cohesion) 있는 경계 설계 필수.
### 매 service patterns
- **API gateway**.
- **Service mesh** (Istio, Linkerd).
- **Sidecar**.
- **Circuit breaker**.
- **Bulkhead**.
- **Saga** (distributed transaction).
- **Outbox** (reliable messaging).
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 대규모 트래픽과 가용성 요구사항을 충족하기 위한 분산 컴퓨팅의 원리를 이해하고, 네트워크 불확실성에 대응하는 견고한 시스템 설계 표준 정립.
### 매 messaging
- **Kafka**: 매 high-throughput log.
- **RabbitMQ**: 매 traditional queue.
- **NATS**: 매 simple, fast.
- **Pulsar**: 매 modern Kafka alternative.
- **Redis Streams**.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 observability
- 매 distributed tracing (OpenTelemetry).
- 매 structured logs.
- 매 metrics.
- 매 chaos engineering.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. **Web app at scale**.
2. **Cloud database** (Spanner, CockroachDB).
3. **ML training** (data + model parallel).
4. **Blockchain** (BFT + permissionless).
5. **Edge computing**.
6. **CDN**.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Raft (etcd / consul)
```python
# 매 simplified
class RaftNode:
def __init__(self):
self.state = 'follower'
self.term = 0
self.voted_for = None
self.log = []
self.commit_index = 0
def request_vote(self, term, candidate_id, last_log_index, last_log_term):
if term > self.term:
self.term = term
self.state = 'follower'
if self.voted_for in (None, candidate_id) and self.is_log_up_to_date(last_log_index, last_log_term):
self.voted_for = candidate_id
return True
return False
def append_entries(self, term, leader_id, entries):
if term < self.term: return False
self.log.extend(entries)
return True
```
## 🤔 의사결정 기준 (Decision Criteria)
### Sharding (consistent hashing)
```python
import hashlib
from sortedcontainers import SortedList
**선택 A를 써야 할 때:**
- *(TODO)*
class ConsistentHash:
def __init__(self, nodes, virtual_nodes=150):
self.ring = SortedList()
self.node_map = {}
for node in nodes:
for i in range(virtual_nodes):
key = self._hash(f'{node}#{i}')
self.ring.add(key)
self.node_map[key] = node
def _hash(self, s):
return int(hashlib.md5(s.encode()).hexdigest(), 16)
def get_node(self, key):
if not self.ring: return None
h = self._hash(key)
idx = self.ring.bisect_right(h)
if idx == len(self.ring): idx = 0
return self.node_map[self.ring[idx]]
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Saga pattern (distributed transaction)
```python
class OrderSaga:
"""매 매 step + 매 compensating action."""
async def execute(self, order):
completed = []
try:
await self.reserve_inventory(order); completed.append('inventory')
await self.charge_payment(order); completed.append('payment')
await self.create_shipment(order); completed.append('shipment')
return 'success'
except Exception as e:
# 매 compensate in reverse
for step in reversed(completed):
await getattr(self, f'undo_{step}')(order)
return f'failed: {e}'
```
**기본값:**
> *(TODO)*
### Outbox pattern (reliable messaging)
```sql
-- 매 매 transaction 의 outbox row 도 insert
BEGIN;
INSERT INTO orders (...) VALUES (...);
INSERT INTO outbox (event_type, payload, status)
VALUES ('OrderCreated', '{...}', 'pending');
COMMIT;
## ❌ 안티패턴 (Anti-Patterns)
-- 매 separate worker
SELECT * FROM outbox WHERE status = 'pending' LIMIT 100 FOR UPDATE SKIP LOCKED;
-- publish to Kafka
UPDATE outbox SET status = 'published' WHERE id = $1;
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Circuit breaker
```ts
class CircuitBreaker {
state: 'closed' | 'open' | 'half-open' = 'closed';
failures = 0;
lastFailure = 0;
async call<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'open') {
if (Date.now() - this.lastFailure > 30_000) this.state = 'half-open';
else throw new ServiceUnavailable();
}
try {
const r = await fn();
this.state = 'closed';
this.failures = 0;
return r;
} catch (e) {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= 5) this.state = 'open';
throw e;
}
}
}
```
### Vector clock (causal ordering)
```python
class VectorClock:
def __init__(self, node_id, n_nodes):
self.node_id = node_id
self.clock = [0] * n_nodes
def tick(self):
self.clock[self.node_id] += 1
def update(self, other_clock):
self.clock = [max(a, b) for a, b in zip(self.clock, other_clock)]
self.tick()
def happens_before(self, other):
return all(a <= b for a, b in zip(self.clock, other.clock)) and \
any(a < b for a, b in zip(self.clock, other.clock))
```
### CRDT (G-Counter)
```python
class GCounter:
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)
```
### Service mesh (Istio sidecar)
```yaml
# 매 매 Pod 의 Envoy sidecar
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata: { name: orders }
spec:
hosts: [orders]
http:
- route:
- destination: { host: orders, subset: v1, weight: 90 }
- destination: { host: orders, subset: v2, weight: 10 }
fault:
delay: { percentage: { value: 0.1 }, fixedDelay: 5s } # 매 chaos
```
### Distributed tracing
```python
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
@tracer.start_as_current_span('process_order')
def process(order):
with tracer.start_as_current_span('validate'):
validate(order)
with tracer.start_as_current_span('charge'):
charge(order)
with tracer.start_as_current_span('ship'):
ship(order)
```
### Chaos engineering
```python
# 매 Chaos Monkey 식
import random
class ChaosMonkey:
def maybe_kill(self, instance, p=0.001):
if random.random() < p:
log(f'CHAOS: killing {instance.id}')
instance.terminate()
```
## 매 결정 기준
| 상황 | Pattern |
|---|---|
| Strong consistency | Raft / Paxos (etcd, CockroachDB) |
| High availability | Eventual + CRDT (Cassandra, DynamoDB) |
| Distributed transaction | Saga + Outbox |
| Service-to-service | Service mesh |
| High-throughput msg | Kafka |
| Real-time low-latency | NATS / Redis |
| Multi-region read | CDN / Edge cache |
| Cross-region write | Spanner / FoundationDB |
**기본값**: 매 K8s + service mesh + Raft for state + Kafka for events + tracing.
## 🔗 Graph
- 부모: [[Software-Architecture]] · [[System-Design]] · [[Computer-Science]]
- 변형: [[CAP-Theorem]] · [[PACELC]] · [[Microservices]] · [[Service-Mesh]] · [[CRDT]]
- 응용: [[Raft]] · [[Paxos]] · [[Saga]] · [[Outbox]] · [[Circuit-Breaker]]
- Tools: [[Kafka]] · [[Cassandra]] · [[etcd]] · [[Spanner]] · [[Kubernetes]]
- Adjacent: [[Availability-and-Persistence]] · [[Architecture-Styles]] · [[Bottlenecks]] · [[Antifragility]]
## 🤖 LLM 활용
**언제**: 매 system design. 매 scalability planning. 매 reliability engineering. 매 multi-region.
**언제 X**: 매 single-machine app. 매 prototype.
## ❌ 안티패턴
- **8 fallacies 의 ignore**.
- **Distributed monolith** (sync chain).
- **Synchronous everything** (no event-driven).
- **No idempotency** (retry corruption).
- **No observability**.
- **Premature microservices**.
- **No circuit breaker** (cascade fail).
## 🧪 검증 / 중복
- Verified (Kleppmann "DDIA", Raft paper, Paxos paper, Google papers).
- 신뢰도 A.
- Related: [[CAP-Theorem]] · [[Availability-and-Persistence]] · [[Architecture-Styles]] · [[Bottlenecks]] · [[Bounded-Contexts]] · [[Antifragility]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 8 fallacies + patterns + 매 Raft / sharding / Saga / Outbox / circuit breaker / CRDT code |