Chapter 14 — High-Level Process Frameworks: Workflows & Agents
You already know the raw material: gen_server, gen_statem, supervisors,
registries. Chapters 10–13 showed Elixir libraries that arrange those parts
into web layers and pipelines. This chapter covers the frameworks one
abstraction higher still: they take recurring shapes of process
architecture — multi-step sagas with rollback, long-lived stateful actors
that react to events — and make the pattern itself the library.
The names you will hear most: Reactor (workflow/saga orchestration) and Jido (autonomous agents), beside Oban (durable jobs, Ch 13). None of them replaces OTP. Each compiles a pattern you could hand-write onto the primitives you already know.
14.1 The Abstraction Ladder
Place every tool on one ladder — from the metal up:
| Rung | Concern | Hand-written OTP shape | Reach for |
|---|---|---|---|
| 1 | One request-scoped conversation | a single gen_server / gen_statem | nothing — write it |
| 2 | Work that must survive restarts | table + poller + workers | Oban (Ch 13) |
| 3 | Continuous ingestion under load | producer/consumer credit accounting | Broadway / GenStage (Ch 13) |
| 4 | Multi-step consistency across services | task fan-out + hand-rolled undo log | Reactor |
| 5 | Long-lived event-driven actors | fleet of supervised gen_servers + registry | Jido |
flowchart TD
G["raw processes<br/>gen_server · gen_statem"] --> OB["Oban<br/>durable jobs"]
G --> BS["Broadway / GenStage<br/>backpressured flow"]
OB --> RE["Reactor<br/>sagas: DAG + undo"]
BS --> RE
RE --> JI["Jido<br/>agents: state + signals"]
From Erlang you know: this is the same trajectory as
proc_lib→gen_server→ OTP behaviours, repeated one level up. The framework does not remove the runtime semantics — restarts, mailboxes, linking still happen exactly as before — it removes the boilerplate of a pattern you have already written by hand.
Rule of thumb, especially coming from Erlang: drop down a rung whenever
the framework earns nothing. A three-line handle_call beats a workflow
engine. These libraries pay off when the pattern is the product: many
steps, real failure modes between them, or fleets of similar actors.
14.2 Reactor — Sagas as Dependency Graphs
A saga is a transaction you cannot wrap in try/after because its steps
live in different services. Reactor (from the Ash ecosystem — Ch 12) lets
you write one as steps wired by data dependencies:
- You declare what each step consumes (
result(:other_step)); Reactor builds the DAG and runs independent steps concurrently by default, on supervised tasks - A failed step runs its
compensate— retry it, substitute a fallback value, or accept failure - Successful steps that declared an
undoare rolled back in reverse order when a later failure survives compensation — the saga rollback
# An undoable step as a module — note the four-argument callbacks:
defmodule ChargeCard do
use Reactor.Step
@impl true
def run(%{order_id: id, reservation: r}, _ctx, _opts),
do: Payments.charge(id, r)
@impl true
def compensate(%Payments.Timeout{}, _a, _c, _o), do: :retry
def compensate(_reason, _a, _c, _o), do: :ok # decline → begin rollback
@impl true
def undo(payment, _args, _ctx, _opts) do
Payments.refund(payment)
:ok
end
end
defmodule FulfillOrder do
use Reactor
input :order_id
step :reserve_inventory do
argument :order_id, input(:order_id)
max_retries 2
run fn %{order_id: id}, _ctx ->
Inventory.reserve(id)
end
compensate fn _reason, _args, _ctx -> :retry end # holds are cheap to retry
end
step :charge_card, ChargeCard do # module step from above
argument :order_id, input(:order_id)
argument :reservation, result(:reserve_inventory)
end
step :ship do
argument :payment, result(:charge_card)
run fn %{payment: p}, _ctx -> Shipping.dispatch(p) end
end
return :ship
end
{:ok, shipment} = Reactor.run(FulfillOrder, %{order_id: 42})
Nothing here executes top-to-bottom. Input-only steps start immediately;
:charge_card waits for its argument; :ship waits for the payment. If
shipping fails and compensation cannot fix it, Reactor walks the undo stack:
flowchart LR
subgraph F["happy path"]
A["reserve_inventory"] --> B["charge_card"] --> C["ship"]
end
C -.->|"fails"| U1["undo ship"]
U1 --> U2["undo charge_card:<br/>refund"]
U2 --> U3["undo reserve:<br/>release hold"]
Compensation returns decide each step’s outcome: :retry (bounded by
max_retries — unlimited by default, so set it explicitly when retries
have a cost; an optional backoff callback delays attempts),
{:continue, value} (substitute a fallback and carry on), :ok (accept
the failure, proceed to rollback), or {:error, reason} (fail the whole
reactor).
Around the core: compose for sub-reactors, switch/map control-flow
steps, where/guard conditions, telemetry middleware out of the box, and
Mermaid export of the graph — this book’s diagrams, generated from your
code. Ash.Reactor extends the DSL so Ash resource actions (Ch 12) become
steps with transaction-aware undo.
Reactor vs Oban: Different Durability Stories
They answer different questions and combine cleanly:
- Reactor holds the run in memory — rich coordination, but a node crash abandons the saga mid-flight
- Oban (Ch 13) holds each unit as a Postgres row — survives crashes and retries across nodes, but each job is a straight line
- Combined: an Oban worker whose
perform/1callsReactor.run/2gives a crash-durable entry point into an in-memory saga; on error the job is retried per itsmax_attemptsand the DAG regenerates from scratch
14.3 Jido — Agents as Supervised Processes
Where Reactor orchestrates one run, Jido formalizes long-lived actors:
processes that hold state for days, react to events, choose among actions,
and coordinate with peers — agent-shaped systems, with or without LLMs
inside (AI arrives as a companion package, jido_ai, not a core
dependency).
Four concepts, each mapped to something you already operate:
| Jido concept | What it is | Erlang analogue |
|---|---|---|
| Agent | immutable state struct + one command function, cmd/2 | a gen_server’s state + callbacks |
| Action | validated unit of work: params in → state delta (+ effects) out | your handle_call body, minus boilerplate |
| Signal | typed message envelope (CloudEvents format) routing events between agents | a tagged message, standardized |
| Directive | an effect the runtime should perform: emit, spawn, schedule, stop | the sends/spawns your callbacks trigger implicitly |
# 1. The runtime supervisor — one child manages every live agent:
defmodule Support.Jido do
use Jido, otp_app: :support
end
# 2. An action: validated inputs, explicit outputs
defmodule Support.Actions.Triage do
use Jido.Action,
name: "triage",
description: "Sets priority and logs a triage note",
schema: [
priority: [type: :atom, required: true]
]
alias Jido.Agent.Directive
alias Jido.Signal
def run(%{priority: prio}, ctx) do
note = "triaged #{prio} at #{DateTime.utc_now()}"
signal =
Signal.new!("ticket.triaged",
%{ticket_id: ctx.state.ticket_id, priority: prio},
source: "/ticket-agent")
{:ok, %{status: :triaged, notes: [note | ctx.state.notes]},
%Directive.Emit{signal: signal}}
end
end
# 3. The agent: declares state shape, nothing else
defmodule Support.TicketAgent do
use Jido.Agent,
name: "ticket_agent",
schema: [
ticket_id: [type: :string, required: true],
status: [type: :atom, default: :new],
notes: [type: {:list, :string}, default: []]
]
end
Use it twice, at two different altitudes:
# As data — no process yet. Pure function over immutable state:
agent = Support.TicketAgent.new(%{ticket_id: "T-42"})
{agent, directives} =
Support.TicketAgent.cmd(agent, {Support.Actions.Triage, %{priority: :high}})
agent.state.status #=> :triaged — tested without any process running
# As a process — supervised, addressable, signal-driven:
{:ok, pid} = Support.Jido.start_agent(Support.TicketAgent, id: "T-42")
{:ok, agent} =
Jido.AgentServer.call(pid,
Jido.Signal.new!("triage", %{priority: :high}, source: "/dashboard"))
That split is the design’s point. Because cmd/2 is pure — state in,
state-plus-directives out — decision logic is unit-testable and replayable.
Because directives describe effects instead of performing them, the runtime
owns delivery, scheduling, spawning, and shutdown. Signal types a running
agent handles are declared in its signal_routes; execution strategies plug
in behind the same interface (Direct today; an FSM strategy when behavior
is a gen_statem-shaped lifecycle).
From Erlang you know: every running agent is an ordinary supervised process.
start_agentregisters it, Observer shows it, killing it exercises the supervisor — all the Ch 01 machinery applies unchanged. What Jido adds is discipline around the callback: validated inputs, explicit effects, and lookup that scales past a local name table.
When an Agent Framework Earns Its Keep
Honest thresholds, in the framework’s own terms:
- Yes: fleets of similar actors (per-user / per-ticket / per-device), event-driven behavior with many entry points, multi-agent coordination, or agentic AI loops (paired with Ch 28)
- No: a handful of singleton processes with two call sites — that is a
gen_server, and you should write thegen_server
14.4 Choosing: The Decision in One Table
| Symptom in your design | Correct rung |
|---|---|
| “If step 3 fails I must undo steps 1–2” | Reactor saga |
| “Overnight work must survive deploys and node loss” | Oban (Ch 13) |
| “10k events/sec from Kafka; slow downstream must throttle us” | Broadway (Ch 13) |
| “A thing with state that many clients poke via events, forever” | Jido agent — or a hand-written gen_server if there are only a few |
| “One request, one conversation, done in microseconds” | a plain function or gen_server |
The frameworks also stack: a webhook hits a Jido agent, an action returns a directive, the app enqueues an Oban job for the durable part, and that job runs a Reactor saga for the multi-service transaction. Each layer stays simple because the layer below absorbs its failure modes.
From Erlang you know: you have already made every one of these decisions by hand. The ladder is not new technology — it is your own
gen_serverdiscipline, priced and packaged.
Explore More
- Reactor guides — start with Your First Reactor, then Error Handling with Compensation and Undo; the cheatsheet covers DSL syntax
- Jido documentation — agents, actions, signals, and directives guides; jido_action details the schema/validation contract
- Exercise idea: take Ch 13’s Oban worker and convert its body into a
two-step Reactor saga (charge + notify) with an
undorefund — then kill the node mid-run and observe what survives - Exercise idea: drive a Jido agent from a Livebook cell (Ch 15) —
cmd/2it as pure data first, thenstart_agent/2and send it signals
Checkpoint
- What does Reactor give you that a linear function pipeline does not?
- A Reactor step failed and its compensation returned
:ok. What happens to the steps that succeeded before it? - In Jido, why does an action return a directive instead of emitting the signal itself?
- When is plain OTP still the right answer despite these frameworks?
- How do Oban and Reactor complement each other?
Answers
- Dependency-driven execution (independent steps run concurrently) plus per-step compensation and LIFO undo of successful steps — saga rollback across services.
- Each is undone in reverse completion order — but only steps that defined
an
undo; others are left as-is. - So effects belong to the runtime, not the decision logic:
cmd/2stays pure (testable/replayable as data), and the runtime owns delivery, scheduling, spawning, and shutdown uniformly. - When the pattern is small: few processes, few steps, no cross-service rollback. The framework’s vocabulary must cost less than the boilerplate it removes.
- Oban contributes durability (Postgres rows survive crashes, retries, scheduling); Reactor contributes in-memory coordination (concurrent DAG, compensation, undo). Wrap the reactor in a worker to get both.
Next: Chapter 15 — Livebook