Workflow 패턴 (Patterns)
다양한 유형의 워크플로 패턴을 작성하는 방법을 살펴봐요. Dapr Workflow는 마이크로서비스 아키텍처의 복잡하고 상태 기반인 조정 요구를 단순화합니다. 다음 섹션에서는 Dapr Workflow가 유용하게 쓰일 수 있는 여러 애플리케이션 패턴을 설명합니다.
출처: Dapr 문서
본문
태스크 체이닝 (Task chaining)
태스크 체이닝 패턴에서는 워크플로의 여러 단계를 연속으로 실행하며, 한 단계의 출력이 다음 단계의 입력으로 전달될 수 있습니다. 태스크 체이닝 워크플로는 전형적으로 어떤 데이터에 대해 수행해야 하는 일련의 연산(예: 필터링, 변환, 리듀스)을 만드는 것을 포함합니다. 어떤 경우에는 워크플로의 단계를 여러 마이크로서비스에 걸쳐 오케스트레이션해야 할 수 있습니다. 신뢰성과 확장성을 높이기 위해, 여러 단계를 트리거하는 데 큐를 사용할 가능성도 높아요. 패턴 자체는 단순하지만 구현에는 숨은 복잡성이 많습니다. 예를 들어:
- 마이크로서비스 중 하나가 오랜 기간 사용 불가하면 어떻게 되나요?
- 실패한 단계를 자동으로 재시도할 수 있나요?
- 그렇지 않다면, 해당된다면 이미 완료된 단계의 롤백을 어떻게 지원하나요?
- 구현 세부 사항을 제외하고, 다른 엔지니어가 무엇을 하는지·어떻게 동작하는지 이해할 수 있도록 워크플로를 시각화할 방법이 있나요?
Dapr Workflow는 태스크 체이닝 패턴을 다음 예제처럼 선택한 프로그래밍 언어의 간단한 함수로 간결하게 구현할 수 있게 함으로써 이 복잡성을 해결합니다.
- Python
- JavaScript
- .NET
- Java
- Go
import dapr.ext.workflow as wf
def task_chain_workflow(ctx: wf.DaprWorkflowContext, wf_input: int):
try:
result1 = yield ctx.call_activity(step1, input=wf_input)
result2 = yield ctx.call_activity(step2, input=result1)
result3 = yield ctx.call_activity(step3, input=result2)
except Exception as e:
yield ctx.call_activity(error_handler, input=str(e))
raise
return [result1, result2, result3]
def step1(ctx, activity_input):
print(f'Step 1: Received input: {activity_input}.')
return activity_input + 1
def step2(ctx, activity_input):
print(f'Step 2: Received input: {activity_input}.')
return activity_input * 2
def step3(ctx, activity_input):
print(f'Step 3: Received input: {activity_input}.')
return activity_input ^ 2
def error_handler(ctx, error):
print(f'Executing error handler: {error}.')
참고: 워크플로 재시도 정책은 Python SDK의 향후 버전에서 사용 가능할 예정입니다.
import { DaprWorkflowClient, WorkflowActivityContext, WorkflowContext, WorkflowRuntime, TWorkflow } from "@dapr/dapr";
async function start() {
// Update the gRPC client and worker to use a local address and port
const daprHost = "localhost";
const daprPort = "50001";
const workflowClient = new DaprWorkflowClient({
daprHost,
daprPort,
});
const workflowRuntime = new WorkflowRuntime({
daprHost,
daprPort,
});
const hello = async (_: WorkflowActivityContext, name: string) => {
return `Hello ${name}!`;
};
const sequence: TWorkflow = async function* (ctx: WorkflowContext): any {
const cities: string[] = [];
const result1 = yield ctx.callActivity(hello, "Tokyo");
cities.push(result1);
const result2 = yield ctx.callActivity(hello, "Seattle");
cities.push(result2);
const result3 = yield ctx.callActivity(hello, "London");
cities.push(result3);
return cities;
};
workflowRuntime.registerWorkflow(sequence).registerActivity(hello);
// Wrap the worker startup in a try-catch block to handle any errors during startup
try {
await workflowRuntime.start();
console.log("Workflow runtime started successfully");
} catch (error) {
console.error("Error starting workflow runtime:", error);
}
// Schedule a new orchestration
try {
const id = await workflowClient.scheduleNewWorkflow(sequence);
console.log(`Orchestration scheduled with ID: ${id}`);
// Wait for orchestration completion
const state = await workflowClient.waitForWorkflowCompletion(id, undefined, 30);
console.log(`Orchestration completed! Result: ${state?.serializedOutput}`);
} catch (error) {
console.error("Error scheduling or waiting for orchestration:", error);
}
await workflowRuntime.stop();
await workflowClient.stop();
// stop the dapr side car
process.exit(0);
}
start().catch((e) => {
console.error(e);
process.exit(1);
// Add logic here to undo partial changes (e.g., refund payment)
});
// Expotential backoff retry policy that survives long outages
var retryOptions = new WorkflowTaskOptions
{
RetryPolicy = new WorkflowRetryPolicy(
firstRetryInterval: TimeSpan.FromMinutes(1),
backoffCoefficient: 2.0,
maxRetryInterval: TimeSpan.FromHours(1),
maxNumberOfAttempts: 10),
};
try
{
var result1 = await context.CallActivityAsync<string>("Step1", wfInput, retryOptions);
var result2 = await context.CallActivityAsync<byte[]>("Step2", result1, retryOptions);
var result3 = await context.CallActivityAsync<long[]>("Step3", result2, retryOptions);
return string.Join(", ", result4);
}
catch (TaskFailedException) // Task failures are surfaced as TaskFailedException
{
// Retries expired - apply custom compensation logic
await context.CallActivityAsync<long[]>("MyCompensation", options: retryOptions);
throw;
}
참고: 위 예제에서 "Step1", "Step2", "Step3", "MyCompensation"는 워크플로 액티비티를 나타냅니다. 이 액티비티들은 코드에서 워크플로의 단계를 실제로 구현하는 함수입니다. 간결함을 위해 이 액티비티 구현은 예제에서 생략했습니다.
public class ChainWorkflow extends Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
StringBuilder sb = new StringBuilder();
String wfInput = ctx.getInput(String.class);
String result1 = ctx.callActivity("Step1", wfInput, String.class).await();
String result2 = ctx.callActivity("Step2", result1, String.class).await();
String result3 = ctx.callActivity("Step3", result2, String.class).await();
String result = sb.append(result1).append(',').append(result2).append(',').append(result3).toString();
ctx.complete(result);
};
}
}
class Step1 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step1.class);
logger.info("Starting Activity: " + ctx.getName());
// Add step-specific logic here (e.g. data transformation)
return null;
}
}
class Step2 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step2.class);
logger.info("Starting Activity: " + ctx.getName());
// Add step-specific logic here (e.g. data transformation)
return null;
}
}
class Step3 implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(Step3.class);
logger.info("Starting Activity: " + ctx.getName());
// Add step-specific logic here (e.g. data transformation)
return null;
}
}
func TaskChainWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return "", err
}
var result1 int
if err := ctx.CallActivity(Step1, workflow.ActivityInput(input)).Await(&result1); err != nil {
return nil, err
}
var result2 int
if err := ctx.CallActivity(Step2, workflow.ActivityInput(input)).Await(&result2); err != nil {
return nil, err
}
var result3 int
if err := ctx.CallActivity(Step3, workflow.ActivityInput(input)).Await(&result3); err != nil {
return nil, err
}
return []int{result1, result2, result3}, nil
}
func Step1(ctx workflow.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return "", err
}
fmt.Printf("Step 1: Received input: %s", input)
return input + 1, nil
}
func Step2(ctx workflow.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return "", err
}
fmt.Printf("Step 2: Received input: %s", input)
return input * 2, nil
}
func Step3(ctx workflow.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return "", err
}
fmt.Printf("Step 3: Received input: %s", input)
return int(math.Pow(float64(input), 2)), nil
}
보시다시피, 워크플로는 선택한 프로그래밍 언어의 일련의 간단한 문장으로 표현됩니다. 이를 통해 조직의 어떤 엔지니어든 전체 시스템 아키텍처를 반드시 이해하지 않아도 엔드투엔드 플로우를 빠르게 이해할 수 있어요. 뒤에서 Dapr Workflow 런타임은:
- 워크플로를 실행하고 완주까지 보장합니다.
- 진행 상황을 자동으로 저장합니다.
- 워크플로 프로세스가 어떤 이유로든 실패하면 마지막 완료 단계에서 워크플로를 자동으로 재개합니다.
- 대상 프로그래밍 언어에서 오류 처리를 자연스럽게 표현할 수 있게 해, 보상 로직을 쉽게 구현할 수 있게 합니다.
- 워크플로의 개별 단계에 대한 복잡한 재시도 정책 구성 과정을 단순화하는 내장 재시도 구성 프리미티브를 제공합니다.
팬아웃/팬인 (Fan-out/fan-in)
팬아웃/팬인 설계 패턴에서는 잠재적으로 여러 워커에 걸쳐 여러 태스크를 동시에 실행하고, 완료를 기다린 다음, 결과에 대해 어떤 집계를 수행합니다. 이전 패턴에서 언급한 과제 외에도, 팬아웃/팬인 패턴을 수동으로 구현할 때 고려할 중요한 질문이 몇 가지 있습니다.
- 병렬성의 정도를 어떻게 제어하나요?
- 후속 집계 단계를 언제 트리거할지 어떻게 알 수 있나요?
- 병렬 단계 수가 동적이면 어떻게 하나요?
Dapr Workflow는 다음 예제처럼 팬아웃/팬인 패턴을 간단한 함수로 표현할 수 있는 방법을 제공합니다.
dapr workflow run DataProcessingWorkflow \
--app-id processor \
--input '{"items": ["item1", "item2", "item3"]}'
dapr workflow history <instance-id> --app-id processor --output json
- Python
- JavaScript
- .NET
- Java
- Go
import time
from typing import List
import dapr.ext.workflow as wf
def batch_processing_workflow(ctx: wf.DaprWorkflowContext, wf_input: int):
work_batch = yield ctx.call_activity(get_work_batch, input=wf_input)
parallel_tasks = [ctx.call_activity(process_work_item, input=work_item) for work_item in work_batch]
outputs = yield wf.when_all(parallel_tasks)
total = sum(outputs)
yield ctx.call_activity(process_results, input=total)
def get_work_batch(ctx, batch_size: int) -> List[int]:
return [i + 1 for i in range(batch_size)]
def process_work_item(ctx, work_item: int) -> int:
print(f'Processing work item: {work_item}.')
time.sleep(5)
result = work_item * 2
print(f'Work item {work_item} processed. Result: {result}.')
return result
def process_results(ctx, final_result: int):
print(f'Final result: {final_result}.')
import {
Task,
DaprWorkflowClient,
WorkflowActivityContext,
WorkflowContext,
WorkflowRuntime,
TWorkflow,
} from "@dapr/dapr";
// Wrap the entire code in an immediately-invoked async function
async function start() {
// Update the gRPC client and worker to use a local address and port
const daprHost = "localhost";
const daprPort = "50001";
const workflowClient = new DaprWorkflowClient({
daprHost,
daprPort,
});
const workflowRuntime = new WorkflowRuntime({
daprHost,
daprPort,
});
function getRandomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
async function getWorkItemsActivity(_: WorkflowActivityContext): Promise<string[]> {
const count: number = getRandomInt(2, 10);
console.log(`generating ${count} work items...`);
const workItems: string[] = Array.from({ length: count }, (_, i) => `work item ${i}`);
return workItems;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function processWorkItemActivity(context: WorkflowActivityContext, item: string): Promise<number> {
console.log(`processing work item: ${item}`);
// Simulate some work that takes a variable amount of time
const sleepTime = Math.random() * 5000;
await sleep(sleepTime);
// Return a result for the given work item, which is also a random number in this case
// For more information about random numbers in workflow please check
// https://learn.microsoft.com/azure/azure-functions/durable/durable-functions-code-constraints?tabpane=csharp#random-numbers
return Math.floor(Math.random() * 11);
}
const workflow: TWorkflow = async function* (ctx: WorkflowContext): any {
const tasks: Task<any>[] = [];
const workItems = yield ctx.callActivity(getWorkItemsActivity);
for (const workItem of workItems) {
tasks.push(ctx.callActivity(processWorkItemActivity, workItem));
}
const results: number[] = yield ctx.whenAll(tasks);
const sum: number = results.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
return sum;
};
workflowRuntime.registerWorkflow(workflow);
workflowRuntime.registerActivity(getWorkItemsActivity);
workflowRuntime.registerActivity(processWorkItemActivity);
// Wrap the worker startup in a try-catch block to handle any errors during startup
try {
await workflowRuntime.start();
console.log("Worker started successfully");
} catch (error) {
console.error("Error starting worker:", error);
}
// Schedule a new orchestration
try {
const id = await workflowClient.scheduleNewWorkflow(workflow);
console.log(`Orchestration scheduled with ID: ${id}`);
// Wait for orchestration completion
const state = await workflowClient.waitForWorkflowCompletion(id, undefined, 30);
console.log(`Orchestration completed! Result: ${state?.serializedOutput}`);
} catch (error) {
console.error("Error scheduling or waiting for orchestration:", error);
}
// stop worker and client
await workflowRuntime.stop();
await workflowClient.stop();
// stop the dapr side car
process.exit(0);
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
// Get a list of N work items to process in parallel.
object[] workBatch = await context.CallActivityAsync<object[]>("GetWorkBatch", null);
// Schedule the parallel tasks, but don't wait for them to complete yet.
var parallelTasks = new List<Task<int>>(workBatch.Length);
for (int i = 0; i < workBatch.Length; i++)
{
Task<int> task = context.CallActivityAsync<int>("ProcessWorkItem", workBatch[i]);
parallelTasks.Add(task);
}
// Everything is scheduled. Wait here until all parallel tasks have completed.
await Task.WhenAll(parallelTasks);
// Aggregate all N outputs and publish the result.
int sum = parallelTasks.Sum(t => t.Result);
await context.CallActivityAsync("PostResults", sum);
public class FaninoutWorkflow extends Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
// Get a list of N work items to process in parallel.
Object[] workBatch = ctx.callActivity("GetWorkBatch", Object[].class).await();
// Schedule the parallel tasks, but don't wait for them to complete yet.
List<Task<Integer>> tasks = Arrays.stream(workBatch)
.map(workItem -> ctx.callActivity("ProcessWorkItem", workItem, int.class))
.collect(Collectors.toList());
// Everything is scheduled. Wait here until all parallel tasks have completed.
List<Integer> results = ctx.allOf(tasks).await();
// Aggregate all N outputs and publish the result.
int sum = results.stream().mapToInt(Integer::intValue).sum();
ctx.complete(sum);
};
}
}
func BatchProcessingWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return 0, err
}
var workBatch []int
if err := ctx.CallActivity(GetWorkBatch, workflow.ActivityInput(input)).Await(&workBatch); err != nil {
return 0, err
}
parallelTasks := workflow.NewTaskSlice(len(workBatch))
for i, workItem := range workBatch {
parallelTasks[i] = ctx.CallActivity(ProcessWorkItem, workflow.ActivityInput(workItem))
}
var outputs int
for _, task := range parallelTasks {
var output int
err := task.Await(&output)
if err == nil {
outputs += output
} else {
return 0, err
}
}
if err := ctx.CallActivity(ProcessResults, workflow.ActivityInput(outputs)).Await(nil); err != nil {
return 0, err
}
return 0, nil
}
func GetWorkBatch(ctx workflow.ActivityContext) (any, error) {
var batchSize int
if err := ctx.GetInput(&batchSize); err != nil {
return 0, err
}
batch := make([]int, batchSize)
for i := 0; i < batchSize; i++ {
batch[i] = i
}
return batch, nil
}
func ProcessWorkItem(ctx workflow.ActivityContext) (any, error) {
var workItem int
if err := ctx.GetInput(&workItem); err != nil {
return 0, err
}
fmt.Printf("Processing work item: %d\n", workItem)
time.Sleep(time.Second * 5)
result := workItem * 2
fmt.Printf("Work item %d processed. Result: %d\n", workItem, result)
return result, nil
}
func ProcessResults(ctx workflow.ActivityContext) (any, error) {
var finalResult int
if err := ctx.GetInput(&finalResult); err != nil {
return 0, err
}
fmt.Printf("Final result: %d\n", finalResult)
return finalResult, nil
}
이 예제의 핵심 요점은 다음과 같습니다.
- 팬아웃/팬인 패턴은 일반 프로그래밍 구문을 사용하는 간단한 함수로 표현할 수 있습니다.
- 병렬 태스크 수는 정적이거나 동적일 수 있어요.
- 워크플로 자체가 병렬 실행의 결과를 집계할 수 있습니다.
게다가 워크플로의 실행은 내구성이 있습니다. 워크플로가 100개의 병렬 태스크 실행을 시작했는데 프로세스가 크래시되기 전에 40개만 완료되었다면, 워크플로는 자동으로 재시작되고 남은 60개 태스크만 스케줄합니다. 더 나아가 언어별 단순한 구문으로 동시성 정도를 제한할 수도 있습니다. 아래 샘플 코드는 팬아웃 정도를 동시 액티비티 실행 5개로 제한하는 방법을 보여줍니다.
- .NET
//Revisiting the earlier example...
// Get a list of N work items to process in parallel.
object[] workBatch = await context.CallActivityAsync<object[]>("GetWorkBatch", null);
const int MaxParallelism = 5;
var results = new List<int>();
var inFlightTasks = new HashSet<Task<int>>();
foreach(var workItem in workBatch)
{
if (inFlightTasks.Count >= MaxParallelism)
{
var finishedTask = await Task.WhenAny(inFlightTasks);
results.Add(finishedTask.Result);
inFlightTasks.Remove(finishedTask);
}
inFlightTasks.Add(context.CallActivityAsync<int>("ProcessWorkItem", workItem));
}
results.AddRange(await Task.WhenAll(inFlightTasks));
var sum = results.Sum(t => t);
await context.CallActivityAsync("PostResults", sum);
WorkflowContext의 다음 확장 메서드를 사용하면 워크플로 액티비티를 병렬로 처리하면서 동시성에 상한을 둘 수 있습니다.
- .NET
//Revisiting the earlier example...
// Get a list of work items to process
var workBatch = await context.CallActivityAsync<object[]>("GetWorkBatch", null);
// Process deterministically in parallel with an upper cap of 5 activities at a time
var results = await context.ProcessInParallelAsync(workBatch, workItem => context.CallActivityAsync<int>("ProcessWorkItem", workItem), maxConcurrency: 5);
var sum = results.Sum(t => t);
await context.CallActivityAsync("PostResults", sum);
이렇게 동시성을 제한하는 것은 공유 리소스에 대한 경합을 제한할 때 유용합니다. 예를 들어 액티비티가 데이터베이스나 외부 API처럼 자체 동시성 제한이 있는 외부 리소스를 호출해야 한다면, 지정된 수 이상의 액티비티가 그 리소스를 동시에 호출하지 않도록 보장하는 것이 유용할 수 있어요.
비동기 HTTP API (Async HTTP APIs)
비동기 HTTP API는 일반적으로 Asynchronous Request-Reply 패턴으로 구현됩니다. 이 패턴을 전통적으로 구현하려면 다음이 포함됩니다.
- 클라이언트가 HTTP API 엔드포인트(시작 API)에 요청을 보냅니다.
- 시작 API는 백엔드 큐에 메시지를 기록해 장기 실행 연산의 시작을 트리거합니다.
- 백엔드 연산을 스케줄한 직후, 시작 API는 상태를 폴링하는 데 사용할 수 있는 식별자와 함께 HTTP 202 응답을 클라이언트에 반환합니다.
- 상태 API는 장기 실행 연산의 상태를 담은 데이터베이스를 조회합니다.
- 클라이언트는 타임아웃이 만료되거나 "완료" 응답을 받을 때까지 상태 API를 반복해서 폴링합니다.
엔드투엔드 플로우는 다음 다이어그램에 설명되어 있습니다.
비동기 요청-응답 패턴을 구현하는 과제는 여러 API와 상태 저장소를 사용한다는 점입니다. 또한 클라이언트가 상태를 자동으로 폴링하고 연산 완료 시기를 알 수 있도록 프로토콜을 올바르게 구현해야 합니다.
Dapr workflow HTTP API는 코드를 작성하거나 상태 관리를 할 필요 없이 비동기 요청-응답 패턴을 기본적으로 지원합니다.
다음 curl 명령은 워크플로 API가 이 패턴을 지원하는 방식을 보여줍니다.
curl -X POST http://localhost:3500/v1.0/workflows/dapr/OrderProcessingWorkflow/start?instanceID=12345678 -d '{"Name":"Paperclips","Quantity":1,"TotalCost":9.95}'
이전 명령은 다음 응답 JSON을 생성합니다.
{"instanceID":"12345678"}
그러면 HTTP 클라이언트는 워크플로 인스턴스 ID로 상태 조회 URL을 구성하고, 페이로드에서 "COMPLETE", "FAILURE", "TERMINATED" 상태를 볼 때까지 반복해서 폴링할 수 있습니다.
curl http://localhost:3500/v1.0/workflows/dapr/12345678
다음은 진행 중인 워크플로 상태의 예시입니다.
{
"instanceID": "12345678",
"workflowName": "OrderProcessingWorkflow",
"createdAt": "2023-05-03T23:22:11.143069826Z",
"lastUpdatedAt": "2023-05-03T23:22:22.460025267Z",
"runtimeStatus": "RUNNING",
"properties": {
"dapr.workflow.custom_status": "",
"dapr.workflow.input": "{\"Name\":\"Paperclips\",\"Quantity\":1,\"TotalCost\":9.95}"
}
}
이전 예제에서 볼 수 있듯이 워크플로의 런타임 상태는 RUNNING이며, 클라이언트는 계속 폴링해야 함을 알 수 있습니다.
워크플로가 완료되면 상태는 다음과 같을 수 있습니다.
{
"instanceID": "12345678",
"workflowName": "OrderProcessingWorkflow",
"createdAt": "2023-05-03T23:30:11.381146313Z",
"lastUpdatedAt": "2023-05-03T23:30:52.923870615Z",
"runtimeStatus": "COMPLETED",
"properties": {
"dapr.workflow.custom_status": "",
"dapr.workflow.input": "{\"Name\":\"Paperclips\",\"Quantity\":1,\"TotalCost\":9.95}",
"dapr.workflow.output": "{\"Processed\":true}"
}
}
이전 예제에서 볼 수 있듯이 워크플로의 런타임 상태는 이제 COMPLETED이며, 클라이언트는 업데이트 폴링을 중단할 수 있음을 뜻합니다.
모니터 (Monitor)
모니터 패턴은 반복되는 프로세스로, 전형적으로:
- 시스템의 상태를 확인합니다.
- 그 상태에 따라 어떤 조치를 취합니다 — 예: 알림 보내기.
- 일정 시간 잠듭니다.
- 반복합니다.
다음 다이어그램은 이 패턴의 대략적인 예시입니다. 비즈니스 필요에 따라 모니터가 하나일 수도 있고, 비즈니스 엔티티(예: 주식)마다 모니터가 하나씩 여러 개일 수도 있습니다. 게다가 상황에 따라 잠드는 시간이 달라져야 할 수 있습니다. 이러한 요구 사항 때문에 cron 기반 스케줄링 시스템을 사용하는 것은 비실용적입니다. Dapr Workflow는 영원한 워크플로(eternal workflows)를 구현할 수 있게 함으로써 이 패턴을 기본적으로 지원합니다. 무한 while 루프(안티 패턴)를 작성하는 대신, Dapr Workflow는 워크플로 작성자가 새 입력으로 워크플로 함수를 처음부터 다시 시작할 수 있게 하는 continue-as-new API를 노출합니다.
참고 (Note)
Continue-as-new는 워크플로를 즉시 재시작하고 완료되지 않은 태스크(시작되었지만 대기되지 않은 액티비티, 타이머, 자식 워크플로 포함)의 결과를 버립니다.
- Python
- JavaScript
- .NET
- Java
- Go
from dataclasses import dataclass
from datetime import timedelta
import random
import dapr.ext.workflow as wf
@dataclass
class JobStatus:
job_id: str
is_healthy: bool
def status_monitor_workflow(ctx: wf.DaprWorkflowContext, job: JobStatus):
status = yield ctx.call_activity(check_status, input=job)
if not ctx.is_replaying:
print(f"Job '{job.job_id}' is {status}.")
if status == "healthy":
job.is_healthy = True
next_sleep_interval = 60 # check less frequently when healthy
else:
if job.is_healthy:
job.is_healthy = False
ctx.call_activity(send_alert, input=f"Job '{job.job_id}' is unhealthy!")
next_sleep_interval = 5 # check more frequently when unhealthy
yield ctx.create_timer(fire_at=ctx.current_utc_datetime + timedelta(minutes=next_sleep_interval))
ctx.continue_as_new(job)
def check_status(ctx, _) -> str:
return random.choice(["healthy", "unhealthy"])
def send_alert(ctx, message: str):
print(f'*** Alert: {message}')
const statusMonitorWorkflow: TWorkflow = async function* (ctx: WorkflowContext): any {
let duration;
const status = yield ctx.callActivity(checkStatusActivity);
if (status === "healthy") {
// Check less frequently when in a healthy state
duration = 60 * 60;
} else {
yield ctx.callActivity(alertActivity, "job unhealthy");
// Check more frequently when in an unhealthy state
duration = 5 * 60;
}
// Put the workflow to sleep until the determined time
ctx.createTimer(duration);
// Restart from the beginning with the updated state
ctx.continueAsNew();
};
public override async Task<object> RunAsync(WorkflowContext context, MyEntityState myEntityState)
{
TimeSpan nextSleepInterval;
var status = await context.CallActivityAsync<string>("GetStatus");
if (status == "healthy")
{
myEntityState.IsHealthy = true;
// Check less frequently when in a healthy state
nextSleepInterval = TimeSpan.FromMinutes(60);
}
else
{
if (myEntityState.IsHealthy)
{
myEntityState.IsHealthy = false;
await context.CallActivityAsync("SendAlert", myEntityState);
}
// Check more frequently when in an unhealthy state
nextSleepInterval = TimeSpan.FromMinutes(5);
}
// Put the workflow to sleep until the determined time
await context.CreateTimer(nextSleepInterval);
// Restart from the beginning with the updated state
context.ContinueAsNew(myEntityState);
return null;
}
이 예제는 boolean IsHealthy 속성을 가진 미리 정의된 MyEntityState 클래스를 가정합니다.
public class MonitorWorkflow extends Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
Duration nextSleepInterval;
var status = ctx.callActivity(DemoWorkflowStatusActivity.class.getName(), DemoStatusActivityOutput.class).await();
var isHealthy = status.getIsHealthy();
if (isHealthy) {
// Check less frequently when in a healthy state
nextSleepInterval = Duration.ofMinutes(60);
} else {
ctx.callActivity(DemoWorkflowAlertActivity.class.getName()).await();
// Check more frequently when in an unhealthy state
nextSleepInterval = Duration.ofMinutes(5);
}
// Put the workflow to sleep until the determined time
try {
ctx.createTimer(nextSleepInterval);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Restart from the beginning with the updated state
ctx.continueAsNew();
}
}
}
type JobStatus struct {
JobID string `json:"job_id"`
IsHealthy bool `json:"is_healthy"`
}
func StatusMonitorWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var sleepInterval time.Duration
var job JobStatus
if err := ctx.GetInput(&job); err != nil {
return "", err
}
var status string
if err := ctx.CallActivity(CheckStatus, workflow.ActivityInput(job)).Await(&status); err != nil {
return "", err
}
if status == "healthy" {
job.IsHealthy = true
sleepInterval = time.Minutes * 60
} else {
if job.IsHealthy {
job.IsHealthy = false
err := ctx.CallActivity(SendAlert, workflow.ActivityInput(fmt.Sprintf("Job '%s' is unhealthy!", job.JobID))).Await(nil)
if err != nil {
return "", err
}
}
sleepInterval = time.Minutes * 5
}
if err := ctx.CreateTimer(sleepInterval).Await(nil); err != nil {
return "", err
}
ctx.ContinueAsNew(job, false)
return "", nil
}
func CheckStatus(ctx workflow.ActivityContext) (any, error) {
statuses := []string{"healthy", "unhealthy"}
return statuses[rand.Intn(1)], nil
}
func SendAlert(ctx workflow.ActivityContext) (any, error) {
var message string
if err := ctx.GetInput(&message); err != nil {
return "", err
}
fmt.Printf("*** Alert: %s", message)
return "", nil
}
모니터 패턴을 구현하는 워크플로는 영원히 루프할 수 있고, continue-as-new를 호출하지 않음으로써 스스로 우아하게 종료할 수도 있습니다.
참고 (Note)
이 패턴은 액터와 리마인더로도 표현할 수 있습니다. 차이점은 이 워크플로가 로컬 변수에 상태를 저장한 입력을 가진 단일 함수로 표현된다는 것입니다. 워크플로는 필요하다면 더 강한 신뢰성 보장으로 일련의 동작을 실행할 수도 있어요.
외부 시스템 상호작용 (External system interaction)
어떤 경우에는 워크플로가 일시 중지하고 외부 시스템이 어떤 동작을 수행하기를 기다려야 할 수 있습니다. 예를 들어 워크플로가 일시 중지하고 결제가 수신되기를 기다려야 할 수 있습니다. 이 경우 결제 시스템이 결제 수신 시 pub/sub 토픽에 이벤트를 게시하고, 그 토픽의 리스너가 raise event 워크플로 API로 워크플로에 이벤트를 발생시킬 수 있어요. 또 다른 매우 흔한 시나리오는 구매 주문을 승인할 때처럼 워크플로가 일시 중지하고 사람을 기다려야 하는 경우입니다. Dapr Workflow는 외부 이벤트 기능을 통해 이 이벤트 패턴을 지원합니다. 사람이 관여하는 구매 주문 워크플로의 예는 다음과 같습니다.
- 구매 주문이 수신되면 워크플로가 트리거됩니다.
- 워크플로의 규칙이 사람이 어떤 동작을 수행해야 한다고 결정합니다. 예를 들어 구매 주문 비용이 특정 자동 승인 임계값을 초과하는 경우입니다.
- 워크플로는 사람의 동작을 요청하는 알림을 보냅니다. 예를 들어 지정된 승인자에게 승인 링크가 담긴 이메일을 보냅니다.
- 워크플로는 일시 중지하고 사람이 링크를 클릭해 주문을 승인하거나 거부하기를 기다립니다.
- 지정된 시간 안에 승인이 수신되지 않으면 워크플로는 재개하고 주문 취소 같은 보상 로직을 수행합니다.
다음 다이어그램은 이 플로우를 보여줍니다. 다음 예제 코드는 이 패턴을 Dapr Workflow로 구현하는 방법을 보여줍니다.
- Python
- JavaScript
- .NET
- Java
- Go
from dataclasses import dataclass
from datetime import timedelta
import dapr.ext.workflow as wf
@dataclass
class Order:
cost: float
product: str
quantity: int
def __str__(self):
return f'{self.product} ({self.quantity})'
@dataclass
class Approval:
approver: str
@staticmethod
def from_dict(dict):
return Approval(**dict)
def purchase_order_workflow(ctx: wf.DaprWorkflowContext, order: Order):
if order.cost < 1000:
return "Auto-approved"
yield ctx.call_activity(send_approval_request, input=order)
approval_event = ctx.wait_for_external_event("approval_received")
timeout_event = ctx.create_timer(timedelta(hours=24))
winner = yield wf.when_any([approval_event, timeout_event])
if winner == timeout_event:
return "Cancelled"
yield ctx.call_activity(place_order, input=order)
approval_details = Approval.from_dict(approval_event.get_result())
return f"Approved by '{approval_details.approver}'"
def send_approval_request(_, order: Order) -> None:
print(f'*** Sending approval request for order: {order}')
def place_order(_, order: Order) -> None:
print(f'*** Placing order: {order}')
import {
Task,
DaprWorkflowClient,
WorkflowActivityContext,
WorkflowContext,
WorkflowRuntime,
TWorkflow,
} from "@dapr/dapr";
import * as readlineSync from "readline-sync";
// Wrap the entire code in an immediately-invoked async function
async function start() {
class Order {
cost: number;
product: string;
quantity: number;
constructor(cost: number, product: string, quantity: number) {
this.cost = cost;
this.product = product;
this.quantity = quantity;
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Update the gRPC client and worker to use a local address and port
const daprHost = "localhost";
const daprPort = "50001";
const workflowClient = new DaprWorkflowClient({
daprHost,
daprPort,
});
const workflowRuntime = new WorkflowRuntime({
daprHost,
daprPort,
});
// Activity function that sends an approval request to the manager
const sendApprovalRequest = async (_: WorkflowActivityContext, order: Order) => {
// Simulate some work that takes an amount of time
await sleep(3000);
console.log(`Sending approval request for order: ${order.product}`);
};
// Activity function that places an order
const placeOrder = async (_: WorkflowActivityContext, order: Order) => {
console.log(`Placing order: ${order.product}`);
};
// Orchestrator function that represents a purchase order workflow
const purchaseOrderWorkflow: TWorkflow = async function* (ctx: WorkflowContext, order: Order): any {
// Orders under $1000 are auto-approved
if (order.cost < 1000) {
return "Auto-approved";
}
// Orders of $1000 or more require manager approval
yield ctx.callActivity(sendApprovalRequest, order);
// Approvals must be received within 24 hours or they will be cancelled.
const tasks: Task<any>[] = [];
const approvalEvent = ctx.waitForExternalEvent("approval_received");
const timeoutEvent = ctx.createTimer(24 * 60 * 60);
tasks.push(approvalEvent);
tasks.push(timeoutEvent);
const winner = ctx.whenAny(tasks);
if (winner == timeoutEvent) {
return "Cancelled";
}
yield ctx.callActivity(placeOrder, order);
const approvalDetails = approvalEvent.getResult();
return `Approved by ${approvalDetails.approver}`;
};
workflowRuntime
.registerWorkflow(purchaseOrderWorkflow)
.registerActivity(sendApprovalRequest)
.registerActivity(placeOrder);
// Wrap the worker startup in a try-catch block to handle any errors during startup
try {
await workflowRuntime.start();
console.log("Worker started successfully");
} catch (error) {
console.error("Error starting worker:", error);
}
// Schedule a new orchestration
try {
const cost = readlineSync.questionInt("Cost of your order:");
const approver = readlineSync.question("Approver of your order:");
const timeout = readlineSync.questionInt("Timeout for your order in seconds:");
const order = new Order(cost, "MyProduct", 1);
const id = await workflowClient.scheduleNewWorkflow(purchaseOrderWorkflow, order);
console.log(`Orchestration scheduled with ID: ${id}`);
// prompt for approval asynchronously
promptForApproval(approver, workflowClient, id);
// Wait for orchestration completion
const state = await workflowClient.waitForWorkflowCompletion(id, undefined, timeout + 2);
console.log(`Orchestration completed! Result: ${state?.serializedOutput}`);
} catch (error) {
console.error("Error scheduling or waiting for orchestration:", error);
}
// stop worker and client
await workflowRuntime.stop();
await workflowClient.stop();
// stop the dapr side car
process.exit(0);
}
async function promptForApproval(approver: string, workflowClient: DaprWorkflowClient, id: string) {
if (readlineSync.keyInYN("Press [Y] to approve the order... Y/yes, N/no")) {
const approvalEvent = { approver: approver };
await workflowClient.raiseEvent(id, "approval_received", approvalEvent);
} else {
return "Order rejected";
}
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
public override async Task<OrderResult> RunAsync(WorkflowContext context, OrderPayload order)
{
// Initial business logic (e.g. inventory check)
// Require orders over a certain threshold to be approved
if (order.TotalCost > OrderApprovalThreshold)
{
try
{
// Request human approval for this order
await context.CallActivityAsync(nameof(RequestApprovalActivity), order);
// Pause and wait for a human to approve the order
ApprovalResult approvalResult = await context.WaitForExternalEventAsync<ApprovalResult>(
eventName: "ManagerApproval",
timeout: TimeSpan.FromDays(3));
if (approvalResult == ApprovalResult.Rejected)
{
// The order was rejected, end the workflow here
return new OrderResult(Processed: false);
}
}
catch (TaskCanceledException)
{
// An approval timeout results in automatic order cancellation
return new OrderResult(Processed: false);
}
}
// Final business logic (e.g. shipping confirmation)
// End the workflow with a success result
return new OrderResult(Processed: true);
}
참고: 위 예제에서 RequestApprovalActivity는 호출할 워크플로 액티비티의 이름이고 ApprovalResult는 워크플로 앱이 정의한 열거형입니다. 간결함을 위해 이 정의들은 예제 코드에서 생략했습니다.
public class ExternalSystemInteractionWorkflow extends Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
// Initial business logic (e.g. inventory check)
Integer orderCost = ctx.getInput(int.class);
// Require orders over a certain threshold to be approved
if (orderCost > ORDER_APPROVAL_THRESHOLD) {
try {
// Request human approval for this order
ctx.callActivity("RequestApprovalActivity", orderCost, Void.class).await();
// Pause and wait for a human to approve the order
boolean approved = ctx.waitForExternalEvent("ManagerApproval", Duration.ofDays(3), boolean.class).await();
if (!approved) {
// The order was rejected, end the workflow here
ctx.complete("Process reject");
}
} catch (TaskCanceledException e) {
// An approval timeout results in automatic order cancellation
ctx.complete("Process cancel");
}
}
// Final business logic (e.g. shipping confirmation)
// End the workflow with a success result
ctx.complete("Process approved");
};
}
}
type Order struct {
Cost float64 `json:"cost"`
Product string `json:"product"`
Quantity int `json:"quantity"`
}
type Approval struct {
Approver string `json:"approver"`
}
func PurchaseOrderWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var order Order
if err := ctx.GetInput(&order); err != nil {
return "", err
}
// Orders under $1000 are auto-approved
if order.Cost < 1000 {
return "Auto-approved", nil
}
// Orders of $1000 or more require manager approval
if err := ctx.CallActivity(SendApprovalRequest, workflow.ActivityInput(order)).Await(nil); err != nil {
return "", err
}
// Approvals must be received within 24 hours or they will be cancelled
var approval Approval
if err := ctx.WaitForExternalEvent("approval_received", time.Hour*24).Await(&approval); err != nil {
// Assuming that a timeout has taken place - in any case; an error.
return "error/cancelled", err
}
// The order was approved
if err := ctx.CallActivity(PlaceOrder, workflow.ActivityInput(order)).Await(nil); err != nil {
return "", err
}
return fmt.Sprintf("Approved by %s", approval.Approver), nil
}
func SendApprovalRequest(ctx workflow.ActivityContext) (any, error) {
var order Order
if err := ctx.GetInput(&order); err != nil {
return "", err
}
fmt.Printf("*** Sending approval request for order: %v\n", order)
return "", nil
}
func PlaceOrder(ctx workflow.ActivityContext) (any, error) {
var order Order
if err := ctx.GetInput(&order); err != nil {
return "", err
}
fmt.Printf("*** Placing order: %v", order)
return "", nil
}
워크플로 실행을 재개하는 이벤트를 전달하는 코드는 워크플로 외부에 있습니다. 다음 예제처럼 raise event 워크플로 관리 API를 사용하여 워크플로 이벤트를 대기 중인 워크플로 인스턴스에 전달할 수 있습니다.
- Python
- JavaScript
- .NET
- Java
- Go
from dapr.clients import DaprClient
from dataclasses import asdict
with DaprClient() as d:
d.raise_workflow_event(
instance_id=instance_id,
workflow_component="dapr",
event_name="approval_received",
event_data=asdict(Approval("Jane Doe")))
import { DaprClient } from "@dapr/dapr";
public async raiseEvent(workflowInstanceId: string, eventName: string, eventPayload?: any) {
this._innerClient.raiseOrchestrationEvent(workflowInstanceId, eventName, eventPayload);
}
// Raise the workflow event to the waiting workflow
await daprClient.RaiseWorkflowEventAsync(
instanceId: orderId,
workflowComponent: "dapr",
eventName: "ManagerApproval",
eventData: ApprovalResult.Approved);
System.out.println("**SendExternalMessage: RestartEvent**");
client.raiseEvent(restartingInstanceId, "RestartEvent", "RestartEventPayload");
func raiseEvent() {
daprClient, err := client.NewClient()
if err != nil {
log.Fatalf("failed to initialize the client")
}
err = daprClient.RaiseEventWorkflow(context.Background(), &client.RaiseEventWorkflowRequest{
InstanceID: "instance_id",
WorkflowComponent: "dapr",
EventName: "approval_received",
EventData: Approval{
Approver: "Jane Doe",
},
})
if err != nil {
log.Fatalf("failed to raise event on workflow")
}
log.Println("raised an event on specified workflow")
}
외부 이벤트가 반드시 사람이 직접 트리거할 필요는 없습니다. 다른 시스템이 트리거할 수도 있어요. 예를 들어 워크플로가 일시 중지하고 결제가 수신되기를 기다려야 할 수 있습니다. 이 경우 결제 시스템이 결제 수신 시 pub/sub 토픽에 이벤트를 게시하고, 그 토픽의 리스너가 raise event 워크플로 API로 워크플로에 이벤트를 발생시킬 수 있습니다.
보상 (Compensation)
보상 패턴(일명 saga 패턴)은 워크플로가 도중에 실패했을 때 이미 실행된 연산을 롤백하거나 되돌리는 메커니즘을 제공합니다. 이 패턴은 전통적인 데이터베이스 트랜잭션이 실현 불가능한, 여러 마이크로서비스에 걸치는 장기 실행 워크플로에서 특히 중요합니다. 분산 마이크로서비스 아키텍처에서는 여러 서비스에 걸친 연산을 조정해야 하는 경우가 많습니다. 이 연산들을 단일 트랜잭션으로 감쌀 수 없을 때, 보상 패턴은 워크플로의 각 단계에 대한 보상 동작을 정의해 일관성을 유지하는 방법을 제공합니다. 보상 패턴은 몇 가지 중요한 과제를 해결합니다.
- 분산 트랜잭션 관리: 워크플로가 각자 자신의 데이터 저장소를 가진 여러 마이크로서비스에 걸치면, 전통적인 ACID 트랜잭션은 불가능합니다. 보상 패턴은 연산이 모두 성공적으로 완료되거나 모두 보상을 통해 되돌려지도록 보장함으로써 트랜잭션 일관성을 제공합니다.
- 부분 실패 복구: 워크플로가 일부 단계가 성공적으로 완료된 후 실패하면, 보상 패턴으로 그 완료된 단계를 우아하게 되돌릴 수 있습니다.
- 비즈니스 프로세스 무결성: 실패 시 비즈니스 프로세스를 제대로 롤백해 비즈니스 연산의 무결성을 유지하도록 보장합니다.
- 장기 실행 프로세스: 수 시간, 수 일 이상 실행될 수 있는 워크플로에서는 전통적인 잠금 메커니즘은 비실용적입니다. 보상은 이런 시나리오에서 실패를 처리하는 방법을 제공합니다.
보상 패턴의 일반적인 사용 사례는 다음과 같습니다.
- 전자상거래 주문 처리: 재고 예약, 결제 청구, 주문 배송. 배송이 실패하면 재고를 해제하고 결제를 환불해야 합니다.
- 금융 거래: 송금에서 수취 계좌 입금이 실패하면 출금 계좌의 차변을 롤백해야 합니다.
- 리소스 프로비저닝: 여러 공급자에 걸쳐 클라우드 리소스를 프로비저닝할 때, 한 단계가 실패하면 이전에 프로비저닝한 모든 리소스를 정리해야 합니다.
- 다단계 비즈니스 프로세스: 이후 실패 시 되돌려야 할 수 있는 여러 되돌릴 수 없는 단계를 포함하는 모든 비즈니스 프로세스.
Dapr Workflow는 보상 패턴을 지원하므로, 각 단계에 대한 보상 액티비티를 등록하고 필요할 때 역순으로 실행할 수 있습니다. 다음은 전자상거래 프로세스의 예 워크플로입니다.
- 주문이 수신되면 워크플로가 트리거됩니다.
- 재고에 주문 예약이 이루어집니다.
- 결제가 처리됩니다.
- 주문이 배송됩니다.
- 위 동작 중 하나가 오류를 일으키면, 동작은 다른 동작으로 보상됩니다: 배송이 취소됩니다.
- 결제가 환불됩니다.
- 재고 예약이 해제됩니다.
다음 다이어그램은 이 플로우를 보여줍니다.
- Java
public class PaymentProcessingWorkflow implements Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
ctx.getLogger().info("Starting Workflow: " + ctx.getName());
var orderId = ctx.getInput(String.class);
List<String> compensations = new ArrayList<>();
try {
// Step 1: Reserve inventory
String reservationId = ctx.callActivity(ReserveInventoryActivity.class.getName(), orderId, String.class).await();
ctx.getLogger().info("Inventory reserved: {}", reservationId);
compensations.add("ReleaseInventory");
// Step 2: Process payment
String paymentId = ctx.callActivity(ProcessPaymentActivity.class.getName(), orderId, String.class).await();
ctx.getLogger().info("Payment processed: {}", paymentId);
compensations.add("RefundPayment");
// Step 3: Ship order
String shipmentId = ctx.callActivity(ShipOrderActivity.class.getName(), orderId, String.class).await();
ctx.getLogger().info("Order shipped: {}", shipmentId);
compensations.add("CancelShipment");
} catch (TaskFailedException e) {
ctx.getLogger().error("Activity failed: {}", e.getMessage());
// Execute compensations in reverse order
Collections.reverse(compensations);
for (String compensation : compensations) {
try {
switch (compensation) {
case "CancelShipment":
String shipmentCancelResult = ctx.callActivity(
CancelShipmentActivity.class.getName(),
orderId,
String.class).await();
ctx.getLogger().info("Shipment cancellation completed: {}", shipmentCancelResult);
break;
case "RefundPayment":
String refundResult = ctx.callActivity(
RefundPaymentActivity.class.getName(),
orderId,
String.class).await();
ctx.getLogger().info("Payment refund completed: {}", refundResult);
break;
case "ReleaseInventory":
String releaseResult = ctx.callActivity(
ReleaseInventoryActivity.class.getName(),
orderId,
String.class).await();
ctx.getLogger().info("Inventory release completed: {}", releaseResult);
break;
}
} catch (TaskFailedException ex) {
ctx.getLogger().error("Compensation activity failed: {}", ex.getMessage());
}
}
ctx.complete("Order processing failed, compensation applied");
}
// Step 4: Send confirmation
ctx.callActivity(SendConfirmationActivity.class.getName(), orderId, Void.class).await();
ctx.getLogger().info("Confirmation sent for order: {}", orderId);
ctx.complete("Order processed successfully: " + orderId);
};
}
}
// Example activities
class ReserveInventoryActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String orderId = ctx.getInput(String.class);
// Logic to reserve inventory
String reservationId = "reservation_" + orderId;
System.out.println("Reserved inventory for order: " + orderId);
return reservationId;
}
}
class ReleaseInventoryActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String reservationId = ctx.getInput(String.class);
// Logic to release inventory reservation
System.out.println("Released inventory reservation: " + reservationId);
return "Released: " + reservationId;
}
}
class ProcessPaymentActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String orderId = ctx.getInput(String.class);
// Logic to process payment
String paymentId = "payment_" + orderId;
System.out.println("Processed payment for order: " + orderId);
return paymentId;
}
}
class RefundPaymentActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String paymentId = ctx.getInput(String.class);
// Logic to refund payment
System.out.println("Refunded payment: " + paymentId);
return "Refunded: " + paymentId;
}
}
class ShipOrderActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String orderId = ctx.getInput(String.class);
// Logic to ship order
String shipmentId = "shipment_" + orderId;
System.out.println("Shipped order: " + orderId);
return shipmentId;
}
}
class CancelShipmentActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String shipmentId = ctx.getInput(String.class);
// Logic to cancel shipment
System.out.println("Canceled shipment: " + shipmentId);
return "Canceled: " + shipmentId;
}
}
class SendConfirmationActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
String orderId = ctx.getInput(String.class);
// Logic to send confirmation
System.out.println("Sent confirmation for order: " + orderId);
return null;
}
}
Dapr Workflow의 보상 패턴을 사용할 때의 핵심 이점은 다음과 같습니다.
- 보상 제어: 보상 액티비티를 언제·어떻게 실행할지 완전히 제어할 수 있습니다.
- 유연한 구성: 어떤 보상을 실행할지 결정하는 사용자 지정 로직을 구현할 수 있어요.
- 오류 처리: 특정 비즈니스 요구 사항에 따라 보상 실패를 처리합니다.
- 단순한 구현: 추가 프레임워크 의존성이 없습니다 — 표준 워크플로 액티비티와 예외 처리만 있으면 돼요.
보상 패턴은 분산 워크플로가 일관성을 유지하고 실패에서 우아하게 복구할 수 있게 보장하므로, 신뢰할 수 있는 마이크로서비스 아키텍처를 구축하는 데 필수적인 도구입니다.
다음 단계 (Next steps)
Workflow architecture >>
관련 링크 (Related links)
- 퀵스타트로 Dapr Workflow 체험하기
- Workflow 개요
- Workflow API 레퍼런스
- 다음 예제를 확인해 보세요: Python
- JavaScript
- .NET
- Java
- Go