Saga
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)Content copied to clipboard
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}")
}Content copied to clipboard
With retry and timeout:
val saga = saga<String> {
stepWithRetry("Flaky API", retries = 3, action = { callApi() })
stepWithTimeout("Slow service", timeout = 5.seconds, action = { callSlow() })
}Content copied to clipboard
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) }
)
}Content copied to clipboard