Write a Saga
A saga turns what one aggregate decided into commands for others: an order awaiting validation reserves its stock, a confirmed reservation confirms the order, a refused one cancels it. The saga holds no state of its own. It reads committed events and returns commands, and the runtime sends them. This page writes the eShop's order process. Subscriptions, Failures and Replay explains how a saga is delivered its events.
Derive commands from events
A saga is a class annotated @Saga. Each handler, annotated @OnEvent, takes a committed event and, if it needs it, the SagaContext, and returns the commands it derives as CommandRequests:
@OnEvent
fun onOrderSubmitted(
event: StateTypedEvent<OrderState, OrderSubmitted>
): CommandRequest<AwaitStockValidation> = AwaitStockValidation.toCommandRequest(event.ref.id)- What it takes. A
StateTypedEvent<S, E>calls the handler once for each eventEin a committed stream, witheventthat event andstatethe aggregate's state after the whole commit. AStateEvent<S>calls it once per stream, with all itsevents. The state typeSselects the aggregates of the module's context whose state it is. The aggregate's access attributes are members of its state (@Access), so a saga reads them fromstate, as of the commit, rather than from the snapshot, which may lag behind it. - What it costs. A
StateEvent<S>handler takes every commit of its aggregates: each is decoded and its state read before the handler sees it. A handler that names its event (E, orStateTypedEvent<S, E>when it needs the state) is passed over for a commit without one, before that work: its position moves on, and a wait at its hop is answered at once. So name the event a handler acts on. An operator then sees nohandle <subscription>span and nowow.subscription.lagsample for a commit the handler does not take. - What it returns. One
CommandRequest, several (aList, anyIterable, aSequence, aFlow, or a ReactorMonoorFlux), ornull, an empty list orUnitfor none. The runtime turns each request into a deterministic command (below). - Which commands. When the return type names the command classes (
CommandRequest<ReserveStock>, a list of them, a sealed type), the compiler knows them. When it does not, as withList<CommandRequest<*>>, declare them in@Sends(derives = [...]), so the Manifest lists them and a wait can follow the saga into their contexts; a handler that does neither does not compile. The runtime holds the handler to them: sending a class it does not declare fails the handling for good, and the aggregate parks at once. - Its name. Each handler is a subscription of its own,
<processor>.<function>, with its own checkpoint, and nothing orders it with the saga's other handlers (Order between handlers):OrderProcessSaga.onOrderAwaitingValidation.@Name("…")on the function names it instead, so renaming the function with@Name("<its former name>")keeps the subscription, its checkpoint and its executions. The processor's name and the handler's are each a name by the rule of every name ([A-Za-z][A-Za-z0-9_-]*). - Its dependencies. The saga's constructor parameters, bound from the application's beans.
Build the commands
| Request | Derives |
|---|---|
body.toCommandRequest(id) | A command to the aggregate id of the type that decides body's class, in the tenant of the commit |
body.toCommandRequest() | A creating command to a new aggregate of that type, whose id the target gives it; a command whose body names its aggregate (@AggregateId), to that aggregate |
body.toCommandRequest(to = ref) | A command to the aggregate ref names, of any type and tenant |
body.toCommandRequest { type(type) } | A creating command to a new aggregate of type, whose id the target gives it |
toCommandRequest is a function of every command, imported from the client package: import me.ahoo.wow.api.client.toCommandRequest. Its block sets the request's other fields by the names a Java caller chains on CommandRequest.builder(body): to(ref), type, targetTenant, targetScope, requestId, expectedVersion. CommandRequest.of, CommandRequest.to and the builder make the same request.
A command whose body names its aggregate (Name the aggregate in the body) needs no id, in this context or another: a request that names one beside the body names the same aggregate, and one that names another, or a body that names a blank id, fails the handler. A request without a type finds the target's type from the commands each context declares: this service's own Manifest, and the contract each peer's api jar carries. The handler fails when no context on the class path decides the class, or when several aggregates do; give the request its type then. targetScope (TargetScope.of(tenant, scope)), or targetTenant alone, sends the command to another tenant or scope: a scope left out keeps the commit's, as a ref's tenant does (to(ref)). expectedVersion asks the target for that version.
Every derived command is deterministic:
- Its id and request id come from the execution (
subscription:ref@version) and what it asks, prefixedwow:, which no caller's request id may start with: its target, its command type and its business key. A handler that sends one command of a type to a target needs no key. One that sends several commands of one type to one target gives each arequestIdof its own, a business key such as the item it is about (below), so that handling the commit again derives the same requests in whatever order the handler builds them, even when a read answers in another order, and each target decides each one once. Without them the handler fails unrecoverable and parks, its message naming the handler, the command type and the target. A handler of each event of a type (@OnEventtaking one event) tells its calls apart by their event's place in the stream, so a call that sends one command to a target needs no key, however many such events the stream holds, and a key tells apart the commands of one call: two calls that key their commands by one value send two requests (a test computes such an id withExecutionSagaContext.derivedId(…, eventIndex = typed.eventIndex)). Two commands equal in type, target and body under two keys are two requests; a key handled again with another body is the same request, and its target answers it with the first one's commit, as any repeated request. The command's own request id is that derived id, never therequestIdthe request gives, and the derived id includes the commit being handled: a business key set there tells requests of one handling apart (of one call, for a handler of each event), and does not deduplicate the commands of two commits. - It carries the operator, the owner and the space of the commit it is derived from. An aggregate it creates belongs to the same owner: a basket's checkout creates an order that belongs to the basket's buyer. Derived commands are trusted, so the target's scope guard does not check them: a wrong target is not refused. Test the targets in
sagaSpec. - The subscription sends it and waits for nothing: a request with a
waitor atimeoutfails the handler. context.idsdraws new ids on every handling, as the node's generators do. A derived command's request id comes from its target, the target's id included, so a command whose target is named by a drawn id would be another request each time the commit is handled, to another aggregate. Wow refuses it: a command a handler returns, schedules, cancels or calls whose target's id it drew fromcontext.idsin the same handling fails the handler unrecoverable (anIllegalArgumentException), and the aggregate parks with a message saying what to do. Name the target by an id computed from what is handled (the source aggregate's id, a business key of the event), or send the creating request without an id (its request id is the same on every handling, and the target's admission gives it the aggregate its first attempt created) and send what follows the creation from the@OnCommittedhandler of its receipt, which names the aggregate created. A drawn id in a command's body is not refused.sagaSpecrefuses the same way on the first handling.
Several commands to one target
An order whose lines reserve stock in one warehouse sends one reservation per line to the same aggregate, so each is keyed by the item it reserves:
@OnEvent
fun onOrderPlaced(event: StateTypedEvent<OrderState, OrderPlaced>): List<CommandRequest<Reserve>> =
event.event.lines.map { line ->
Reserve(line.sku, line.quantity).toCommandRequest("warehouse-1") { requestId(line.sku) }
}Handling the commit again, after a reservation failed, reserves each sku once, whatever order the lines come in. The eShop's delivery job keys each stock receipt by its delivery note's number the same way (Scheduling).
Where the commands go
| The target | How it is sent | The saga's hop is done when |
|---|---|---|
| This context | The node decides it within the saga's handling | It is committed |
| Another context | Its command topic, wow.<context>.commands | The broker has it |
A service that executes the commands of other contexts sets wow.kafka.command-intake.enabled: true. A node whose sagas send another context's commands needs a command transport, Kafka (wow.kafka.bootstrap-servers) in production, and does not start without one. Kafka describes the topics.
Order between handlers
Each handler is a subscription of its own, with its own checkpoint, so nothing orders two handlers of one saga, for one aggregate either. One handler takes an aggregate's commits in version order, and takes the next only once the commands it derived from the one before are done, as the table above says; a command topic keeps one aggregate's commands in the order they were sent (Kafka). Two handlers do not wait for each other. After a backlog (a restart, a deployment, a handler that is slow, retries or has parked the aggregate) both catch up at once, and the command one handler derives from a later event may reach its target before the command another handler derives from an earlier event.
Two handlers that send to one target show it, an order process written with a handler per event: it reserves an order's stock when the order awaits its validation, and releases it when the order is cancelled.
@OnEvent
fun onOrderAwaitingValidation(
event: StateTypedEvent<OrderState, OrderAwaitingValidation>
): List<CommandRequest<ReserveStock>> = event.state.quantities().map { (productId, quantity) ->
ReserveStock(event.ref.id, quantity).toCommandRequest(productId)
}
@OnEvent
fun onOrderCancelled(
event: StateTypedEvent<OrderState, OrderCancelled>
): List<CommandRequest<ReleaseReservation>> = event.state.products().map { productId ->
ReleaseReservation(event.ref.id).toCommandRequest(productId)
}In a quiet system the reservations are sent long before any cancellation, and the commands arrive in order. After a backlog, an order cancelled while it awaits its validation may have its release reach a stock first: the stock holds nothing for the order yet, so the release changes nothing, and the reservation that follows holds the units for good, with no rejection and no parked entry. A step whose target rejects it while its prerequisite is missing fails the other way, as a stock rejects a CommitReservation with no-reservation when it holds nothing for the order: an @OnRejected handler that accepts every code drops that step, with an INFO line as its only trace (Handle a rejection). What holds today:
Steps that depend on each other are derived by one handler. Its subscription keeps the order. A handler of the whole commit (
StateEvent<S>) dispatches on each event's type. A handler of each event of a type takes the events' common sealed or interface supertype,StateTypedEvent<S, E>withEthat supertype, and is called once for each such event of a commit, in their order. HereOrderStockStepis a sealed interface thatOrderAwaitingValidation,OrderCancelledandOrderShippedimplement, declared beside them in the api:kotlin@OnEvent @Sends(derives = [ReserveStock::class, ReleaseReservation::class, CommitReservation::class]) fun onStockStep(event: StateTypedEvent<OrderState, OrderStockStep>): List<CommandRequest<*>> = when (event.event) { OrderAwaitingValidation -> event.state.quantities().map { (productId, quantity) -> ReserveStock(event.ref.id, quantity).toCommandRequest(productId) } is OrderCancelled -> event.state.products().map { ReleaseReservation(event.ref.id).toCommandRequest(it) } OrderShipped -> event.state.products().map { CommitReservation(event.ref.id).toCommandRequest(it) } }Its subscription lists each event of
Ein the Manifest, and a commit without one is still passed over before its state is read. For another context's stream,Eis one of that context's api event classes or a sealed type of them: a plain interface is refused, and a subscriber cannot add a sealed parent to a peer's api, so where the api has none over the events, the one handler takesStateEvent<S>and dispatches on each event.Merging handlers that already run keeps one name's checkpoint (
@Name) and leaves the others' behind (Renaming and rewinding), and the merged handler derives every step under the kept name, so the dropped handlers' steps get new request ids: the commits between a dropped handler's checkpoint and the kept one are handled again, their commands sent as new requests, or never get that handler's steps. So merge at a point where nothing lies between them: stop the writes to the source aggregate type (the commands that commit on it, those sagas derive and those that fall due), let every handler being merged reachwow.subscription.backlog0 with no parked aggregate (wow.subscription.parked.aggregates0), deploy the merged handler, then let the writes resume. The dropped handlers' checkpoints stay behind, which each node names at its first start, and their settings go with them: a node refuses to start on awow.subscriptions.[<context>.<processor.function>].*setting of a subscription it does not have.A dependent step is derived from the event its prerequisite commits, when the saga reads the target's stream, or from the prerequisite's receipt in an
@OnCommittedhandler (Opt in to a receipt): it then follows its prerequisite whichever handler runs ahead, as for the commands of one handler (Handle a rejection).For a command to the saga's own context, a rejection that means "not there yet" is not accepted. The handler names the codes it accepts with
rejected.accept(code, …)and leaves that one out: the source aggregate parks under the subscription of the handler that derived the command, and is retried automatically (wow.subscription.parked.*: first after three minutes, doubling, ten retries, set per subscription withwow.subscriptions.[<context>.<processor.function>].parked.*). The retry runs that handler again, which derives the same command, and the target decides it anew, since a rejection without events commits nothing: once the prerequisite has committed, the command commits. A command to another context does not go that way: its rejection parks the aggregate underwow.receipts.<context>, a retry hands the same receipt over again and parks again, the command is not derived again, and the entry holds back the aggregate's later receipts until a release whose handler takes the code is deployed or an operator skips it. For another context, use one of the two forms above.
Learn that a command succeeded
A derived command answers the saga nothing by default: the saga's hop ends once the command is committed in its own context, or once the broker has it for another. Its success already has a fact of its own, the events the target commits, so a saga learns of it the way it learns of anything:
Follow the target's stream. Handle the event the success produces, as any other event. The payment saga requests a payment, and pays the order once that payment's own
PaymentSucceededis committed:kotlin@OnEvent fun onPaymentSucceeded( event: StateTypedEvent<PaymentState, PaymentSucceeded> ): CommandRequest<PayOrder> = PayOrder(event.ref.id, event.state.amount).toCommandRequest(event.state.orderId)A target of another context is followed on its published stream: the handler takes that context's event class, whose aggregate its contract names (Publish and Consume Streams).
Set a deadline. When the success may never come, schedule the command that compensates, and cancel it when the success arrives. Both are steps at the order, the cancel depending on the schedule, so one handler takes both events, through their sealed supertype
StockValidation(declared beside them in the api):kotlinimport me.ahoo.wow.api.client.toCommandRequest import me.ahoo.wow.api.subscribe.schedule private const val STOCK_DEADLINE = "stock-deadline" @OnEvent @Sends(derives = [ReserveStock::class], schedules = [CancelOrder::class]) fun onStockValidation( event: StateTypedEvent<OrderState, StockValidation>, context: SagaContext, ): List<CommandRequest<ReserveStock>> = when (event.event) { OrderAwaitingValidation -> { context.schedule(STOCK_DEADLINE, ScheduleRule.after(10.minutes), CancelOrder("No stock in time."), event.ref.id) event.state.quantities().map { (productId, quantity) -> ReserveStock(event.ref.id, quantity).toCommandRequest(productId) } } OrderStockConfirmed -> { context.cancelSchedule(STOCK_DEADLINE, event.ref) emptyList() } }Split into a handler of each event, the cancel could reach the order before the schedule after a backlog, cancel nothing, and leave the deadline set (Order between handlers); it would then cancel an order whose stock was confirmed, since the eShop's
OrdertakesCancelOrderuntil it is paid. The target schedules the command for itself, so it must decide it. A scheduled command the target refuses when it falls due is logged and not retried, and no@OnRejectedsees it: cancel the schedule on the success, as above, or give the target a command it refuses by its state once the success is in. Any handler of the saga schedules and cancels, an@OnRejectedor@OnCommittedone included.A success that writes nothing produces no event, so the saga sees nothing: a target that accepts a command with
Decision.NoOpcommits nothing. When someone must know, let the target decide a business event instead.
Opt in to a receipt
A saga that must know that its own command committed, because the target's stream is not published to it or because the success produces no event, declares an @OnCommitted handler of the command's type. It takes a CommandReceipt.Committed<C> and returns the commands it derives in turn:
/** A product the inventory reserved confirms it on the order that asked for it. */
@OnCommitted
fun onReserveCommitted(
committed: CommandReceipt.Committed<ReserveStock>
): CommandRequest<ConfirmOrderStock> =
ConfirmOrderStock(committed.ref.id).toCommandRequest(committed.source.id)source is the aggregate whose commit derived the command, here the order; ref is the aggregate the command was committed on, here the product's stock. Only the commands an @OnCommitted handler takes ask for a receipt of their commit, so no other command costs one; every command to another context asks for its rejection's receipt (Handle a rejection). A command that an @OnRejected or @OnCommitted handler derives asks for no receipt of its commit, even of a class an @OnCommitted handler takes: its commit is handed to no handler, in the saga's context or in another. A command to another context carries the request with it, and the target sends the receipt back on wow.<sender>.receipts once the command is committed. The receipt carries the command's result, not the target's state.
A receipt comes for a command the target accepted without change too (Decision.NoOp), with its version unchanged, and for one it had already committed, marked as a duplicate. An @OnCommitted handler, like an @OnRejected one, takes the SagaContext when it needs it: it derives, schedules and calls as an @OnEvent handler does, and declares what it sends in its own @Sends.
Handle a rejection
A derived command may be refused: the stock is short, the order was cancelled meanwhile. A rejection is a business outcome, so the saga handles it in an @OnRejected handler of the command's type, which takes a CommandReceipt.Rejected<C> and returns the commands that compensate. A rejection no handler takes is not passed over as 9.x passed over a failed derived command: it parks the saga's source aggregate, whatever context the command went to, as below.
/** A product the inventory cannot reserve cancels the order that asked for it. */
@OnRejected
fun onReserveRejected(rejected: CommandReceipt.Rejected<ReserveStock>): CommandRequest<CancelOrder> =
CancelOrder("${rejected.ref.id} cannot be reserved: ${rejected.error.message}")
.toCommandRequest(rejected.source.id)CommandReceipt.Rejected names the command (commandId, commandType, ref), its error (code, message, violations, extensions), the saga's executionId and its source, the aggregate whose commit derived the command; it does not carry the command's body. A rejection from another context comes back as a receipt. The runtime hands each rejection over once.
Each derived command is settled on its own: a rejected command stops none of the others, and each rejection goes to its handler. The commands to one aggregate run in the order the saga derived them; those to different aggregates run concurrently, so work that depends on another command's outcome is not derived beside it: derive it from the event the first command commits. The rejections of the saga's own context's commands that it has no handler for park the aggregate once for the saga's subscription, as a failure would, listing every rejected command. A command to another context always asks for its rejection's receipt, and for its commit's only when an @OnCommitted handler takes it. A rejection no handler takes parks the aggregate when its receipt comes back, at once and without a retry, its reason naming the command, the code and the message. That entry is under the context's receipts subscription, wow.receipts.<context>, not the saga handler's name, and it holds back the aggregate's later receipts on that subscription until an operator acts on it: a retry hands the receipt over again, so it parks again until a release with a handler that takes it is deployed; a skip passes it over and lets the later receipts through (Parked aggregates). So the saga's context needs its receipts topic whenever one of its sagas may send commands to another context: a lifecycle or schedule command counts, since every aggregate decides it (Kafka). A command whose class the context's own aggregates decide, sent to another context's aggregate by a saga whose context has no receipts topic, would ask for a receipt nobody reads: that handling fails at once, unrecoverable, before any command is executed, and its reason names the class to declare an @OnRejected handler of. A rejection that needs no compensation is accepted by naming its code: rejected.accept(code, …) returns for a code it names, and the handler derives nothing. Any other code is one the handler does not expect, so it does not take it: the saga's aggregate parks at once, without a retry, as for a rejection no handler takes, its reason naming the handler, the command and the code, and a wait at the saga's hop ends rejected. That holds for a rejection from another context too, whose receipt the handler takes:
/**
* A release the inventory rejects for a product it has no stock of needs no compensation: that product reserved
* nothing either, so the handler accepts that code and derives nothing. Any other code is one it does not expect:
* the order parks at once, its reason naming the code, as without a handler.
*/
@OnRejected
fun onReleaseRejected(rejected: CommandReceipt.Rejected<ReleaseReservation>) =
rejected.accept(FrameworkCodes.AGGREGATE_NOT_FOUND)A handler that compensates one code and accepts another returns a nullable request: if (rejected.error.code == …) CancelOrder(…).toCommandRequest(rejected.source.id) else { rejected.accept(…); null }, declared CommandRequest<CancelOrder>?. A handler that returns Unit without calling accept accepts every code, as a 9.x saga went on after any failed derived command. It accepts too a rejection that only the lack of order between the saga's handlers produces, a step that reached its target before the step it depends on (Order between handlers): the checkpoint moves on and the step is lost. So name the codes a handler expects. Each rejection a handler accepts, deriving nothing, is logged at INFO under the logger wow.saga.rejection in the saga's service, naming the handler, the command, its target and the code (Observability): an accepted rejection is never dropped in silence.
CommandReceipt.Rejected<*> and CommandReceipt.Committed<*> take every command the saga derives, and Rejected<*> the commands it calls too.
A compensation is not compensated. A command that an @OnRejected or an @OnCommitted handler derives, and that is rejected in turn, is not handed to an @OnRejected handler: every command the handler derived is still executed, and their rejections park the aggregate once, listing each, as a rejection no handler takes does. That holds whatever context the command went to. A rejection within the saga's context parks the aggregate under the subscription that ran the handler: the saga's own, for a receipt of its own context's command, or wow.receipts.<context>, for one from another context. A command sent to another context asks for its rejection's receipt, which parks the aggregate under wow.receipts.<context> when it comes back, its reason saying a compensation is not compensated. A handover of several steps, where one receipt derives the next command and that command's rejection must be compensated, therefore derives the next command from an @OnEvent handler, from an event the first command commits, so that its rejection reaches its own @OnRejected handler.
Call another context synchronously
By default a saga derives its commands and the command topic delivers them. When the target being online is a precondition and the saga needs the result now, the handler calls the target's command gateway instead, with context.call:
@OnEvent
@Sends(calls = [SubmitOrder::class])
suspend fun onBasketCheckedOut(event: StateTypedEvent<BasketState, BasketCheckedOut>, context: SagaContext) {
val checkedOut = event.event
context.call(SubmitOrder(checkedOut.items.map { OrderItem(it.productId, it.unitPrice, it.quantity) }))
}- The handler declares the classes it calls in
@Sends(calls = [...]). The Manifest lists them, a wait follows the call, andcallrefuses any other class. calltakes the command, its id and a block of the request's other fields, astoCommandRequestdoes, imported withimport me.ahoo.wow.api.subscribe.call; a request already built is passed as it is,context.call(request), and a request given with a block fails the handling. The request is derived as a returned one is, andcallreturns the command's result once it is committed on the target: its deterministic request id makes every retry the same request, which the target decides once. A call waits for the commit, so its request takes nowaitortimeout.- A creation may name no id, as the checkout's
SubmitOrderdoes: the target gives the aggregate its id (the ordering numbers the order,SO-261031-42), and the result names it. A retry or a replay is the same request, answered with the same aggregate, and takes no other id. - A refusal throws
CommandRejectedException, a business outcome that is not retried. A handler that lets it through hands it to the saga's@OnRejectedhandler of the called command, as a derived command's rejection; without one, the aggregate parks at once. A call that fails or reaches no result throwsWowProblemException, retryable with the same request id: the handler fails and is retried, then parks the aggregate. These are the exceptions aCommandClientthrows. - The node reaches the target on its internal port: its nodes are found by DNS from the service its contract names, or at
wow.peers.<context>.url(Configure a peer). A node does not start when a handler calls a context it cannot reach. A command of the service's own contexts, and a system command, is derived, never called: the build refuses such a call, as it refuses a call of a command that no context of the service or of the peer contracts on its class path decides, naming the handler and the command. callis asuspendfunction, so a saga written in Java derives its commands instead.
Schedule a command
context.schedule(key, rule, command, id) (import me.ahoo.wow.api.subscribe.schedule; a block sets the request's other fields, and context.schedule(key, rule, request) takes a request already built) asks the target to schedule the command for itself under key; context.cancelSchedule(key, target) cancels it. Both record into the context: the runtime sends them after the commands the handler returns, in the order the handler called them. Any handler of the saga may schedule, an @OnSchedule job's too. The handler declares the scheduled commands' classes in @Sends(schedules = [...]), which the Manifest lists by full type name. An aggregate can also schedule commands from its own decision, with the DecideScope: Write an Aggregate.
Where it starts
A saga's subscription that has no checkpoint in a partition starts at the end of its own context's log, so deploying it does not act on the history again. One that reads another context's stream starts where its service joins the stream: at the beginning when no other subscription of the service has read it yet, so a service that joins later still gets what was published before, else at the end, so a handler added later does not send commands for events its service read long ago (JOIN in the Manifest). @OnEvent(start = ...) overrides it, and so does the host's wow.subscriptions.[<context>.<processor.function>].start. After its first checkpoint a subscription goes on from there.
Test it
sagaSpec hands a saga committed events, receipts and rejections, and checks the commands it derives: Test Domain Code.
Next
- Publish and Consume Streams: read another context's events in a saga.