[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
@@ -2,91 +2,183 @@
id: wiki-2026-0508-load-balancing-strategies
title: Load Balancing Strategies
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [SYS-LB-001]
aliases: [Load Balancer, LB, Reverse Proxy]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [infrastructure, load-balancing, high-availability, Scalability, _system-design]
confidence_score: 0.9
verification_status: applied
tags: [networking, load-balancer, nginx, envoy, haproxy, aws-alb]
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
tech_stack: { language: Config, framework: Nginx/Envoy/HAProxy/AWS }
---
# Load Balancing Strategies (부하 분산 전략)
# Load Balancing Strategies
## 📌 한 줄 통찰 (The Karpathy Summary)
> "단일 지점의 과부하를 방지하고 시스템 전체의 체력을 균형 있게 활용하여, 어떠한 파도(Traffic)에도 무너지지 않는 견고한 요새를 구축하라" — 클라이언트의 요청을 여러 서버로 효율적으로 분산시켜 응답 시간을 최적화하고 특정 서버의 장애가 전체 서비스 중단으로 이어지지 않게 하는 시스템 아키텍처 전략.
## 한 줄
> **"매 LB = traffic 분산 + health check + sticky"**. 알고리즘은 균등성과 affinity의 trade-off.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Distributed Traffic Mediation" — 중앙의 로드 밸런서가 각 노드의 상태를 실시간으로 확인(Health Check)하고, 가용한 자원에게 요청을 지능적으로 전달하여 시스템의 가용성과 확장성을 동시에 확보하는 중재 패턴.
- **주요 알고리즘:**
- **Round Robin:** 서버 순서대로 차례차례 할당. 서버 성능이 동일할 때 유리.
- **Least Connections:** 현재 연결 수가 가장 적은 서버 우선. 작업 처리 시간이 제각각일 때 효과적.
- **IP Hash:** 클라이언트 IP를 해싱하여 특정 서버에 고정(Sticky Session). 세션 유지가 필요할 때 사용.
- **Weighted Strategies:** 서버 사양에 따라 가중치를 부여하여 더 좋은 서버에 더 많은 부하 배정.
- **L4 vs L7:**
- **L4 (Transport Layer):** IP/Port 기반 분산. 빠르지만 세밀한 제어 불가.
- **L7 (Application Layer):** URL, 쿠키, 헤더 등 콘텐츠 기반 분산. 지능적인 라우팅 가능.
## 매 핵심
### 매 알고리즘
- **Round-robin**: 순차. 단순, 동질 서버.
- **Weighted RR**: 용량 차등.
- **Least connections**: 활성 연결 최소. long-lived 적합.
- **Least response time**: 평균 응답 + connection 수.
- **IP hash**: client IP→server. session affinity.
- **Consistent hash**: cache/shard. node 추가 시 K/n key만 재배치.
- **Random / P2C**: power of two choices, least-loaded 선택. 간단·강력.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 고가의 하드웨어 장비 중심에서, 이제는 클라우드 기반의 탄력적 로드 밸런싱(ELB, ALB)과 서비스 메시(Service Mesh)를 통한 정교한 트래픽 제어로 패러다임 전환.
- **정책 변화:** Antigravity 프로젝트의 백엔드 아키텍처는 L7 로드 밸런싱을 통해 에이전트 요청의 유형(지식 검색 vs 모델 생성)에 따라 최적화된 연산 노드로 트래픽을 라우팅함.
### 매 Layer
- **L4 (TCP/UDP)**: 빠름, opaque. NLB, HAProxy TCP mode.
- **L7 (HTTP)**: header/path 기반 라우팅, TLS 종료. ALB, Nginx, Envoy.
## 🔗 지식 연결 (Graph)
- [[High-Availability-Systems|High-Availability-Systems]], System-Design-for-AI-Scale, Cloud-Computing-Foundations, [[Kubernetes-for-AI-Orchestration|Kubernetes-for-AI-Orchestration]]
- **Raw Source:** 10_Wiki/Topics/AI/Load-Balancing-Strategies.md
### 매 Health check
- Active: /health 주기적 GET
- Passive: 실제 요청 실패 카운트
- Slow start: 신규 노드에 점진적 traffic
- Outlier detection (Envoy): 연속 5xx → eject
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Session affinity (sticky)
- Cookie-based (LB가 cookie 발급)
- Source IP (NAT 뒤에 모이면 unbalanced)
- Header-based (custom)
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Web app: ALB + multi-AZ
2. gRPC/HTTP2: Envoy (L7 multiplex)
3. DB read replica: ProxySQL, PgBouncer
4. Cache shard: consistent hash (Redis cluster)
5. Service mesh: Envoy sidecar (Istio, Linkerd)
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
## 💻 패턴
### Nginx upstream
```nginx
upstream backend {
least_conn; # algorithm
server app1:8080 weight=3 max_fails=3 fail_timeout=30s;
server app2:8080 weight=1;
server app3:8080 backup; # only if others down
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_next_upstream error timeout http_502 http_503;
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### HAProxy
```
backend web
balance leastconn
option httpchk GET /health
server s1 10.0.0.1:8080 check weight 100
server s2 10.0.0.2:8080 check weight 50
cookie SRV insert indirect nocache # sticky
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Envoy (L7, gRPC)
```yaml
clusters:
- name: api
type: STRICT_DNS
lb_policy: LEAST_REQUEST
health_checks:
- timeout: 1s
interval: 5s
http_health_check: { path: "/health" }
outlier_detection:
consecutive_5xx: 5
base_ejection_time: 30s
load_assignment:
cluster_name: api
endpoints:
- lb_endpoints:
- endpoint: { address: { socket_address: { address: api1, port_value: 8080 }}}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### AWS ALB (Terraform)
```hcl
resource "aws_lb" "app" {
name = "app-alb"
load_balancer_type = "application"
subnets = var.public_subnets
}
resource "aws_lb_target_group" "api" {
port = 8080
protocol = "HTTP"
health_check { path = "/health"; interval = 15 }
stickiness { type = "lb_cookie"; enabled = true }
}
```
**기본값:**
> *(TODO)*
### Consistent hash (Python sketch)
```python
import bisect, hashlib
class Ring:
def __init__(self, nodes, vnodes=150):
self.ring = []
for n in nodes:
for i in range(vnodes):
h = int(hashlib.md5(f"{n}-{i}".encode()).hexdigest(), 16)
bisect.insort(self.ring, (h, n))
def get(self, key):
h = int(hashlib.md5(key.encode()).hexdigest(), 16)
i = bisect.bisect(self.ring, (h, ""))
return self.ring[i % len(self.ring)][1]
```
## ❌ 안티패턴 (Anti-Patterns)
### P2C (power of two choices)
```python
import random
def p2c(servers, load):
a, b = random.sample(servers, 2)
return a if load[a] <= load[b] else b
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | LB / 알고리즘 |
|---|---|
| AWS web app | ALB + round_robin |
| TCP / 빠름 | NLB / HAProxy L4 |
| gRPC, mesh | Envoy least_request |
| Cache shard | Consistent hash |
| DB connection pool | PgBouncer/ProxySQL |
| Bare metal HTTP | Nginx least_conn |
| 동질 서버 + short req | RR/Random |
| 이질 서버 / long conn | Weighted least-conn |
**기본값**: HTTP는 ALB or Nginx least_conn. 마이크로서비스는 Envoy.
## 🔗 Graph
- 부모: [[Distributed-Systems]], [[Networking]]
- 변형: [[Consistent-Hashing]], [[Reverse-Proxy]]
- 응용: [[High-Availability]], [[Service-Mesh]], [[CDN]]
- Adjacent: [[Health-Check]], [[Auto-Scaling]], [[API-Gateway]]
## 🤖 LLM 활용
**언제**: config 작성, 알고리즘 선택, troubleshoot 가설.
**언제 X**: production tuning은 metric 기반 검증 필수.
## ❌ 안티패턴
- IP hash + NAT/CGNAT (모든 client가 한 노드)
- Sticky session 과의존 → 노드 죽으면 세션 다 잃음
- Health check 너무 짧은 interval → flapping
- L7 LB에서 keepalive 비활성화 → 성능↓
- Hash ring vnode 부족 → 불균형
- TLS termination만 보고 backend mTLS 무시
## 🧪 검증 / 중복
- Verified (Nginx/Envoy/HAProxy docs, Mitzenmacher P2C, AWS ELB docs). 신뢰도 A.
- 중복: 없음.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Envoy/AWS/consistent-hash 코드 추가 |