Saga

class Saga<T>(source)

Saga pattern for distributed transactions with compensation.

A Saga coordinates a sequence of local transactions where each transaction has a compensating action to undo its effects. If any step fails, all previously completed steps are compensated (rolled back) in reverse order.

Pattern:

Step 1 -> Step 2 -> Step 3 -> ... -> Success
↓ ↓ ↓
Comp 1 Comp 2 Comp 3 (executed in reverse on failure)

Basic usage:

val result = executeSaga<OrderId> {
step("Reserve inventory",
action = { inventoryService.reserve(items) },
compensation = { inventoryService.release(it) }
)
step("Charge payment",
action = { paymentService.charge(amount) },
compensation = { paymentService.refund(it) }
)
step("Create order",
action = { orderService.create(order) },
compensation = { orderService.cancel(it) }
)
}

when (result) {
is SagaResult.Success -> println("Order ${result.result} created")
is SagaResult.Failure -> println("Failed: ${result.error}")
}

With retry and timeout:

val saga = saga<String> {
stepWithRetry("Flaky API", retries = 3, action = { callApi() })
stepWithTimeout("Slow service", timeout = 5.seconds, action = { callSlow() })
}

DSL builder:

val saga = saga<OrderResult> {
step(
name = "Reserve inventory",
action = { inventoryService.reserve(items) },
compensation = { result -> inventoryService.release(result) }
)

step(
name = "Process payment",
action = { paymentService.charge(amount) },
compensation = { result -> paymentService.refund(result) }
)
}

Types

Link copied to clipboard
object Companion

Factory for Saga.

Functions

Link copied to clipboard
suspend fun execute(): SagaResult<T>

Executes the saga, running all steps in sequence.