Конечные автоматы для оркестрации
Применяйте концепции конечных автоматов для создания надежных и предсказуемых оркестраторов Саги, отслеживающих ход транзакции.
«Конечные автоматы для оркестрации» — бесплатный урок Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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_CREATEDstate andORDER_PLACEDevent occurs, transition toPAYMENT_PENDING. - If in
PAYMENT_PENDINGstate andPAYMENT_SUCCESSevent occurs, transition toPAID.
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.
Изучай Microservices Communication Patterns (Saga, Circuit Breaker) с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Конечные автоматы для оркестрации» бесплатный?
Да — полный текст урока «Конечные автоматы для оркестрации» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Microservices Communication Patterns (Saga, Circuit Breaker), подпишись на CoddyKit PRO. Курс Microservices Communication Patterns (Saga, Circuit Breaker) содержит 4 уроков всего.
Чему я научусь в уроке «Конечные автоматы для оркестрации»?
Применяйте концепции конечных автоматов для создания надежных и предсказуемых оркестраторов Саги, отслеживающих ход транзакции. Ты практикуешь Microservices Communication Patterns (Saga, Circuit Breaker) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Microservices Communication Patterns (Saga, Circuit Breaker)?
Предыдущий опыт не требуется. Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Конечные автоматы для оркестрации»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Microservices Communication Patterns (Saga, Circuit Breaker)?
Да. Каждый урок Microservices Communication Patterns (Saga, Circuit Breaker) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Проектирование оркестраторов Саги
- Конечные автоматы для оркестрации
- Реализация с помощью движка рабочих процессов
- Тестирование оркестрованных саг