Skip to content

Thách thức của Distributed Systems

Mở đầu

Khi 1 máy không đủ, vấn đề mới bắt đầu. Distributed system = nền tảng Internet hiện đại — từ chat Zalo đến order Shopee, đằng sau là vài trăm máy cộng tác. Nhưng "distributed" không miễn phí, mang theo loạt thách thức mà single-machine chưa gặp.

Bạn sẽ học:

  • Core theorem: CAP + ảnh hưởng design
  • Consistency models: strong, eventual, causal
  • 8 challenges: core difficulties
  • Consensus algorithms: Paxos, Raft
  • Practical patterns: 2PC, Saga, CRDT
ChươngNội dung
1Sao cần distributed
2CAP theorem
3Consistency models
48 challenges
5Consensus algorithms
6Distributed transaction

0. Toàn cảnh: sao cần distributed?

Single-machine đơn giản đáng tin, nhưng 3 bottleneck không vượt:

BottleneckNoteDistributed giải
Perf ceilingCPU, RAM, disk physical limitHorizontal scale: thêm máy
Single point of failure1 máy chết, cả service chếtRedundant replica
Geographic latencyUser toàn cầu, 1 máy 1 chỗMulti-site deploy gần user

Cost distributed

Distributed giải vấn đề trên, nhưng mang complexity mới: network unreliable, clock asynchronous, partial failure, data consistency...

Peter Deutsch's 8 Fallacies of Distributed Computing — các giả định sai trong distributed:

  1. Network reliable
  2. Latency = zero
  3. Bandwidth = infinite
  4. Network secure
  5. Topology không đổi
  6. Chỉ 1 admin
  7. Transport cost = zero
  8. Network homogeneous

1. CAP theorem: "tam giác bất khả"

2000, Eric Brewer đưa ra CAP conjecture (sau chứng minh = theorem): distributed system tối đa thoả 2/3 properties:

PropertyNghĩaPlain
ConsistencyMọi node cùng lúc thấy same dataATM nào cũng cùng balance
AvailabilityMỗi request nhận response non-errorSystem luôn respond, không "unavailable"
Partition toleranceNetwork partition vẫn runCáp đứt 1 phần, system vẫn work
CAP 定理交互演示
点击选择两个属性,查看对应的系统类型
C
一致性
所有节点看到相同的数据
A
可用性
每个请求都能得到响应
P
分区容错
网络分区时系统仍能运行
请选择两个属性查看结果

Sao chỉ 2/3?

Trong distributed, network partition (P) không tránh được — cáp quang bị cuốc, switch fail, DC mất net. P = bắt buộc, thực tế chọn giữa C + A:

  • Chọn CP: partition → reject request không chắc, giữ data đúng → finance, inventory
  • Chọn AP: partition → tiếp tục serve, data có thể tạm khác → social, content

CAP không black-white

System thật không "CP hoặc AP" đơn giản. Nhiều system khác op khác choice — vd cùng DB, read = AP (cho đọc data cũ), write = CP (yêu cầu majority confirm).


2. Consistency models: "strictness" của data sync

Consistency không switch (có/không), mà spectrum.

一致性模型对比
点击查看不同一致性模型的行为差异
强一致性
最终一致性
因果一致性
强一致性
写入成功后,所有节点立即返回最新值。像单机数据库一样的体验。
T1
节点A
v1
节点B
v1
节点C
v1
初始状态,所有节点数据一致
T2
节点A
v2 ✍️
节点B
同步中...
节点C
同步中...
客户端写入 v2,等待所有节点确认
T3
节点A
v2
节点B
v2
节点C
v2
所有节点确认后才返回成功,读任意节点都是 v2
权衡:延迟高(需要等所有节点确认),可用性低(节点故障时可能阻塞)
ModelGuaranteeLatencyUse
StrongĐọc = giá trị write mới nhấtCao (đợi sync)Banking, inventory
EventualCuối mọi replica = nhau, middle có thể đọc cũThấp (write return ngay)Social, DNS
CausalOp có causality giữ orderTrungComment reply, collab edit
LinearizableMọi op như serial single-machineCao nhấtDistributed lock, leader election
SessionTrong session đảm bảo read own writesThấp-trungUser personal data

"Read Your Own Writes" consistency

Need thực tế nhất: user sửa data của mình → mình thấy update ngay (user khác có thể trễ). Đây là enhancement của eventual consistency.


3. 8 challenges

分布式系统八大挑战
点击查看每个挑战的详情和应对策略
🔌
网络不可靠
时钟不同步
✂️
网络分区
🔄
数据一致性
💥
部分失败
🧠
脑裂问题
📋
事件排序
🔐
分布式事务
🔌 网络不可靠
分布式系统的节点通过网络通信,而网络随时可能丢包、延迟、断开。这是分布式系统最根本的挑战——你永远不能假设网络是可靠的。
场景举例:服务 A 调用服务 B,请求发出后 3 秒没收到响应。是 B 没收到?还是 B 处理了但响应丢了?A 无法区分。
应对策略:
  • 超时 + 重试:设置合理超时,失败后重试(需保证幂等性)
  • 心跳检测:定期发送心跳包检测连接是否存活
  • 断路器模式:连续失败后暂停调用,避免雪崩

Quan hệ giữa các challenges

8 challenges không độc lập, mà liên quan:

  • Network unreliableNetwork partitionCAP trade-off
  • Clock asyncEvent ordering khóData consistency
  • Partial failure → có thể Split brain → cần Consensus
  • Data consistency → cần Distributed transaction → bị ảnh hưởng Network unreliable

No silver bullet

Distributed không có solution "hoàn hảo", chỉ "phù hợp". Hiểu essence challenges = design đúng trade-off.


4. Consensus algorithms

Core distributed: multi-node agree về 1 value? Dù 1 phần node fail hoặc network trễ.

4.1 Paxos

Leslie Lamport 1990, algorithm đầu tiên proven correct.

RoleJob
ProposerPropose value
AcceptorVote accept/reject
LearnerHọc value chosen cuối

2-phase flow:

  1. Prepare: Proposer send proposal number, Acceptor commit không accept number nhỏ hơn
  2. Accept: Proposer send value, majority Acceptor accept → through

Vấn đề Paxos

Paxos correct nhưng nổi tiếng khó hiểu + implement. Lamport's paper dùng metaphor Greek parliament, làm nhiều người confused hơn.

4.2 Raft: vì understandability

2014 Diego Ongaro đưa Raft, target "Paxos dễ hiểu". Chia consensus thành 3 sub-problem:

SubNote
Leader electionChọn 1 Leader, mọi write qua Leader
Log replicationLeader replicate log đến Follower
SafetyĐảm bảo log committed không bị overwrite

Raft core flow:

  1. Start, mọi node = Follower
  2. Follower timeout không nhận heartbeat → Candidate, start election
  3. Candidate được majority vote → New Leader
  4. Leader receive client request, replicate log đến majority → commit

4.3 Compare

AlgorithmYearUnderstandabilitySystems
Paxos1990KhóGoogle Chubby
Raft2014Dễetcd, Consul, TiKV
ZAB2011TrungZooKeeper
EPaxos2013KhóAcademic

5. Distributed transaction: cross-node "all-or-nothing"

Single-DB transaction dùng local lock + log đảm bảo ACID. Nhưng business op span nhiều service/DB, atomicity thế nào?

5.1 Two-Phase Commit (2PC)

Protocol kinh điển, 2 phase:

PhaseCoordinatorParticipant
PrepareHỏi mọi participant "commit được?"Execute op nhưng không commit, reply Yes/No
CommitYes hết → send CommitCommit thật; có No → rollback hết

Vấn đề 2PC:

  • Blocking: sau Prepare, coordinator chết → participant đợi mãi
  • Single point of failure: coordinator chết → transaction kẹt
  • Perf kém: multi-round trip, lock hold lâu

5.2 Saga

Saga chia 1 big transaction thành nhiều local transaction, mỗi cái có compensating op. 1 step fail → execute compensation ngược.

E-commerce order Saga:

StepForwardCompensation
T1Tạo order (pending)Cancel order
T2Trừ stockRestore stock
T3Trừ balanceRefund balance
T4Confirm order (paid)

T3 fail → C2 (restore stock) → C1 (cancel order).

2 orchestration:

  • Choreography: mỗi service listen event, tự quyết next. Đơn giản nhưng global state khó track
  • Orchestration: central coordinator control flow. Rõ nhưng coordinator single point

5.3 TCC (Try-Confirm-Cancel)

TCC = 2PC business layer, mỗi op 3 phase:

PhaseNoteVd (trừ stock)
TryReserve resource, không execute thậtFreeze 10 stock
ConfirmConfirm execute, consume reservedFrozen -10 (trừ thật)
CancelCancel reservationFrozen -10, available +10

5.4 Comparison

SolutionConsistencyPerfComplexityUse
2PCStrongThấpTrungDB level cross-DB
SagaEventualCaoCaoLong process (order, logistics)
TCCEventualTrungCao nhấtMoney-related, high reliability

Recommendation

  • Single-DB transaction được → đừng distributed
  • Đa số scenario Saga + MQ đủ
  • TCC cho consistency cực cao (banking) nhưng dev cost cao
  • 2PC cho DB middleware (ShardingSphere) handle tự động

Tổng kết

Distributed system = infrastructure Internet hiện đại, nhưng complexity vượt single-machine. Hiểu challenges không phải "giải", mà design trade-off đúng.

  1. CAP: network partition không tránh được, trade-off C ↔ A
  2. Consistency: strong → eventual = spectrum, theo business need
  3. 8 challenges: network unreliable, clock async, partition, split brain liên quan nhau
  4. Consensus: Raft thực tế nhất, etcd/Consul base
  5. Distributed transaction: Saga đa số, TCC cho banking, 2PC cho DB

2026 cho VN dev

  • VN context:
    • Banking VN dùng 2PC + Oracle XA
    • E-commerce VN dùng Saga + Kafka/RabbitMQ
    • Startup dùng eventual consistency + retry
  • Modern tools 2026:
    • etcd / Consul: service discovery + config dùng Raft
    • Temporal.io: durable workflow, simplify Saga implementation
    • CockroachDB / TiDB: distributed SQL, hide complexity từ dev
    • ScyllaDB / Cassandra: AP-leaning NoSQL
  • AI scenario: LLM-based agent state coordination cần distributed consensus (multi-agent system)

Tài liệu