Skip to content

Evolution: từ Monolith đến Microservice

Mở đầu

Không architecture nào "tốt nhất", chỉ "phù hợp giai đoạn hiện tại". Từ monolith sang microservice không phải nhảy 1 bước, mà evolve dần theo scale business + team. Tách microservice quá sớm = quá muộn = đều nguy hiểm.

Bạn sẽ học:

  • Path evolution: 4 stage từ monolith → microservice
  • Tách khi nào: tín hiệu nên/không nên
  • Strategy tách: phương pháp theo business domain
  • Communication pattern: sync/async giữa service
  • Data tách: thách thức + solution
ChươngNội dung
1Path evolution
2Khi nào tách
3Strategy tách
4Service communication
5Data tách

1. Path evolution

Architecture evolution không driven bởi tech, mà organization scale. Team 5 → 500 người, monolith collab efficiency giảm rõ.

StageArchitectureTeamĐặc điểm
Khởi đầuMonolith1-10Code trong 1 project, deploy đơn giản
Lớn dầnModular monolith10-50Code chia module, vẫn deploy chung
Mở rộngSOA50-200Tách service coarse theo business line
ScaleMicroservice200+Service fine, team độc lập dev + deploy
架构演进路径
点击查看每个阶段的架构特点
1
单体架构
2
模块化单体
3
服务化(SOA)
4
微服务架构
单体架构
所有功能打包在一个应用中,共享一个数据库。简单直接,适合早期快速迭代。
用户模块
订单模块
支付模块
商品模块
单体应用(一个进程)
MySQL
适用规模:团队 < 10 人,日活 < 10 万
核心挑战:代码耦合严重,一个模块的 Bug 可能拖垮整个系统

Conway's Law

"Design system của 1 organization, architecture sinh ra = communication structure của organization." — Melvin Conway

Đơn giản: 3 team làm 1 system → cuối thành 3 service. Architecture tách bản chất = organization tách.

Reverse Conway: muốn architecture thế nào → tạo organization như vậy. Vd muốn tách payment service độc lập, trước hết tạo payment team độc lập. Nhiều cty fail microservice không phải tech, mà organization không chỉnh theo.


2. Khi nào tách microservice?

Không mọi system cần microservice. Tách sớm = complexity vô ích.

Tín hiệuNoteRecommend
Deploy conflict liên tụcNhiều team sửa cùng repo, hay conflictCân nhắc tách
Module cần scale riêngSearch cần 10x resourceCân nhắc tách
Stack khác biệtAI module Python, main JavaCân nhắc tách
Team < 10 ngườiCommunication cost thấp, monolith đủĐừng tách
Business explorationRequirement đổi nhanh, boundary chưa rõĐừng tách
Không có DevOpsKhông CI/CD, container, monitoringĐừng tách

3. Strategy tách

3.1 Tách theo business domain (DDD Bounded Context)

DDD Bounded Context = principle tốt nhất tách microservice. Mỗi bounded context = 1 business domain độc lập, có data model + business rule riêng.

Bounded context là gì? Cùng 1 từ trong business domain khác nghĩa khác. Vd "user" trong user domain = thông tin register (name, email), trong order domain = người đặt (address, payment), trong recommend domain = behavior profile (history, preference). Bounded context = vẽ ranh giới rõ, trong đó term + model thống nhất.

┌─────────────┐  ┌─────────────┐  ┌─────────────┐
│   User      │  │   Order     │  │  Payment    │
│   domain    │  │   domain    │  │  domain     │
│             │  │             │  │             │
│ User        │  │ Order       │  │ Payment     │
│ Profile     │  │ OrderItem   │  │ Refund      │
│ Address     │  │ Cart        │  │ Transaction │
│             │  │             │  │             │
│ User service│  │ Order svc   │  │ Payment svc │
└──────┬──────┘  └──────┬──────┘  └──────┬──────┘
       │                │                │
       └────── API call / Event ─────────┘
ContextCore entityService
UserUser, Profile, AddressUser service
ProductProduct, Category, SKUProduct service
OrderOrder, OrderItemOrder service
PaymentPayment, RefundPayment service
LogisticsShipment, TrackingLogistics service

3.2 Strangler Fig Pattern

Đừng rewrite monolith 1 lần, thay dần module bằng service mới (như cây strangler fig):

  1. Tạo service mới ngoài monolith
  2. Proxy route 1 phần traffic sang service mới
  3. Verify ổn, migrate thêm traffic
  4. Cuối thay hoàn toàn module cũ

4. Service communication patterns

MethodProtocolĐặc điểmUse
RESTHTTP/JSONĐơn giản, ecosystemPublic API, CRUD
gRPCHTTP/2 + ProtobufHigh perf, type-safeService internal high-freq
Message queueAMQP/KafkaAsync decouple, smoothingEvent, async task
GraphQLHTTP/JSONClient query theo nhu cầuBFF, mobile

Sync vs Async

  • Cần return ngay → sync (REST/gRPC)
  • Không cần return ngay → async (MQ)
  • 1 event trigger nhiều action → async (pub-sub)

Rule of thumb: được async thì async, sync chain càng dài, system càng fragile.


5. Data tách: phần khó nhất

Tách microservice đau khổ nhất không phải code, mà DB. Mỗi service nên có DB riêng → cross-service query khó.

ChallengeDescriptionSolution
Cross-service JOINKhông JOIN 2 service đượcAPI composition, data redundancy
Distributed transactionCross-DB transaction không localSaga, local message table
Data consistencyMulti-service data có thể tạm khácEventual consistency, event-driven
Data migrationTừ shared DB → independentDual-write transition, sync tool

Tổng kết

Từ monolith → microservice là quá trình tiệm tiến, không revolution.

  1. Path: monolith → modular monolith → SOA → microservice, mỗi step có driver rõ
  2. Khi nào tách: team size, deploy conflict, scale need = signal
  3. Strategy: DDD bounded context guide, strangler fig migrate dần
  4. Communication: async được thì async, sync chain ngắn nhất
  5. Data tách: khó nhất nhưng quan trọng nhất, accept eventual consistency = mindset shift key

2026 cho VN dev

  • VN context:
    • Startup MVP → modular monolith
    • VN scale-up (Tiki, Grab, MoMo) → microservice nhưng vẫn có monolith core
    • VN bank → Spring Boot enterprise + slow migrate microservice
  • Modern trends 2026:
    • Modular monolith comeback: Shopify, Stack Overflow giữ monolith scale
    • Self-contained service: vs traditional microservice, larger granularity
    • Service mesh (Istio, Linkerd): handle service-to-service complexity
    • DDD + Event Storming workshop popular cho design service boundary
  • AI scenario: tách AI service (LLM gateway) khỏi business service → cost + perf control độc lập

Tài liệu