Development

Saga Pattern คืออะไร? คู่มือ Distributed Transactions ใน Microservices SME ไทย 2026

คู่มือ Saga Pattern สำหรับ SME ไทย แก้ปัญหา Distributed Transactions ใน Microservices ด้วย Choreography และ Orchestration พร้อมตัวอย่างจริงและ Best Practices ปี 2026

AF
ADS FIT Team
·8 นาที
Share:
Saga Pattern คืออะไร? คู่มือ Distributed Transactions ใน Microservices SME ไทย 2026

# Saga Pattern คืออะไร? คู่มือ Distributed Transactions ใน Microservices SME ไทย 2026

เมื่อระบบของคุณย้ายจาก Monolith มาเป็น Microservices ความท้าทายที่ใหญ่ที่สุดเรื่องหนึ่งคือ "Distributed Transactions" — การทำงานที่ต้องใช้หลายบริการพร้อมกัน เช่น สั่งซื้อสินค้าที่ต้องตัด Stock ตัด Wallet และส่ง Email Confirmation

ใน Monolith เราใช้ Database Transaction (ACID) ได้ง่ายๆ แต่ใน Microservices แต่ละ Service มี Database ของตัวเอง การใช้ 2-Phase Commit ก็ Lock นานและมี Single Point of Failure

นี่คือเหตุผลที่ Saga Pattern กลายเป็น Standard ของการจัดการ Distributed Transactions ใน Modern Microservices ปี 2026 บทความนี้จะอธิบายตั้งแต่หลักการ ไปจนถึงตัวอย่างจริงและขั้นตอนการ Implement

Saga Pattern คืออะไร?

Saga Pattern เป็นรูปแบบการออกแบบระบบที่แบ่ง Distributed Transaction ใหญ่ออกเป็น Local Transactions เล็กๆ ที่แต่ละ Service จัดการเอง โดยมี Compensating Transactions สำหรับย้อนกลับเมื่อขั้นตอนใดขั้นตอนหนึ่งล้มเหลว

แนวคิดนี้ถูกตีพิมพ์ครั้งแรกในปี 1987 โดย Hector Garcia-Molina และ Kenneth Salem แต่กลับมาเป็นที่นิยมในยุค Microservices

หลักการสำคัญ

| คุณสมบัติ | คำอธิบาย |

|----------|---------|

| Local Transaction | แต่ละขั้นตอนเป็น ACID ใน Service เดียว |

| Compensating Action | ทุก Step ต้องมี Action ย้อนกลับ |

| Eventually Consistent | ข้อมูลจะ Consistent ในที่สุด ไม่ใช่ทันที |

| No Lock | ไม่มี Global Lock เหมือน 2PC |

Saga Pattern Types: 2 รูปแบบหลัก

1. Choreography-based Saga

แต่ละ Service สื่อสารกันผ่าน Events โดยไม่มี Central Coordinator ทำงานเหมือน "เต้นรำ" ที่แต่ละคนรู้จังหวะของตัวเอง

ข้อดี:

  • ไม่มี Single Point of Failure
  • Decoupling สูง - แต่ละ Service Independent
  • เหมาะกับ Workflow ที่ไม่ซับซ้อน
  • ข้อเสีย:

  • ติดตาม State ยากเมื่อ Workflow ซับซ้อน
  • Testing & Debugging ยากกว่า
  • Cyclic Dependencies เกิดง่าย
  • 2. Orchestration-based Saga

    มี Central Orchestrator คอยสั่งการแต่ละ Service ตาม Workflow ที่กำหนด เหมือน "วาทยกร" ในวงออร์เคสตร้า

    ข้อดี:

  • เห็น Business Logic ทั้งหมดในที่เดียว
  • Debug ง่าย - มี Audit Trail ชัดเจน
  • จัดการ Compensation อัตโนมัติ
  • ข้อเสีย:

  • Orchestrator เป็น Single Point of Failure
  • Coupling สูงกว่า Choreography
  • ต้อง Maintain Orchestrator แยก
  • ตัวอย่างจริง: ระบบสั่งซื้อ E-Commerce

    Workflow ปกติ

  • **Order Service**: สร้าง Order (status = PENDING)
  • **Payment Service**: ตัดเงินจาก Wallet
  • **Inventory Service**: ตัด Stock
  • **Shipping Service**: สร้าง Shipment
  • **Order Service**: Update status = COMPLETED
  • กรณี Stock หมด (Compensation)

    หาก Inventory Service พบว่า Stock หมดที่ Step 3 ระบบต้องย้อนกลับ:

  • Inventory: ส่ง Event "OrderFailed"
  • Payment: Refund เงินกลับ Wallet
  • Order: Update status = FAILED
  • Choreography Implementation ตัวอย่าง (Node.js + Kafka)

    Order Service - Producer

    ```javascript

    async function createOrder(data) {

    const order = await db.orders.create({

    ...data,

    status: 'PENDING'

    });

    await kafka.produce('order.created', {

    orderId: order.id,

    userId: data.userId,

    amount: data.amount,

    items: data.items

    });

    return order;

    }

    ```

    Payment Service - Consumer + Producer

    ```javascript

    kafka.consume('order.created', async (event) => {

    try {

    const payment = await wallet.deduct(event.userId, event.amount);

    await kafka.produce('payment.completed', {

    orderId: event.orderId,

    paymentId: payment.id

    });

    } catch (error) {

    await kafka.produce('payment.failed', {

    orderId: event.orderId,

    reason: error.message

    });

    }

    });

    ```

    Compensation Logic

    ```javascript

    kafka.consume('inventory.failed', async (event) => {

    const payment = await db.payments.findByOrder(event.orderId);

    await wallet.refund(payment.userId, payment.amount);

    await kafka.produce('payment.refunded', {

    orderId: event.orderId

    });

    });

    ```

    Orchestration Implementation ตัวอย่าง (Temporal/Camunda)

    Saga Workflow Definition

    ```javascript

    async function orderSaga(orderId) {

    const compensations = [];

    try {

    // Step 1: Reserve Payment

    await paymentService.reserve(orderId);

    compensations.push(() => paymentService.refund(orderId));

    // Step 2: Reserve Inventory

    await inventoryService.reserve(orderId);

    compensations.push(() => inventoryService.release(orderId));

    // Step 3: Create Shipment

    await shippingService.create(orderId);

    compensations.push(() => shippingService.cancel(orderId));

    // Step 4: Confirm Order

    await orderService.confirm(orderId);

    } catch (error) {

    // Run compensations in reverse order

    for (const compensate of compensations.reverse()) {

    await compensate();

    }

    throw error;

    }

    }

    ```

    Saga Pattern vs Alternatives

    | รูปแบบ | ข้อดี | ข้อจำกัด | เหมาะกับ |

    |--------|------|---------|---------|

    | Saga | Eventually Consistent, Scalable | Compensation Logic ซับซ้อน | Microservices ทั่วไป |

    | 2PC | Strong Consistency | Lock นาน, Single Point Failure | Legacy Systems |

    | TCC (Try-Confirm-Cancel) | Reservation-based | ต้องออกแบบ Resource ให้รองรับ | Financial Systems |

    | Event Sourcing | Audit Trail สมบูรณ์ | ซับซ้อน, Storage มาก | High-Compliance Systems |

    Best Practices สำหรับ SME ไทย

  • **เริ่มด้วย Choreography**: ระบบขนาดเล็ก-กลางใช้ Choreography ก็พอ ลดความซับซ้อนได้
  • **เปลี่ยนเป็น Orchestration เมื่อ Workflow >5 Steps**: Workflow ซับซ้อนต้องการ Visibility
  • **Idempotency คือหัวใจ**: ทุก Step ต้องเรียกซ้ำได้โดยไม่กระทบ State (ใช้ Idempotency Key)
  • **Compensation ต้อง Reliable**: ออกแบบให้ Compensation ทำงานสำเร็จเสมอ ไม่งั้น State จะค้าง
  • **Saga Log / Event Store**: บันทึกทุก Step เพื่อ Replay เมื่อ Service Restart
  • **Timeout & Retry**: กำหนด Timeout ที่เหมาะสม และ Retry ด้วย Exponential Backoff
  • **Monitoring & Alerting**: Track Saga Duration และ Failure Rate ผ่าน Distributed Tracing
  • Tools & Frameworks ปี 2026

  • **Temporal**: Open-source Workflow Engine ที่กำลัง Hot สุดในปัจจุบัน
  • **Camunda Zeebe**: BPMN-based Orchestrator ระดับ Enterprise
  • **AWS Step Functions**: Serverless Orchestration บน AWS
  • **Apache Kafka + Kafka Streams**: Choreography-based Event Bus
  • **NServiceBus / MassTransit**: .NET Saga Frameworks
  • **Axon Framework**: Java/Kotlin CQRS + Saga
  • ปัญหาที่พบบ่อยและวิธีแก้

    ปัญหา 1: Compensation ล้มเหลว

    สาเหตุ: Service ที่ต้อง Compensate Down อยู่

    วิธีแก้: ใช้ Outbox Pattern + Retry Queue เพื่อรับประกันว่า Compensation จะทำงานในที่สุด

    ปัญหา 2: Duplicate Processing

    สาเหตุ: Network Issue ทำให้ Event ถูกส่งซ้ำ

    วิธีแก้: Implement Idempotency Key ในทุก Endpoint เพื่อให้ Process ซ้ำได้

    ปัญหา 3: Lost Updates ระหว่าง Compensation

    สาเหตุ: User เพิ่ม Wallet ก่อน Refund ทำงาน

    วิธีแก้: ใช้ Optimistic Locking หรือ Compensation-aware Business Logic

    สรุปและก้าวต่อไป

    Saga Pattern เป็นเครื่องมือสำคัญในการสร้าง Microservices ที่เสถียรและ Scalable สำหรับ SME ไทยในปี 2026 ที่กำลัง Modernize ระบบจาก Monolith การเริ่มต้นด้วย Choreography-based Saga และค่อยๆ ขยับไปใช้ Orchestration เมื่อ Workflow ซับซ้อนขึ้น คือเส้นทางที่เหมาะสม

    หากคุณกำลังออกแบบระบบ Microservices หรือ Modernize Legacy System ทีมงาน ADS FIT พร้อมให้คำปรึกษาเรื่อง Architecture Design และ Implementation ติดต่อเราเพื่อรับ Architecture Review ฟรี หรืออ่านบทความที่เกี่ยวข้องเรื่อง [Webhooks & Event-Driven Architecture](/blog/webhooks-event-driven-architecture-api-integration-guide-sme-thailand-2026) และ [Domain Driven Design](/blog/domain-driven-design-strategic-tactical-patterns-microservices-guide-sme-thailand-2026)

    Tags

    #Saga Pattern#Microservices#Distributed Transactions#Choreography#Orchestration

    สนใจโซลูชันนี้?

    ปรึกษาทีม ADS FIT ฟรี เราพร้อมออกแบบระบบที่ฟิตกับธุรกิจของคุณ

    ติดต่อเรา →

    บทความที่เกี่ยวข้อง