Skip to content

บทที่ 6 — Modern Patterns

← บทที่ 5 | สารบัญ

หลังจบบทนี้ คุณจะสามารถ:

  • เข้าใจหลักของ Service Mesh, Sidecar, Ambassador
  • ใช้ CRDT สำหรับ collaborative app
  • ทำ eventually consistent UI
  • รู้จัก gossip protocol (กอส-ซิป โพรโตคอล — โพรโตคอลแบบ "ซุบซิบ" คือ node แต่ละตัวสุ่มกระจายข่าวให้เพื่อนบ้านเหมือนข่าวลือ) และ anti-entropy
  • เห็นภาพรวมของ distributed systems ในยุคปี 2026 เป็นต้นไป

1. Service Mesh — เลเยอร์ network ที่จัดการ cross-cutting concerns

คำศัพท์เริ่มต้น: cross-cutting concern = ปัญหา/feature ที่ "ตัดผ่าน" ทุก layer ของระบบ — ทุก service ต้องทำเหมือนกันหมด เช่น retry, timeout, logging, security, observability; แทนที่จะให้แต่ละ service เขียนซ้ำ → ย้ายไปอยู่ที่ infrastructure ชั้นเดียวจบ

text
ปัญหา:
- มี microservice เยอะ
- แต่ละตัวต้องมี cross-cutting concern เหมือนกัน:
    retry, timeout, circuit breaker, mTLS, tracing, metrics
- ถ้า implement ในทุก service: เขียนซ้ำ + ไม่สม่ำเสมอ

ทางแก้: Service Mesh
- ย้าย cross-cutting concern (เรื่องที่ "ตัด" ผ่านทุก layer — logging, auth,
  security ที่ทุก service ต้องทำเหมือนกัน) ไปอยู่ที่ network layer
- มี sidecar proxy 1 ตัวต่อ 1 service
- config รวมศูนย์ (control plane)

สถาปัตยกรรม

📝 Sidecar (ไซด์-คาร์ = รถพ่วงข้าง) — มาจาก "รถพ่วงข้างมอเตอร์ไซค์" — service ที่ "พ่วง" ติดกับ service หลักแบบ 1:1 อยู่ใน pod เดียวกัน แชร์ network localhost กัน

Sidecar handles: mTLS, retry/timeout/circuit breaker, routing (canary, A/B), observability (metrics, traces, logs), rate limiting.

เครื่องมือที่นิยม

text
Istio:
- Most features
- Steep learning curve
- ปี 2026: Istio 1.25 — Ambient Mesh production-grade (sidecar-less, ใช้ Ztunnel L4 + Waypoint L7)
- Used in: large enterprises, Google

Linkerd:
- Simpler than Istio
- Linkerd 2.16 (2025+):
    - control plane = Go
    - data plane proxy (linkerd2-proxy) = Rust (efficient, memory-safe)
- Good for medium scale

Cilium Service Mesh:
- Sidecar-less ตั้งแต่ day 1 (ใช้ eBPF ใน kernel)
- รวม CNI + service mesh เป็นชุดเดียว — ลด component
- Production: Datadog, Capital One, IKEA, Form3

Consul Connect (HashiCorp):
- Service mesh + service discovery
- Multi-platform

AWS App Mesh:
- Managed
- Tight AWS integration

Kuma / Kong Mesh:
- Universal (K8s + VMs)

เมื่อไหร่ควรใช้ Service Mesh

text
✅ 50+ microservices
✅ Multi-language
✅ Need consistent cross-cutting (security, observability)
✅ K8s already in place

❌ Small app (10 services)
❌ Don't have ops capacity
❌ Latency-sensitive — sidecar adds latency:
    - sidecar Envoy classic: ~0.3-1ms (optimized) ถึง 1-3ms (L7 + mTLS)
    - Ambient mesh / Cilium sidecar-less: < 0.1ms typical

→ ทางเลือกในยุคนี้: gRPC + interceptors แยกตามภาษา (ลด infra ที่ต้องดูแล)

eBPF Era — ปฏิวัติ observability + security + networking (ปี 2024-2026)

⚠️ (ขั้นต่อยอด · SRE/Platform engineer) — basic app dev ทั่วไป ข้าม section นี้ได้; section นี้สำหรับคนที่ดูแล K8s cluster ขนาดใหญ่ หรือทำงานในทีม Infrastructure

⚠️ มือใหม่: section นี้ใส่ tool หลายตัวมาก (Falco, Pixie, Cilium, Tetragon ฯลฯ) — ผ่านได้ กลับมาเมื่อต้องดูแล K8s production ใหญ่ ๆ

text
eBPF (อี-บี-พี-เอฟ = extended Berkeley (เบิร์ก-ลีย์) Packet Filter):
- โปรแกรมที่รัน sandboxed ใน Linux kernel โดยไม่ต้อง patch kernel
- ลด overhead ของ kernel hook 10-100x เทียบกับ traditional approach
- Programming model: C/Rust → BPF bytecode → JIT compile in kernel

3 use cases หลักในวงการปี 2026:

1. Observability (สังเกตการณ์):
   - Falco — runtime security events (CNCF Graduated 2024)
   - Pixie — auto-instrument Go/C++ apps (no code change)
   - Parca — continuous profiling

2. Networking + Service Mesh:
   - Cilium — CNI + service mesh (sidecarless)
   - Calico eBPF mode — high-perf K8s networking
   - Katran — L4 load balancer (Meta open-source)

3. Security:
   - Tetragon (Cilium) — runtime security enforcement
   - Tracee (Aqua) — runtime threat detection
   - Falco — alert on suspicious syscalls

Performance advantage:
- Cilium service mesh: เคลม 50% less CPU vs Istio sidecar (benchmark ของ Cilium เอง; independent benchmark โดยทั่วไปวัดได้ 20-50% ขึ้นกับ workload)
- Falco: < 1% CPU overhead for kernel-wide tracing
- Pixie: ~3% CPU for full observability

Tooling:
- bpftrace — DTrace-like CLI for ad-hoc tracing
- libbpf — modern eBPF library (replaces BCC)
- aya — Rust eBPF library

สรุป tool eBPF ที่นิยม (อ่านชื่อ + บทบาท):

Toolคำอ่านบทบาท
Ciliumซิ-เลียมCNI + sidecar-less service mesh (CNCF Graduated)
Falcoฟัล-โคruntime security event (CNCF Graduated 2024)
Tetragonเท-ตรา-กอนruntime security enforcement (โดย Cilium)
Pixieพิก-ซีauto-instrument observability (no code change)

📚 เรียนต่อ: "Learning eBPF" (Liz Rice, 2023) — free ebook

🚀 Quickstart (basic ที่อยากลอง): Cilium "Getting Started Guide" (K8s) → Istio Ambient Mesh docs "Install" → Falco "Quickstart" — แต่ละตัวมี Helm chart 1 command setup

Service Mesh Config — ตัวอย่าง Istio

ลองดู config จริงสำหรับ feature ที่นิยม

📝 หมายเหตุสำหรับมือใหม่: นี่คือไฟล์ config สำหรับ Kubernetes (K8s) — ไม่ต้องเข้าใจทุกบรรทัด ดูแค่ส่วนที่ comment ภาษาไทยกำกับ เพื่อจับหลักว่า service mesh ทำอะไรให้ได้บ้าง; ตัว Istio object หลักที่ใช้ในตัวอย่าง:

  • VirtualService — กำหนด routing rules (ส่ง traffic ไปไหน, retry, timeout)
  • DestinationRule — กำหนด policy ฝั่งปลายทาง (connection pool, circuit breaker)
  • PeerAuthentication — กำหนด mTLS mode
  • AuthorizationPolicy — กำหนดว่าใครเรียกใครได้ (RBAC)

1. Retry + Timeout per route

yaml
apiVersion: networking.istio.io/v1beta1   # Istio networking API
kind: VirtualService                       # ← กำหนด routing rule
metadata:
  name: payment-service                    # ชื่อ rule
spec:
  hosts:
  - payment-service                        # ใช้กับ service ปลายทางชื่อนี้
  http:
  - route:
    - destination:
        host: payment-service              # ส่งไป service จริงตัวเดิม (no version split)
    timeout: 5s              # หากไม่ตอบใน 5s = abort
    retries:
      attempts: 3            # ลอง 3 ครั้ง
      perTryTimeout: 2s      # แต่ละครั้ง max 2s
      retryOn: 5xx,gateway-error,connect-failure,reset   # retry เมื่อเจอ error เหล่านี้

2. Circuit Breaker

yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: payment-service
spec:
  host: payment-service
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
        http2MaxRequests: 100
    outlierDetection:           # ← Circuit breaker
      consecutive5xxErrors: 5   # 5 errors ติดกัน
      interval: 30s             # ดูทุก 30s
      baseEjectionTime: 60s     # ถูก eject 60s
      maxEjectionPercent: 50    # eject ไม่เกิน 50% ของ pods

3. Canary Deployment (10% traffic ไป version ใหม่)

yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: payment-canary
spec:
  hosts:
  - payment-service
  http:
  - route:
    - destination:
        host: payment-service
        subset: v1
      weight: 90               # 90% ไป version เดิม
    - destination:
        host: payment-service
        subset: v2
      weight: 10               # 10% ไป version ใหม่

4. mTLS (Service-to-Service Encryption)

yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
spec:
  mtls:
    mode: STRICT      # ทุก service ต้องใช้ mTLS, reject plaintext

5. RBAC (Who can call whom)

yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: allow-orders-to-payment
spec:
  selector:
    matchLabels:
      app: payment-service
  rules:
  - from:
    - source:
        principals: 
        - cluster.local/ns/default/sa/order-service
    to:
    - operation:
        methods: ["POST"]
        paths: ["/charge"]

→ ทั้ง 5 features นี้ — ทำใน app code = ใช้เวลาเป็นเดือน, ใช้ service mesh = config 10-50 บรรทัด

Performance Impact — ผลกระทบด้านประสิทธิภาพ

text
Sidecar (Envoy) overhead:
- Latency: +0.5-3 ms per hop ขึ้นกับ L4 vs L7 + mTLS
    - L4 plaintext: ~0.5 ms
    - L7 + mTLS (production): 1-3 ms
- Memory: ~50-100 MB per pod
- CPU: 0.1-0.5 core per pod

Trade-off:
- 100 microservices × 2 hops/request = +50-100ms ในระบบใหญ่
- ROI ดีถ้า security/observability เป็น top priority
- ไม่ดีถ้า ultra-low-latency (high-frequency trading)

Alternative: Sidecarless mesh (Cilium, Ambient Mesh)
- ใช้ eBPF / shared proxy
- Lower overhead (50% less CPU, 30% less memory เทียบกับ sidecar)
- ✅ Production-ready ปี 2026 (ดู update ข้างล่าง)

📅 Sidecarless Mesh — production status update (2026):

  • Cilium Service Mesh — GA ตั้งแต่ 2022; production use: Datadog, Capital One, Cybozu, IKEA, Form3
  • Istio Ambient Mesh — GA Q4 2024 (Istio 1.24); ใช้ Ztunnel (L4 sidecar-less) + Waypoint proxy (L7 ตามต้องการ); Istio 1.25 (2025) เพิ่ม L7 feature ระดับ production ใน waypoint proxy
  • Linkerd 2.16 — data plane (linkerd2-proxy) = Rust, control plane = Go; ไม่ใช่ Rust ทั้งระบบ
  • Cilium + Tetragon — eBPF security + L7 observability ครบชุด

คำแนะนำปี 2026:

  • new deployment → พิจารณา sidecarless ก่อน (Cilium SM ถ้าใช้ Cilium CNI; Ambient ถ้าใช้ Istio)
  • existing sidecar → migrate ไม่เร่งด่วน; benefits มากเมื่อ scale > 50 services
  • ultra-low latency (HFT, AdTech) → eBPF kernel-bypass = sidecarless ได้ผลดีกว่ามาก

2. Sidecar Pattern — เพื่อนข้าง ๆ ที่ช่วยทำงาน

sidecar คือการรัน process ผู้ช่วยไว้ "ข้าง ๆ" แอปหลักใน pod เดียวกัน โดยแชร์ network และ volume — แอปหลักโฟกัสที่ business logic ส่วนงานทั่วไป (proxy, เก็บ log, service mesh) ยกให้ sidecar จัดการ เป็นรากฐานของ pattern อย่าง ambassador และ adapter:

text
"Run helper process alongside main app"

[Pod (K8s)]
├── Main Container: your app
└── Sidecar Container: helper (Envoy, Fluentbit, etc.)

Both share:
- Network (localhost)
- Volume (logs, files)

Sidecar examples:
- Envoy (proxy)
- Fluentbit (log collector)
- Istio sidecar
- Service registration agent

→ Sidecar เป็นรูปทั่วไปของ pattern อย่าง "ambassador" และ "adapter"

เปรียบเทียบ 3 รูปแบบ:

Patternทำอะไรหลักตัวอย่างจริง
Sidecar (ทั่วไป)helper ข้าง main app ทำงาน cross-cuttingEnvoy proxy, Fluentbit log collector
Ambassadorsidecar เฉพาะการเรียก "ออก" (outbound) — auth/retry/protocolproxy ที่ทำ TLS termination หรือ auth header
Adaptersidecar ที่ "แปลง" interface — protocol conversionsidecar ที่แปลง app metrics → Prometheus format

3. Ambassador Pattern — sidecar เฉพาะการเรียกออก

ambassador เป็น sidecar รูปแบบเฉพาะที่ดูแล "การเรียกออกไปข้างนอก" แทนแอป — มันจัดการ retry, auth, encryption, connection pooling ให้ ทำให้แอปหลักเรียก HTTP ธรรมดา ๆ ได้โดยไม่ต้องรู้จัก protocol ซับซ้อน:

text
Sidecar that handles outbound calls

[Main App] → [Ambassador] → [External]

Ambassador handles:
- Retry
- Authentication
- Encryption
- Connection pooling

Use:
- App can use simple HTTP (no auth library)
- Ambassador handles complex protocol

4. Backend for Frontend (BFF) — backend ต่อ frontend

BFF = backend layer ที่ปรับแต่งข้อมูลให้เหมาะกับ frontend แต่ละแบบ (web/mobile/TV) ดู glossary บท 11

→ แยกการพัฒนา frontend ออกจาก backend อย่างชัดเจน


5. API Composition / Federation — รวม API ข้าม service

เมื่อ client ต้องการข้อมูลที่กระจายอยู่หลาย service จะรวมยังไง? มี 3 ทาง: API composition (gateway เรียกทุก service มารวม แต่ latency = ผลรวม), GraphQL Federation (หลาย service ร่วมกันเป็น schema เดียว), หรือ CQRS read model (เก็บ view ที่ join ไว้ล่วงหน้า อ่านครั้งเดียวจบ) แต่ละแบบเหมาะกับสถานการณ์ต่างกัน:

text
For complex query across services:

Option 1: API Composition
- BFF/Gateway aggregates by calling each service
- Sequential or parallel
- Issue: latency = sum of (or max of) all calls

Option 2: GraphQL Federation
- Multiple services contribute to single schema
- Client queries logical schema, federation gateway calls services
- Apollo Federation, Hot Chocolate

Option 3: CQRS read model
- Maintain materialized view of joined data
- Updated via events
- Read = single query

6. Edge Computing — run code ที่ขอบ network

แทนที่จะรันโค้ดในศูนย์ข้อมูลเดียวที่อาจไกลจากผู้ใช้ edge computing รันโค้ดที่ "ขอบ" network ใกล้ผู้ใช้ทั่วโลก (เช่น Cloudflare Workers ที่ 250+ จุด) ทำให้ latency ต่ำมาก เหมาะกับงานเบา ๆ ที่ต้องเร็ว เช่น auth, A/B test, personalization, bot detection:

text
Run code at edge of network (near user)

Cloudflare Workers:
- Run JS / WebAssembly at 300+ data centers
- < 50ms latency to most users globally
- CPU limit ขึ้นกับ plan:
    - Free: ~10ms CPU/request
    - Bundled (paid): 50ms CPU/request
    - Unbound: up to 30s CPU/request

Use cases:
- Authentication
- A/B testing
- Personalization
- Bot detection
- Image transformation
- API caching + rate limiting

Tools:
- Cloudflare Workers (V8 isolates + Wasm)
- Fastly Compute@Edge (Wasmtime + WASI — WebAssembly-native)
- AWS Lambda@Edge / CloudFront Functions
- Vercel Edge (V8 isolates)
- Deno Deploy

💡 WebAssembly at edge: Wasm กลายเป็น runtime หลักของ edge compute ปี 2024+ — เพราะ cold start ~1ms (เทียบ container ~200-1000ms), sandboxed, รองรับหลายภาษา (Rust/Go/JS); Fastly Compute@Edge ใช้ Wasm 100%, Cloudflare Workers รองรับทั้ง V8 isolate + Wasm


7. Database Geo-Replication ยุคใหม่ — DB ที่กระจายข้าม region

แอปที่มีผู้ใช้ทั่วโลกอยากให้ทุกภูมิภาคเข้าถึง DB ได้เร็ว — DB ยุคใหม่จึงกระจายข้าม region โดยอัตโนมัติ มีหลายตัวให้เลือกตาม trade-off: CockroachDB/YugabyteDB (strong consistency ทั่วโลกด้วย HLC) หรือ Aurora Global (async ง่ายกว่าแต่มี lag) มาดูจุดเด่นของแต่ละตัว:

CockroachDB — เลียนแบบแนวคิดของ Spanner

text
Multi-region distributed SQL
- Each row/table can specify "home region"
- Auto-replication
- Strong consistency globally (HLC + uncertainty intervals)
  → ความ correctness ขึ้นกับ `max_offset` bound (default 500ms)
    ที่ NTP-synced clocks ต้องเคารพ — ถ้า clock skew เกิน, node จะ crash
    ตัวเอง (fail-safe) ไม่ใช่คืน wrong data

Survives:
- Single region failure
- Multiple AZ failures
- Lower latency than Spanner (HLC vs TrueTime hardware clock)

YugabyteDB — distributed SQL ที่ Postgres-compatible

text
Similar to CockroachDB
- Distributed SQL
- Postgres-compatible
- Multi-region

Aurora (AWS) — managed cross-region

text
Aurora Global Database:
- 1 primary region + up to 5 read-only regions
- Async replication (~1 sec lag)
- Failover:
    - **Managed failover** (planned): < 1 min RTO, RPO ≈ 0
    - **Unplanned failover** (disaster): ~1 min RTO, อาจมี data loss ภายในกรอบ RPO

Trade-off: async = lag, but simpler than full multi-master

8. CRDT Use Cases — การใช้งานในปัจจุบัน

Collaborative Editing — แก้เอกสารร่วมกัน

text
Production CRDT libraries (ปี 2024-2026):

Yjs (JS/TS) ⭐ — most mature, **basic เริ่มจากที่นี่ (community ใหญ่สุด, docs ครบ)**
- Used by: Linear (issues), Notion (some features), JupyterLab RTC
- Optimized binary protocol, conflict-free RGA for text
- Performance: 10K+ ops/sec, < 1MB memory for large docs
- **Tiptap** (ProseMirror + Yjs collaborative editor framework) ใช้ Yjs ภายใน — เป็น standard ของ collaborative rich-text editor ปี 2024-2026 (GitLab, Linear, อื่น ๆ)

Automerge (JS/Rust)
- Used by: PushPin, internal tools at Ink & Switch
- JSON-CRDT (whole document, not just text)
- Better for structured data than text

Loro (Rust + WASM, 2023+) — emerging
- Performance-focused, smaller payload than Yjs
- Used by: some new collaborative apps

Diamond Types (Rust + WASM, 2022)
- Specifically for text editing
- Very fast (~10x Yjs in benchmarks)

State-based vs Operation-based CRDT

text
State-based (CvRDT):
- Each replica sends ENTIRE state to others
- Merge = converge by lattice rules
- Examples: G-Counter, OR-Set, LWW-Register
- Pro: simpler, no message ordering needed
- Con: bandwidth heavy

Operation-based (CmRDT):
- Each replica sends OPERATIONS
- Need reliable causal broadcast
- Examples: most text editing CRDTs (RGA, Treedoc)
- Pro: bandwidth efficient
- Con: requires reliable delivery + causal order

Delta-CRDT (modern):
- Hybrid: send "delta state" not full
- Used in Yjs, Automerge

Real-world architecture (Linear / Figma pattern)

text
Client (Browser/Mobile):
- CRDT instance (Yjs)
- Local-first writes (immediate UX)
- Persist to IndexedDB / SQLite

Sync server:
- WebSocket (real-time) or HTTP (polling)
- Append-only event log
- Broadcast to other clients

Conflict resolution:
- CRDT auto-merges (deterministic)
- No "last write wins" needed
- All clients converge to same state guaranteed

📚 เรียนต่อ: crdt.tech — comprehensive reference + papers; Yjs docs; Ink & Switch's "Local-First Software" essay (Kleppmann et al. 2019)

Offline-First Apps — ใช้งานได้แม้ offline

text
User edits offline → syncs when online

Without CRDT:
- Conflict resolution complex
- May lose data

With CRDT:
- Auto-converge on sync
- No manual resolution
- Used: Linear, mobile note apps

Distributed Counters — ตัวนับแบบกระจาย

text
G-Counter:
- Each node tracks own count
- Total = sum
- Always converges

Use:
- Page view counter
- Like count
- Vote count
- No coordination needed

Sets — set แบบกระจาย

text
OR-Set (Observed-Remove):
- Add: insert with unique tag
- Remove: only items we observed
- Merge: union of adds, exclude removes
- Allow add + remove with convergence

Use:
- Collaborative todo list
- Multi-user permission set

9. Eventually Consistent UI — UI ที่ optimistic ก่อน

eventual consistency ไม่ได้อยู่แค่ฝั่ง backend — ฝั่ง UI ก็จัดการได้ด้วย "optimistic update": อัปเดตหน้าจอทันทีโดยสมมติว่าสำเร็จ (เช่นกดไลก์แล้วปุ่มเปลี่ยนเลย) แล้วค่อย rollback ถ้า server ตอบ fail ทำให้ UX ลื่นไหลแม้ network ช้า แลกกับความ inconsistent ชั่วครู่:

text
Optimistic UI:
- Update UI immediately (assume success)
- Send request to server
- Rollback if fail

Example:
- User clicks "Like"
- UI: button immediately filled
- Server: process like
- If fail: rollback UI + show error

✅ Snappy UX
❌ Brief inconsistency
❌ Rollback awkward

TanStack Query Pattern — optimistic mutation

typescript
// Optimistic mutation
const likeMutation = useMutation({
    mutationFn: (postId) => api.like(postId),
    
    onMutate: async (postId) => {
        // Cancel outgoing queries
        await queryClient.cancelQueries({ queryKey: ['posts'] });
        
        // Snapshot current
        const previous = queryClient.getQueryData(['posts']);
        
        // Optimistically update
        queryClient.setQueryData(['posts'], old => 
            old.map(p => p.id === postId 
                ? { ...p, liked: true, likeCount: p.likeCount + 1 }
                : p
            )
        );
        
        return { previous };
    },
    
    onError: (err, postId, context) => {
        // Rollback
        queryClient.setQueryData(['posts'], context.previous);
    },
    
    onSettled: () => {
        // Refetch to ensure consistency
        queryClient.invalidateQueries({ queryKey: ['posts'] });
    }
});

10. Real-time Collaborative Patterns — รูปแบบทำงานร่วมแบบ real-time

แอปอย่าง Google Docs / Figma ที่หลายคนแก้พร้อมกันแบบเห็น cursor กันสด ๆ ต้องใช้รูปแบบเฉพาะ — เชื่อมทุก client ด้วย WebSocket ไปยัง server ที่ถือ state กลาง แล้วใช้ CRDT หรือ OT จัดการ conflict ของการแก้ที่ชนกัน ส่วนนี้เจาะสถาปัตยกรรมของระบบ collaborative:

Server maintains canonical document state. Clients optimistically update + send changes. CRDT preferred in modern systems (simpler).

ตัวอย่าง Yjs

typescript
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';

const ydoc = new Y.Doc();
const provider = new WebsocketProvider('wss://example.com', 'room-1', ydoc);

// Shared types
const ytext = ydoc.getText('content');

// Listen
ytext.observe(() => {
    console.log('Text changed:', ytext.toString());
});

// Edit
ytext.insert(0, 'Hello, ');

// → Auto-synced with other clients in 'room-1'

11. Gossip Protocol — "ข่าวลือ" ที่ scale ได้

Intuition — ทำไม Gossip ดีกว่า broadcast?

text
ปัญหา: ใน cluster ขนาด 1000 nodes — แต่ละ node จะรู้สถานะของ node อื่นได้ยังไง?

Naive approach (Centralized):
   ทุก node → ping master → master broadcast ให้ทุกตัว
   ❌ Master = SPOF
   ❌ Master scaling ยาก (1000 × ping)

Naive approach (Full mesh):
   ทุก node → ping ทุกตัวอื่น
   ❌ O(N²) network — ระเบิดที่ N > 50

Gossip approach:
   ทุก node → ping random 3-5 ตัวต่อรอบ
   ผ่านไป log(N) รอบ → ทุก node รู้ข่าว
   ✅ O(N log N) network — scale ได้
   ✅ ไม่มี SPOF

Algorithm — Anti-entropy Gossip (ลด entropy ระหว่าง node)

text
ทุก ๆ T วินาที (เช่น 1 วินาที):
  
1. Node A เลือก peer B แบบ random
2. A → B: "ฉันรู้ X, Y, Z (with version)"
3. B compare กับของตัวเอง:
   - ของ A ใหม่กว่า → B copy ของ A
   - ของ B ใหม่กว่า → B ส่งกลับให้ A
   - ทั้งคู่เหมือนกัน → ไม่ทำอะไร
4. ทั้งสองนั้น sync (anti-entropy)

Trace — ข่าวลือกระจาย

text
สมมุติ 8 nodes: A, B, C, D, E, F, G, H
Event: node A เพิ่งรู้ว่า "X = 5"

Round 1: A gossip ไป random peer (เช่น B)
   รู้ข่าว: {A, B}

Round 2: A, B gossip ไป random peers (เช่น C, D)
   รู้ข่าว: {A, B, C, D}

Round 3: 4 ตัวที่รู้ → gossip ไปอีก 4
   รู้ข่าว: {A, B, C, D, E, F, G, H}  ← all 8 nodes ❤

→ N = 8 ใช้แค่ 3 รอบ
   N = 1000 ใช้ ~10 รอบ (log₂ 1000 = ~10)

คุณสมบัติของ Gossip

text
✅ Scales: O(log N) rounds for full propagation
✅ Fault tolerant: ไม่มี SPOF, lose 30% nodes ก็ยังทำงาน
✅ Eventually consistent: ทุก node converge ในที่สุด
✅ Adaptive: random peer selection หลีกเลี่ยง hot spot

❌ Latency: เน้น throughput, ไม่ใช่ real-time
❌ Bandwidth: redundant gossip (ส่งซ้ำให้ peer ที่รู้แล้ว)
❌ Eventually only: ระยะสั้น อาจไม่ตรงกัน

ระบบจริงที่ใช้ Gossip

text
- Cassandra (แคส-ซาน-ดรา — membership + failure detection)
- Dynamo / Riak (replica sync)
- Consul + Serf (service discovery)
- Bitcoin (block propagation)
- HashiCorp Memberlist (general-purpose)

Variants — แบบ Push / Pull / Push-Pull

text
Push:
  A → B "ฉันมี X, Y, Z"
  → ส่งข่าว, ไม่สนว่า B รู้แล้วหรือไม่
  → Bandwidth สูง

Pull:
  A → B "เธอมีอะไรบ้าง?"
  B ตอบ
  → Bandwidth ต่ำกว่า แต่ slow propagation

Push-Pull (most common):
  A ↔ B exchange summaries → reconcile
  → Best of both

Phi Accrual Failure Detector ใน Cassandra

ใน Cassandra — gossip + phi accrual ผสมกัน:

text
Each node maintains "phi" (suspicion level) ของ peers

ปกติ: heartbeat มาทุก 1 วินาที ± 0.1
ถ้าหายไป 3 วินาที → phi เริ่มสูง
ถ้าหายไป 10 วินาที → phi > threshold → ประกาศ DOWN

ดียังไง:
- ไม่ใช่ "yes/no" แต่เป็น "ความน่าจะเป็น"
- Adaptive: ปรับ threshold ตาม network variance
- ดีกว่า fixed timeout

ดู บทที่ 0 — Failure Detection สำหรับรายละเอียดของ phi accrual


12. Distributed Hash Table (DHT) + Consistent Hashing — "หา data เจอใน cluster ใหญ่"

DHT (Distributed Hash Table) = ตารางแบบ key→value ที่กระจายข้ามหลาย node (เช่น Cassandra ring, BitTorrent) ดู glossary บท 11

ปัญหาที่ DHT แก้

text
สมมุติ: 1B records (1,000,000,000) ต้องเก็บใน 100 servers
"User 12345 — อยู่ server ไหน?"

Naive approach (mod):
   server_index = hash(key) % N
   N = 100 → server_id = hash % 100
   ❌ ถ้า add/remove node → N เปลี่ยน → key ส่วนใหญ่ต้อง move!
   (e.g., N: 100 → 101 → 99% keys remap)

Consistent Hashing — Solution

แนวคิด: ใช้ "ring" 0 → 2³² → 0

text
Hash Ring (visualize as circle):

           0 / 2³²

          ●        ●
        ●            ●
       ●              ●
       ●              ●
        ●            ●
          ●        ●

            2³¹

วาง nodes และ keys บน ring:

text
                  Node A (hash = 50)

              Key1●          ●Key2
                              
                              ●Node B (hash = 100)
                              
        Key3●                
                              ●Key4
              ●          ●

                  Node C (hash = 200)

กฎ: "key → walk clockwise to next node"

text
Key1 (hash=60) → walk clockwise → next = Node B (hash=100) ✅
Key2 (hash=80) → next = Node B (hash=100) ✅
Key3 (hash=150) → next = Node C (hash=200) ✅
Key4 (hash=220) → next = Node A (hash=50, wrapping around) ✅

ข้อดี — Add/Remove Node ไม่ทำลายระบบ

text
ตอนแรก: Node A, B, C
เพิ่ม Node D (hash=120):

ก่อนเพิ่ม D:
- Key1 (60) → B (100)
- Key2 (80) → B
- Key3 (150) → C (200)
- Key4 (220) → A (wrap)

หลังเพิ่ม D (hash=120):
- Key1 (60) → B    ← ไม่เปลี่ยน!
- Key2 (80) → B    ← ไม่เปลี่ยน!
- Key3 (150) → C   ← ไม่เปลี่ยน!
- Key4 (220) → A   ← ไม่เปลี่ยน!
- Key X (110) → D  ← key ใหม่ที่เคยไป B, ตอนนี้ไป D

→ ย้ายแค่ keys ระหว่าง B กับ D (ส่วนเล็ก)
→ Keys อื่น 99% อยู่เหมือนเดิม

Virtual Nodes (vnodes) — แก้ปัญหา hot spot

text
ปัญหา: ถ้าใช้ node 1 ตัวต่อ position บน ring
- บาง node อาจรับ keys เยอะมาก (เพราะ random hash)
- บาง node อาจรับน้อย

Solution: vnodes
- 1 physical node = 100-256 vnodes (positions บน ring)
- กระจายทั่ว ring → load balanced

ตัวอย่าง:
Node A → vnodes A_0, A_1, A_2, ..., A_255 (256 positions)
Node B → vnodes B_0, B_1, ..., B_255
...

ใช้ใน: Cassandra (default 256 vnodes), DynamoDB, Riak

Replication ใน DHT — เก็บสำเนาไว้บน ring

text
Replication factor RF=3:
- Key → walk clockwise → primary owner
- Continue walking → 2 next nodes = replicas

Key X → hash 110 → primary = D (120)
                  replica 1 = next after D = C (200)
                  replica 2 = next after C = A (50)
                  
→ 3 copies of Key X อยู่บน D, C, A
→ ถ้า D ตาย → C ขึ้นมาเป็น primary

DHT ที่นิยมในระบบจริง

Algorithmที่ใช้ในNote
ChordAcademic, P2P researchFirst "structured" DHT
KademliaBitTorrent, IPFS, EthereumXOR distance metric
Cassandra RingCassandra, ScyllaDBMurmur3 hash + 256 vnodes
DynamoDB Hash RingDynamoDBClosed-source variant
Riak RingRiak64 vnodes default

การใช้งานจริง

text
1. Distributed databases (Cassandra, DynamoDB, Riak)
2. Distributed caches (Memcached cluster, Redis Cluster)
3. P2P networks (BitTorrent, IPFS)
4. CDN routing (Cloudflare, Akamai)
5. Service mesh load balancing

ข้อจำกัด

text
❌ Range queries ทำยาก
   - "SELECT * WHERE id BETWEEN 100 AND 200"
   - Keys 100-200 อาจอยู่หลาย nodes
   - ต้อง query หลาย nodes + merge
   
❌ Skewed data (Hot keys)
   - 1 user มี traffic 1M/sec
   - Hash → ตัวเดียว → node เดียวพัง
   - แก้: shard hot key + custom routing
   
❌ Rebalancing ใช้เวลา
   - เพิ่ม node → move data → high I/O

13. MapReduce + Modern Variants — ประมวลผล batch ขนาดใหญ่

เมื่อต้องประมวลผลข้อมูลขนาดใหญ่เกินเครื่องเดียว MapReduce (Google, 2004) เป็นต้นแบบ — แตกงานเป็น map (แปลง) → shuffle (จัดกลุ่มตาม key) → reduce (รวม) กระจายไปหลายเครื่อง ปัจจุบันมีเครื่องมือที่เร็วกว่า (Spark ในหน่วยความจำ, Flink สำหรับ stream) แต่หลักการ map-reduce ยังเป็นพื้นฐาน:

text
MapReduce (Google, 2004):
- Map: transform input
- Shuffle: group by key
- Reduce: aggregate per key

Example: word count
- Map: each line → words
- Shuffle: group by word
- Reduce: count per word

Use:
- Batch processing
- Big data analytics
- Hadoop, originally

Modern Alternatives — เครื่องมือยุคใหม่

text
Apache Spark:
- In-memory (much faster than Hadoop)
- DataFrame API
- SQL support
- ML library

Apache Flink:
- Stream + batch
- Lower latency than Spark
- Stateful stream processing

Dataflow (Google):
- Apache Beam
- Unified batch + stream

14. Lambda Architecture vs Kappa — สอง path vs path เดียว

เมื่อต้องการทั้งผลลัพธ์ที่แม่นยำ (batch) และเร็วทันที (real-time) มีสองแนวคิดสถาปัตยกรรม — Lambda แยกสองสาย (batch ช้าแต่แม่น + speed เร็วแต่ประมาณ แล้วรวมกัน) แต่ต้องดูแลโค้ดสองชุด, ส่วน Kappa ใช้ stream สายเดียวแล้ว replay เมื่อต้องคำนวณใหม่ ง่ายกว่าและเป็นเทรนด์ปัจจุบัน:

Lambda Architecture — batch + speed สองทาง

text
Two paths:

Batch layer:
- All data persisted
- Recompute everything periodically
- Slow but accurate

Speed layer:
- Process incoming events real-time
- Approximate result
- Fast

Serving layer:
- Merge batch + speed
- Serve to clients

Complexity: maintain 2 code paths

Kappa Architecture — streaming เพียงทางเดียว

text
Single path: streaming

All data goes through stream processor
Replay from beginning to rebuild

Simpler than Lambda
Possible with: Kafka + Flink

Trend: industry moving toward Kappa

15. Modern Data Stack — เครื่องมือ data ปัจจุบัน

text
Old:
- ETL: Extract, Transform, Load
- Transform before load
- Expensive transform

Modern (ELT):
- Extract, Load, Transform
- Load raw to data warehouse
- Transform in SQL (dbt)
- Use cheap warehouse compute

Tools:
- Extract: Fivetran, Airbyte, custom
- Load: BigQuery, Snowflake, ClickHouse, Databricks
- Transform: dbt (most popular; dbt Labs IPO 2024)
    - dbt Mesh (cross-project model dependencies) = standard ของ org ใหญ่ตั้งแต่ 2024+
    - SQLMesh (2023) — open-source alternative ที่มี virtual environments
- Orchestration: Dagster, Airflow, Prefect
- Observability: Monte Carlo, Datafold

ดู Data Engineering (เล่มแยก — ยังไม่มีในคลังนี้) สำหรับรายละเอียดเชิงลึก


16. Modern Microservices Patterns — รวม pattern ที่นิยม

text
1. Backend for Frontend (BFF)
   - Per-frontend optimized API

2. Strangler Fig
   - Gradually replace monolith
   - Route new features to new service
   - Old code = obsolete eventually

3. Sidecar
   - Run helper next to service

4. Anti-corruption layer
   - Translate between legacy + modern systems

5. Saga
   - Distributed transaction via events

6. CQRS + Event Sourcing
   - Separate write/read, store events

7. Outbox
   - Atomic DB + event publish

8. Bulkhead
   - Isolate failure (separate pool / cluster)

9. Circuit Breaker
   - Stop calling failing service

10. Retry + Backoff
    - Recover from transient failure

→ ดู System Design book สำหรับรายละเอียดเชิงลึก


17. Service Discovery ยุคใหม่ — หา service ใน infra ที่เปลี่ยนตลอด

ใน infra สมัยใหม่ (K8s, autoscaling) IP ของ service เปลี่ยนตลอด pod เกิด-ดับเป็นปกติ — แล้วจะหากันเจอได้ยังไง? มี 3 แนวทาง: DNS-based (ง่าย, K8s service เป็น DNS name), service registry (Consul/etcd ให้ลงทะเบียน) หรือ service mesh (sidecar จัดการให้โปร่งใส) ส่วนนี้เทียบทั้งสาม:

text
Dynamic infrastructure (K8s, autoscaling):
- IPs change
- Services come/go
- Need to find service

Approach 1: DNS-based
- K8s Service → DNS name
- Resolves to current pod IPs
- Simple, language-agnostic

Approach 2: Service Registry
- Consul, etcd, ZooKeeper
- Services register on startup
- Clients query registry

Approach 3: Service Mesh
- Sidecar handles discovery
- Transparent to app
- Most powerful

18. Zero Trust Architecture — ไม่ trust ใครจนกว่าจะ verify

โมเดลความปลอดภัยเก่าเชื่อว่า "อยู่ใน network ภายในแล้วปลอดภัย" — แต่พอ network ภายในโดนเจาะ ผู้บุกรุกก็เข้าถึงทุกอย่าง Zero Trust พลิกแนวคิดเป็น "ไม่เชื่อใครจนกว่าจะ verify" ทุก request ต้อง authenticate + authorize แม้แต่ service-to-service (mTLS) จำกัดความเสียหายเมื่อถูกเจาะ:

text
Old model: "Trust internal network"
- VPN → corporate network → access everything

Zero Trust:
- "Never trust, always verify"
- Every request authenticated + authorized
- Service-to-service: mTLS
- User: continuous auth (not just login)

Implementation:
- Service mesh (mTLS)
- SPIFFE / SPIRE (CNCF Graduated) — standard ของ "workload identity" ใน zero-trust microservices
- BeyondCorp (Google's model)
- Identity-aware proxy

Benefits:
- Internal breach contained
- Same auth model internal + external
- Compliance (least privilege)

19. Modern Container Orchestration — จัดการ container ในระดับ cluster

เมื่อมี container หลายร้อยตัวกระจายข้ามเครื่องหลายเครื่อง ต้องมีตัวจัดการระดับ cluster — Kubernetes เป็นมาตรฐานโดยพฤตินัย ทำ scheduling, service discovery, auto-scaling, rolling update และ self-healing ให้ มีทั้ง managed (EKS/GKE/AKS), แบบเบา (K3s) และทางเลือกอื่น (Nomad, ECS):

text
Kubernetes (de facto standard):
- Container scheduling
- Service discovery
- Auto-scaling
- Rolling update
- Self-healing
- Networking (Service, Ingress)
- Storage (PV, PVC)

Variants:
- EKS (AWS)
- GKE (GCP)
- AKS (Azure)
- Self-hosted (kubeadm)
- Lightweight (K3s, MicroK8s)

Alternative:
- Nomad (HashiCorp) — simpler
- ECS (AWS)
- Cloud Run (GCP)
- Container Apps (Azure)

20. Wasm (WebAssembly) — เทคโนโลยีน่าจับตา

text
Wasm:
- Portable bytecode
- Runs in browser + server
- Sandboxed (secure)

Server-side:
- Lightweight (vs container)
- Cold start ~1ms (vs containers seconds)
- Multi-language (Rust, Go, JS, more)

Use cases:
- Edge functions (Cloudflare, Fastly)
- Plugin systems
- Serverless functions
- Service mesh data plane (envoy filters)

Tools:
- WasmEdge
- Wasmer
- Wasmtime
- Spin (Fermyon)

ปี 2026 Wasm คือ production-mature แล้ว — ไม่ใช่ของ future อีกต่อไป: Component Model GA ตั้งแต่ปี 2024, Cloudflare Workers + Fastly Compute@Edge รัน Wasm หลัก ๆ ระดับ billions of requests/day; ตอนนี้คือเลือกใช้ ไม่ใช่ "รอดู"

Wasm at Edge — production details (2026)

⚠️ (ขั้นต่อยอด · edge dev) — basic ที่ทำ backend ปกติบน K8s/cloud ข้าม section นี้ได้; section นี้สำหรับคนทำ edge computing (Cloudflare Workers, Fastly Compute@Edge)

text
WASI evolution:
- WASI-preview 1 (legacy) — Cloudflare Workers uses this
- WASI-preview 2 (2024) — Component Model, multi-language interop
  → "wasm components" can call each other (Go calls Rust calls JS)

Cold start performance:
- Container (K8s pod, Lambda): 200-1000 ms
- Wasm sandbox: 0.5-5 ms (100x faster)
- Why? No OS, no syscall layer, AOT or JIT to native

Production platforms:
- Cloudflare Workers (V8 isolates + Wasm support)
- Fastly Compute@Edge (Wasmtime + WASI)
- Vercel Edge (Edge Runtime, V8 isolates)
- Spin (Fermyon) — Wasm-native serverless
- WasmCloud (CNCF Incubating) — distributed actors in Wasm

State management at edge:
- Cloudflare Workers KV — eventual consistency, < 1ms read
- Cloudflare D1 — SQLite at edge (since 2024)
- Cloudflare Durable Objects — strong consistency per object
- Fastly KV Store
- Vercel KV / Edge Config

Limitations (ปี 2026):
- File I/O: WASI gives capability-based file access (no /etc, no env vars by default)
- Networking: outbound limited (no raw sockets, only HTTP)
- Memory: 128MB typical limit per invocation
- No long-running connections (some platforms support WebSocket via separate primitives)

📚 เรียนต่อ: Bytecode Alliance docs, "WebAssembly: The Definitive Guide" (Brian Sletten, 2022), Cloudflare Workers docs


21. AI/LLM ใน Distributed Systems — เมื่อ AI เข้ามาเป็นส่วนหนึ่งของระบบ

แอปยุคใหม่ผนวก AI เข้าไปในระบบมากขึ้น (recommendation, search ranking, chatbot, code gen) ซึ่งสร้างความต้องการ pattern ใหม่ในระบบกระจาย — model serving, vector search, RAG และ AI Gateway ที่คุม rate limit/cost/multi-provider ส่วนนี้ชี้ให้เห็นจุดที่ AI แตะกับสถาปัตยกรรม distributed:

text
Modern apps using AI:
- Recommendations
- Search ranking
- Content moderation
- Customer support (chatbot)
- Code generation
- Image generation

Patterns:
- Model serving (TensorFlow Serving, Triton)
- Vector search (pgvector, Pinecone, Qdrant)
- RAG (Retrieval-Augmented Generation)
- AI Gateway (rate limit, cost track, multi-provider)

ดู [AI/LLM book](../ai-llm/README.md)

AI Infrastructure ที่ engineer distributed ต้องรู้ (2024-2026)

⚠️ (ขั้นต่อยอด · AI/ML engineer) — basic ที่ใช้ OpenAI/Anthropic API เป็นหลัก ข้าม section นี้ได้; section นี้สำหรับคนที่ต้องดูแล LLM serving / vector DB / RAG pipeline เอง

LLM Serving — รัน LLM ในระบบเอง

text
ตัวเลือก serving frameworks:

vLLM (Berkeley, 2023):
- PagedAttention — efficient KV cache management
- Continuous batching + chunked prefill — throughput สูงสุด
- Used by: Anthropic (internal), many startups
- 2-10x throughput improvement เทียบกับ naive serving (HuggingFace Transformers baseline)
  → ค่า "24x" ที่บางที่อ้างถึงคือ best case ที่ปรับ workload เฉพาะ; จริง ๆ 2-10x

SGLang (Berkeley, 2024):
- RadixAttention — share KV cache สำหรับ prefix ที่ซ้ำ
- เหมาะกับ structured/reasoning workload (DeepSeek R1, OpenAI o1-style)
- ขยายเร็วในปี 2024-2026

Text Generation Inference (TGI, HuggingFace):
- Rust-based, production-grade
- Tensor parallelism, flash attention
- Default for HuggingFace Inference Endpoints

llama.cpp (ggml-based):
- CPU + GPU + Metal (Apple Silicon)
- Quantization (4-bit, 8-bit) — รัน 70B model บน 24GB GPU ได้
- Edge deployment friendly

NVIDIA Triton + TensorRT-LLM:
- Production GPU inference
- Multi-model, multi-framework
- Best for NVIDIA hardware

Embedding Pipeline Architecture

text
Production concerns:
- Chunking strategy: fixed-size vs semantic vs recursive
- Embedding cost: ปี 2026 — **OpenAI text-embedding-3-small = $0.02/1M tokens** (ตั้งแต่ Jan 2024), **3-large = $0.13/1M tokens** → ใช้ 3-small เป็น default: 1M docs ≈ $20, 100M ≈ $2K, 1B ≈ $20K (เทียบ 3-large ที่ $130/$13K/$130K)
- Re-embedding when model upgrades — expensive!
- Multi-modal: text + image + table embeddings
- Hybrid retrieval: vector + BM25 (see บท sd/02)

RAG Production Patterns

text
Naive RAG:
  query → embed → vector search → top-K → LLM context → answer

Advanced RAG (production 2024+):
  1. Query rewriting (HyDE — hypothetical document embeddings)
  2. Multi-query retrieval (rephrase 3-5 ways)
  3. Re-ranking (Cohere Rerank, cross-encoder)
  4. Citation injection (force LLM to cite sources)
  5. Hallucination detection (separate LLM call)

Architecture:
- Hot path: query → cached embedding → vector DB → LLM
- Cold path: doc updates → re-chunk → re-embed → vector DB upsert
- Async observability: trace each query (LangSmith, Langfuse, Arize)

GPU Memory Management — สำคัญสำหรับ AI services

text
ปัญหา:
- LLM 70B fp16 = 140 GB → ไม่พอใน 1 GPU
- Each request: KV cache grows with context length

Solutions:
- Tensor parallelism: split model across GPUs (vLLM, Megatron-LM)
- Pipeline parallelism: split layers across GPUs
- Continuous batching: dynamic batching of in-flight requests
- PagedAttention (vLLM): non-contiguous KV cache pages
- Speculative decoding: small model proposes, large verifies
- KV cache offloading: CPU/disk for cold tokens

Memory math:
- LLaMA 70B fp16 weights: 140 GB
- LLaMA 70B int4 quantized: 35 GB → fit on A100 80GB
- KV cache per token: ~0.5 MB for 70B → 100K context = 50 GB extra

📚 เรียนต่อ: vLLM paper (Kwon et al. 2023), "AI Engineering" (Chip Huyen 2024), AnyScale Ray + Serve docs


22. Observability ยุคใหม่ — รู้ว่าระบบเป็นยังไง

ในระบบกระจายที่ request วิ่งผ่านหลาย service การ debug ยากมากถ้ามองไม่เห็น — observability ยุคใหม่ยืนบน 3 เสา: logs (มีโครงสร้าง), metrics (Prometheus), traces (OpenTelemetry) โดยเฉพาะ distributed tracing ที่ตามรอย request ข้าม service เพื่อหา bottleneck และ debug failure:

text
Three pillars:
1. Logs (structured)
2. Metrics (Prometheus)
3. Traces (OpenTelemetry)

Modern unified:
- OpenTelemetry standard
- Datadog / Honeycomb / Grafana for visualization

Distributed tracing:
- Track request across services
- Identify bottleneck
- Debug failures

ดู [Observability book](../observability/README.md)

23. Chaos Engineering — จงใจทำให้พังเพื่อหา weakness

แทนที่จะรอให้ระบบพังเองใน production แล้วค่อยรู้จุดอ่อน chaos engineering "จงใจทำให้พัง" ในสภาพควบคุม — ตั้งสมมติฐาน, inject failure (kill server, drop packet), สังเกตว่าระบบทำตามที่คาดไหม แล้วอุดช่องโหว่ Netflix บุกเบิกด้วย Chaos Monkey ส่วนนี้สอนหลักการและเครื่องมือ:

text
"Inject failures intentionally to find weakness"

Principles (Netflix):
1. Hypothesis: "If X fails, Y should happen"
2. Inject X (kill server, drop packets)
3. Observe
4. Compare to hypothesis
5. Fix gaps

Tools:
- Chaos Monkey (Netflix)
- LitmusChaos (K8s)
- Chaos Mesh
- Gremlin (commercial)
- AWS Fault Injection Simulator

Practice:
- Game days (quarterly)
- Staging first, then production (gradually)
- Limit blast radius
- Have rollback ready

24. Multi-Tenancy — รองรับหลายลูกค้าใน infra เดียว

SaaS รองรับลูกค้าหลายราย (tenant) บน infra ชุดเดียว — แต่จะแยกข้อมูลและทรัพยากรกันระดับไหน? มีตั้งแต่ single-tenant (แยกขาด แพง), pool (แชร์ทุกอย่าง แยกด้วย tenant_id ถูกแต่เสี่ยง) ถึง silo (แยก namespace) ต้องชั่งน้ำหนักเรื่อง noisy neighbor, data isolation และต้นทุน:

text
SaaS app: many customers in same infrastructure

Tenancy levels:

1. Single tenant:
   - 1 customer per deployment
   - Total isolation
   - Most expensive

2. Pool model:
   - Shared infrastructure
   - Logical isolation (tenant_id in queries)
   - Cheapest, most complex

3. Silo (deployment per tenant):
   - Each tenant: own K8s namespace
   - Some shared infra
   - Compromise

Considerations:
- Noisy neighbor (1 tenant impacts others)
- Data isolation (security + compliance)
- Performance isolation
- Cost

Database Multi-tenancy — แยกข้อมูลใน DB ระดับไหน

text
Strategies:

1. Shared DB, shared schema
   - tenant_id column in every table
   - Cheapest
   - Risk: query forget WHERE tenant_id

2. Shared DB, separate schema
   - Schema per tenant
   - Logical separation
   - Postgres schema_search_path

3. Database per tenant
   - Maximum isolation
   - Expensive at scale

25. GDPR + Data Sovereignty — กฎหมายเรื่องที่อยู่ของข้อมูล

กฎหมายหลายประเทศบังคับว่าข้อมูลของพลเมืองต้องอยู่ในเขตของตัวเอง (เช่น ข้อมูล EU ต้องอยู่ใน EU) — เรื่องนี้กลายเป็นข้อจำกัดทางวิศวกรรมจริง: ต้อง geo-shard ตาม region, ตอบให้ได้ว่า "ข้อมูลนี้อยู่ที่ไหน", ระวัง cross-border replication และทำ "right to deletion" ให้ replicate การลบไปทุกที่:

text
EU users → data must stay in EU
Different regions = different laws

Patterns:
- Geo-sharding: shard by user region
- Region-specific deployment
- Data classification (PII vs non-PII)
- Right to deletion (replicate the delete!)

Engineering:
- "Where is this data?" must be answerable
- Avoid cross-border replication unless legal
- Encryption at rest (per region key)
- Audit log

26. Cloud-Native Patterns — แนวคิดสำหรับโลก cloud

"cloud-native" คือชุดแนวคิดในการออกแบบระบบให้ใช้ประโยชน์จาก cloud เต็มที่ — immutable infrastructure (ไม่แก้เซิร์ฟเวอร์ แต่แทนทั้งตัว), declarative (บอกว่าอยากได้อะไร ไม่ใช่สั่งทีละขั้น), self-healing, zero-downtime deploy และ GitOps เป็นมาตรฐานของระบบยุค Kubernetes:

text
Patterns from CNCF + cloud-native community:

1. Immutable infrastructure
   - Don't update servers, replace
   - K8s pods, container images

2. Declarative (vs imperative)
   - "I want 3 replicas" not "Run replica 1, 2, 3"
   - K8s manifests, Terraform

3. Self-healing
   - K8s restarts failed pods
   - Auto-replace failed nodes

4. Zero-downtime deployment
   - Rolling update
   - Blue-green
   - Canary

5. Observability built-in
   - Health endpoints
   - Metrics endpoints
   - Trace propagation

6. GitOps
   - Git = source of truth for config
   - Continuous reconciliation (ArgoCD, Flux)

27. WebSocket at Scale — connection จำนวนมากในระดับ production

WebSocket scale ยากกว่า HTTP เพราะมันเป็น connection ที่เปิดค้างและมี state — server หลายตัวต้องรู้ว่า user แต่ละคนต่ออยู่ตัวไหน วิธีแก้คือใช้ pub-sub (Redis/Kafka) เป็นสะพานให้ server คุยกัน เมื่อ user A ส่ง message ผ่าน server 1 มันจะ publish ให้ server 2 ส่งต่อให้ user B:

Server 1 publishes message → Server 2 receives → forwards to User B.

Tools: Socket.IO with Redis adapter, AWS API Gateway WebSocket, Pusher/Ably (managed), Centrifugo.

Edge case: connections survive deploy — drain connections (don't drop mid-stream), persistent connection state in Redis.


28. Cost Optimization — ลดค่าใช้จ่ายของระบบ distributed

ระบบกระจายแพงโดยธรรมชาติ — การคุมค่าใช้จ่ายจึงสำคัญ จุดที่เงินรั่วบ่อยคือ cross-region transfer, resource ที่เปิดทิ้งไว้ไม่ได้ใช้, เลือก storage tier ผิด และ observability ที่เก็บ trace/log มากเกิน ส่วนนี้รวมจุดที่ควรจับตาและวิธีลดต้นทุน:

text
Distributed = expensive. Watch:

1. Cross-region transfer ($$$)
   - AWS: $0.02/GB cross-region
   - Process data where it lives

2. Idle resources
   - Auto-scale aggressively
   - Spot instances for fault-tolerant work
   - Serverless for bursty workload

3. Storage tier
   - Hot: SSD (expensive)
   - Warm: HDD
   - Cold: S3 Glacier (very cheap)

4. Database
   - Reserved instances (1-3 year commitment) — 50% off
   - Right-size (don't over-provision)
   - Read replicas only when needed

5. Observability
   - Sampling for traces (1% in prod)
   - Log filtering
   - Metric cardinality limits

ปิดท้ายด้วยการมองไปข้างหน้า — เทรนด์ที่กำลังมาแรงในระบบกระจาย: Wasm-based service (cold start เร็วกว่า container), AI-driven autoscaling (ทำนายโหลดล่วงหน้า), eBPF สำหรับ networking (Cilium แทน iptables) จับตาไว้เพื่อเตรียมพร้อมสำหรับสถาปัตยกรรมรุ่นถัดไป:

text
1. Wasm-based services
   - Faster cold start than containers
   - Multi-language polyglot

2. AI-driven autoscaling
   - Predict load, pre-scale
   - Better than reactive

3. eBPF for networking
   - Cilium replacing iptables
   - L7 visibility in kernel

4. Eventual everywhere (then snap to consistent when needed)
   - Most data → AP
   - Critical → bounded consistency

5. Multi-cloud / vendor neutrality
   - Avoid lock-in
   - Crossplane, etc.

6. Edge-first development
   - Start at edge, sync to origin
   - Local-first apps (Linear, Notion)

7. CRDT everywhere
   - Standard for collaborative
   - Better SDK support

8. WebRTC for P2P
   - Reduce server bandwidth
   - Real-time video, gaming

30. Checkpoint — แบบฝึกหัดท้ายบท

ลองสัมผัส pattern สมัยใหม่ด้วยมือตัวเอง — แบบฝึกหัดนี้ให้คุณตั้ง service mesh, สร้าง collaborative editor ด้วย CRDT (Yjs), ทำ optimistic UI และลองเล่น Wasm ทำครบจะเห็นว่าแนวคิดในบทนี้นำไปใช้จริงได้แค่ไหน:

🛠️ Checkpoint 6.1 — ลอง Service Mesh

  • ตั้ง Istio หรือ Linkerd ในเครื่อง
  • deploy 3 service
  • เพิ่ม mTLS + retry + traces
  • ดู traffic ใน dashboard

🛠️ Checkpoint 6.2 — Yjs Collaborative

  • สร้าง text editor แบบ collaborative
  • เปิด 2 แท็บ browser ให้ sync แบบ real-time
  • ตัด connection 1 แท็บ แก้ไข แล้วต่อใหม่ → merge

🛠️ Checkpoint 6.3 — Optimistic UI

  • TanStack Query + React
  • ปุ่ม Like:
    • อัปเดตหน้าจอทันที
    • rollback ถ้า fail
    • reconcile ในที่สุด

🛠️ Checkpoint 6.4 — อ่าน DDIA บทที่ 12
"Future of Data Systems" — อ่าน + คิดทบทวน

🛠️ Checkpoint 6.5 — สำรวจ Wasm

  • ตั้ง Spin (Fermyon)
  • เขียน HTTP service ง่าย ๆ ด้วย Rust → Wasm
  • เทียบ cold start กับ container

31. สรุปบท

ทบทวน pattern สมัยใหม่ทั้งหมดในบทนี้ — service mesh, sidecar/ambassador/BFF, CRDT + collaborative, edge computing, geo-replication, Zero Trust, Kubernetes, Wasm และการผนวก AI เช็กลิสต์นี้รวมเครื่องมือและแนวคิดที่กำหนดทิศทางระบบกระจายในยุคปัจจุบัน:

Service Mesh = cross-cutting ที่ network layer (mTLS, retry, trace)
Sidecar / Ambassador / BFF = pattern การประกอบ
CRDT = data structure แบบ eventually consistent — แอป collaborative
Eventually consistent UI = optimistic update + rollback
Yjs = CRDT พร้อมใช้ production (แอปแบบ Notion)
Gossip protocol = anti-entropy ที่ scale ได้ (Cassandra, Consul)
DHT + consistent hashing = key-value แบบกระจาย
MapReduce → Spark → Flink (stream + batch)
Lambda vs Kappa architecture — kappa ง่ายกว่า
Zero Trust = mTLS + auth ตลอดเวลา
Kubernetes = orchestrator มาตรฐานของวงการ
Wasm = ทางเลือกเบา ๆ ที่กำลังมาแทน container
AI/LLM ผนวกผ่าน vector DB + model serving
✅ เรื่องต้นทุนสำคัญ — การส่งข้อมูลข้าม region แพง


🎉 จบ Distributed Systems Book

หลังจากบทที่ 0-6 คุณมี:

  • Distributed mindset + 8 fallacies
  • Consistency models + CAP/PACELC
  • Consensus (Raft, Paxos) + replication
  • Distributed transactions (2PC, Saga, Event Sourcing)
  • Time + ordering (Lamport, Vector, HLC, TrueTime)
  • Event-driven architecture + Kafka
  • Modern patterns (mesh, CRDT, edge, wasm)

หัวข้อต่อยอด — เรียนรู้ต่อจากนี้

ทำอะไร
DDIA chapter 7-12Database internals, batch + stream processing, future
Spanner paperGoogle's globally consistent DB
Raft paperUnderstand internals
Hands-on KafkaBuild event-driven app
CockroachDB / TiDBProduction distributed SQL
Service mesh hands-onIstio or Linkerd tutorial
Build CRDT appCollaborative editor with Yjs
Chaos engineeringGame day in staging
AI integrationRAG with vector DB
Read engineering blogsDiscord, Stripe, Uber, Netflix

← บทที่ 5 | ← สารบัญ Distributed Systems | ← สารบัญหลัก