Saga Step
Immutable descriptor of a saga step with forward and compensation logic.
Each saga step consists of:
A unique step identifier (string or enum wrapped in TypedValue)
A forward action that produces a result (suspend function for async operations)
An optional compensation action that can undo the forward action (suspend function)
An idempotency flag indicating if the step is safe to retry
An optional timeout for the forward action
An optional retry policy for handling transient failures
Forward and Compensation Actions
The forward action receives the saga context and produces a result. The compensation action receives the result from the forward action, allowing it to use information from the successful execution to perform the compensation.
Both forward and compensation actions are suspend functions, allowing for non-blocking asynchronous operations using Kotlin coroutines.
Timeout Support
Steps can specify a timeout duration. If the forward action exceeds this timeout, a TimeoutCancellationException is thrown and compensation runs.
Retry Support
Steps can specify a retry policy to handle transient failures with exponential backoff. Retries are applied before compensation.
Example
SagaStep(
step = TypedValue.fromEnum(OrderSteps.CHARGE_PAYMENT),
timeout = 5.seconds, // Timeout after 5 seconds
retryPolicy = RetryPolicy.CONSERVATIVE, // Retry on transient failures
forward = { context ->
paymentService.charge(context.amount) // Can be a suspend call
// Returns transaction ID
},
compensation = { transactionId ->
paymentService.refund(transactionId) // Can be a suspend call
},
idempotent = true // Safe to retry if execution fails
)Parameters
The type of context passed to the forward action
The type of result produced by the forward action
Constructors
Properties
Optional suspend function that compensates (undoes) the step
Whether this step is safe to retry (idempotent operation)
Optional retry policy for handling transient failures
Step identifier wrapped in TypedValue (can be enum or string)