Skip to content

M4-S2 — The reaction engine: runs, sagas and the outbox

Section titled “M4-S2 — The reaction engine: runs, sagas and the outbox”
ModuleM4 — The process engines
After this session you canTrace a reaction from the event that matched it to the run that finished it, including a run that was parked, resumed or failed, and explain who it ran as.
Time77 min with a facilitator · about 77 min on your own
Before you startM4-S1 (timers and chunked runs), M2-S2 (commands, events and the outbox) and M3-S2 (how criteria become a database query). Larkspur Lab, signed in as Rami Aziz, with the workbench windows open. The CMMS stub is running in the lab (the seed starts it).
Go deeperEngine: Reactions · Reaction model and API reference

◆ Orientation (1 min) — Inside every automation

Section titled “◆ Orientation (1 min) — Inside every automation”

Every reaction you have built since ACD, and every timer you opened in M4-S1, ends in the same engine. In ACE M3-S1 you composed reactions into chains and learned three rules: follow-ups may run twice, the executor is a security decision, and you must check that a run happened. This session shows why those rules are true, by opening the engine that runs them. You will see how an event finds its reactions, how a run waits for another service without blocking anything, and what happens to it when the pod running it dies. Then you build a chain on Work Orders, break one step and read the evidence.

▤ Concept (10 min) — From event to finished run

Section titled “▤ Concept (10 min) — From event to finished run”

Matching: which reactions does this event start?

Section titled “Matching: which reactions does this event start?”

The reaction service subscribes to the platform’s domain events on the bus: an entry created or updated, a workflow step reached, a timer fired, a reaction finished, and so on. For each event it selects reactions in two stages:

  1. Coarse selection. A database query loads the reactions defined on the event’s entity that are not disabled, then keeps those whose event type matches.
  2. Fine matching. For some event types a small matcher compares the reaction’s event settings with the event: which step was reached, which fields changed, which reaction finished. No matcher means the reaction matches.

Then come the reaction’s criteria, the condition you set in the designer, merged with a saved query if it names one. Since 1.10 the engine evaluates them in MongoDB against the event’s entry held in memory (an aggregation over an in-memory document list), so criteria have real query semantics: what you learned about criteria trees in M3-S2 holds here. One consequence: operators that need a real collection, such as full-text search, cannot be used in a reaction’s criteria. A criteria mismatch is a skip, logged at information level, with no run recorded. That is why “it did not run” is often a criteria question, not a failure.

Finally the engine expands the reaction across its space scope (Triggering Space, All Spaces and the others) and skips any entry that lives in another store than the entity’s write store. Each entry gets a trace id: the event’s correlation id, suffixed with the entry’s index when one event touches several entries. That trace id follows the run everywhere, and it is the id you search for in the logs.

A run executes the reaction’s actions in order, one at a time. The builder creates one action per reaction, so in practice a run has one action, and a sequence is a chain of reactions; the engine itself accepts a list. Each action passes the loop guard you configured in ACE, runs its handler, and returns a result: success or failure, with its input and output. A failing action does not abort the run: the engine records the failure and moves on, then classifies the run as success, partial success or failure. Nothing is rolled back. An entry the first action created stays created even if the second action fails.

At the end the run’s tail writes one history record (what you read in Reaction Logs), caches the run’s context for chained reactions, and publishes a trigger executed event that chained reactions listen to. Metrics count and time every action along the way.

Sagas: a run that can wait without blocking

Section titled “Sagas: a run that can wait without blocking”

Many actions need another service to do the work. Update Data Entry asks the data service to write; Move Workflow To Step asks it to move the workflow. Before 1.10 an action sent a command and then waited, for up to 30 seconds, for the reply, inside the handler of the event that started the run.

That stopped being possible when the bus gained a transactional outbox, which you met in M2-S2: a message sent from inside a handler is held back and dispatched only when that handler finishes. A handler that sends a command and waits for its reply would wait forever: the reply cannot come because the command has not left, and the command cannot leave because the handler is still waiting. So on the 1.10 line a run is a saga: a durable, resumable record of one run.

sequenceDiagram
  participant E as Event handler
  participant RS as Run (saga)
  participant ST as Saga state store
  participant D as Data service
  E->>RS: criteria passed, start the run
  RS->>ST: save state: cursor at action 1, waiting for step s1
  RS-->>E: return (the handler finishes, the outbox sends the command)
  E-)D: command: update the entry
  D-)RS: completed event, tagged with the run id and step id
  RS->>ST: load state, record the result, advance the cursor
  RS->>ST: last action done: write history, mark finished

What to notice: between sending the command and receiving the answer, nothing is waiting in memory. The state is in the store, so the answer can be handled by any reaction-service pod.

The run’s state (which action it reached, called the cursor, the result so far, and what it is waiting for) is saved in a collection called BusWorkflowState. The name comes from the bus library, which calls its durable units “workflows”; they have nothing to do with Osos workflows, which is why this course says saga. The answer, a completed or failed event, carries the run’s id and the step’s id, so whichever pod receives it can load the right state, check that the answer matches the step it is waiting for, and continue. A failure answer counts as an answer: the run records it and moves on.

Each wait has a deadline: 30 seconds per command by default, longer for a batch, and the file generation step asks for its own 30 minutes. A saga writes its state with compare-and-set, so a redelivered answer, or a deadline that races a late answer, has exactly one winner.

Timer runs and button runs over many entries go through the BullMQ chunk workers you saw in M4-S1. A worker is not a bus handler, so the outbox does not apply there: those runs use a blocking mode that sends one command at a time and waits, as before 1.10.

Two things can strand a run: its pod dies while it waits, or its pod dies after the answer arrived but before the new state was saved. A sweep runs every minute on every reaction-service pod and finds both kinds; each claim is a compare-and-set, so exactly one pod wins. What recovery does is deliberately limited:

SituationWhat happens
Waiting, and the answer arrivesAny pod resumes the run from its stored state
Waiting, and the deadline passes with no answerThe step is recorded as expired and the run continues or ends accordingly
Stranded with nothing to wait for, quiet for 10 minutesThe run is closed out: its history is written for the actions that finished, and the remaining actions never run

The third row is the one masters must design for. Reaction actions are not idempotent, so replaying “create an entry” after an unknown failure would be worse than not running it. The contract is: the record survives, the rest of the work does not. A closed-out run writes an error line Closing out a stalled reaction run without continuing its actions with its cursor.

Recovery has one more effect. A recovered run’s tail is replayed, and while its history record is written exactly once, its trigger executed event may be published twice. A reaction chained on Reaction Succeeded or On Reaction Failed can therefore run twice for one logical run. This is the engine-level reason for ACE’s first rule.

Completed saga states expire seven days after they finish; running ones are never deleted, which is what makes the sweeps safe.

A chained reaction listens to the trigger executed event of the reaction it names, by entity and reaction. When the event arrives, the engine loads the parent’s history and applies a gate: Reaction Succeeded runs when at least one action succeeded, On Reaction Failed only when every action failed. A partial failure therefore takes the success path. Then it rehydrates the parent’s context, which is cached for 10 minutes, compressed, and, since 1.10, cached only if an enabled listener existed when the parent finished. A chained reaction that you create or enable afterwards finds no context for earlier runs, and a chain whose parent finished more than ten minutes before the event is handled silently stops.

On 1.10 two save rules are not enforced yet: a chained reaction must name both the watched entity and reaction, and its scope should be Triggering Space. A missing name means it never fires; a wider scope runs it once per space.

Event Executor Type decides the identity of the run. Executor runs as the user who caused the event, with their permissions. System and Manager run as an administrative modification: the run may skip the checks a person would face (for example, who owns the current workflow step), and with System the run’s user is replaced by the system user and any delegate is cleared. The history’s Executed by shows exactly that. Timer runs have no causing user, so they need System.

▶ Guided demo (10 min) — One run, three windows

Section titled “▶ Guided demo (10 min) — One run, three windows”

Starting state. Larkspur Lab as seeded. Work Orders has the reaction Stamp the start time: On Workflow Step Reached, step In Progress, Update Data Entry on Self, setting Started at to now.

  1. Open work order WO-1007 (Pump P-104 bearing noise) and run its workflow action to move it to In Progress. The form shows Started at filled a moment later.

  2. In Administration › Monitoring › Reaction Logs, open the newest run of Stamp the start time. Read Status Succeeded, Executed by, and the action’s input and output.

  3. Copy the run’s trace id from the run details, then search the logs for it: kubectl -n larkspur logs -l app.kubernetes.io/instance=lk --all-containers --prefix --since=5m | grep <trace id>. Lines from the data service (the write) and the reaction service (the run) share it.

  4. In the record-query window, open the reaction service’s operations database and read the newest saga state:

    db.BusWorkflowState.find({}, { status: 1, "data.cursor": 1, expiresAt: 1, "data.appId": 1 }).sort({ _id: -1 }).limit(1)

    It is finished, its cursor is past the only action, and expiresAt is seven days ahead.

  5. In the bus console, open the data service’s queue and the reaction service’s queue. Move WO-1007 back and forward again while you watch: one message arrives at each, the command and its completion event.

  6. Open the run in Reaction Logs once more. One run per move: the saga resumed and finished.

Screenshot pending Reaction Logs run details for Stamp the start time, with status Succeeded, Executed by, and the action's input and output What to notice: the history shows one run with one action, even though two messages crossed the bus; the wait in between is invisible here and visible only in the saga state.

✓ Practice (4 min) — Matching and sagas

Section titled “✓ Practice (4 min) — Matching and sagas”
PracticeChoose one answer.

A reaction on Work Orders fires On Entry Updated with the criteria Priority equals High. A planner changes a work order’s Priority from Low to Medium. Reaction Logs shows no run, and the reaction service log shows no error. What happened?

  1. Explanation for A

    ✗ Incorrect

    Not this one: a stranded run is closed out with its history written, so it would appear in the logs. See when a pod dies.

  2. Explanation for B

    ✓ Correct

    Correct: a criteria mismatch is logged at information level and records no run, so “no run, no error” is the normal shape of a skip. See matching.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a loop-guard refusal records a failed action in the history, so a run would show. See one run, action by action.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

An engineer proposes a new reaction action that sends a command to the data service and waits, in the same handler, for the reply before returning. On the 1.10 line, what happens when it runs on the saga path?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the reply can never arrive, because the command is held in the outbox until the handler returns. See sagas.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the outbox holds every message sent from inside a handler, whatever pod the receiver is in. See sagas.

  3. Explanation for C

    ✓ Correct

    Correct: the outbox sends the command only when the handler finishes, and the handler is waiting for the reply; the run must park its state instead. See sagas.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A reaction’s criteria use a full-text search operator on the entry’s Description. On the 1.10 line, what do you expect?

  1. Explanation for A

    ✗ Incorrect

    Not this one: they are evaluated by MongoDB, but over an in-memory document list, which cannot run operators that need a real collection. See matching.

  2. Explanation for B

    ✓ Correct

    Correct: since 1.10 criteria run against the event’s entry held in memory, so collection-only operators such as full-text search are not available. See matching.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a timer selects its entries with the database, but this question is about criteria evaluated against an event’s entry. See matching.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

⛏ Lab (42 min) — A three-step chain on Work Orders, broken and read

Section titled “⛏ Lab (42 min) — A three-step chain on Work Orders, broken and read”

Goal. When a work order reaches In Progress, its asset is marked under maintenance, the CMMS stub is told, and the planners are notified, as a chain of three reactions. You then break the middle step and read the failure path.

Before you start. Larkspur Lab; Rami Aziz in the designer; the CMMS stub’s address from the workbench (inside the cluster, allowed by the lab’s outbound settings). Work order WO-1012 (Compressor C-220 oil leak) is at Planned.

Build the chain

  1. Open Data Entities › Work Orders › Reactions › Add Reaction. Name it Mark asset under maintenance. Event On Workflow Step Reached, step In Progress. Event Executor Type System. Triggering Space.
  2. Action Type Update Data Entry, mode Reference, the field Asset: set the asset’s Status to Under maintenance. Confirm and save.
  3. Add a second reaction, Tell the CMMS. Event Reaction Succeeded, watching Mark asset under maintenance on Work Orders. Triggering Space.
  4. Action Type Call API: Choose HTTP Type POST; API URL the CMMS stub’s address followed by /work-orders; Enable custom payload, with the work order’s Number and Asset; and in API Headers the header X-Api-Key set to the lab key from the workbench, marked Redact in history. Confirm and save.
  5. Add a third reaction, Notify the planners. Event Reaction Succeeded, watching Tell the CMMS. Action Type Send Notification to the group Maintenance Planners, text “Work order {{Number}} is in progress”. Confirm and save.
  6. Add a fourth reaction, CMMS call failed. Event On Reaction Failed, watching Tell the CMMS. Action Type Update Data Entry on Self: set CMMS sync to Failed. Save.

Run it and read it

  1. Move WO-1012 to In Progress. Within seconds its asset C-220 shows Under maintenance.

  2. In the CMMS stub’s request list, one POST with WO-1012.

  3. As Omar Haddad (a planner), open the notifications: “Work order WO-1012 is in progress”.

  4. In Reaction Logs, filter on WO-1012: three runs, in the order of the chain, each Succeeded. Open Tell the CMMS and confirm that the X-Api-Key value is stored as ****.

  5. Query the saga states of the last five minutes and count them: one per run, all finished.

    db.BusWorkflowState.countDocuments({ _id: { $gt: ObjectId.createFromTime(Date.now()/1000 - 300) } })

Break the middle step

  1. Edit Tell the CMMS and change the address to http://10.255.255.1/work-orders, a private address the lab does not allow. Save.
  2. Move work order WO-1015 (Valve V-31 seal check) from Planned to In Progress.
  3. In Reaction Logs: Mark asset under maintenance Succeeded; Tell the CMMS Failed, its error CALL_API_DESTINATION_BLOCKED; CMMS call failed Succeeded; Notify the planners did not run.
  4. Open WO-1015: CMMS sync reads Failed, and its asset is still marked Under maintenance: the first step was not rolled back.

Screenshot pending Reaction Logs filtered on WO-1015 showing three runs: one succeeded, one failed with a blocked destination, and the failure reaction succeeded What to notice: the failure path ran because every action of the run failed, and the planners’ notification is absent because no action succeeded.

Restore

  1. Put the stub’s address back in Tell the CMMS and save.

Check.

  • Four reactions exist, the two chained ones on Triggering Space.
  • WO-1012: asset under maintenance, one request at the stub, one notification to the planners.
  • Three succeeded runs for WO-1012, in chain order, with the API key stored as ****.
  • One finished saga state per run.
  • WO-1015: Tell the CMMS failed with a blocked destination, the failure reaction ran, and the planners’ notification did not.
  • WO-1015’s asset stayed Under maintenance.
  • Tell the CMMS points at the stub again.

Pass condition. For WO-1012 and WO-1015 you can show, in Reaction Logs, the runs that happened and the ones that did not, and explain each with the success and failure gates.

If something goes wrong

What you seeWhat to do
No run at all for the first reactionCheck the step: On Workflow Step Reached must name In Progress. Then check the criteria, if you added any.
Tell the CMMS never runsThe chained reaction must name both Work Orders and Mark asset under maintenance, and it must have been enabled before the first run finished. Move another work order.
The stub call fails with a blocked destination in step 8You used an address outside the lab’s allowed list. Use the exact stub address from the workbench.
Notify the planners ran after the failureYou chained it on Mark asset under maintenance instead of Tell the CMMS.
A run is refused, not failedSee Plan limits in the docs: licensing and plan limits.
Model answer

The chain. Moving WO-1012 to In Progress raised a step-reached event. The first reaction matched it, wrote the asset through a command to the data service (its saga parked and resumed), and finished with one successful action. Its trigger executed event matched Tell the CMMS, whose gate passed because at least one action succeeded; that run posted to the stub. Its success, in turn, started Notify the planners. Three runs, three saga states, one history record each, and the key redacted because you marked it.

The break. For WO-1015 the Call API action refused the private address before sending anything, so the run’s only action failed and the run was a failure. On Reaction Failed requires every action to fail, which a one-action run satisfies, so CMMS call failed ran; Reaction Succeeded requires at least one success, so Notify the planners did not. The asset stayed under maintenance because actions are never rolled back: compensation, if you want it, is another reaction.

◇ Worked scenario (3 min) — The duplicate CMMS orders

Section titled “◇ Worked scenario (3 min) — The duplicate CMMS orders”

On Tuesday the CMMS team reports that work order WO-1044 reached them twice, two minutes apart. Nobody moved the work order twice. Decide at each step before you read on.

Step 1. One run or two? In Reaction Logs you filter on WO-1044. Mark asset under maintenance has one run. Tell the CMMS has two runs, each Succeeded. So the parent ran once and its follow-up twice. What can make a chained reaction run twice for one parent run?

Step 2. The logs. You search the reaction service’s log for the parent’s trace id. Between the two child runs there is a warning Closed out stalled reaction runs and an information line The trigger history row was already written; replaying the rest of the tail. A reaction-service pod was replaced during a node drain while the parent run’s tail was finishing. The sweep found the run, found its history already written, and replayed the rest of the tail, which publishes the trigger executed event. That event is at-least-once on the recovery path, so Tell the CMMS matched it twice.

Step 3. Whose bug is it? The engine behaved as designed: it chose a duplicate notification over a lost record. The chain did not, because it assumed exactly one firing. There are two fixes and you apply both. On the platform side, Tell the CMMS sends the work order’s Number as an idempotency key, which the CMMS already supports. On the receiving side, the CMMS deduplicates on that key, as the receiver contract in ACE M6-S1 asks.

Step 4. Could recovery have lost work instead? Yes, in the other direction: if the pod had died before the parent’s action finished, the run would have been closed out and Tell the CMMS would never have run at all. So you add a check to the program’s runbook: a daily query of work orders at In Progress whose CMMS sync is empty, which catches a chain that stopped silently.

The lesson: on the recovery path the engine promises that the record survives, not that the rest of the work happens exactly once. Design every chained step to tolerate running twice or not at all.

✓ Practice (6 min) — Chains, gates and executors

Section titled “✓ Practice (6 min) — Chains, gates and executors”
PracticeChoose one answer.

A reaction has a single action, which fails. A colleague’s follow-up is chained on Reaction Succeeded, and another on On Reaction Failed. Which one runs?

  1. Explanation for A

    ✗ Incorrect

    Not this one: both listen to the event, but each applies a gate on the run’s outcome. See chaining, inside.

  2. Explanation for B

    ✓ Correct

    Correct: the failure path needs every action to fail, which a one-action failed run satisfies, and the success path needs at least one success. See chaining, inside.

  3. Explanation for C

    ✗ Incorrect

    Not this one: completing is not succeeding; the gate reads the actions’ results. See chaining, inside.

  4. Explanation for D

    ✗ Incorrect

    Not this one: every finished run publishes its event, whatever its outcome. See one run, action by action.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

To audit a chain, a builder creates and enables a new reaction on Reaction Succeeded of Tell the CMMS at 10:15. Tell the CMMS last ran at 10:12. At 10:20 nothing has run. Why?

  1. Explanation for A

    ✓ Correct

    Correct: since 1.10 the parent’s context is cached only when an enabled listener exists at that moment, so a later listener finds nothing for earlier runs. See chaining, inside.

  2. Explanation for B

    ✗ Incorrect

    Not this one: only eight minutes passed; the context was simply never stored. See chaining, inside.

  3. Explanation for C

    ✗ Incorrect

    Not this one: reactions are loaded from the database for every event, so no restart is needed. See matching.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

A run of a three-action reaction (created through the API) is stranded after its first action, with nothing left to wait for, and stays quiet for 15 minutes. What does recovery do?

  1. Explanation for A

    ✗ Incorrect

    Not this one: recovery never continues a stranded run, because actions are not safe to replay. See when a pod dies.

  2. Explanation for B

    ✗ Incorrect

    Not this one: replaying an action after an unknown partial failure is exactly what recovery avoids. See when a pod dies.

  3. Explanation for C

    ✓ Correct

    Correct: the contract is that the record survives and the rest of the work does not. See when a pod dies.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A reaction on Purchase Requests moves the request to the next workflow step. With Executor it fails for some requests; with System it always succeeds. Why?

  1. Explanation for A

    ✗ Incorrect

    Not this one: deadlines do not depend on the executor. See sagas.

  2. Explanation for B

    ✓ Correct

    Correct: with Executor the run carries the causing user’s identity, who is not always the step’s owner; System and Manager skip those checks. See who a run executes as.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the mode depends on where the run starts, not on the executor. See sagas.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose every answer that applies.

Which designs make a follow-up on Reaction Succeeded safe on the 1.10 line? Choose all that apply.

  1. Explanation for A

    ✓ Correct

    Correct: a chained run can happen twice on the recovery path, and a deduplicating receiver makes the second one harmless. See the duplicate CMMS orders.

  2. Explanation for B

    ✓ Correct

    Correct: an idempotent write tolerates the at-least-once event without a duplicate. See when a pod dies.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the loop guard counts repeats along a trace; it does not deduplicate a replayed completion event. See when a pod dies.

  4. Explanation for D

    ✓ Correct

    Correct: on 1.10 a wider scope runs the chained reaction once per space, a duplicate you can avoid by design. See chaining, inside.

Check your answer

The correct answers are A, B and D. Open the explanation under each option to see why.

↺ Recap (1 min) — Every automation, explained

Section titled “↺ Recap (1 min) — Every automation, explained”

You can now follow a reaction from the event that matched it, through its criteria and its saga, to the history record and the event that starts the next link of a chain. You know why a run never blocks a worker on the 1.10 line, what recovery saves and what it drops, and why chained steps must tolerate running twice. Next, M4-S3: the workflow engine, whose step moves are among the commands your reactions send, and whose state machine decides what happens to a Purchase Request.