Back to blog

Patterns of Distributed Systems: Lộ Trình Toàn Diện

distributed-systemssystem-designsoftware-architecturebackenddesign-patternsroadmap
Patterns of Distributed Systems: Lộ Trình Toàn Diện

Bạn đã build monolith, deploy microservices, và design event-driven architectures. Nhưng khi hệ thống trải trên nhiều máy, một loạt challenge hoàn toàn khác xuất hiện:

"Chuyện gì xảy ra khi một node crash giữa lúc đang write?"
"Làm sao ba server đồng ý ai là leader?"
"Giữ data consistent across replicas thế nào khi network bị split?"
"Có thể tin timestamps trong distributed system không?"

Đây chính là những câu hỏi mà Patterns of Distributed Systems trả lời. Được cataloging bởi Unmesh Joshi trong Martin Fowler's signature series (Addison-Wesley, 2023), các pattern này mô tả recurring solutions được tìm thấy trong các hệ thống như Kafka, etcd, ZooKeeper, Cassandra và CockroachDB.

Mọi distributed system bạn tương tác — mọi database cluster, mọi message broker, mọi coordination service — đều được xây dựng từ tổ hợp các pattern này. Hiểu chúng là sự khác biệt giữa dùng distributed systems và hiểu tại sao chúng hoạt động theo cách đó.

Tại Sao Học Distributed Systems Patterns?

✅ Hiểu infrastructure của bạn — Kafka dùng WAL + segmented log + leader/followers + high-water mark bên dưới
✅ Debug production incidents — Khi leader failover lâu quá, hiểu heartbeat và generation clock patterns giải thích tại sao
✅ Design hệ thống resilient — Chọn giữa strong consistency và availability một cách tự tin
✅ Phỏng vấn system design — Distributed systems patterns là core của các buổi phỏng vấn senior/staff-level
✅ Đánh giá technology — So sánh etcd vs ZooKeeper vs Consul bằng cách hiểu patterns chúng implement
✅ Tránh sai lầm tốn kém — Biết khi nào cần consensus, khi nào eventual consistency là đủ, và khi nào 2PC nguy hiểm
✅ Career growth — Distributed systems knowledge phân biệt senior engineers với staff/principal engineers

Series Này Dành Cho Ai?

  • Backend Engineers — Build hoặc vận hành hệ thống trải trên nhiều máy
  • DevOps/SRE Engineers — Hiểu internals của infrastructure bạn quản lý
  • Senior Developers — Đào sâu kiến thức về patterns dùng trong databases, message brokers và coordination services
  • Tech Leads & Architects — Đưa ra quyết định sáng suốt về consistency, replication và partitioning strategies
  • Interview Candidates — Chuẩn bị cho system design rounds tại các công ty hàng đầu

Kiến Thức Tiên Quyết

Kiến thức bắt buộc:
✅ Thành thạo ít nhất một backend language (Java, Go, Python hoặc TypeScript)
✅ Kinh nghiệm build web applications với databases và APIs
✅ Hiểu cơ bản về networking (TCP, HTTP, client-server model)
✅ Quen thuộc với databases (transactions, replication concepts)

Hữu ích nhưng không bắt buộc:

Không cần kinh nghiệm distributed systems! Lộ trình này bắt đầu từ cơ bản và xây dựng dần lên.


Tại Sao Distributed Systems Khó

Trước khi đi vào patterns, hãy hiểu tại sao distributed systems cần patterns đặc biệt mà centralized systems không cần:

Ba Thách Thức Cơ Bản

Network Partitions: Trong centralized system, function calls không fail vì network down. Trong distributed system, bất kỳ message nào giữa hai nodes đều có thể bị mất, delay, duplicate, hoặc đến không đúng thứ tự. Bạn không phân biệt được node chậm với node chết.

Partial Failures: Khi monolith crash, mọi thứ dừng lại. Khi một node trong distributed system crash, các nodes khác vẫn chạy — và chúng có thể không đồng ý về chuyện gì đã xảy ra. Bạn cần cơ chế để detect failures, elect leaders mới, và recover state.

Clock Skew: Trên một máy duy nhất, time.Now() cho thứ tự nhất quán của events. Across machines, clocks drift xa nhau (kể cả có NTP). Hai events trên hai machines khác nhau có thể có conflicting timestamps, khiến "cái nào xảy ra trước?" trở thành câu hỏi khó bất ngờ.

CAP Theorem Trong Thực Tế

CAP theorem nói rằng trong khi network partition xảy ra, distributed system phải chọn giữa:

PropertyMô tảVí dụ
Consistency (C)Mọi read nhận được write gần nhấtetcd, ZooKeeper, CockroachDB
Availability (A)Mọi request nhận được response (không errors)Cassandra, DynamoDB, Riak
Partition Tolerance (P)Hệ thống tiếp tục hoạt động dù network bị partitionMọi distributed systems (không thể bỏ qua)

Vì network partitions là không thể tránh khỏi trong thực tế, lựa chọn thực sự là CP (consistency hơn availability) hay AP (availability hơn consistency) trong lúc partition. Các patterns khác nhau trong series này optimize cho các phía khác nhau của trade-off này.

Lưu ý quan trọng: CAP là simplification. Hệ thống thực tế hoạt động trên spectrum of consistency models — từ linearizability (mạnh nhất) đến eventual consistency (yếu nhất). Các patterns trong series này cho bạn vocabulary để navigate spectrum đó.


Pattern Language Approach

Điều làm series này đặc biệt là cách tiếp cận pattern language. Mỗi pattern:

  1. Giải quyết một problem cụ thể — ví dụ: "Làm sao detect leader đã fail?"
  2. Có một cái tên — ví dụ: "HeartBeat"
  3. Kết nối với patterns khác — HeartBeat failure kích hoạt Generation Clock, rồi kích hoạt leader election qua Majority Quorum

Patterns không tồn tại riêng lẻ — chúng compose để build complete systems. Hiểu connections giữa các patterns quan trọng ngang với hiểu từng pattern riêng lẻ.


Bức Tranh Toàn Cảnh Distributed Systems Patterns


Tổng Quan Lộ Trình Học

Series này được tổ chức thành 6 phases với 12 bài viết toàn diện:

Phase 1: Durability Foundations (1 bài)

Cách persist data đáng tin cậy — nền tảng mà mọi distributed system cần trước khi replication hay consensus.

Phase 2: Leader Election & Consensus (3 bài)

Cách nodes đồng ý ai dẫn đầu, cách detect failures, và cách đạt agreement — trái tim của distributed systems.

Phase 3: Replication & Conflict Resolution (2 bài)

Cách giữ replicas đồng bộ, serve reads từ followers, và resolve conflicts khi nodes không đồng ý.

Phase 4: Partitioning & Time (2 bài)

Cách chia data across nodes và cách sắp xếp events khi clocks không đáng tin.

Phase 5: Coordination & Decentralization (2 bài)

Cách coordinate cluster với consistent core nhỏ, và khi nào nên dùng gossip-based decentralized approaches.

Phase 6: Communication & Capstone (2 bài)

Communication patterns hiệu suất cao và bài tổng kết kết hợp mọi patterns vào real system designs.

PDS-1 (Roadmap & Overview) ← Bạn đang ở đây
  │
  ├─ Phase 1: Durability Foundations (Bài 2)
  │   └─ PDS-2: Write-Ahead Log, Segmented Log & Low-Water Mark
  │       └─ Crash recovery, log segmentation, log compaction
  │
  ├─ Phase 2: Leader Election & Consensus (Bài 3-5)
  │   ├─ PDS-3: Leader and Followers, HeartBeat & Generation Clock
  │   │   └─ Single-leader replication, failure detection, epoch numbers
  │   ├─ PDS-4: Majority Quorum, Paxos & Replicated Log
  │   │   └─ Consensus algorithms, Raft, Multi-Paxos
  │   └─ PDS-5: High-Water Mark, Follower Reads & Singular Update Queue
  │       └─ Committed entries, read scaling, ordered processing
  │
  ├─ Phase 3: Conflict Resolution (Bài 6)
  │   └─ PDS-6: Versioned Value, Version Vector & Idempotent Receiver
  │       └─ MVCC, concurrent update detection, exactly-once semantics
  │
  ├─ Phase 4: Partitioning & Time (Bài 7-8)
  │   ├─ PDS-7: Fixed Partitions, Key-Range Partitions & Two-Phase Commit
  │   │   └─ Hash partitioning, range partitioning, distributed transactions
  │   └─ PDS-8: Lamport Clock, Hybrid Clock & Clock-Bound Wait
  │       └─ Logical clocks, hybrid timestamps, Google Spanner's TrueTime
  │
  ├─ Phase 5: Coordination & Decentralization (Bài 9-10)
  │   ├─ PDS-9: Consistent Core, Lease & State Watch
  │   │   └─ Metadata management, distributed locks, change notifications
  │   └─ PDS-10: Gossip Dissemination & Emergent Leader
  │       └─ Epidemic protocols, SWIM, decentralized leadership
  │
  └─ Phase 6: Communication & Capstone (Bài 11-12)
      ├─ PDS-11: Single-Socket Channel, Request Batch, Pipeline & Waiting List
      │   └─ Connection management, batching, pipelining, async responses
      └─ PDS-12: Putting It All Together — Building Distributed Systems with Patterns
          └─ Kafka, etcd, Cassandra, CockroachDB pattern maps, decision framework

Cấu Trúc Lộ Trình Chi Tiết

Bài #1: Patterns of Distributed Systems Roadmap (Overview) ✅ Bạn đang ở đây

  • Tại sao distributed systems khó
  • Pattern language approach
  • Tổng quan catalog toàn bộ patterns
  • Các learning paths và time estimates
  • Cách real systems kết hợp patterns

Phase 1: Durability Foundations

Bài #2: Write-Ahead Log, Segmented Log & Low-Water Mark — Durability Foundations

Chủ đề:

  • Write-Ahead Log (WAL):

    • Persist mọi state change dưới dạng command vào append-only log trước khi apply
    • Crash recovery bằng cách replay log từ checkpoint cuối
    • WAL trong PostgreSQL, MySQL InnoDB và Kafka
  • Segmented Log:

    • Chia một log file lớn thành nhiều segments nhỏ hơn
    • Segment rotation và cleanup policies
    • Cách Kafka dùng log segments cho retention và performance
  • Low-Water Mark:

    • Theo dõi phần nào của log có thể safely discard
    • Snapshot-based vs time-based low-water marks
    • Log compaction trong Kafka
    • Mối quan hệ WAL → segments → low-water mark
  • Cách Chúng Hoạt Động Cùng Nhau:

    • WAL cung cấp durability, segments quản lý file sizes, low-water mark cho phép cleanup
    • Ví dụ thực tế từ PostgreSQL, Kafka và etcd

Kết Quả Học Tập:
✅ Implement basic write-ahead log cho crash recovery
✅ Hiểu cách Kafka quản lý hàng tỷ messages với segmented logs
✅ Configure log retention và compaction dùng low-water mark patterns
✅ Giải thích tại sao mọi distributed system bắt đầu với WAL

Thời gian ước tính: 3-5 ngày


Phase 2: Leader Election & Consensus

Bài #3: Leader and Followers, HeartBeat & Generation Clock — Leader Election

Chủ đề:

  • Leader and Followers:

    • Một server duy nhất điều phối replication — tại sao single leader đơn giản hóa consistency
    • Trách nhiệm của leader: accept writes, replicate tới followers
    • Điều gì kích hoạt leader election (startup, leader failure, network partition)
  • HeartBeat:

    • Periodic messages để detect server availability
    • Cấu hình heartbeat intervals và timeout
    • Trade-off: fast failure detection (short timeout) vs false positives (network hiccups)
    • Cách ZooKeeper và etcd dùng heartbeats
  • Generation Clock:

    • Monotonically increasing epoch/term numbers
    • Ngăn stale leaders (split-brain scenarios)
    • Generation numbers trong Raft (term), Paxos (ballot number), ZooKeeper (epoch)
    • Flow: heartbeat timeout → increment generation → new leader election

Kết Quả Học Tập:
✅ Design leader-follower replication topology
✅ Configure heartbeat intervals cho availability requirements của bạn
✅ Giải thích cách generation clocks ngăn split-brain
✅ Trace complete leader election flow từ failure detection đến new leader

Thời gian ước tính: 4-6 ngày


Bài #4: Majority Quorum, Paxos & Replicated Log — Consensus Protocols

Chủ đề:

  • Majority Quorum:

    • Yêu cầu majority agreement để ngăn split-brain
    • Quorum math: 2f+1 nodes chịu được f failures (3 nodes chịu 1, 5 nodes chịu 2)
    • Read quorums và write quorums — tune consistency vs availability
  • Paxos:

    • Consensus algorithm nền tảng
    • Hai phases: prepare/promise và accept/accepted
    • Multi-Paxos cho continuous consensus trên chuỗi giá trị
    • Tại sao Paxos nổi tiếng là khó implement đúng
  • Replicated Log:

    • Giữ state đồng bộ dùng consensus trên mỗi log entry
    • Raft như alternative dễ hiểu hơn Paxos
    • Log replication trong etcd (Raft) và ZooKeeper (ZAB)
    • Khi nào cần strong consensus vs eventual consistency

Kết Quả Học Tập:
✅ Tính quorum sizes cho các fault tolerance requirements khác nhau
✅ Giải thích hai phases của Paxos algorithm và tại sao chúng cần thiết
✅ So sánh Raft, Paxos và ZAB consensus approaches
✅ Xác định khi nào strong consensus đáng chi phí performance

Thời gian ước tính: 5-7 ngày


Bài #5: High-Water Mark, Follower Reads & Singular Update Queue — Replication Control

Chủ đề:

  • High-Water Mark:

    • Theo dõi log entry cuối cùng replicated thành công tới quorum
    • Committed vs uncommitted entries — khi nào data "an toàn"?
    • Cách clients biết data đã durable
    • Kafka's high-water mark cho consumer visibility
  • Follower Reads:

    • Phục vụ read requests từ followers để scale read throughput
    • Read-your-own-writes consistency guarantees
    • Stale reads trade-off: read scaling vs consistency
    • Linearizable reads qua read index protocol
  • Singular Update Queue:

    • Xử lý mọi state-changing requests qua single thread
    • Duy trì ordering mà không cần locks
    • Request waiting list cho async responses
    • Cách các patterns này kết hợp cho consistent replication

Kết Quả Học Tập:
✅ Giải thích tại sao Kafka consumers chỉ thấy messages dưới high-water mark
✅ Design hệ thống scale reads dùng followers mà vẫn maintain consistency
✅ Implement ordered processing với singular update queue
✅ Chọn giữa linearizable reads và eventually consistent reads

Thời gian ước tính: 4-6 ngày


Phase 3: Conflict Resolution

Bài #6: Versioned Value, Version Vector & Idempotent Receiver — Conflict Resolution

Chủ đề:

  • Versioned Value:

    • Lưu mọi update với version number mới
    • Đọc historical values cho audit và rollback
    • MVCC trong databases (PostgreSQL, CockroachDB)
    • Optimistic concurrency control với version checks
  • Version Vector:

    • Duy trì vector of counters (một per node) để detect concurrent updates
    • Phát hiện conflicts vs causal ordering
    • Version vectors trong Dynamo-style databases (Cassandra, Riak)
    • Vector clocks vs version vectors — khác biệt tinh tế nhưng quan trọng
  • Idempotent Receiver:

    • Gán unique IDs cho client requests để safely ignore duplicates
    • Exactly-once semantics trong message processing
    • Idempotency keys trong payment APIs (Stripe, PayPal)
    • Deduplication trong Kafka consumers

Kết Quả Học Tập:
✅ Implement MVCC-style versioned values cho concurrent access
✅ Dùng version vectors để detect conflicting updates trong multi-leader systems
✅ Design idempotent APIs safely handle duplicate requests
✅ Chọn giữa conflict prevention (locking) và conflict detection (versioning)

Thời gian ước tính: 4-6 ngày


Phase 4: Partitioning & Time

Bài #7: Fixed Partitions, Key-Range Partitions & Two-Phase Commit — Data Partitioning

Chủ đề:

  • Fixed Partitions:

    • Giữ số lượng partitions cố định để data-to-partition mapping ổn định
    • Hash-based partition assignment và consistent hashing
    • Partition rebalancing khi nodes join hoặc leave
    • Kafka's fixed partition model
  • Key-Range Partitions:

    • Partition data theo sorted key ranges cho efficient range queries
    • Split và merge ranges dynamically
    • Hot spots và mitigation strategies
    • Cách HBase và CockroachDB dùng range partitions
  • Two-Phase Commit (2PC):

    • Coordinate atomic updates across multiple partitions/nodes
    • Prepare và commit phases — vai trò của coordinator
    • Coordinator failure và blocking problem
    • Alternatives: Saga pattern, TCC (Try-Confirm-Cancel)

Kết Quả Học Tập:
✅ Chọn giữa hash và range partitioning cho data access patterns của bạn
✅ Design partition rebalancing strategies minimize data movement
✅ Giải thích 2PC blocking problem và practical implications
✅ So sánh 2PC với Saga pattern cho distributed transactions

Thời gian ước tính: 5-7 ngày


Bài #8: Lamport Clock, Hybrid Clock & Clock-Bound Wait — Distributed Time

Chủ đề:

  • Tại Sao Wall Clocks Không Đáng Tin:

    • Clock skew, NTP drift, leap seconds
    • Hai events trên machines khác nhau với conflicting timestamps
    • Vấn đề "cái nào xảy ra trước?"
  • Lamport Clock:

    • Logical timestamps capture causal ordering (happens-before relation)
    • Increment khi send/receive
    • Hạn chế: không detect được concurrent events
  • Hybrid Clock:

    • Kết hợp physical timestamps với logical counters
    • Versions vừa có ordering vừa human-readable
    • HLC trong CockroachDB và YugabyteDB
  • Clock-Bound Wait:

    • Wait để cover uncertainty in time across cluster nodes
    • Google Spanner's TrueTime API — đánh đổi latency lấy consistency
    • Commit-wait và start-wait strategies
    • Tại sao Spanner có thể cung cấp external consistency across data centers

Kết Quả Học Tập:
✅ Giải thích tại sao wall clocks không đủ để ordering events trong distributed systems
✅ Implement Lamport clocks cho causal ordering
✅ Hiểu cách CockroachDB dùng hybrid clocks cho versioning
✅ Mô tả cách Google Spanner đạt global consistency với TrueTime

Thời gian ước tính: 5-7 ngày


Phase 5: Coordination & Decentralization

Bài #9: Consistent Core, Lease & State Watch — Cluster Coordination

Chủ đề:

  • Consistent Core:

    • Duy trì cluster nhỏ (3-5 nodes) với strong consistency để coordinate cluster data lớn hơn
    • Metadata management và configuration storage
    • ZooKeeper và etcd là consistent cores
    • Khi nào dùng coordination service riêng vs embed consensus
  • Lease:

    • Time-bound tokens cho coordinating activities
    • Leader leases để ngăn split-brain
    • Distributed locks với automatic expiry
    • Cuộc tranh luận Redlock — Redis có thể cung cấp distributed locks không?
  • State Watch:

    • Notify clients khi values thay đổi trên server
    • Watch mechanism trong etcd và ZooKeeper
    • Tránh polling với push notifications
    • Handle watch events đáng tin cậy (revision-based watches)

Kết Quả Học Tập:
✅ Design hệ thống dùng consistent core cho metadata coordination
✅ Implement distributed locks với lease-based expiry
✅ Build reactive systems dùng state watch cho configuration changes
✅ Đánh giá Redis, etcd, hay ZooKeeper phù hợp cho coordination needs

Thời gian ước tính: 4-6 ngày


Bài #10: Gossip Dissemination & Emergent Leader — Decentralized Management

Chủ đề:

  • Gossip Dissemination:

    • Dùng random selection of nodes để truyền thông tin
    • Epidemic/gossip protocols và convergence guarantees
    • SWIM membership protocol cho failure detection
    • Gossip trong Cassandra và Consul
  • Emergent Leader:

    • Sắp xếp cluster nodes theo age/criteria cho automatic leader selection
    • Seniority-based leadership không cần explicit election
    • So sánh với explicit leader election (Raft/Paxos)
    • Use cases khi decentralized approaches vượt trội centralized consensus
  • Khi Nào Dùng Gossip vs Consensus:

    • Strong consistency (consensus) vs convergent state (gossip)
    • AP vs CP systems trong thực tế
    • Hybrid approaches: consensus cho metadata, gossip cho data

Kết Quả Học Tập:
✅ Implement gossip-based failure detection và membership management
✅ Design systems converge mà không cần centralized coordination
✅ Chọn giữa gossip và consensus dựa trên consistency requirements
✅ Giải thích cách Cassandra kết hợp gossip với tunable consistency

Thời gian ước tính: 4-5 ngày


Phase 6: Communication & Capstone

Bài #11: Single-Socket Channel, Request Batch, Request Pipeline & Request Waiting List — Communication Patterns

Chủ đề:

  • Single-Socket Channel:

    • Duy trì request order bằng single TCP connection per node pair
    • Tránh out-of-order delivery
    • Connection management và reconnection strategies
  • Request Batch:

    • Kết hợp multiple requests để optimize network utilization
    • Batch size trade-offs: latency vs throughput
    • Batching trong Kafka producer và database drivers
  • Request Pipeline:

    • Gửi multiple requests không cần chờ responses
    • Pipelining trong HTTP/2, gRPC streaming và database protocols
    • Pipeline depth và flow control
  • Request Waiting List:

    • Theo dõi client requests cần deferred responses
    • Correlate requests với async completions
    • Callback patterns trong distributed protocols

Kết Quả Học Tập:
✅ Design high-throughput inter-node communication dùng batching và pipelining
✅ Configure Kafka producer batching cho optimal throughput vs latency
✅ Implement async request tracking với waiting lists
✅ Hiểu cách các patterns này kết hợp cho efficient cluster communication

Thời gian ước tính: 3-5 ngày


Bài #12: Putting It All Together — Building Distributed Systems with Patterns

Chủ đề:

  • Cách Real Systems Kết Hợp Patterns:

    • Kafka: WAL + segmented log + leader/followers + high-water mark + fixed partitions
    • etcd: WAL + Raft + consistent core + state watch + lease
    • Cassandra: Gossip + version vector + key-range partitions + emergent leader
    • CockroachDB: Raft + hybrid clock + key-range partitions + 2PC
  • Pattern Selection Decision Framework:

    • Chọn giữa CP và AP
    • Khi nào cần consensus vs eventual consistency
    • Single-leader vs multi-leader vs leaderless replication
    • Hash partitioning vs range partitioning
  • Common Anti-Patterns:

    • Distributed monolith — tệ nhất của cả hai thế giới
    • Premature distributed systems — thêm complexity trước khi cần
    • Bỏ qua partial failures — coi remote calls như local calls
    • Vi phạm two generals' problem — giả sử messages luôn đến
  • Build Simple Distributed Key-Value Store:

    • Kết hợp patterns từ series này thành working system
    • WAL cho durability, Raft cho consensus, hash partitioning cho scaling

Kết Quả Học Tập:
✅ Map patterns vào real systems (Kafka, etcd, Cassandra, CockroachDB)
✅ Áp dụng systematic framework cho việc chọn distributed system patterns
✅ Nhận diện và tránh common anti-patterns trong distributed system design
✅ Design distributed key-value store từ first principles dùng patterns

Thời gian ước tính: 5-7 ngày


Cách Real Systems Dùng Các Patterns Này

Hiểu patterns nào real systems dùng giúp bạn thấy mọi thứ kết nối:

SystemDurabilityLeadershipConsensusReplicationPartitioningTimeCoordination
KafkaWAL, Segmented Log, Low-Water MarkLeader/FollowersISR (quorum-like)High-Water MarkFixed Partitions—ZooKeeper/KRaft
etcdWALLeader/Followers, HeartBeatRaft (Replicated Log)High-Water Mark——Consistent Core, Lease, State Watch
ZooKeeperWALLeader/Followers, HeartBeatZABHigh-Water Mark——Consistent Core, Lease, State Watch
CassandraWALEmergent Leader— (AP system)—Key-Range Partitions—Gossip Dissemination
CockroachDBWALLeader/FollowersRaftHigh-Water MarkKey-Range PartitionsHybrid Clock—
Google SpannerWALLeader/FollowersPaxosHigh-Water MarkKey-Range PartitionsClock-Bound Wait (TrueTime)—

Learning Paths Theo Mục Tiêu

Path 1: Backend Engineer (6-8 tuần)

Mục tiêu: Hiểu patterns đằng sau infrastructure bạn dùng hàng ngày

Thứ tự khuyến nghị:

  1. Bài #1: Roadmap Overview
  2. Bài #2: Durability Foundations (WAL, Segmented Log)
  3. Bài #3: Leader Election (Leader/Followers, HeartBeat)
  4. Bài #5: Replication Control (High-Water Mark, Follower Reads)
  5. Bài #7: Data Partitioning
  6. Bài #12: Putting It All Together

Kết quả: Hiểu cách Kafka, databases và coordination services hoạt động bên dưới


Path 2: Distributed Systems Engineer (10-14 tuần)

Mục tiêu: Kiến thức toàn diện về mọi distributed systems patterns

Thứ tự khuyến nghị:

  1. Bài #1-6: Mọi Durability, Election, Consensus, Replication và Conflict Resolution (6 tuần)
  2. Bài #7-8: Partitioning và Distributed Time (2 tuần)
  3. Bài #9-10: Coordination và Decentralization (2 tuần)
  4. Bài #11-12: Communication và Capstone (2 tuần)

Kết quả: Sẵn sàng design và đánh giá distributed systems với proper pattern selection


Path 3: SRE / DevOps Engineer (5-7 tuần)

Mục tiêu: Hiểu failure modes và recovery patterns cho systems bạn vận hành

Thứ tự khuyến nghị:

  1. Bài #2: Durability Foundations (crash recovery, log management)
  2. Bài #3: Leader Election (failure detection, heartbeats)
  3. Bài #5: Replication Control ("committed" nghĩa là gì)
  4. Bài #9: Cluster Coordination (leases, watches)
  5. Bài #10: Gossip và Decentralized Management

Kết quả: Debug production incidents, tune heartbeat timeouts, hiểu failover behavior


Path 4: Chuẩn Bị Phỏng Vấn (4-6 tuần)

Mục tiêu: Sẵn sàng cho system design interviews

Thứ tự khuyến nghị:

  1. Bài #3: Leader Election (chủ đề phỏng vấn phổ biến)
  2. Bài #4: Consensus Protocols (Raft, Paxos)
  3. Bài #6: Conflict Resolution (version vectors, idempotency)
  4. Bài #7: Data Partitioning (hash vs range, 2PC vs Saga)
  5. Bài #12: Putting It All Together (decision framework)

Trọng tâm:

  • CAP theorem trade-offs và practical implications
  • Consensus: khi nào dùng Raft vs Paxos, quorum math
  • Partitioning: hash vs range, rebalancing strategies
  • Consistency models: linearizable, sequential, eventual
  • Pattern combinations cho specific system designs

Thời Gian Ước Tính Tổng

Learning StylePhase 1-2 (Bài 2-5)Phase 3-4 (Bài 6-8)Phase 5-6 (Bài 9-12)Tổng Thời Gian
Fast Track2-3 tuần2-3 tuần2-3 tuần6-9 tuần
Standard3-4 tuần3-4 tuần3-4 tuần9-12 tuần
Thorough4-6 tuần4-6 tuần4-5 tuần12-17 tuần

Lưu ý: Time estimates giả sử 8-12 giờ mỗi tuần học và practice.


Catalog Toàn Bộ Patterns

Durability Patterns

PatternMô tảDùng Trong
Write-Ahead LogAppend mọi state change vào log trước khi applyPostgreSQL, Kafka, etcd
Segmented LogChia log thành segments cho manageable file sizesKafka, etcd
Low-Water MarkTheo dõi log entries nào có thể safely discardKafka (log compaction), ZooKeeper

Leader Election Patterns

PatternMô tảDùng Trong
Leader and FollowersSingle leader accept writes, followers replicateKafka, MySQL replication, etcd
HeartBeatPeriodic messages detect server availabilityZooKeeper, etcd, Raft
Generation ClockMonotonic epoch numbers ngăn stale leadersRaft (term), Paxos (ballot), ZooKeeper (epoch)

Consensus Patterns

PatternMô tảDùng Trong
Majority QuorumYêu cầu majority agreement cho decisionsRaft, Paxos, ZAB
PaxosConsensus algorithm nền tảng hai phasesGoogle Chubby, Spanner
Replicated LogĐồng bộ state qua consensus trên log entriesetcd (Raft), ZooKeeper (ZAB)

Replication Control Patterns

PatternMô tảDùng Trong
High-Water MarkTheo dõi entry cuối replicated tới quorumKafka, Raft
Follower ReadsServe reads từ followers để scale throughputCockroachDB, etcd, Kafka consumers
Singular Update QueueSingle-threaded processing cho ordered updatesetcd, ZooKeeper

Conflict Resolution Patterns

PatternMô tảDùng Trong
Versioned ValueLưu updates với version numbers (MVCC)PostgreSQL, CockroachDB
Version VectorDetect concurrent updates across nodesCassandra, Riak, DynamoDB
Idempotent ReceiverIgnore duplicate requests qua unique IDsKafka consumers, payment APIs

Partitioning Patterns

PatternMô tảDùng Trong
Fixed PartitionsStable partition count với hash-based assignmentKafka, Redis Cluster
Key-Range PartitionsSorted key ranges cho efficient range queriesHBase, CockroachDB, Spanner
Two-Phase CommitAtomic updates across partitionsDistributed databases, XA transactions

Distributed Time Patterns

PatternMô tảDùng Trong
Lamport ClockLogical timestamps cho causal orderingNhiều distributed algorithms
Hybrid ClockPhysical + logical counters cho ordered, readable versionsCockroachDB, YugabyteDB
Clock-Bound WaitWait để cover time uncertainty trước read/writeGoogle Spanner (TrueTime)

Cluster Coordination Patterns

PatternMô tảDùng Trong
Consistent CoreCluster nhỏ strongly-consistent coordinate cluster lớn hơnZooKeeper, etcd
LeaseTime-bound tokens cho coordination và distributed locksetcd, ZooKeeper, Redis
State WatchPush notifications khi values thay đổietcd, ZooKeeper

Decentralized Patterns

PatternMô tảDùng Trong
Gossip DisseminationRandom node-to-node information spreadingCassandra, Consul, SWIM
Emergent LeaderAutomatic leader selection theo node orderingCassandra

Communication Patterns

PatternMô tảDùng Trong
Single-Socket ChannelMột TCP connection per node pair cho orderingKafka inter-broker, etcd
Request BatchKết hợp requests cho network efficiencyKafka producer, database drivers
Request PipelineGửi mà không chờ responsesHTTP/2, gRPC streaming
Request Waiting ListTheo dõi deferred async responsesDistributed protocol implementations

Series Này Kết Nối Với Các Roadmaps Khác Thế Nào


Các Sai Lầm Thường Gặp Cần Tránh

Sai lầm về khái niệm:

❌ Coi CAP là binary — real systems hoạt động trên consistency spectrum, không phải checkbox
❌ Giả sử network đáng tin — messages bị mất, delay, duplicate và sắp xếp lại
❌ Coi remote calls như local calls — latency, partial failures và timeouts thay đổi mọi thứ
❌ "Chúng ta cần strong consistency ở mọi nơi" — hầu hết data không cần linearizability

Sai lầm thiết kế:

❌ Premature distribution — thêm distributed complexity trước khi single node chưa đủ
❌ Distributed monolith — tightly coupled services phải deploy cùng nhau
❌ Bỏ qua partial failures — giả sử operations hoặc thành công hoàn toàn hoặc fail hoàn toàn
❌ Không có idempotency — retry requests mà không deduplication tạo duplicate effects

Sai lầm vận hành:

❌ Sai heartbeat timeout — quá ngắn gây false failovers, quá dài delay real recovery
❌ Cluster hai nodes — không có majority nếu một node fail, nên không consensus được
❌ Trộn CP và AP assumptions — dùng Cassandra (AP) ở chỗ cần strict consistency
❌ Bỏ qua clock skew — dùng wall-clock timestamps làm version numbers across machines

Sai lầm tư duy:

❌ "Thêm consistency sau" — retrofit consensus cực kỳ khó
❌ "Kubernetes handle distributed systems cho mình" — K8s manage containers, không phải data consistency
❌ "Eventually consistent nghĩa là đôi khi consistent" — eventual consistency có precise guarantees
❌ "Mình tự implement Paxos" — dùng existing library; implement consensus đúng tốn nhiều năm


Mẹo Để Thành Công

1. Map Patterns Vào Systems Bạn Đã Dùng

  • Nếu bạn dùng Kafka, bạn đã depend vào WAL, segmented log, leader/followers và high-water mark
  • Nếu bạn dùng etcd hoặc ZooKeeper, bạn depend vào Raft/ZAB, consistent core, lease và state watch
  • Nếu bạn dùng PostgreSQL replication, bạn depend vào WAL, leader/followers và streaming replication
  • Đặt tên patterns trước, rồi đào sâu understanding

2. Bắt Đầu Với Durability, Rồi Build Lên

  • Mọi distributed system bắt đầu với WAL — hiểu nền tảng này trước
  • Leader election build trên durability (bạn cần replicate log)
  • Consensus build trên leader election (bạn cần agreement về leader's log)
  • Mỗi layer thêm capabilities mà layer tiếp theo depend vào

3. Nghiên Cứu Một Real System Sâu

  • Chọn một system (Kafka, etcd, hoặc CockroachDB) và trace cách patterns compose
  • Đọc design docs và source code — patterns trở nên concrete
  • Hiểu sâu một system transfers sang hiểu các systems khác

4. Build Toy Implementation

  • Implement simple Raft node bằng language bạn chọn
  • Build basic partitioned key-value store với WAL
  • Patterns chỉ "click" khi bạn đã chiến đấu với edge cases

5. Nghĩ Theo Trade-offs, Không Phải Best Practices

  • Mọi pattern trade something: consistency lấy availability, latency lấy durability, complexity lấy correctness
  • "Tùy trường hợp" là đáp án đúng — skill là biết tùy vào cái gì
  • Bài capstone cung cấp decision framework cho các trade-offs này

Sau Khi Hoàn Thành Lộ Trình Này

Bạn Sẽ Có Khả Năng:

✅ Giải thích cách Kafka, etcd, ZooKeeper, Cassandra và CockroachDB hoạt động internally
✅ Design distributed systems với proper replication, partitioning và consensus strategies
✅ Debug production incidents bằng cách hiểu leader election, heartbeats và failover behavior
✅ Chọn giữa CP và AP approaches dựa trên actual requirements
✅ Đánh giá distributed databases và coordination services bằng patterns chúng implement
✅ Phỏng vấn system design với deep knowledge về distributed systems patterns
✅ Tránh common anti-patterns như distributed monoliths và premature distribution
✅ Kết hợp patterns thành cohesive system designs dùng principled decision framework

Bước Tiếp Theo:

  1. Áp dụng patterns tại công việc — Nhận diện patterns nào infrastructure bạn dùng và đào sâu understanding
  2. Đọc sách Unmesh Joshi — Patterns of Distributed Systems có implementation details series này tóm tắt
  3. Đọc Martin Kleppmann's DDIA — Designing Data-Intensive Applications cung cấp complementary depth
  4. Contribute vào distributed systems — Dùng pattern vocabulary để contribute vào open-source projects như etcd, Kafka, hoặc CockroachDB
  5. Khám phá Software Architecture Patterns — Kết nối distributed patterns với system-level architecture

Sẵn Sàng Bắt Đầu?

Lộ trình này cung cấp mọi thứ bạn cần để master patterns driving distributed systems. Hành trình từ hiểu write-ahead logs đến tự tin design distributed systems mất 2-4 tháng nỗ lực nhất quán.

Bắt đầu với Bài #2: Write-Ahead Log, Segmented Log & Low-Water Mark và bắt đầu hiểu durability foundation mà mọi distributed system được xây dựng trên!


Tóm Tắt và Điểm Chính

✅ Distributed systems khó vì network partitions, partial failures và clock skew
✅ Lộ trình này covers 12 bài viết toàn diện tổ chức thành 6 phases với hơn 30 patterns
✅ Dựa trên Patterns of Distributed Systems của Unmesh Joshi — patterns tìm thấy trong Kafka, etcd, ZooKeeper, Cassandra và CockroachDB
✅ Patterns compose — Kafka = WAL + segmented log + leader/followers + high-water mark + fixed partitions
✅ Bốn learning paths theo các mục tiêu khác nhau (Backend Engineer, Distributed Systems Engineer, SRE, Chuẩn Bị Phỏng Vấn)
✅ Các quyết định chính: CP vs AP, consensus vs gossip, hash vs range partitioning, strong vs eventual consistency
✅ Thời gian ước tính: 6-17 tuần tùy pace và depth
✅ Khi hoàn thành, bạn sẽ hiểu không chỉ distributed systems làm gì, mà tại sao chúng làm vậy


Series Liên Quan

Lộ trình Patterns of Distributed Systems bổ sung cho các learning paths khác:


Hiểu patterns, master systems, build với sự tự tin!

Happy building! 🏗️


Có câu hỏi về lộ trình này hay distributed systems patterns? Đừng ngại liên hệ!

📬 Đăng ký nhận bản tin

Nhận những bài viết mới nhất qua email mỗi tuần. Không spam, hủy đăng ký bất cứ lúc nào.

Chúng tôi tôn trọng quyền riêng tư của bạn. Hủy đăng ký bất cứ lúc nào.

💬 Comments

Đăng nhập để bình luận

Chúng tôi sẽ không đăng bất cứ điều gì mà không có sự cho phép của bạn.