DDD in Action: จาก Sticky Note สู่ Production Code¶
ทฤษฎีน่ะง่าย ตอนลงมือทำจริงต่างหากที่ DDD เริ่มยาก และทีมส่วนใหญ่ก็ติดกันตรงนี้
คุณอ่านเรื่อง Bounded Context กับ Aggregate มาแล้ว เข้าใจ Ubiquitous Language แล้ว แต่พอนั่งกับทีมหน้า codebase จริง มี business requirement จริงวางอยู่ตรงหน้า คำถามสำคัญก็ยังค้างอยู่: ตกลงต้องลงมือยังไง?
บทความนี้พาเดิน DDD ครบทั้งเส้นทางบนระบบที่จับต้องได้ คือร้านหนังสือออนไลน์ เริ่มจาก workshop แรกที่ทุกคนมาช่วยกันคิด ไปจนถึง production code ที่รันได้จริง ทุก design decision มีเหตุผลกำกับ ทุกความผิดพลาดจะให้ดูก่อน แล้วค่อยแก้ อ่านจบคุณจะได้ playbook ที่หยิบไปใช้กับระบบตัวเองได้ซ้ำ ๆ
บทความนี้คือ Part 2 ของซีรีส์ DDD
บทความนี้เน้นฝั่ง ลงมือทำ ถ้ายังไม่แน่นเรื่องทฤษฎีพื้นฐาน อย่าง Bounded Context, Aggregate, Value Object และ Domain Event แนะนำให้อ่าน DDD Complete Guide ก่อน
ตัวอย่างที่ใช้ทั้งบทความ: ร้านหนังสือออนไลน์¶
ทั้งบทความเราจะสร้างแกนหลักของร้านหนังสือออนไลน์ชื่อ Bookly ร้านนี้ขายทั้งหนังสือเล่มและ e-book มี membership ที่ได้ส่วนลด และส่งของไปทั่วโลก
ดูแวบแรกเหมือนง่าย แต่พอทำ Event Storming จะเห็นว่า domain นี้ลึกและซับซ้อนกว่าที่คิดเยอะ ระบบแบบนี้แหละที่ทำ DDD แล้วคุ้มที่สุด
ภาพรวมทั้งเส้นทาง¶
DDD ตอนลงมือจริงแบ่งเป็น 6 phase เราจะลงลึกทีละ phase:
Phase 1 Phase 2 Phase 3
DISCOVER → DEFINE → DESIGN
(Event (Bounded (Aggregates
Storming) Contexts) & Models)
│
│
Phase 6 Phase 5 Phase 4
VALIDATE ← INTEGRATE ← IMPLEMENT
(Tests & (Events & (Code the
Refinement) APIs) Domain)
Phase 1: สำรวจ Domain ด้วย Event Storming¶
ถ้าอยากให้ทั้งทีมเข้าใจ domain ที่ซับซ้อนตรงกัน Event Storming คือทางที่เร็วที่สุด Alberto Brandolini เป็นคนคิดวิธีนี้ขึ้นมา domain ขนาดเท่า Bookly ใช้เวลาราว 4–8 ชั่วโมง
ใครต้องอยู่ในห้องบ้าง¶
session นี้ไม่ได้มีแค่ developer ต้องชวนทุกคนที่รู้ธุรกิจสักส่วนหนึ่งมาด้วย:
| Role | ช่วยอะไรได้ |
|---|---|
| Domain Experts | ธุรกิจทำงานกันจริง ๆ ยังไง |
| Product Managers | ธุรกิจอยากได้ผลลัพธ์อะไร |
| Developers | ทางเทคนิคทำอะไรได้บ้าง |
| UX Designers | user เจอประสบการณ์แบบไหน |
| Support / Ops | อะไรพังบ้าง และแก้กันยังไง |
ช่วงที่ได้ของมากที่สุดใน Event Storming คือตอนที่ developer พูดว่า "เดี๋ยวนะ ผมเข้าใจมาตลอดว่าไม่ได้ทำงานแบบนี้" แล้ว domain expert ตอบว่า "นั่นแหละ ปัญหาที่เราเจอมาหลายปีแล้ว"
เตรียมห้อง¶
ของที่ต้องเตรียม:
- ผนังกว้างอย่างน้อย 5 เมตร (เอากระดาษม้วนมาต่อกันแล้วแปะผนัง)
- Sticky note 6 สี ซื้อเผื่อไว้สีละ 300 แผ่นขึ้นไป
- ปากกาเมจิกหัวใหญ่ (Sharpie) ปากกาหัวเล็กยืนห่าง ๆ แล้วอ่านไม่ออก
- เวลาราว 2 ชั่วโมงต่อ session (domain เต็ม ๆ ใช้ 4 session)
| สี | แทนอะไร | เขียนแบบไหน |
|---|---|---|
| 🟠 ส้ม | Domain Events | กริยารูปอดีต — "Order Placed" |
| 🔵 น้ำเงิน | Commands | กริยาคำสั่ง — "Place Order" |
| 🟡 เหลือง | Actors / Users | ใครเป็นคนสั่ง command |
| 🟣 ม่วง | Policies | "เมื่อ X เกิดขึ้น ให้ทำ Y" |
| 🩷 ชมพู | External Systems | Stripe, SendGrid, FedEx API |
| 🟢 เขียว | Read Models | user เห็นข้อมูลอะไร |
Step 1: ระดมแบบไม่มีกฎ (45 นาที)¶
ทุกคนเขียน Domain Event ลง sticky สีส้มแล้วแปะบนผนัง ไม่ต้องเรียง ไม่มีกฎ facilitator มีหน้าที่อย่างเดียวคือคุมให้ห้องคึกไว้
Event คือสิ่งที่ เกิดขึ้นไปแล้ว ในธุรกิจ เขียนเป็นรูปอดีต ใช้ภาษาธุรกิจ และ domain expert อ่านแล้วต้องเข้าใจ:
🟠 Book Searched 🟠 Book Added to Cart 🟠 Checkout Started
🟠 Payment Processed 🟠 Order Confirmed 🟠 Inventory Reserved
🟠 Shipment Dispatched 🟠 Book Downloaded 🟠 Membership Activated
🟠 Review Submitted 🟠 Refund Requested 🟠 Order Cancelled
🟠 Delivery Confirmed 🟠 Discount Applied 🟠 Wishlist Updated
🟠 Coupon Redeemed 🟠 Address Validated 🟠 Fraud Detected
กฎ 'ไม่มีคำถามโง่'
ช่วงนี้ไม่มี sticky note ใบไหนผิด ชวนให้ทุกคนเขียนซ้ำกันได้เลย ของที่ซ้ำกันจะบอกว่าแต่ละคนเรียกสิ่งเดียวกันไม่เหมือนกัน และนั่นคือสิ่งที่เราอยากขุดออกมา
Step 2: เรียง Timeline (30 นาที)¶
เรียง event จากซ้ายไปขวาตามลำดับเวลาคร่าว ๆ ไม่ต้องเป๊ะ เป้าหมายคือให้เห็นเรื่องราวทั้งเส้น:
TIMELINE (left → right = earlier → later):
──────────────────────────────────────────────────────────────────→ time
[Book [Book Added [Checkout [Payment [Order [Book
Searched] to Cart] Started] Processed] Confirmed] Downloaded]
↕
[Payment
Failed]
[Order [Inventory [Shipment [Delivery [Review
Confirmed] Reserved] Dispatched] Confirmed] Submitted]
เถียงกันเรื่องลำดับเมื่อไหร่ ได้ของดีเมื่อนั้น เพราะจะเจอ step ที่ตกหล่น งานที่ไม่ชัดว่าใครดูแล และความซับซ้อนที่ซ่อนอยู่
Step 3: Command และ Actor (30 นาที)¶
แต่ละ event ให้เพิ่ม Command สีน้ำเงิน ที่ทำให้ event นั้นเกิด และ Actor สีเหลือง ที่เป็นคนสั่ง:
🟡 Customer 🔵 Search Books → 🟠 Book Searched
🟡 Customer 🔵 Add to Cart → 🟠 Book Added to Cart
🟡 Customer 🔵 Initiate Checkout → 🟠 Checkout Started
🟡 Payment GW 🔵 Process Payment → 🟠 Payment Processed
🟣 Policy [When Payment OK] → 🟠 Order Confirmed
🟣 Policy [When Order OK] → 🟠 Inventory Reserved
🟡 Warehouse 🔵 Dispatch Order → 🟠 Shipment Dispatched
🟡 System 🔵 Deliver File → 🟠 Book Downloaded
Step 4: Aggregate และ Policy (30 นาที)¶
จับ command กับ event มารวมกลุ่มไว้ใต้ sticky Aggregate สีเหลือง (ใช้แผ่นใหญ่) แล้วเพิ่ม sticky Policy สีม่วง สำหรับกฎ automation:
🟡 CART Aggregate:
[Add to Cart] → [Book Added to Cart]
[Remove from Cart] → [Book Removed from Cart]
[Apply Coupon] → [Coupon Applied]
🟡 ORDER Aggregate:
[Place Order] → [Order Placed]
[Cancel Order] → [Order Cancelled]
[Confirm Order] ← 🟣 "When payment succeeds"
🟡 PAYMENT Aggregate:
[Process Payment] → [Payment Processed]
→ [Payment Failed]
[Refund Payment] → [Refund Issued]
🟣 POLICY: When Order Confirmed → Reserve Inventory
🟣 POLICY: When Payment Failed → Restore Cart Items
🟣 POLICY: When Inventory Reserved → Schedule Shipment
Step 5: External System (20 นาที)¶
เพิ่ม sticky สีชมพูแทนระบบภายนอกที่ domain ต้องคุยด้วย:
🩷 Stripe (payment processing)
🩷 SendGrid (email notifications)
🩷 FedEx API (shipping rates + tracking)
🩷 Google Books API (book metadata enrichment)
🩷 Fraud Detection (order risk scoring)
อ่านผลจาก Event Storm¶
ถอยออกมามองทั้งบอร์ด คุณจะเห็นกลุ่มที่เกาะกันเองตามธรรมชาติ บริเวณที่ sticky จับกลุ่มกันแน่น ๆ นั่นแหละคือ candidate Bounded Context:
┌─────────────────┐ ┌──────────────┐ ┌──────────────────┐
│ CATALOG cluster │ │ ORDER cluster│ │ PAYMENT cluster │
│ │ │ │ │ │
│ Book Searched │ │ Cart Updated │ │ Payment Process │
│ Catalog Updated │ │ Order Placed │ │ Fraud Checked │
│ Review Added │ │ Order Cancel │ │ Refund Issued │
└─────────────────┘ └──────────────┘ └──────────────────┘
┌──────────────────┐ ┌───────────────┐ ┌──────────────┐
│ INVENTORY cluster│ │SHIPPING cluster│ │ MEMBER cluster│
│ │ │ │ │ │
│ Stock Reserved │ │ Shipment Sched │ │ Member Joined│
│ Stock Released │ │ Label Printed │ │ Points Earned│
│ Stock Adjusted │ │ Delivered │ │ Tier Upgraded│
└──────────────────┘ └───────────────┘ └──────────────┘
Phase 2: กำหนด Bounded Context¶
ได้ผลจาก Event Storm แล้ว ขั้นต่อไปคือขีดเส้นแบ่งขอบเขตให้ชัด
Bounded Context ทั้ง 6 ของ Bookly¶
┌───────────────────────────────────────────────────────────────────┐
│ BOOKLY PLATFORM │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
│ │ CATALOG │ │ ORDERS │ │ PAYMENTS │ │ INVENTORY │ │
│ │ │ │ │ │ │ │ │ │
│ │Books │ │Cart │ │Transact │ │Stock │ │
│ │Authors │ │Orders │ │Refunds │ │Reservations │ │
│ │Reviews │ │Returns │ │Invoices │ │Adjustments │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────────┘ │
│ │
│ ┌──────────────┐ ┌─────────────────────────────────────────┐ │
│ │ SHIPPING │ │ MEMBERSHIP │ │
│ │ │ │ │ │
│ │Shipments │ │Members Tiers Points Discounts │ │
│ │Tracking │ │ │ │
│ │Carriers │ └─────────────────────────────────────────┘ │
│ └──────────────┘ │
└───────────────────────────────────────────────────────────────────┘
คำเดียวกัน แต่คนละโลก¶
ลองดูคำว่า "Book" ในแต่ละ context ความหมายไม่เหมือนกันเลย:
| Context | "Book" หมายถึง | Attribute หลัก |
|---|---|---|
| Catalog | สิ่งที่ลูกค้าค้นแล้วเจอ | Title, author, description, cover image, reviews, ISBN |
| Orders | รายการหนึ่งในคำสั่งซื้อ | Product ID, title (snapshot), ราคา ณ ตอนสั่ง |
| Inventory | stock หนึ่งหน่วย | SKU, จำนวนที่มีในคลัง, reorder threshold, ตำแหน่งใน warehouse |
| Shipping | พัสดุจริงหนึ่งกล่อง | น้ำหนัก, ขนาด, แตกง่ายแค่ไหน, ประเภทการจัดส่ง |
ตั้งใจให้เป็นแบบนี้ ไม่ใช่ design พลาด
concept เดียวกันแต่ model ไม่เหมือนกันในแต่ละ context แบบนี้แหละ DDD ที่ถูก ถ้าบังคับให้ทุก context ใช้ model Book ตัวเดียวกัน ระบบจะผูกกันแน่นและพังง่าย แยก model ออกจากกันดีกว่า ซ้ำกันบ้างก็ไม่เป็นไร
สร้าง Context Map¶
ขั้นนี้เขียนให้ชัดว่า bounded context แต่ละตัวสัมพันธ์กันแบบไหน:
BOOKLY CONTEXT MAP
┌──────────┐ ┌──────────┐
│ CATALOG │ ──── Open Host Service ────→ │ ORDERS │
│ (U) │ Published Language │ (D/ACL) │
└──────────┘ └────┬─────┘
│ Customer-Supplier
│ (Orders → Payments)
▼
┌──────────┐
│ PAYMENTS │
│ │
│ 🩷 Stripe │
│ (Conform│
│ ist) │
└──────────┘
ORDERS ──── Domain Events ────→ INVENTORY (eventual consistency)
ORDERS ──── Domain Events ────→ SHIPPING (eventual consistency)
ORDERS ──── Domain Events ────→ MEMBERSHIP (eventual consistency)
ทำไมเลือก pattern พวกนี้?
- Catalog → Orders (Open Host + ACL): Catalog เป็น reference service ที่ค่อนข้างนิ่ง Orders ดึงข้อมูลจาก Catalog ก็จริง แต่แปลง
Bookของ catalog เป็นOrderLineItemของตัวเองผ่าน ACL ก่อนทุกครั้ง catalog จะเปลี่ยนอะไร orders ก็ไม่พัง - Orders → Payments (Customer-Supplier): Orders เป็นฝ่ายบอกว่าต้องเก็บเงินเท่าไหร่ Payments ไม่ยุ่งกับ business logic มีหน้าที่จัดการเงินอย่างเดียว
- Payments → Stripe (Conformist): เราต้องทำตาม API ของ Stripe เขาไม่มาเปลี่ยนเพื่อเราแน่นอน
- Orders → Inventory/Shipping/Membership (Domain Events): คุยกันผ่าน async event เลยผูกกันหลวม ๆ orders ไม่ต้องรู้ด้วยซ้ำว่ามี service พวกนี้อยู่
Phase 3: ออกแบบ Aggregate¶
ส่วนนี้จะเจาะที่ bounded context Orders ตัวเดียว เพื่อให้เห็นการออกแบบ aggregate แบบละเอียด
หา Aggregate ยังไง¶
ออกแบบ aggregate โดยถาม 3 ข้อนี้:
- อะไรบ้างที่ต้อง consistent ไปพร้อมกัน? (consistency boundary)
- การเปลี่ยนแปลงทั้งหมดต้องเข้าทางไหน? (aggregate root)
- อะไรรอ eventually consistent ได้? (ใช้ event แทน direct reference)
Candidate Aggregate ใน Orders Context¶
จาก Event Storm ใน Orders context มี event พวกนี้:
Cart: Book Added to Cart, Book Removed from Cart, Coupon Applied,
Checkout Started, Cart Abandoned
Order: Order Placed, Order Confirmed, Order Cancelled,
Return Requested, Return Approved
ดูแล้วน่าจะแยกได้ 2 aggregate คือ Cart กับ Order
ทำไมไม่รวมเป็น Aggregate "Purchase" ก้อนเดียว?¶
มือใหม่มักรวม Cart กับ Order เป็น aggregate Purchase ก้อนเดียว มาดูกันว่าทำไมไม่ควรทำ:
# BAD: one giant aggregate — everything locked together
@dataclass
class Purchase:
id: UUID
customer_id: UUID
cart_items: list[CartItem] # changes frequently
order_status: OrderStatus # changes rarely
payment_info: PaymentInfo # PCI-sensitive data
shipping_address: Address
return_requests: list[Return] # different lifecycle
invoices: list[Invoice] # finance team owns this
ปัญหาที่ตามมา: - ลูกค้าเพิ่มหนังสือลง cart ทีเดียว ทั้ง record Purchase โดน lock ไปด้วย support agent ที่กำลังทำเรื่องคืนสินค้าก็ต้องรอ - แค่จะโหลด order มาโชว์สถานะ ก็ต้องลากประวัติ cart ทั้งหมดมาด้วย - แต่ละทีมต้องดูแลคนละส่วน แต่ถ้าใช้ aggregate ก้อนเดียวร่วมกัน แบ่งกันดูแลไม่ได้เลย
Model ที่ควรเป็น: Aggregate เล็ก ๆ สองตัว¶
# GOOD: small, focused aggregates
@dataclass
class Cart: # Aggregate Root
id: UUID
customer_id: UUID
_items: list[CartItem]
_coupon: Optional[Coupon]
# Cart cares about: items, totals, coupon validity
@dataclass
class Order: # Aggregate Root
id: UUID
customer_id: UUID
cart_id: UUID # reference by ID only — not the object
_line_items: list[OrderLineItem]
_status: OrderStatus
_shipping_address: Address
# Order cares about: status transitions, line items (snapshot), shipping
Cart กับ Order เชื่อมกันแค่ cart_id เป็น ID reference ไม่ใช่ object reference ตอนแปลง Cart เป็น Order ตัว Order จะเก็บ snapshot ของในตะกร้าไว้ จากนั้น Cart กับ Order ก็เปลี่ยนไปตามทางของตัวเอง ไม่เกี่ยวกันอีก
Phase 4: เขียน Domain เป็น Code¶
มาสร้าง bounded context Orders ให้ครบทั้งตัวกัน ตัวอย่างใช้ Python แต่ pattern ทุกตัวเอาไปใช้กับภาษาไหนก็ได้
โครงสร้าง Folder¶
orders/
├── domain/
│ ├── __init__.py
│ ├── cart.py # Cart aggregate
│ ├── order.py # Order aggregate
│ ├── value_objects.py # Money, Address, Coupon, etc.
│ ├── events.py # Domain events
│ └── exceptions.py # Domain exceptions
├── application/
│ ├── __init__.py
│ ├── cart_service.py # Use cases for cart
│ ├── order_service.py # Use cases for orders
│ └── dto.py # Data Transfer Objects
├── infrastructure/
│ ├── __init__.py
│ ├── postgres_cart_repo.py
│ ├── postgres_order_repo.py
│ └── event_publisher.py
└── api/
├── __init__.py
├── cart_router.py
└── order_router.py
Value Object¶
Value object เก็บความหมายและบังคับ constraint ได้ในตัว โดยไม่ต้องมี identity:
# domain/value_objects.py
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
from uuid import UUID
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
def __post_init__(self):
if self.amount < 0:
raise ValueError(f"Money amount cannot be negative: {self.amount}")
if len(self.currency) != 3:
raise ValueError(f"Currency must be ISO 3-letter code: {self.currency}")
# Normalize to 2 decimal places
object.__setattr__(self, 'amount', self.amount.quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP
))
def add(self, other: 'Money') -> 'Money':
self._assert_same_currency(other)
return Money(self.amount + other.amount, self.currency)
def subtract(self, other: 'Money') -> 'Money':
self._assert_same_currency(other)
result = self.amount - other.amount
if result < 0:
raise ValueError("Result would be negative")
return Money(result, self.currency)
def multiply(self, factor: Decimal) -> 'Money':
return Money(self.amount * factor, self.currency)
def _assert_same_currency(self, other: 'Money') -> None:
if self.currency != other.currency:
raise ValueError(
f"Currency mismatch: {self.currency} vs {other.currency}"
)
def __str__(self) -> str:
return f"{self.amount} {self.currency}"
@classmethod
def zero(cls, currency: str = "USD") -> 'Money':
return cls(Decimal("0.00"), currency)
@dataclass(frozen=True)
class BookId:
value: UUID
def __str__(self):
return str(self.value)
@dataclass(frozen=True)
class CustomerId:
value: UUID
def __str__(self):
return str(self.value)
@dataclass(frozen=True)
class Address:
street_line_1: str
street_line_2: str
city: str
state_or_province: str
postal_code: str
country_code: str # ISO 3166-1 alpha-2
def __post_init__(self):
if not self.street_line_1.strip():
raise ValueError("Street address is required")
if len(self.country_code) != 2:
raise ValueError("Country code must be ISO 2-letter code")
@property
def is_international(self) -> bool:
return self.country_code != "US"
@dataclass(frozen=True)
class Coupon:
code: str
discount_percent: int # 0-100
def __post_init__(self):
if not (0 < self.discount_percent <= 100):
raise ValueError(f"Discount must be 1-100%: {self.discount_percent}")
if not self.code.strip():
raise ValueError("Coupon code cannot be empty")
def apply_to(self, amount: Money) -> Money:
discount = amount.multiply(Decimal(self.discount_percent) / 100)
return amount.subtract(discount)
Domain Event¶
Event คือบันทึกว่าเกิดอะไรขึ้นไปแล้ว สร้างแล้วแก้ไม่ได้:
# domain/events.py
from dataclasses import dataclass, field
from datetime import datetime, UTC
from uuid import UUID, uuid4
from .value_objects import Money
@dataclass(frozen=True)
class DomainEvent:
event_id: UUID = field(default_factory=uuid4)
occurred_at: datetime = field(default_factory=lambda: datetime.now(UTC))
@dataclass(frozen=True)
class BookAddedToCart(DomainEvent):
cart_id: UUID
customer_id: UUID
book_id: UUID
book_title: str
unit_price: Money
quantity: int
@dataclass(frozen=True)
class BookRemovedFromCart(DomainEvent):
cart_id: UUID
book_id: UUID
@dataclass(frozen=True)
class CouponApplied(DomainEvent):
cart_id: UUID
coupon_code: str
discount_percent: int
@dataclass(frozen=True)
class CartCheckedOut(DomainEvent):
cart_id: UUID
customer_id: UUID
total_amount: Money
@dataclass(frozen=True)
class OrderPlaced(DomainEvent):
order_id: UUID
customer_id: UUID
cart_id: UUID
total_amount: Money
item_count: int
@dataclass(frozen=True)
class OrderConfirmed(DomainEvent):
order_id: UUID
customer_id: UUID
total_amount: Money
@dataclass(frozen=True)
class OrderCancelled(DomainEvent):
order_id: UUID
customer_id: UUID
reason: str
refund_amount: Money
@dataclass(frozen=True)
class ReturnRequested(DomainEvent):
order_id: UUID
customer_id: UUID
reason: str
Domain Exception¶
ใช้ exception ที่เจาะจง และตั้งชื่อตาม Ubiquitous Language:
# domain/exceptions.py
class DomainError(Exception):
"""Base class for all domain errors."""
class EmptyCartError(DomainError):
"""Cannot check out an empty cart."""
class BookAlreadyInCartError(DomainError):
def __init__(self, book_id: str):
super().__init__(f"Book {book_id} is already in the cart")
class CartItemLimitExceededError(DomainError):
def __init__(self, limit: int):
super().__init__(f"Cannot add more than {limit} items to a cart")
class CouponAlreadyAppliedError(DomainError):
"""Only one coupon can be applied per cart."""
class InvalidOrderStatusTransitionError(DomainError):
def __init__(self, current: str, attempted: str):
super().__init__(
f"Cannot transition order from {current} to {attempted}"
)
class OrderAlreadyConfirmedError(DomainError):
"""Order has already been confirmed and cannot be modified."""
class ReturnWindowExpiredError(DomainError):
"""The 30-day return window has expired for this order."""
Cart Aggregate¶
# domain/cart.py
from dataclasses import dataclass, field
from decimal import Decimal
from uuid import UUID, uuid4
from typing import Optional
from .value_objects import Money, BookId, CustomerId, Coupon
from .events import (
BookAddedToCart, BookRemovedFromCart,
CouponApplied, CartCheckedOut, DomainEvent
)
from .exceptions import (
BookAlreadyInCartError, CartItemLimitExceededError,
CouponAlreadyAppliedError, EmptyCartError
)
MAX_CART_ITEMS = 50
@dataclass(frozen=True)
class CartItem:
"""Value Object — a snapshot of a book's details at add-to-cart time."""
book_id: BookId
book_title: str
unit_price: Money
quantity: int
@property
def subtotal(self) -> Money:
return self.unit_price.multiply(Decimal(self.quantity))
@dataclass
class Cart:
"""
Aggregate Root for the shopping cart.
Invariants enforced:
- Max 50 items
- A book appears at most once (quantity updated, not duplicated)
- Only one coupon can be active at a time
- Cart total is always consistent with items
"""
id: UUID
customer_id: CustomerId
_items: list[CartItem] = field(default_factory=list)
_coupon: Optional[Coupon] = field(default=None)
_events: list[DomainEvent] = field(default_factory=list)
# ── Factory ────────────────────────────────────────────────────
@classmethod
def create(cls, customer_id: CustomerId) -> 'Cart':
return cls(id=uuid4(), customer_id=customer_id)
# ── Commands ───────────────────────────────────────────────────
def add_book(
self,
book_id: BookId,
book_title: str,
unit_price: Money,
quantity: int = 1
) -> None:
# Enforce: max items limit
if len(self._items) >= MAX_CART_ITEMS:
raise CartItemLimitExceededError(MAX_CART_ITEMS)
# Enforce: no duplicates — update quantity instead
existing = self._find_item(book_id)
if existing:
raise BookAlreadyInCartError(str(book_id))
item = CartItem(
book_id=book_id,
book_title=book_title,
unit_price=unit_price,
quantity=quantity,
)
self._items.append(item)
self._record(BookAddedToCart(
cart_id=self.id,
customer_id=self.customer_id.value,
book_id=book_id.value,
book_title=book_title,
unit_price=unit_price,
quantity=quantity,
))
def remove_book(self, book_id: BookId) -> None:
item = self._find_item(book_id)
if item:
self._items.remove(item)
self._record(BookRemovedFromCart(
cart_id=self.id,
book_id=book_id.value,
))
def apply_coupon(self, coupon: Coupon) -> None:
if self._coupon is not None:
raise CouponAlreadyAppliedError(
f"Coupon {self._coupon.code} is already applied. "
f"Remove it before applying a new one."
)
self._coupon = coupon
self._record(CouponApplied(
cart_id=self.id,
coupon_code=coupon.code,
discount_percent=coupon.discount_percent,
))
def checkout(self) -> None:
if not self._items:
raise EmptyCartError("Cannot check out an empty cart")
self._record(CartCheckedOut(
cart_id=self.id,
customer_id=self.customer_id.value,
total_amount=self.total,
))
# ── Queries ────────────────────────────────────────────────────
@property
def items(self) -> list[CartItem]:
return list(self._items) # defensive copy
@property
def subtotal(self) -> Money:
if not self._items:
return Money.zero()
result = self._items[0].subtotal
for item in self._items[1:]:
result = result.add(item.subtotal)
return result
@property
def total(self) -> Money:
sub = self.subtotal
if self._coupon:
return self._coupon.apply_to(sub)
return sub
@property
def item_count(self) -> int:
return sum(item.quantity for item in self._items)
def is_empty(self) -> bool:
return len(self._items) == 0
# ── Event infrastructure ───────────────────────────────────────
def pull_events(self) -> list[DomainEvent]:
events = list(self._events)
self._events.clear()
return events
# ── Private helpers ────────────────────────────────────────────
def _find_item(self, book_id: BookId) -> Optional[CartItem]:
return next((i for i in self._items if i.book_id == book_id), None)
def _record(self, event: DomainEvent) -> None:
self._events.append(event)
Order Aggregate¶
# domain/order.py
from dataclasses import dataclass, field
from datetime import datetime, UTC, timedelta
from decimal import Decimal
from enum import Enum
from uuid import UUID, uuid4
from typing import Optional
from .value_objects import Money, BookId, CustomerId, Address
from .events import (
OrderPlaced, OrderConfirmed, OrderCancelled,
ReturnRequested, DomainEvent
)
from .exceptions import (
InvalidOrderStatusTransitionError, OrderAlreadyConfirmedError,
ReturnWindowExpiredError
)
from .cart import Cart, CartItem
RETURN_WINDOW_DAYS = 30
class OrderStatus(Enum):
PENDING_PAYMENT = "pending_payment"
CONFIRMED = "confirmed"
PROCESSING = "processing"
SHIPPED = "shipped"
DELIVERED = "delivered"
CANCELLED = "cancelled"
RETURN_REQUESTED = "return_requested"
REFUNDED = "refunded"
def can_cancel(self) -> bool:
return self in (
OrderStatus.PENDING_PAYMENT,
OrderStatus.CONFIRMED,
OrderStatus.PROCESSING,
)
def can_request_return(self) -> bool:
return self in (OrderStatus.DELIVERED,)
@dataclass(frozen=True)
class OrderLineItem:
"""
Value Object — a frozen snapshot of a cart item.
Prices and titles do NOT update when the catalog changes.
This is intentional — it records what the customer agreed to pay.
"""
book_id: BookId
book_title: str # snapshot — not a live reference
unit_price: Money # snapshot — price at time of order
quantity: int
@property
def subtotal(self) -> Money:
return self.unit_price.multiply(Decimal(self.quantity))
@dataclass
class Order:
"""
Aggregate Root for a customer's purchase.
Invariants enforced:
- Status can only follow valid transitions
- Cannot cancel a shipped/delivered order
- Returns only within 30-day window
- Line items are immutable after order placement
"""
id: UUID
customer_id: CustomerId
cart_id: UUID
status: OrderStatus
shipping_address: Address
_line_items: list[OrderLineItem]
placed_at: datetime
confirmed_at: Optional[datetime] = None
delivered_at: Optional[datetime] = None
_events: list[DomainEvent] = field(default_factory=list)
# ── Factory ────────────────────────────────────────────────────
@classmethod
def place_from_cart(
cls,
cart: Cart,
shipping_address: Address,
) -> 'Order':
"""
Creates an Order from a Cart.
Takes a snapshot of cart items — Cart and Order then evolve independently.
"""
if cart.is_empty():
raise ValueError("Cannot place an order from an empty cart")
# Snapshot all cart items into OrderLineItems
line_items = [
OrderLineItem(
book_id=item.book_id,
book_title=item.book_title,
unit_price=item.unit_price,
quantity=item.quantity,
)
for item in cart.items
]
order = cls(
id=uuid4(),
customer_id=cart.customer_id,
cart_id=cart.id,
status=OrderStatus.PENDING_PAYMENT,
shipping_address=shipping_address,
_line_items=line_items,
placed_at=datetime.now(UTC),
)
order._record(OrderPlaced(
order_id=order.id,
customer_id=cart.customer_id.value,
cart_id=cart.id,
total_amount=order.total,
item_count=len(line_items),
))
return order
# ── Commands ───────────────────────────────────────────────────
def confirm(self) -> None:
if self.status != OrderStatus.PENDING_PAYMENT:
raise InvalidOrderStatusTransitionError(
self.status.value, OrderStatus.CONFIRMED.value
)
self.status = OrderStatus.CONFIRMED
self.confirmed_at = datetime.now(UTC)
self._record(OrderConfirmed(
order_id=self.id,
customer_id=self.customer_id.value,
total_amount=self.total,
))
def cancel(self, reason: str) -> None:
if not self.status.can_cancel():
raise InvalidOrderStatusTransitionError(
self.status.value, OrderStatus.CANCELLED.value
)
self.status = OrderStatus.CANCELLED
self._record(OrderCancelled(
order_id=self.id,
customer_id=self.customer_id.value,
reason=reason,
refund_amount=self.total,
))
def mark_shipped(self) -> None:
if self.status != OrderStatus.PROCESSING:
raise InvalidOrderStatusTransitionError(
self.status.value, OrderStatus.SHIPPED.value
)
self.status = OrderStatus.SHIPPED
def mark_delivered(self) -> None:
if self.status != OrderStatus.SHIPPED:
raise InvalidOrderStatusTransitionError(
self.status.value, OrderStatus.DELIVERED.value
)
self.status = OrderStatus.DELIVERED
self.delivered_at = datetime.now(UTC)
def request_return(self, reason: str) -> None:
if not self.status.can_request_return():
raise InvalidOrderStatusTransitionError(
self.status.value, OrderStatus.RETURN_REQUESTED.value
)
if not self._within_return_window():
raise ReturnWindowExpiredError(
f"Return window of {RETURN_WINDOW_DAYS} days has expired"
)
self.status = OrderStatus.RETURN_REQUESTED
self._record(ReturnRequested(
order_id=self.id,
customer_id=self.customer_id.value,
reason=reason,
))
# ── Queries ────────────────────────────────────────────────────
@property
def line_items(self) -> list[OrderLineItem]:
return list(self._line_items) # defensive copy
@property
def total(self) -> Money:
if not self._line_items:
return Money.zero()
result = self._line_items[0].subtotal
for item in self._line_items[1:]:
result = result.add(item.subtotal)
return result
def _within_return_window(self) -> bool:
if not self.delivered_at:
return False
window_end = self.delivered_at + timedelta(days=RETURN_WINDOW_DAYS)
return datetime.now(UTC) <= window_end
# ── Event infrastructure ───────────────────────────────────────
def pull_events(self) -> list[DomainEvent]:
events = list(self._events)
self._events.clear()
return events
def _record(self, event: DomainEvent) -> None:
self._events.append(event)
Repository¶
Interface อยู่ใน domain layer ส่วน implementation ไปอยู่ใน infrastructure:
# domain/repositories.py (interface)
from abc import ABC, abstractmethod
from uuid import UUID
from typing import Optional
from .cart import Cart
from .order import Order
from .value_objects import CustomerId
class CartRepository(ABC):
@abstractmethod
def save(self, cart: Cart) -> None: ...
@abstractmethod
def find_by_id(self, cart_id: UUID) -> Optional[Cart]: ...
@abstractmethod
def find_active_by_customer(self, customer_id: CustomerId) -> Optional[Cart]: ...
class OrderRepository(ABC):
@abstractmethod
def save(self, order: Order) -> None: ...
@abstractmethod
def find_by_id(self, order_id: UUID) -> Optional[Order]: ...
@abstractmethod
def find_by_customer(self, customer_id: CustomerId) -> list[Order]: ...
Application Service (Use Case)¶
Application service มีหน้าที่ประสานงาน (orchestrate) อย่างเดียว ไม่มี business logic อยู่ข้างใน:
# application/order_service.py
from uuid import UUID
from dataclasses import dataclass
from ..domain.cart import Cart
from ..domain.order import Order
from ..domain.value_objects import CustomerId, BookId, Money, Address, Coupon
from ..domain.repositories import CartRepository, OrderRepository
from ..domain.exceptions import DomainError
@dataclass
class AddBookToCartCommand:
customer_id: UUID
book_id: UUID
book_title: str
unit_price_amount: str
currency: str
quantity: int = 1
@dataclass
class PlaceOrderCommand:
customer_id: UUID
street_line_1: str
city: str
state_or_province: str
postal_code: str
country_code: str
class CartApplicationService:
def __init__(
self,
cart_repo: CartRepository,
order_repo: OrderRepository,
event_publisher, # injected from outside
):
self._carts = cart_repo
self._orders = order_repo
self._events = event_publisher
def add_book_to_cart(self, cmd: AddBookToCartCommand) -> UUID:
customer_id = CustomerId(cmd.customer_id)
# Get or create cart
cart = self._carts.find_active_by_customer(customer_id)
if not cart:
cart = Cart.create(customer_id=customer_id)
# Delegate to domain — all business logic is there
cart.add_book(
book_id=BookId(cmd.book_id),
book_title=cmd.book_title,
unit_price=Money(amount=Decimal(cmd.unit_price_amount), currency=cmd.currency),
quantity=cmd.quantity,
)
# Persist and publish events
self._carts.save(cart)
for event in cart.pull_events():
self._events.publish(event)
return cart.id
def place_order(self, cmd: PlaceOrderCommand) -> UUID:
customer_id = CustomerId(cmd.customer_id)
cart = self._carts.find_active_by_customer(customer_id)
if not cart:
raise DomainError("No active cart found for this customer")
address = Address(
street_line_1=cmd.street_line_1,
street_line_2="",
city=cmd.city,
state_or_province=cmd.state_or_province,
postal_code=cmd.postal_code,
country_code=cmd.country_code,
)
# Cart checks out
cart.checkout()
# Order is created from cart snapshot
order = Order.place_from_cart(cart=cart, shipping_address=address)
# Save both
self._carts.save(cart)
self._orders.save(order)
# Publish all events (CartCheckedOut, OrderPlaced)
for event in cart.pull_events():
self._events.publish(event)
for event in order.pull_events():
self._events.publish(event)
return order.id
Phase 5: เชื่อม Bounded Context ด้วย Domain Event¶
พอ publish OrderPlaced ออกไป จะมีอีก 3 bounded context ที่ต้องตอบสนอง:
OrderPlaced event published
│
├──→ INVENTORY subscribes: "Reserve the books"
├──→ PAYMENTS subscribes: "Initiate payment collection"
└──→ MEMBERSHIP subscribes: "Start earning points"
แบบนี้เรียกว่า asynchronous event-driven integration Orders ไม่มี compile-time dependency กับ Inventory, Payments หรือ Membership เลย แต่ละ context subscribe เฉพาะ event ที่ตัวเองสนใจ
Event Schema (Published Language)¶
Event ที่วิ่งข้าม context ต้องมี schema ที่นิ่งและมี version กำกับ:
# This is the Published Language — shared schema between contexts
# Published as JSON on a message bus (Kafka, RabbitMQ, etc.)
# orders/events/order_placed_v1.py
@dataclass(frozen=True)
class OrderPlacedV1:
"""
Published event: emitted when a customer places an order.
Consumers: Inventory, Payments, Membership, Notifications.
Schema version: 1 (additive changes only — never remove fields).
"""
schema_version: str = "1"
event_type: str = "order.placed"
order_id: str
customer_id: str
placed_at: str # ISO 8601
total_amount: str # decimal string to avoid float issues
currency: str
item_count: int
items: list[dict] # [{book_id, title, quantity, unit_price}]
def to_dict(self) -> dict:
return {
"schema_version": self.schema_version,
"event_type": self.event_type,
"order_id": self.order_id,
"customer_id": self.customer_id,
"placed_at": self.placed_at,
"total_amount": self.total_amount,
"currency": self.currency,
"item_count": self.item_count,
"items": self.items,
}
ฝั่ง Inventory Context รับ Event¶
# inventory/application/event_handlers.py
class OrderPlacedHandler:
"""
Inventory reacts to orders placed in the Orders context.
This is the Anti-Corruption Layer — we translate the external event
into our own domain language before processing.
"""
def __init__(self, stock_service: StockReservationService):
self._stock = stock_service
def handle(self, event_data: dict) -> None:
# Translate external schema → our domain concepts (ACL)
order_id = event_data["order_id"]
items = [
StockReservationItem(
sku=item["book_id"], # "book_id" in Orders = "sku" in Inventory
quantity=item["quantity"],
)
for item in event_data["items"]
]
# Delegate to our own domain logic
self._stock.reserve_for_order(order_id=order_id, items=items)
รับมือกับ Eventual Consistency¶
พอใช้ async event ก็ต้องเตรียมรับกรณีที่ step หนึ่งผ่าน แต่อีก step พัง:
Scenario: OrderPlaced published, but Inventory reservation fails
Option 1 — Saga / Process Manager:
OrderPlaced → InventoryReserved → PaymentRequested
↑ ↓ (fails)
└── OrderCancelled ← InventoryReservationFailed
Option 2 — Outbox Pattern:
Write Order + Event to DB in one transaction.
Separate process reads Outbox table and publishes events.
Guarantees "at least once" delivery.
# The Outbox Pattern — guarantees no event is lost on publish failure
# In your repository save():
def save(self, order: Order) -> None:
with self._session.begin():
# 1. Save the order record
order_record = self._mapper.to_record(order)
self._session.merge(order_record)
# 2. Save events to outbox table in THE SAME TRANSACTION
for event in order.pull_events():
outbox_entry = OutboxEntry(
id=uuid4(),
event_type=type(event).__name__,
payload=json.dumps(event.to_dict()),
created_at=datetime.now(UTC),
published=False,
)
self._session.add(outbox_entry)
# Separate background process:
# SELECT * FROM outbox WHERE published = false
# → publish each to message bus
# → mark as published
# Retry failed publishes automatically
Phase 6: Test Domain Model¶
ข้อดีใหญ่ ๆ ของ domain model ที่ออกแบบดีคือ test business logic ได้ครบ ไม่ต้องมี database, web framework หรือ external service เลย
Unit Test Aggregate¶
# tests/domain/test_cart.py
import pytest
from decimal import Decimal
from uuid import uuid4
from orders.domain.cart import Cart
from orders.domain.value_objects import BookId, CustomerId, Money, Coupon
from orders.domain.exceptions import (
BookAlreadyInCartError, CartItemLimitExceededError,
CouponAlreadyAppliedError, EmptyCartError
)
from orders.domain.events import BookAddedToCart, CartCheckedOut
class TestCart:
def setup_method(self):
self.customer_id = CustomerId(uuid4())
self.cart = Cart.create(customer_id=self.customer_id)
self.book_id = BookId(uuid4())
self.price = Money(Decimal("29.99"), "USD")
def test_add_book_creates_cart_item(self):
self.cart.add_book(self.book_id, "Clean Code", self.price, quantity=1)
assert len(self.cart.items) == 1
assert self.cart.items[0].book_title == "Clean Code"
assert self.cart.total == self.price
def test_add_same_book_twice_raises_error(self):
self.cart.add_book(self.book_id, "Clean Code", self.price)
with pytest.raises(BookAlreadyInCartError):
self.cart.add_book(self.book_id, "Clean Code", self.price)
def test_total_includes_all_items(self):
book_2 = BookId(uuid4())
price_2 = Money(Decimal("19.99"), "USD")
self.cart.add_book(self.book_id, "Clean Code", self.price)
self.cart.add_book(book_2, "The Pragmatic Programmer", price_2)
assert self.cart.total == Money(Decimal("49.98"), "USD")
def test_coupon_reduces_total(self):
self.cart.add_book(self.book_id, "Clean Code", Money(Decimal("100.00"), "USD"))
self.cart.apply_coupon(Coupon(code="SAVE20", discount_percent=20))
assert self.cart.total == Money(Decimal("80.00"), "USD")
def test_cannot_apply_two_coupons(self):
self.cart.add_book(self.book_id, "Clean Code", self.price)
self.cart.apply_coupon(Coupon(code="FIRST", discount_percent=10))
with pytest.raises(CouponAlreadyAppliedError):
self.cart.apply_coupon(Coupon(code="SECOND", discount_percent=20))
def test_checkout_empty_cart_raises_error(self):
with pytest.raises(EmptyCartError):
self.cart.checkout()
def test_add_book_emits_event(self):
self.cart.add_book(self.book_id, "Clean Code", self.price)
events = self.cart.pull_events()
assert len(events) == 1
assert isinstance(events[0], BookAddedToCart)
assert events[0].book_title == "Clean Code"
def test_checkout_emits_event_with_correct_total(self):
self.cart.add_book(self.book_id, "Clean Code", self.price)
self.cart.checkout()
events = self.cart.pull_events()
checkout_events = [e for e in events if isinstance(e, CartCheckedOut)]
assert len(checkout_events) == 1
assert checkout_events[0].total_amount == self.price
class TestOrder:
def test_cannot_cancel_shipped_order(self):
order = self._make_order_in_status(OrderStatus.SHIPPED)
with pytest.raises(InvalidOrderStatusTransitionError):
order.cancel("Changed my mind")
def test_return_outside_window_raises_error(self):
order = self._make_delivered_order(days_ago=31)
with pytest.raises(ReturnWindowExpiredError):
order.request_return("Book was damaged")
def test_return_within_window_succeeds(self):
order = self._make_delivered_order(days_ago=5)
order.request_return("Book was damaged")
assert order.status == OrderStatus.RETURN_REQUESTED
def test_confirm_publishes_event(self):
order = self._make_order_in_status(OrderStatus.PENDING_PAYMENT)
order.confirm()
events = order.pull_events()
confirmed = [e for e in events if isinstance(e, OrderConfirmed)]
assert len(confirmed) == 1
assert confirmed[0].order_id == order.id
Integration Test ด้วย In-Memory Repository¶
# tests/application/test_cart_service.py
class InMemoryCartRepository(CartRepository):
def __init__(self):
self._store: dict[UUID, Cart] = {}
def save(self, cart: Cart) -> None:
self._store[cart.id] = cart
def find_by_id(self, cart_id: UUID) -> Optional[Cart]:
return self._store.get(cart_id)
def find_active_by_customer(self, customer_id: CustomerId) -> Optional[Cart]:
return next(
(c for c in self._store.values()
if c.customer_id == customer_id),
None
)
class FakeEventPublisher:
def __init__(self):
self.published: list = []
def publish(self, event) -> None:
self.published.append(event)
class TestCartApplicationService:
def setup_method(self):
self.cart_repo = InMemoryCartRepository()
self.order_repo = InMemoryOrderRepository()
self.events = FakeEventPublisher()
self.service = CartApplicationService(
cart_repo=self.cart_repo,
order_repo=self.order_repo,
event_publisher=self.events,
)
def test_add_book_creates_new_cart(self):
customer_id = uuid4()
cmd = AddBookToCartCommand(
customer_id=customer_id,
book_id=uuid4(),
book_title="Domain-Driven Design",
unit_price_amount="54.99",
currency="USD",
)
cart_id = self.service.add_book_to_cart(cmd)
cart = self.cart_repo.find_by_id(cart_id)
assert cart is not None
assert len(cart.items) == 1
assert cart.items[0].book_title == "Domain-Driven Design"
def test_add_book_publishes_event(self):
cmd = AddBookToCartCommand(
customer_id=uuid4(),
book_id=uuid4(),
book_title="Clean Architecture",
unit_price_amount="39.99",
currency="USD",
)
self.service.add_book_to_cart(cmd)
assert len(self.events.published) == 1
assert isinstance(self.events.published[0], BookAddedToCart)
Swift Method: จาก Event Storm สู่ Story¶
ถ้าทีมใช้ Jira หรือ Linear จัดการ story อยู่แล้ว Swift Method (จาก blog post ต้นฉบับ) ช่วยต่อผลจาก Event Storming ให้กลายเป็น development story
BORIS — Business Object Relationships and Interaction Specification¶
หลัง Event Storming เสร็จ ใช้ BORIS map ว่า actor ไหนคุยกับ aggregate ไหน แล้วได้ event อะไรออกมา:
BORIS table for Bookly Orders context:
┌──────────────┬─────────────────────┬──────────────────────────┐
│ Actor │ Command │ Event(s) │
├──────────────┼─────────────────────┼──────────────────────────┤
│ Customer │ Add Book to Cart │ BookAddedToCart │
│ Customer │ Apply Coupon │ CouponApplied │
│ Customer │ Initiate Checkout │ CartCheckedOut │
│ Customer │ Place Order │ OrderPlaced │
│ Customer │ Cancel Order │ OrderCancelled │
│ Customer │ Request Return │ ReturnRequested │
│ Payment GW │ Confirm Payment │ OrderConfirmed │
│ Payment GW │ Reject Payment │ OrderCancelled │
│ Warehouse │ Dispatch Order │ OrderShipped │
│ Courier │ Confirm Delivery │ OrderDelivered │
└──────────────┴─────────────────────┴──────────────────────────┘
SNAP — Specification by NAmePart¶
SNAP เอาแต่ละแถวของ BORIS มาเขียนเป็น story specification ทำทีละคู่ Command → Event:
SNAP for "Add Book to Cart":
GIVEN: Customer [X] has an active cart (or will get a new one)
WHEN: Customer adds Book [Y] with quantity [Z]
THEN: Book is in the cart with correct subtotal
AND: BookAddedToCart event is published
AND: Cart total is recalculated
Acceptance Criteria:
✅ Adding the same book twice raises an error (not duplicated)
✅ Adding more than 50 books raises an error
✅ Total correctly reflects the coupon discount if applied
✅ Checkout with an empty cart is rejected
SNAP spec พวกนี้แปลงเป็น Jira user story และ unit test case ได้ตรง ๆ spec กับ test คือของชิ้นเดียวกัน
หลุมพราง DDD ที่เจอบ่อยตอนทำจริง¶
1. เริ่มจาก Database Schema¶
ความผิดพลาด: เปิด SQL editor ออกแบบ table ก่อน แล้วค่อยเขียน code มาใส่ข้อมูล
ทำไมถึงพัง: สุดท้ายได้ anemic domain model ที่หน้าตาเหมือน table ไม่ใช่เหมือนธุรกิจ business rule กระจายไปอยู่ใน stored procedure, service และ controller
วิธีแก้: ออกแบบ domain model ก่อน แล้วค่อยให้ database schema ตามมาจาก model ไม่ใช่กลับกัน
2. Aggregate ใหญ่เกิน → Lock กันวุ่นวาย¶
อาการ: user สองคนใช้ระบบพร้อมกันไม่ได้ operation ธรรมดา ๆ ก็ timeout
สาเหตุ: มัด business object ทุกตัวไว้ใน aggregate เดียว operation ไหนก็ lock ทั้งก้อน
วิธีแก้: ถามตัวเองว่า "ข้อมูลชุด เล็กที่สุด ที่ต้อง consistent คืออะไร?" แล้วออกแบบ aggregate รอบข้อมูลชุดนั้น ที่เหลือใช้ eventual consistency (domain event) ไป
3. ใช้ Database ร่วมกันระหว่าง Bounded Context¶
ความผิดพลาด: service Orders กับ service Inventory ต่างก็ SELECT และ UPDATE table orders ตัวเดียวกัน
ทำไมถึงพัง: แก้ schema ทีไรพังทั้งสอง service แต่ละ context พัฒนาแยกกันไม่ได้ deploy ก็ต้องผูกกันไปด้วย
วิธีแก้: แต่ละ bounded context มี database ของตัวเอง ถ้า Inventory อยากได้ข้อมูล order ก็ subscribe event OrderPlaced แล้วเก็บ projection ของตัวเองไว้
# BAD: Inventory queries the Orders database directly
def reserve_stock(order_id):
order = orders_db.execute("SELECT * FROM orders WHERE id = ?", order_id)
# Now Inventory is coupled to Orders' schema forever
# GOOD: Inventory maintains its own read model, populated by events
class InventoryOrderProjection:
def on_order_placed(self, event: dict) -> None:
# Store only what Inventory cares about
self._db.execute(
"INSERT INTO inventory_orders (order_id, items) VALUES (?, ?)",
event["order_id"], json.dumps(event["items"])
)
4. ยัด Business Logic ไว้ใน Application Service¶
อาการ: method ใน application service ยาวเป็นร้อยบรรทัด ส่วน domain object เหลือแค่ data class เปล่า ๆ
วิธีแก้: if ตัวไหนที่เป็น business rule ย้ายเข้าไปใน aggregate ให้หมด application service ควรอ่านแล้วสั้นเหมือนสรุป: "ดึงอันนี้ เรียกอันนั้น save แล้ว publish"
5. ข้าม Event Storming ("เรารู้ domain อยู่แล้ว")¶
ทำไมถึงพัง: เราไม่รู้หรอกว่าตัวเองยังไม่รู้อะไร ของที่มีค่าที่สุดจาก Event Storming คือเรื่องที่ทำให้ทุกคนอึ้ง เช่น business rule ที่อยู่ในหัวใครสักคน แต่ไม่ได้เขียนไว้ในเอกสารไหนเลย
ต่อให้คิดว่ารู้ domain ดีแล้ว ก็ลองทำ event storming สัก 2 ชั่วโมง แค่ได้เจอช่วง "เดี๋ยวนะ อะไรนะ?" ไม่กี่ครั้ง ก็คุ้มเวลาไปหลายเท่าแล้ว
DDD in Action: Playbook ของคุณ¶
ตอนเริ่มโปรเจกต์ DDD ใช้ checklist นี้ไล่ทีละข้อ:
Discovery Phase
- ไล่ดูว่ามี stakeholder ใครบ้าง ใครเป็นคนถือความรู้เรื่อง domain?
- ทำ Event Storming (domain ที่มีเนื้อพอสมควร ใช้อย่างน้อย 4 ชั่วโมง)
- ทำ event timeline แล้วหา hotspot (จุดที่คนสับสนหรือซับซ้อน)
- ร่าง glossary ของ Ubiquitous Language ฉบับแรก
Design Phase
- ขีดเส้น candidate Bounded Context ลงบนผลของ Event Storm
- ตั้งชื่อ bounded context แต่ละตัว (เริ่มจากหนึ่งทีมดูแลหนึ่ง context)
- เขียน Context Map (context ไหนสัมพันธ์กันยังไง ใช้ pattern อะไร)
- หา aggregate ของแต่ละ context เริ่มจากเล็ก ๆ ก่อน จำเป็นค่อยแยกทีหลัง
- เช็กขอบเขต aggregate: "อะไรบ้างที่ต้อง consistent ไปพร้อมกัน?"
Implementation Phase
- สร้างโครงสร้าง folder (domain / application / infrastructure / api)
- Implement Value Object ก่อน (เป็น pure code และ test ง่าย)
- Implement Aggregate พร้อม business invariant และ domain event
- กำหนด Repository interface ใน domain layer
- Implement Application Service (ทำแค่ orchestration บาง ๆ)
- Implement Repository ใน infrastructure layer
- ส่ง event ออกผ่าน Outbox Pattern
Validation Phase
- Unit test aggregate ทุกตัวแบบแยกเดี่ยว (ไม่ต้องมี database)
- Integration test application service ด้วย in-memory repository
- Test ว่า publish และ consume event ข้าม context ได้จริง
- Review: code อ่านแล้วเหมือนเล่าเรื่องธุรกิจไหม? domain expert อ่านแล้วเข้าใจหรือเปล่า?
- อัปเดต glossary ของ Ubiquitous Language ทุกครั้งที่เข้าใจ domain มากขึ้น
สรุป¶
DDD ตอนลงมือจริงคือ loop แบบนี้:
Discover the domain → Draw the boundaries → Design the aggregates
↑ ↓
Refine the model ← Test rigorously ← Implement in code
หัวใจของเรื่องนี้คือ code คือ model ของสิ่งที่คุณเข้าใจเกี่ยวกับ domain ยิ่งเข้าใจลึกขึ้น ไม่ว่าจากการทำ Event Storming คุยกับ stakeholder หรือ ship feature ออกไป model ก็ควรลึกตามไปด้วย
Practice ที่ทำให้ทั้งหมดนี้เวิร์ก:
- Event Storming ช่วยให้ทุกคนเข้าใจตรงกัน ก่อนเขียน code บรรทัดแรก
- Bounded Context ให้แต่ละทีมทำงานได้อิสระ และกันไม่ให้คำเดียวกันมีความหมายตีกัน
- Aggregate เล็ก ๆ รักษา consistency ได้ โดยไม่ต้อง lock ทั้งระบบ
- Domain Event เชื่อม context เข้าหากันโดยไม่ผูกติด
- Rich Domain Model เก็บ business logic ไว้ในที่ที่ควรอยู่ คือใน domain
- Outbox Pattern การันตีว่า event ไม่หายไปเงียบ ๆ
- Test ที่อ่านแล้วเหมือน specification เขียนแบบ SNAP แล้วได้ทั้ง spec และ test ในทีเดียว
DDD ไม่ได้มีไว้ใช้ pattern เพื่อ pattern แต่มีไว้ทำ software ที่ ซื่อตรง ซื่อตรงกับสิ่งที่ธุรกิจทำจริง ซื่อตรงว่าใครดูแลอะไร และซื่อตรงว่าความซับซ้อนอยู่ตรงไหน เป็น code ที่ domain expert คนไหนมาเปิดดูก็พูดได้ว่า "ใช่ เราทำงานกันแบบนี้แหละ"
อยากลงลึกทฤษฎีพื้นฐานที่อยู่เบื้องหลัง practice พวกนี้ อ่านต่อได้ที่ Domain-Driven Design: The Complete Guide มีคำถามอะไร ทักมาได้ทาง LinkedIn, X หรือ email
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.