อธิบาย Explicit Architecture: รวม DDD, Hexagonal, Onion, Clean และ CQRS ไว้ในแผนที่เดียว¶
DDD, Hexagonal, Onion, Clean และ CQRS ไม่ได้เป็นห้า architecture ที่แข่งกัน จริงๆ แล้วเป็นไอเดียเดียวกันที่มองจากห้ามุม Herberto Graça เอาทั้งห้ามาต่อรวมเป็นแผนที่เดียว แล้วตั้งชื่อว่า Explicit Architecture1 โพสต์นี้จะไล่แผนที่นั้นทีละชิ้นตามลำดับของเขา โดยใช้ตัวอย่าง Python ชุดเดียวตลอดทั้งโพสต์ คุณจะเห็นเลยว่าแต่ละ class ควรอยู่ตรงไหน
ก่อนเริ่ม
ถ้า port, adapter และ dependency rule ยังใหม่สำหรับคุณ อ่าน Hexagonal vs Clean Architecture ก่อน โพสต์นี้ข้ามพื้นฐานพวกนั้นไป แล้วไปเน้นสิ่งที่ Graça เพิ่มเข้ามา คือ component, การ decouple component, data ownership และ flow of control
บทความต้นฉบับเขียนไว้ตั้งแต่ปี 2017 แต่กลไกยังเหมือนเดิม ที่เปลี่ยนคือหน้าตาเวลาเอาไปใช้ ปี 2026 "component" มักเป็น bounded context ที่วันหลังแยกออกไปเป็น service ของตัวเอง ส่วน "event" ก็มักหมายถึง broker คู่กับ outbox pattern (เขียนไว้ใน DDD in Action) แต่ทุกอย่างในโพสต์นี้ยังใช้กับ monolith ที่ deploy เป็นก้อนเดียวได้ และตรงนั้นแหละที่ได้ประโยชน์มากที่สุด
ตัวอย่างที่ใช้ทั้งโพสต์: ร้านค้าออนไลน์เล็กๆ ที่มีสาม component คือ orders, billing และ accounts เราจะตาม use case เดียวตั้งแต่ต้นจนจบ: ลูกค้าสั่งซื้อ แล้ว billing ออก invoice ส่วน value object อย่าง Money, Percent และ OrderLine ขอถือว่ามีอยู่แล้ว วิธีสร้างดูได้ในหัวข้อ value_objects.py ของ DDD in Action
แผนที่ทั้งหมดในภาพเดียว¶
ภาพข้างล่างคือแผนที่ทั้งหมด หัวข้อต่อจากนี้จะซูมเข้าไปดูทีละส่วน
DRIVING SIDE DRIVEN SIDE
(tools that tell the app) (tools the app tells)
┌───────────┐ ┌────────────┐
│ Web / API │──┐ ┌──▶│ PostgreSQL │
└───────────┘ │ ┌───────────────────────────────┐ │ └────────────┘
┌───────────┐ │ │ APPLICATION CORE │ │ ┌────────────┐
│ CLI │──┼──▶│ ┌───────────────────────────┐ │────┼──▶│ Email │
└───────────┘ │ │ │ Application Layer │ │ │ └────────────┘
┌───────────┐ │ │ │ ┌─────────────────────┐ │ │ │ ┌────────────┐
│ Consumer │──┘ │ │ │ Domain Services │ │ │ └──▶│ Broker │
└───────────┘ │ │ │ ┌───────────────┐ │ │ │ └────────────┘
│ │ │ │ Domain Model │ │ │ │
primary / │ │ │ └───────────────┘ │ │ │ secondary /
driving │ │ └─────────────────────┘ │ │ driven
adapters │ └───────────────────────────┘ │ adapters
USE ports │ ports live on this border │ IMPLEMENT ports
└───────────────────────────────┘
ALL source-code dependencies point INWARD, toward the Domain Model
| Pattern | เติมอะไรให้แผนที่ |
|---|---|
| Ports & Adapters (Hexagonal) | เส้นขอบ: port อยู่ใน adapter อยู่นอก แบ่งเป็นฝั่ง driving กับฝั่ง driven |
| Onion / Clean | Layer ที่ซ้อนกันเป็นวง กับกฎที่ว่า dependency ชี้เข้าข้างในอย่างเดียว |
| DDD | ของที่อยู่ ใน แต่ละ layer: application service, domain service, entity, value object, event, bounded context |
| CQRS | แยก flow เป็น command (เปลี่ยน state) กับ query (อ่าน state) จะวิ่งผ่าน bus ด้วยก็ได้ |
| Package by component | หั่นทั้งระบบแนวตั้งตาม business capability แทนที่จะหั่นตาม layer |
1. สามบล็อกหลัก¶
ทุกแอปแบ่งได้เป็นสามบล็อก:
- User Interface — ช่องทางที่พาแอปไปถึงผู้ใช้ เช่น หน้าเว็บ, REST API, CLI, mobile app
- Application Core — โค้ดที่ทำงานจริง ส่วนนี้แหละคือตัวแอป
- Infrastructure — โค้ดที่ต่อ core เข้ากับ tool ต่างๆ เช่น database, search engine, email, message broker, third-party API
Flow เป็นแบบนี้ทุกครั้ง: UI → Core → Infrastructure → Core → UI
UI เปลี่ยน แต่ core ไม่ต้องเปลี่ยน PWA, mobile app, CLI และ public API ต่างก็เรียก use case "place order" ตัวเดียวกัน ถ้ามี logic สั่งซื้อสี่ชุด แยกชุดละ UI แบบนั้นไม่ได้มี core แล้ว แต่มีสี่แอป
# The same use case, triggered from two different UIs.
# ui/http/orders.py (FastAPI)
@router.post("/orders")
def place_order_http(body: PlaceOrderBody, bus: CommandBus = Depends(get_bus)):
bus.dispatch(PlaceOrder(customer_id=body.customer_id, items=body.items))
# ui/cli/orders.py (Typer)
@app.command()
def place_order_cli(customer_id: str, sku: str, qty: int):
bus = get_bus()
bus.dispatch(PlaceOrder(customer_id=customer_id, items=[(sku, qty)]))
Entry point ทั้งสองตัวเป็นแค่โค้ดแปลง input สิบบรรทัด ไม่มีตัวไหนรู้เลยว่าการสั่งซื้อทำงานยังไง
2. Tool กับการควบคุมสองทิศทาง¶
Tool คืออะไรก็ได้ที่อยู่นอกโค้ดเรา แต่แอปต้องทำงานด้วย เช่น web server, CLI runtime, PostgreSQL, Elasticsearch, SMTP, Kafka
Graça สังเกตว่า tool มีสองทิศทาง:
"CLI console กับ web server มีไว้ สั่งให้แอปของเราทำอะไรสักอย่าง ส่วน database engine เป็นฝ่ายที่ แอปของเราสั่งให้ทำ"1
แค่ความต่างข้อนี้ข้อเดียว ก็บอกได้แล้วว่าจะต่อ tool แต่ละตัวแบบไหน:
| Tool ที่ สั่ง แอป | Tool ที่แอป สั่ง | |
|---|---|---|
| ตัวอย่าง | Web server, CLI, queue consumer, cron | Database, search engine, mailer, payment API |
| ใครเริ่มก่อน | Tool | Core ของเรา |
| ประเภท adapter | Primary / driving | Secondary / driven |
| Adapter กับ port | ห่อและเรียกใช้ port | Implement port |
3. Port: สัญญาที่ core กำหนดเอง¶
"Port ก็แค่ specification ว่า tool จะใช้ application core ได้ยังไง หรือ Application Core จะใช้ tool ยังไง"1
ใน Python ก็คือ Protocol หรือ abstract base class รวมกับ DTO ที่รับเข้าหรือส่งออก
กฎที่คนพลาดบ่อยที่สุด: ออกแบบ port ตามสิ่งที่ core ต้องการ ไม่ใช่ ตาม API ของ tool Graça เขียนไว้ชัด: "Port สร้างขึ้นให้พอดีกับที่ Application Core ต้องการ ไม่ใช่แค่ลอก API ของ tool มา"1
# ❌ Mirrors the tool. The core now thinks in SMTP.
class SmtpPort(Protocol):
def connect(self, host: str, port: int) -> None: ...
def sendmail(self, from_addr: str, to_addrs: list[str], msg: bytes) -> None: ...
# ✅ Shaped by the core's need. SMTP, SES, or a test fake can all implement it.
class InvoiceNotifier(Protocol):
def invoice_issued(self, customer_email: str, invoice_id: str, total: Money) -> None: ...
Port อยู่ใน core ส่วน adapter อยู่นอก core วางแบบนี้แล้ว ลูกศร dependency จะชี้เข้าข้างในเอง
4. Adapter: Driving กับ Driven¶
4.1 Primary (driving) adapter ห่อ port¶
Driving adapter รับเรื่องจากโลกภายนอก แล้วแปลงเป็นการเรียก core ในงานจริงก็คือ controller หรือ console command ที่ inject ของที่ implement port ของ core เข้ามา จะเป็น application service, repository interface หรือ command/query bus ก็ได้
# ui/http/orders.py — a driving adapter
@router.post("/orders", status_code=202)
def place_order(body: PlaceOrderBody, bus: CommandBus = Depends(get_bus)) -> None:
# 1. translate HTTP → Command 2. hand it to the core 3. that's it
bus.dispatch(PlaceOrder(customer_id=body.customer_id, items=body.items))
4.2 Secondary (driven) adapter implement port¶
Driven adapter implement port ตัวหนึ่ง แล้ว core ขอ port นั้นที่ไหน ก็ inject adapter ตัวนี้เข้าไปที่นั่น
ตัวอย่างของ Graça: แอปง่ายๆ ตัวหนึ่งต้องเก็บข้อมูล คุณก็สร้าง "persistence interface ที่ตรงกับที่แอปต้องการ มี method save array ของข้อมูล กับ method delete แถวในตารางตาม ID"1 แล้ว implement สำหรับ MySQL วันหลังถ้าจะย้ายไป PostgreSQL หรือ MongoDB "เราก็แค่สร้าง adapter ตัวใหม่"1
# core/port/persistence.py — the port (inside the core)
class Persistence(Protocol):
def save(self, table: str, data: dict) -> None: ...
def delete(self, table: str, id: str) -> None: ...
# infrastructure/persistence/postgres.py — a driven adapter (outside)
class PostgresPersistence:
def __init__(self, conn: psycopg.Connection):
self._conn = conn
def save(self, table: str, data: dict) -> None:
cols = ", ".join(data)
vals = ", ".join(f"%({k})s" for k in data)
updates = ", ".join(f"{k} = EXCLUDED.{k}" for k in data)
self._conn.execute(
f"INSERT INTO {table} ({cols}) VALUES ({vals}) "
f"ON CONFLICT (id) DO UPDATE SET {updates}", data)
def delete(self, table: str, id: str) -> None:
self._conn.execute(f"DELETE FROM {table} WHERE id = %s", (id,))
จะเปลี่ยน database ก็แค่เขียน MongoPersistence แล้วแก้บรรทัดเดียวใน composition root โค้ดใน core ไม่ต้องแก้สักบรรทัด
4.3 Inversion of control: ทำไมลูกศรถึงชี้เข้าข้างใน¶
- Adapter depend on ทั้ง tool และ port
- Core depend on port อย่างเดียว และ port ก็ออกแบบมาเพื่อ core อยู่แล้ว
ผลคือ dependency ทุกตัวที่ข้ามขอบ core จะชี้ เข้าข้างใน นี่คือกฎข้อเดียวที่ Ports & Adapters, Onion และ Clean ใช้ร่วมกัน Core ไม่รู้ว่ามี Postgres Postgres ก็ไม่รู้ว่ามี core คนที่รู้จักทั้งสองฝั่งมีแค่ adapter
กฎนี้บังคับใน CI ได้เลย ไม่ต้องนั่งหวังว่า reviewer จะจับได้:
# .importlinter
[importlinter]
root_package = shop
[importlinter:contract:core-is-pure]
name = Core must not import infrastructure or UI
type = forbidden
source_modules = shop.core
forbidden_modules =
shop.infrastructure
shop.ui
sqlalchemy
fastapi
5. ข้างใน Core: Application Layer กับ Domain Layer¶
ตัว core เองก็แบ่ง layer แบบ DDD และ dependency ก็ยังชี้เข้าหาตรงกลางอย่างเดียวเหมือนเดิม
┌───────────────────── Application Layer ─────────────────────┐
│ use cases: application services, command & query handlers │
│ ports: repository, persistence, notifier, event dispatcher │
│ application events: OrderPlaced (use-case outcome) │
│ ┌─────────────────── Domain Layer ──────────────────────┐ │
│ │ domain services: logic spanning several entities │ │
│ │ ┌──────────────── Domain Model ──────────────────┐ │ │
│ │ │ entities, value objects, enums, domain events │ │ │
│ │ │ depends on NOTHING outside itself │ │ │
│ │ └────────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
5.1 Application layer: ที่อยู่ของ use case¶
Application layer เก็บ use case คือ process ที่ UI สั่งให้ทำได้ ข้างในมี:
- Application service (ตัวหลักของ layer นี้) พร้อม interface
- Port interface สำหรับ ORM, search, messaging, email
- Command handler กับ query handler ถ้าใช้ bus
- Application event ไว้ประกาศว่า use case จบแล้วได้ผลอะไร
Application service ส่วนใหญ่ทำแค่สามอย่าง: โหลด entity จาก repository สั่งให้ entity ทำ domain logic แล้ว save กลับ
# core/component/orders/application/place_order.py
class PlaceOrderService:
def __init__(self, orders: OrderRepository, customers: CustomerRepository,
pricing: PricingService, events: EventDispatcher):
self._orders, self._customers = orders, customers
self._pricing, self._events = pricing, events
def place(self, customer_id: str, items: list[tuple[str, int]]) -> str:
customer = self._customers.get(customer_id) # 1. load
order = Order.create(customer_id, items) # 2. domain logic
self._pricing.apply_discounts(order, customer) # (domain service)
self._orders.add(order) # 3. persist
self._events.dispatch(OrderPlaced(order.id, customer_id, customer.email, order.total))
return order.id
Application event คือตัวจุด side effect เช่น ส่ง email ยืนยัน แจ้ง third-party API ส่ง push notification หรือไปเริ่ม use case ใน component อื่น (อย่าง billing ที่จะเห็นข้างล่าง)
Command handler เขียนได้สองแบบ Graça พูดถึงไว้ทั้งคู่:1
| แบบ | Handler ทำอะไร | ใช้เมื่อ |
|---|---|---|
| Handler เป็น use case เอง | มี logic load → act → save อยู่ในตัว | เริ่มโปรเจกต์ใหม่ และ bus เป็น entry point ทางเดียว |
| Handler แค่ต่อสาย | รับ command แล้วส่งต่อให้ application service ที่มีอยู่ | มี application service อยู่แล้ว หรือต้องเรียก logic เดียวกันจาก entry point อื่นที่ไม่ผ่าน bus |
# Wiring style — the handler is three lines of glue
class PlaceOrderHandler:
def __init__(self, service: PlaceOrderService):
self._service = service
def __call__(self, cmd: PlaceOrder) -> None:
self._service.place(cmd.customer_id, cmd.items)
5.2 Domain service: logic ที่ต้องใช้หลาย entity¶
กฎ business บางข้อเกี่ยวกับ entity มากกว่าหนึ่งตัว อย่าง "ให้ส่วนลด loyalty ตาม tier ของลูกค้าและของที่อยู่ใน order" ต้องใช้ทั้ง Customer และ Order จะใส่ไว้ในตัวไหนก็ไม่ใช่
ทางที่ชวนให้ทำแต่ผิด คือเอาไปใส่ใน application service แบบนั้นเสีย encapsulation และที่แย่กว่าคือ reuse ไม่ได้ use case ตัวถัดไปที่ต้องคิดส่วนลดก็ต้อง copy โค้ดไปอีกชุด
ทางแก้คือ domain service: รับ entity เข้ามา รัน business logic แล้วจบ ไม่รู้จัก repository หรือ application service เลย
# core/component/orders/domain/pricing.py
class PricingService:
"""Domain service. No repositories, no I/O, no application-layer imports."""
def apply_discounts(self, order: Order, customer: Customer) -> None:
if customer.tier is Tier.GOLD and order.subtotal >= Money("100.00"):
order.apply_discount(Percent(10), reason="gold-tier")
Domain service เรียก domain service ตัวอื่น หรือใช้ object ใน domain model ได้ แต่ห้ามเรียกย้อนขึ้นไปหา application layer
5.3 Domain model: แกนกลาง¶
วงในสุดเก็บ entity, value object, enum และทุกอย่างที่ เป็น แนวคิดทาง business ตรงๆ วงนี้ไม่ depend on อะไรนอกตัวเองเลย
# core/component/orders/domain/order.py
@dataclass
class Order:
id: str
customer_id: str
lines: list[OrderLine]
discount: Percent = Percent(0)
events: list[DomainEvent] = field(default_factory=list)
@property
def subtotal(self) -> Money:
return sum((l.total for l in self.lines), Money("0"))
def apply_discount(self, pct: Percent, reason: str) -> None:
if pct > Percent(30):
raise DiscountTooLarge(pct)
self.discount = pct
self.events.append(DiscountApplied(self.id, pct, reason))
Domain event เกิดขึ้นตอนข้อมูลใน domain เปลี่ยน และแนบสิ่งที่เปลี่ยนไปด้วย (อย่าง DiscountApplied ข้างบน) ถ้าวันหนึ่งจะทำ event sourcing ตัวนี้คือพื้นฐานที่ต่อยอดได้ทันที
Application event vs domain event
Domain event = "ข้อมูลนี้เปลี่ยนแล้ว" (DiscountApplied) Application event = "use case นี้จบแล้ว" (OrderPlaced) use case เดียวปล่อย domain event ได้หลายตัว แต่ปล่อย application event แค่ตัวเดียว
6. Component: หั่นตาม business ไม่ใช่ตาม layer¶
ที่ผ่านมาเราหั่นโค้ดแนวนอนเป็น layer Graça เพิ่มการหั่นแนวตั้งเข้ามาอีกทาง คือ component ที่แบ่งตาม sub-domain และ bounded context แนวคิดนี้คือ "screaming architecture" ของ Uncle Bob โฟลเดอร์ชั้นบนสุดควรตะโกนบอกว่า แอปนี้ทำอะไร ไม่ใช่ ใช้ framework อะไร
| วิธีจัด package | โฟลเดอร์ชั้นบนบอกว่า… | จะเปลี่ยน "วิธีทำงานของ billing" ต้องแตะ… |
|---|---|---|
| ตาม layer | controllers/, services/, repositories/ | ทุกโฟลเดอร์ |
| ตาม feature | orders/, billing/ — แต่ละตัวมี layer ของตัวเอง เปิด public หมด | โฟลเดอร์เดียว แต่ใคร import ใครก็ได้ |
| ตาม component | orders/, billing/ — แต่ละตัวมี layer ของตัวเอง และ component มองไม่เห็นกัน | โฟลเดอร์เดียว และมีขอบเขตที่บังคับใช้จริง |
# ❌ Package by layer — the architecture screams "Django"
shop/
├── controllers/ (orders, billing, accounts mixed together)
├── services/
├── repositories/
└── models/
# ✅ Package by component — the architecture screams "shop"
shop/
├── core/
│ ├── component/
│ │ ├── orders/
│ │ │ ├── application/ place_order.py, queries.py, events.py, ports.py
│ │ │ └── domain/ order.py, pricing.py, events.py
│ │ ├── billing/
│ │ │ ├── application/ issue_invoice.py, ports.py
│ │ │ └── domain/ invoice.py
│ │ └── accounts/
│ │ ├── application/
│ │ └── domain/
│ ├── port/ ports shared by all components (EventDispatcher, CommandBus)
│ └── shared_kernel/ events & specs every component may import — keep tiny
├── infrastructure/ driven adapters: postgres/, smtp/, kafka/
└── ui/ driving adapters: http/, cli/, consumers/
Graça ยังแนะว่า bounded context อย่าง authentication กับ authorization ควรมองเป็น external tool คือเข้าถึงผ่าน port กับ adapter ไม่ใช่ component ที่ core เป็นเจ้าของเอง
เพิ่ม contract อีกตัว ขอบเขตจะได้ไม่รั่ว:
[importlinter:contract:components-independent]
name = Components must not import each other
type = independence
modules =
shop.core.component.orders
shop.core.component.billing
shop.core.component.accounts
7. Decouple component ออกจากกัน¶
ภายใน component เดียวกัน decouple ด้วย dependency injection กับ dependency inversion ก็พอ คือ depend on interface ไม่ใช่ concrete class
แต่ระหว่าง component เกณฑ์สูงกว่านั้น component หนึ่งต้องไม่รู้จัก component อื่นโดยตรงเลย ห้าม import class ของอีกฝั่ง interface ก็ห้าม เลยต้องใช้เครื่องมือที่ใหญ่ขึ้น ได้แก่ event, shared kernel, eventual consistency และบางทีก็ discovery service
7.1 สั่งให้ component อื่นทำงาน: ใช้ event¶
พอมี order เข้ามา billing ต้องออก invoice ถ้าให้ orders เรียก billing.IssueInvoiceService ตรงๆ สองตัวนี้จะผูกกันทันที
ให้ orders dispatch OrderPlaced ออกไป แล้วให้ billing เป็นฝ่ายฟังแทน
# core/component/billing/application/issue_invoice.py
class IssueInvoiceOnOrderPlaced:
def __init__(self, invoices: InvoiceRepository, notifier: InvoiceNotifier):
self._invoices, self._notifier = invoices, notifier
def __call__(self, event: OrderPlaced) -> None:
invoice = Invoice.for_order(event.order_id, event.customer_id, event.total)
self._invoices.add(invoice)
self._notifier.invoice_issued(event.customer_email, invoice.id, invoice.total)
# composition root (outside the core)
dispatcher.subscribe(OrderPlaced, IssueInvoiceOnOrderPlaced(invoices, notifier))
ตอนนี้ orders ไม่รู้แล้วว่ามี billing อยู่ แต่ยังมี coupling ค้างอยู่จุดหนึ่ง: ทั้งสอง component ต้องรู้จัก class OrderPlaced ถ้า class นี้อยู่ใน orders/ billing ก็ต้อง import จาก orders ซึ่งก็วนกลับมาที่เดิม
7.2 Shared kernel: บ้านของ event¶
ทางแก้คือ shared kernel เป็น library เล็กๆ ของโค้ดใน core ที่ทุก component depend on ได้ โดยที่ component ยังไม่ผูกกันเอง ข้างในมี application event, domain event, specification object และแทบไม่มีอย่างอื่นอีก
# core/shared_kernel/events.py
@dataclass(frozen=True)
class OrderPlaced:
order_id: str
customer_id: str
customer_email: str
total: Money
กฎสองข้อที่ช่วยให้ shared kernel ไม่บวม:
- เล็กไว้ก่อน แก้อะไรในนี้ก็กระทบทุก component ถ้า type ไหนไม่มีอย่างน้อยสอง component ใช้ ก็ไม่ควรอยู่ในนี้
- ระบบหลายภาษา ให้ใช้รูปแบบกลาง แทนที่จะเป็น Python class ตัว kernel จะเก็บ "คำอธิบาย event (เช่น ชื่อ, property…) เป็นภาษากลางอย่าง JSON"1 ปี 2026 ส่วนใหญ่ก็คือ JSON Schema, Avro หรือ Protobuf ที่เก็บไว้ใน schema registry
{
"$id": "shop.orders.OrderPlaced.v1",
"type": "object",
"required": ["order_id", "customer_id", "customer_email", "total"],
"properties": {
"order_id": { "type": "string" },
"customer_id": { "type": "string" },
"customer_email": { "type": "string", "format": "email" },
"total": { "type": "string", "pattern": "^\\d+\\.\\d{2}$" }
}
}
7.3 รอไม่ได้: เรียกแบบ synchronous ผ่าน discovery¶
บางครั้ง component อีกฝั่งต้องทำงาน ทันที จะรอ async event ไม่ได้ กรณีนี้ component A ยิง HTTP request ไปหา component B ได้ แต่ต้องผ่าน discovery service ห้าม hard-code address:
- A ถาม discovery service ก่อนว่าต้องส่ง request ไปที่ไหน แล้วค่อยเรียก B หรือ
- A ส่ง request เข้า discovery service เลย แล้ว discovery service proxy ต่อให้ B และส่ง response กลับมา
แบบนี้ A ผูกกับ discovery service ก็จริง แต่ไม่ได้ผูกกับ B ใน Kubernetes มี cluster DNS กับ Service ทำหน้าที่นี้ให้อยู่แล้ว (http://billing.shop.svc.cluster.local) ส่วนแบบ proxy ก็คือสิ่งที่ service mesh ทำ
7.4 ดึงข้อมูลจาก component อื่น: กฎเรื่องเจ้าของข้อมูล¶
"Component ห้ามแก้ข้อมูลที่ตัวเองไม่ได้ 'เป็นเจ้าของ' แต่จะ query หรือใช้ข้อมูลไหนก็ได้"1
จะใช้กฎนี้แบบไหน ขึ้นกับว่าเก็บข้อมูลไว้ยังไง:
| Shared data storage | Segregated data storage | |
|---|---|---|
| Setup | Database เดียว แต่ละตารางมี component เป็นเจ้าของ | Database (หรือ schema) แยกตาม component |
| อ่านข้อมูลของ component อื่น | Query ตารางนั้นตรงๆ แบบ read-only | เก็บ สำเนาไว้เอง เฉพาะ field ที่ใช้ |
| ข้อมูลอัปเดตยังไง | สดเสมอ เพราะเป็นตารางเดียวกัน | เจ้าของปล่อย domain event ทุกครั้งที่ข้อมูลเปลี่ยน แล้วสำเนาอัปเดตตาม (eventual consistency) |
| เขียนข้อมูลของ component อื่น | ห้าม | ห้าม |
| ต้นทุน | ต้นทุนต่ำ แต่ schema ผูกกันที่ระดับ SQL | ชิ้นส่วนเยอะขึ้น แต่วันหลังแยกแต่ละ component ออกเป็น service ได้ |
# Segregated storage: billing keeps its own copy of customer contact data.
# core/component/billing/application/sync_customer.py
class SyncCustomerContact:
def __init__(self, contacts: BillingContactRepository):
self._contacts = contacts
def __call__(self, event: CustomerEmailChanged) -> None: # emitted by accounts
self._contacts.upsert(event.customer_id, email=event.new_email)
Billing อ่านจากตาราง billing_contacts ของตัวเอง และไม่เคยเขียนลง accounts เลย Accounts จึงยังเป็น single source of truth อยู่เหมือนเดิม
8. Flow of Control: ใครเรียกใคร¶
ชิ้นสุดท้ายคือดูว่าตอน runtime แต่ละ class ต่อกันยังไง มีสองแบบ
8.1 แบบไม่มี command/query bus¶
Controller ──▶ Application Service ──▶ Repository (port) ◀── Postgres adapter
│ │ │
│ ├──▶ Domain Service └── returns Entities
│ ├──▶ Entity.do_logic()
│ └──▶ EventDispatcher (port) ──▶ OrderPlaced
│
└──▶ Query (port) ◀── SQL query adapter ── returns DTO ──▶ ViewModel ──▶ View
- Command (เขียน): controller เรียก application service แล้ว service โหลด entity ผ่าน repository interface รัน domain logic, save และ dispatch event
- Query (อ่าน): controller เรียก query object ที่รัน SQL ซึ่ง optimize แล้วคำสั่งเดียว ได้ DTO ธรรมดากลับมา ไม่ผ่าน entity ไม่ผ่าน repository จากนั้นส่ง DTO ให้ ViewModel ที่ดูแล view logic (format, label) แล้วเติมข้อมูลลง view
# core/component/orders/application/queries.py — the port
@dataclass(frozen=True)
class OrderSummary:
order_id: str
placed_at: datetime
total: str
item_count: int
class OrderSummaries(Protocol):
def for_customer(self, customer_id: str, limit: int = 20) -> list[OrderSummary]: ...
# infrastructure/persistence/postgres_queries.py — the adapter
class PgOrderSummaries:
def for_customer(self, customer_id: str, limit: int = 20) -> list[OrderSummary]:
rows = self._conn.execute("""
SELECT o.id, o.placed_at, o.total::text, count(l.*)
FROM orders o JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = %s
GROUP BY o.id ORDER BY o.placed_at DESC LIMIT %s
""", (customer_id, limit)).fetchall()
return [OrderSummary(*r) for r in rows]
ทำไมต้องมีทั้ง persistence interface และ repository interface? เพราะสองตัวนี้ซ่อนคนละเรื่องกัน:
| Interface | ซ่อนอะไรไว้ | สลับอะไรได้ |
|---|---|---|
| Persistence | ORM / database driver | MySQL → MongoDB โดยโค้ดที่เรียก repository ไม่ต้องแก้ |
| Repository | Query ที่ domain ต้องใช้ | สไตล์ query ของแต่ละ vendor โดยยังใช้ persistence adapter ตัวเดิม |
แอปเล็กๆ มักยุบสองตัวนี้เป็นตัวเดียว ไม่ผิด ขอแค่รู้ว่ายุบตัวไหนไป
8.2 แบบมี command/query bus¶
Controller ──creates──▶ PlaceOrder (command)
│
└──▶ CommandBus (port) ··· config lookup ···▶ PlaceOrderHandler
│
└──▶ (optional) PlaceOrderService
- Controller depend on แค่ bus interface กับ command/query class
- Bus หา handler จาก configuration ไม่ได้เขียนผูกไว้ในโค้ด bus, command และ handler ไม่ import กันเลย
- Handler ทำ use case เอง หรือส่งต่อให้ application service (สองแบบใน §5.1)
# core/port/bus.py — the port
class CommandBus(Protocol):
def dispatch(self, command: object) -> None: ...
# infrastructure/bus/in_memory.py — a minimal adapter
class InMemoryCommandBus:
def __init__(self, handlers: dict[type, Callable[[Any], None]]):
self._handlers = handlers
def dispatch(self, command: object) -> None:
self._handlers[type(command)](command)
# composition root — the only place that knows the mapping
bus = InMemoryCommandBus({
PlaceOrder: PlaceOrderHandler(place_order_service),
CancelOrder: CancelOrderHandler(cancel_order_service),
})
จะเปลี่ยน InMemoryCommandBus เป็นตัวที่ serialize command ลง queue ก็ได้ controller ไม่ต้องแก้สักบรรทัด
| ไม่มี bus | มี bus | |
|---|---|---|
| Controller depend on | Application service, query object | Bus interface + command/query class |
| Logic ของ use case อยู่ที่ | Application service | Handler หรือ service ที่ handler เรียก |
| หา handler ยังไง | เรียก method ตรงๆ | Lookup จาก configuration |
| เพิ่ม cross-cutting behaviour (logging, transaction, retry) | ใส่ decorator ทีละ service | ใส่ bus middleware ตัวเดียว |
| Indirection ที่เพิ่มมา | ไม่มี | เพิ่มหนึ่ง hop กด "go to definition" ตามโค้ดยากขึ้น |
ไม่ว่าแบบไหน ลูกศรทุกเส้นที่ข้ามขอบ core ต้องชี้เข้าข้างใน ข้อนี้คือ invariant ที่ห้ามหลุด
9. แผนที่ไม่ใช่พื้นที่จริง¶
Graça ปิดท้ายด้วยประโยคที่สำคัญที่สุด:
"แผนที่ไม่ใช่พื้นที่จริง… ทั้งหมดนี้เป็นแค่แนวทาง! ตัวแอปต่างหากคือพื้นที่จริง คือความเป็นจริง คือ use case ที่จับต้องได้"1
เขาไม่ได้บอกให้สร้างทุกกล่องตั้งแต่วันแรก แต่ให้ เข้าใจ ทุกกล่องก่อน แล้วค่อยเลือกว่าจะ decouple ไปถึงไหน โดยดูจาก functional requirement, timeline, ประสบการณ์ของทีม และแอปต้องอยู่ไปอีกนานแค่ไหน
และนี่ไม่ใช่ทฤษฎีบนไวท์บอร์ด เขาเล่าว่าใช้แนวคิดนี้จริงใน production ทั้งบนแพลตฟอร์ม SaaS e-commerce ที่มีร้านออนไลน์หลายพันร้าน และ marketplace ที่เปิดอยู่ในสองประเทศ ซึ่ง message bus "รับ message มากกว่า 20 ล้านข้อความต่อเดือน"1
สรุป¶
แผนที่ทั้งหมด สรุปเป็นกฎ:
- Core อยู่ตรงกลาง UI กับ infrastructure เป็น plug-in ที่ถอดเปลี่ยนได้
- Port เป็นของ core ออกแบบตามที่ core ต้องการ ไม่ใช่ตาม API ของ tool
- Driving adapter เรียกใช้ port (controller, CLI, consumer) Driven adapter implement port (DB, mail, broker)
- Application layer = use case load → act → save → dispatch event
- กฎที่ใช้หลาย entity อยู่ใน domain service ไม่ใช่ใน application service
- Domain model ไม่ depend on อะไรเลย
- Package by component component ห้าม import กันเอง
- ข้าม component ใช้ event + shared kernel เล็กๆ ถ้าต้องเรียกแบบ sync ให้ผ่าน discovery
- ข้อมูลของใคร เจ้าของเขียนได้คนเดียว ที่เหลืออ่านได้ หรือเก็บสำเนาที่อัปเดตจาก event
- บังคับใน CI ด้วย import contract อย่าฝากไว้กับ code review
ส่วนนี่คือ decision framework ว่าควรไปไกลแค่ไหน ตามที่โปรเจกต์ต้องการจริง:
| เพิ่มสิ่งนี้… | …เมื่อ | ข้ามได้เมื่อ |
|---|---|---|
| Ports & adapters สำหรับ tool | อยาก test core โดยไม่มี tool ตัวนั้น หรืออาจเปลี่ยน tool | เป็น dependency ที่นิ่งและธรรมดา ส่วนแอปก็อยู่ไม่นาน |
| แยก query object (CQRS-lite) | หน้าจอฝั่งอ่านต้อง join/aggregate จนฝืนกับโครงของ entity | ฝั่งอ่าน map 1:1 กับ entity |
| Command/query bus | มี entry point 3+ ทาง (HTTP, CLI, consumer) หรืออยากรวม transaction/retry ไว้ที่เดียว | มี HTTP API ตัวเดียวและทีมเล็ก เรียก service ตรงๆ ไปเลย |
| Component พร้อม import contract | มี 2+ ทีม หรือมี sub-domain ที่แยกกันชัด 3+ ตัว | ทีมเดียว sub-domain เดียว |
| Shared kernel | มี component 2+ ตัวที่ส่ง event หากัน | มี component ตัวเดียว |
| แยก storage ต่อ component | วางแผนจะแยก component ออกเป็น service หรือทีมแย่งกันแก้ schema | ทีมเดียว database เดียว ไม่มีแผนจะแยก |
| Discovery service สำหรับเรียกแบบ sync | Component deploy แยกกัน | ทุกอย่าง ship เป็น process เดียว ใช้ in-process event ไปเลย |
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.