0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · 강의

오케스트레이션을 위한 상태 머신

트랜잭션 진행 상황을 추적하는 견고하고 예측 가능한 사가 오케스트레이터를 구축하기 위해 상태 머신 개념을 적용합니다.

오케스트레이션을 위한 상태 머신은(는) CoddyKit의 무료 Microservices Communication Patterns (Saga, Circuit Breaker) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Microservices Communication Patterns (Saga, Circuit Breaker) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

State Machines for Sagas

Welcome to this lesson on using state machines to build robust saga orchestrators!

Orchestration sagas manage complex distributed transactions by keeping track of the overall process. State machines are a powerful tool for this.

Why State Machines?

A saga orchestrator needs to know the exact status of a business process at any given moment. This allows it to:

  • Decide the next action to take.
  • Handle failures and trigger compensation.
  • Ensure consistency across multiple services.

State machines provide a clear, structured way to model this complex logic.

State Machine Basics

At its core, a state machine consists of three main concepts:

  • States: Represent different phases or conditions of the saga (e.g., OrderCreated, PaymentPending).
  • Events: Occurrences that trigger changes in the saga (e.g., PaymentSuccessful, ShipmentFailed).
  • Transitions: Rules that define how an event causes the saga to move from one state to another.

Example: Order Processing Saga

Let's consider a common scenario: an online order processing saga.

This saga might involve several services:

  • Order Service
  • Payment Service
  • Shipping Service

The orchestrator needs to coordinate these steps.

Defining Saga States

For our order processing saga, we can define states like:

  • ORDER_CREATED: Initial state.
  • PAYMENT_PENDING: Waiting for payment confirmation.
  • PAID: Payment successful.
  • SHIPPING_PENDING: Waiting for shipment to be initiated.
  • SHIPPED: Item has been shipped.
  • CANCELLED: Order cancelled (due to failure or user action).

Defining Saga Events

And the events that can occur:

  • ORDER_PLACED: Customer places an order.
  • PAYMENT_SUCCESS: Payment service confirms payment.
  • PAYMENT_FAILED: Payment service reports failure.
  • SHIPMENT_SUCCESS: Shipping service confirms shipment.
  • SHIPMENT_FAILED: Shipping service reports an issue.
  • ORDER_CANCELLED_REQUEST: User requests cancellation.

State Transition Logic

The core of a state machine is its transition logic: Current State + Event = New State (and possibly an action).

For example:

  • If in ORDER_CREATED state and ORDER_PLACED event occurs, transition to PAYMENT_PENDING.
  • If in PAYMENT_PENDING state and PAYMENT_SUCCESS event occurs, transition to PAID.

This defines the predictable flow of your saga.

Code: Simple State Transition

Here's a simplified Java example demonstrating how states and events can drive transitions in an orchestrator.

Try running it to see the state changes!

public class SimpleSagaState {

    public enum SagaStepState {
        STARTED,
        PROCESSING_PAYMENT,
        PAYMENT_COMPLETE,
        FAILED
    }

    private SagaStepState currentState;

    public SimpleSagaState() {
        this.currentState = SagaStepState.STARTED;
    }

    public SagaStepState getCurrentState() {
        return currentState;
    }

    public void processEvent(String event) {
        System.out.println("Event: " + event);
        switch (currentState) {
            case STARTED:
                if ("OrderCreated".equals(event)) {
                    currentState = SagaStepState.PROCESSING_PAYMENT;
                }
                break;
            case PROCESSING_PAYMENT:
                if ("PaymentSuccess".equals(event)) {
                    currentState = SagaStepState.PAYMENT_COMPLETE;
                } else if ("PaymentFailed".equals(event)) {
                    currentState = SagaStepState.FAILED;
                }
                break;
            case PAYMENT_COMPLETE:
                // After payment, might go to shipping, etc.
                break;
            case FAILED:
                System.out.println("Saga already failed.");
                break;
        }
        System.out.println("New State: " + currentState);
    }

    public static void main(String[] args) {
        SimpleSagaState saga = new SimpleSagaState();
        System.out.println("Initial State: " + saga.getCurrentState());

        saga.processEvent("OrderCreated");
        saga.processEvent("PaymentSuccess");
        saga.processEvent("ShipmentInitiated"); // This event won't change state in this simplified example

        System.out.println("Final State: " + saga.getCurrentState());
    }
}

Compensation with States

One of the biggest advantages of using state machines for sagas is how they simplify compensation logic.

If a service fails, the orchestrator receives a 'failed' event. Based on the current state, the state machine can determine which compensation actions need to be triggered to reverse previous successful steps.

For example, if in PAID state and SHIPMENT_FAILED occurs, the state machine can transition to CANCELLED and trigger a refund.

State Transition Question

Consider an order saga using a state machine. The order is currently in the PAYMENT_PENDING state.

If the orchestrator receives a PAYMENT_FAILED event, what is the most appropriate next state for the saga, typically indicating compensation?

Recap: States for Orchestration

In this lesson, we explored how state machines are crucial for building robust saga orchestrators.

  • They provide a clear model for tracking saga progress.
  • States, Events, and Transitions define the saga's flow.
  • They simplify handling complex logic, especially for compensation.

By explicitly defining states and transitions, you create predictable and resilient distributed transactions.

자주 묻는 질문

“오케스트레이션을 위한 상태 머신” 강의는 무료인가요?

네 — “오케스트레이션을 위한 상태 머신” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Microservices Communication Patterns (Saga, Circuit Breaker) 강의 전체를 잠금 해제할 수 있습니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.

“오케스트레이션을 위한 상태 머신”에서 뭘 배우나요?

트랜잭션 진행 상황을 추적하는 견고하고 예측 가능한 사가 오케스트레이터를 구축하기 위해 상태 머신 개념을 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Microservices Communication Patterns (Saga, Circuit Breaker)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“오케스트레이션을 위한 상태 머신” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사가 오케스트레이터 설계
  2. 오케스트레이션을 위한 상태 머신
  3. 워크플로 엔진을 사용한 구현
  4. 오케스트레이션 사가 검증
← Microservices Communication Patterns (Saga, Circuit Breaker)(으)로 돌아가기