Durable (Durable v2.0.2)
View SourceA durable, resumable workflow engine for Elixir.
Durable provides a clean DSL for defining workflows with built-in support for:
- Resumability: Sleep, wait for events, wait for human input
- Reliability: Automatic retries with configurable backoff strategies
- Observability: Built-in log capture and graph visualization
- Composability: Decision steps, loops, parallel execution, and more
Installation
Add Durable to your supervision tree:
defmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
MyApp.Repo,
{Durable, repo: MyApp.Repo}
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
endCreate a migration for Durable tables:
defmodule MyApp.Repo.Migrations.AddDurable do
use Ecto.Migration
def up, do: Durable.Migration.up()
def down, do: Durable.Migration.down()
endQuick Start
Define a workflow using the DSL:
defmodule MyApp.OrderWorkflow do
use Durable
use Durable.Helpers
workflow "process_order", timeout: hours(2) do
# A workflow's data has string keys in every step
step :validate, fn order ->
{:ok, assign(order, :order_id, order["id"])}
end
step :charge, [retry: [max_attempts: 3, backoff: :exponential]], fn data ->
receipt = PaymentService.charge(data["order_id"])
{:ok, assign(data, :receipt, receipt)}
end
end
endStart a workflow:
{:ok, workflow_id} = Durable.start(MyApp.OrderWorkflow, %{"id" => "order_123", "items" => items})Query execution status:
{:ok, execution} = Durable.get_execution(workflow_id)Reading
Every function that reads (get_execution/2, list_executions/1,
list_children/2, rollback_plan/2, list_schedules/1, get_schedule/2,
list_nodes/1, paused_queues/1, and all of Durable.Query and
Durable.Stats) returns {:ok, result} or {:error, reason}, and has a
twin ending in ! that returns the result or raises ArgumentError:
{:ok, runs} = Durable.list_executions(status: :failed)
runs = Durable.list_executions!(status: :failed)
{:error, {:invalid_option, :limit}} = Durable.list_executions(limit: -1)
{:error, :not_found} = Durable.get_execution("no-such-run")Durable.Query.Opts lists the reasons.
Configuration Options
:repo- The Ecto repo module (required):name- Instance name for multiple Durable instances (default:Durable):queues- Queue configuration map:queue_enabled- Enable/disable queue processing (default:true)
See Durable.Config for the complete list of options.
Summary
Functions
Injects the Durable DSL into the calling module.
Cancels a pending, running or waiting workflow, and its child workflows.
Cancels every pending, running or waiting run that matches filters, the
filters of list_executions/1, one by one as cancel/2 would (children
included). Returns {:ok, count}. At least one filter is required, and one
that wouldn't narrow the runs (a misspelt name, a nil) raises rather than
cancel everything else.
Cancels what a waiting run is waiting for: its wait returns
{:cancelled, reason} and the run carries on. For a run that waits on its
lanes or a child, the waits under it are cancelled instead.
Returns a child specification for Durable.
Deletes a scheduled workflow.
Disables a scheduled workflow.
Stops this node taking new work and waits for what it's running.
Enables a scheduled workflow.
Gets the execution details for a workflow.
Like get_execution/2, but returns the run or raises ArgumentError.
Gets a scheduled workflow by name.
Like get_schedule/2, but returns the schedule or raises ArgumentError.
Lists child workflow executions for a parent workflow.
Like list_children/2, but returns the runs or raises ArgumentError.
Lists workflow executions with optional filters.
Like list_executions/1, but returns the runs or raises ArgumentError.
Lists the Durable nodes that have heartbeated recently, newest first. Each
has :id, :queues, :version, :started_at, :heartbeat_at, a
:status of :alive or :missing (no heartbeat for 30 s), and :running,
the number of runs it is executing.
Like list_nodes/1, but returns the nodes or raises ArgumentError.
Lists scheduled workflows.
Like list_schedules/1, but returns the schedules or raises ArgumentError.
Pauses a queue on every node. Runs already executing finish; no node claims
new work from the queue until resume_queue/2. The pause survives restarts.
Returns the names of queues currently paused with pause_queue/2.
Like paused_queues/1, but returns the names or raises ArgumentError.
Provides input for a waiting workflow (human-in-the-loop).
Deletes finished runs past the :prune retention now, instead of waiting
for the hourly sweep. Returns the number deleted per group, or %{} when
:prune isn't configured.
Lets a finished run's workflow key go, so the next start with that key
creates a new run even if the workflow's reuse: would refuse it — for
processing an item again on purpose. The run keeps its history and its
key; only holds_key changes.
Starts a fresh run of a finished workflow, with its original input or a new
one. The new run's trigger is :rerun and its trigger_ref is the
original run's id.
Resumes a queue paused with pause_queue/2, on every node.
Resumes a failed workflow at the step that failed.
Undoes a failed run: runs the compensate: of every step that completed,
newest first, on a worker.
What rollback/2 would run for a run: the compensation of every step that
completed, newest first.
Like rollback_plan/2, but returns the plan or raises ArgumentError.
Creates a new scheduled workflow.
Sends an event to a waiting workflow.
Starts a new workflow execution.
Starts a Durable instance.
Starts several runs at once: one {module, input} or {module, input, opts}
per run, with opts (the options of start/3) applying to every item under
the item's own.
Triggers a scheduled workflow immediately.
Updates a scheduled workflow.
Functions
Injects the Durable DSL into the calling module.
Usage
defmodule MyApp.OrderWorkflow do
use Durable
use Durable.Helpers
workflow "process_order" do
step :validate, fn data ->
{:ok, %{order_id: data["id"]}}
end
end
end
Cancels a pending, running or waiting workflow, and its child workflows.
The cancel is final: once it returns :ok the run stays :cancelled and no
later step runs. A step in flight is stopped at the worker's next heartbeat
(:heartbeat_interval, 30 s by default), killed like any process. To stop
cleanly before that, a step can check Durable.Context.cancelled?/0 between
chunks of work.
Cancelling does not run compensations. Pass rollback: true to undo the run
as well: once cancelled it goes back on its queue, a worker runs the
compensate: of every step that completed, newest first, and the run ends
:compensated (or :compensation_failed). What that would run is
rollback_plan/2; with nothing to undo the run stays :cancelled. If a
worker had the run, the undo starts one :heartbeat_interval later, once
that worker has stopped: a step that finished in that time is undone, and
one that was killed part-way isn't, as it never completed. Child workflows
are cancelled, not rolled back.
Returns {:error, :already_completed} if the run has already finished, and
{:error, :not_found} for an unknown id.
Examples
:ok = Durable.cancel(workflow_id)
:ok = Durable.cancel(workflow_id, "User requested cancellation")
# The customer cancelled the order: release the card hold and the stock
:ok = Durable.cancel(workflow_id, "customer cancelled", rollback: true)Options
:rollback- undo the run after cancelling it (default:false):durable- the Durable instance (default:Durable)
@spec cancel_all( keyword(), String.t() | nil ) :: {:ok, non_neg_integer()}
Cancels every pending, running or waiting run that matches filters, the
filters of list_executions/1, one by one as cancel/2 would (children
included). Returns {:ok, count}. At least one filter is required, and one
that wouldn't narrow the runs (a misspelt name, a nil) raises rather than
cancel everything else.
Examples
# An account was closed: stop everything started for it
{:ok, 3} = Durable.cancel_all([tag: "account:7"], "account closed")
{:ok, _} = Durable.cancel_all([workflow: MyApp.Export, status: :waiting])
Cancels what a waiting run is waiting for: its wait returns
{:cancelled, reason} and the run carries on. For a run that waits on its
lanes or a child, the waits under it are cancelled instead.
See Durable.Wait.cancel_wait/2.
Examples
:ok = Durable.cancel_wait(workflow_id, reason: "no longer needed")
@spec child_spec(keyword()) :: Supervisor.child_spec()
Returns a child specification for Durable.
This allows Durable to be used in supervision trees with the
{Durable, opts} syntax.
Deletes a scheduled workflow.
Examples
:ok = Durable.delete_schedule("daily_report")
Disables a scheduled workflow.
Examples
{:ok, schedule} = Durable.disable_schedule("daily_report")
@spec drain(keyword()) :: :ok | {:error, :timeout}
Stops this node taking new work and waits for what it's running.
A node does this by itself when it stops. Call it to start earlier, such as
from a Kubernetes preStop hook. Running runs finish their current step and
go back on their queues for another node. The node doesn't claim again until
it restarts, and other nodes aren't affected.
Returns :ok, or {:error, :timeout} if work was still running when the time
ran out. That work keeps going.
Options
:durable- The Durable instance name (default: Durable):timeout- Milliseconds to wait (default: the:shutdown_grace_period)
Enables a scheduled workflow.
Examples
{:ok, schedule} = Durable.enable_schedule("daily_report")
@spec get_execution( String.t(), keyword() ) :: {:ok, map()} | {:error, Durable.Query.Opts.reason()}
Gets the execution details for a workflow.
Options
:include_steps- Include step execution details (default:false):include_logs- Include logs for each step (default:false)
Examples
{:ok, execution} = Durable.get_execution(workflow_id)
{:error, :not_found} = Durable.get_execution("no-such-run")
execution = Durable.get_execution!(workflow_id, include_steps: true)
Like get_execution/2, but returns the run or raises ArgumentError.
@spec get_schedule( String.t(), keyword() ) :: {:ok, term()} | {:error, Durable.Query.Opts.reason()}
Gets a scheduled workflow by name.
Examples
{:ok, schedule} = Durable.get_schedule("daily_report")
{:error, :not_found} = Durable.get_schedule("nonexistent")
schedule = Durable.get_schedule!("daily_report")
Like get_schedule/2, but returns the schedule or raises ArgumentError.
@spec list_children( String.t(), keyword() ) :: {:ok, [map()]} | {:error, Durable.Query.Opts.reason()}
Lists child workflow executions for a parent workflow.
Options
:status- Filter by status
Examples
{:ok, children} = Durable.list_children(parent_workflow_id)
{:error, :not_found} = Durable.list_children("no-such-run")
running_children = Durable.list_children!(parent_workflow_id, status: :running)
Like list_children/2, but returns the runs or raises ArgumentError.
@spec list_executions(keyword()) :: {:ok, [map()]} | {:error, Durable.Query.Opts.reason()}
Lists workflow executions with optional filters.
Filters
:workflow- Filter by workflow module:status- Filter by status, or a list of statuses:queue- Filter by queue:key- Runs started with this workflow key:tag- Runs started with this tag, across workflows:limit- Maximum number of results (default:50)
Durable.Query.list_executions/1 lists every filter. One of the wrong type
or range is {:error, {:invalid_option, key}}: nothing is clamped.
Examples
{:ok, executions} = Durable.list_executions(status: :running, limit: 100)
{:error, {:invalid_option, :limit}} = Durable.list_executions(limit: -1)
executions = Durable.list_executions!(status: :running, limit: 100)
Like list_executions/1, but returns the runs or raises ArgumentError.
@spec list_nodes(keyword()) :: {:ok, [map()]} | {:error, Durable.Query.Opts.reason()}
Lists the Durable nodes that have heartbeated recently, newest first. Each
has :id, :queues, :version, :started_at, :heartbeat_at, a
:status of :alive or :missing (no heartbeat for 30 s), and :running,
the number of runs it is executing.
{:ok, nodes} = Durable.list_nodes()
nodes = Durable.list_nodes!()
Like list_nodes/1, but returns the nodes or raises ArgumentError.
@spec list_schedules(keyword()) :: {:ok, [term()]} | {:error, Durable.Query.Opts.reason()}
Lists scheduled workflows.
Filters
:enabled- Filter by enabled status:workflow_module- Filter by module:queue- Filter by queue:limit- Maximum results (default: 100):durable- Durable instance name
Examples
{:ok, schedules} = Durable.list_schedules(enabled: true)
schedules = Durable.list_schedules!(enabled: true)
Like list_schedules/1, but returns the schedules or raises ArgumentError.
Pauses a queue on every node. Runs already executing finish; no node claims
new work from the queue until resume_queue/2. The pause survives restarts.
Any name is accepted, whether or not a node runs that queue yet, so a queue
can be paused ahead of the deploy that adds it. A misspelt name therefore
returns :ok and pauses nothing that runs.
Recorded in Durable.Activity as "queue_paused".
Options
:durable- The Durable instance name (default: Durable):by- who paused it, kept with the activity record
@spec paused_queues(keyword()) :: {:ok, [String.t()]} | {:error, Durable.Query.Opts.reason()}
Returns the names of queues currently paused with pause_queue/2.
{:ok, ["reports"]} = Durable.paused_queues()
["reports"] = Durable.paused_queues!()
Like paused_queues/1, but returns the names or raises ArgumentError.
Provides input for a waiting workflow (human-in-the-loop).
Examples
:ok = Durable.provide_input(workflow_id, "approval", %{approved: true})
@spec prune(keyword()) :: %{required(atom()) => non_neg_integer()}
Deletes finished runs past the :prune retention now, instead of waiting
for the hourly sweep. Returns the number deleted per group, or %{} when
:prune isn't configured.
Lets a finished run's workflow key go, so the next start with that key
creates a new run even if the workflow's reuse: would refuse it — for
processing an item again on purpose. The run keeps its history and its
key; only holds_key changes.
Recorded in Durable.Activity as "key_released".
Returns {:error, :not_finished} for a run that's still going (cancel it
first), {:error, :no_key} for a run that doesn't hold a key, and
{:error, :not_found} for an unknown id.
Options
:durable- The Durable instance name (default: Durable):by- who released it, kept with the activity record
Examples
:ok = Durable.release_key(workflow_id, by: "ops@example.com")
Starts a fresh run of a finished workflow, with its original input or a new
one. The new run's trigger is :rerun and its trigger_ref is the
original run's id.
A keyed run's rerun keeps its key and follows the start rules, returning
{:error, {:key_taken, holder_id}} when the key is held. Under
reuse: :never, release_key/2 first.
A lane of a parallel block is part of its block's run, not a workflow of
its own, and is refused with {:error, :lane}: rerun the block's run.
Options
:input- Input for the new run (default: the original run's input):durable- The Durable instance name (default: Durable)
Examples
{:ok, new_id} = Durable.rerun(workflow_id)
{:ok, new_id} = Durable.rerun(workflow_id, input: %{"order_id" => "ORD-1043"})
Resumes a queue paused with pause_queue/2, on every node.
Resumes a failed workflow at the step that failed.
Steps that already completed are not re-run, and the failed step gets its full retry budget again. Inside a parallel block only the children that failed are re-queued.
Returns {:error, :rolled_back} for runs whose compensations ran — use
rerun/2 for those — and {:error, :not_failed} for runs that aren't failed.
A keyed run whose key moved to a newer run takes it back by the same rules
as a start (the newer run is finished and the workflow's reuse: lets it
go), or returns {:error, {:key_taken, holder_id}}.
Options
:durable- The Durable instance name (default: Durable)
Examples
{:ok, ^workflow_id} = Durable.retry(workflow_id)
Undoes a failed run: runs the compensate: of every step that completed,
newest first, on a worker.
A failed run is left as it failed unless its workflow says
on_failure: :rollback, so it can be retried once the cause is fixed. Call
this when it shouldn't be: the customer gave up, the order was cancelled.
The run ends :compensated (or :compensation_failed) and can't be retried
after; a run with nothing to undo stays :failed.
Returns {:error, :rolled_back} for a run already rolled back and
{:error, :not_failed} for one that isn't failed.
Options
:durable- The Durable instance name (default: Durable)
Examples
{:ok, ^workflow_id} = Durable.rollback(workflow_id)
@spec rollback_plan( String.t(), keyword() ) :: {:ok, [{atom(), atom()}]} | {:error, Durable.Query.Opts.reason()}
What rollback/2 would run for a run: the compensation of every step that
completed, newest first.
Durable.rollback_plan(workflow_id)
#=> {:ok, [book_hotel: :cancel_hotel, book_flight: :cancel_flight]}
Durable.rollback_plan!(workflow_id)
#=> [book_hotel: :cancel_hotel, book_flight: :cancel_flight]Empty when there is nothing to undo, and {:error, :not_found} for an id
that isn't a run. Takes :durable like rollback/2.
Like rollback_plan/2, but returns the plan or raises ArgumentError.
Creates a new scheduled workflow.
Arguments
module- The workflow modulecron_expression- Cron expression (e.g., "0 9 *" for 9am daily)opts- Options
Options
:name- Schedule name (defaults to workflow name):workflow- Workflow name (defaults to first workflow in module):input- Input data for each execution:timezone- Timezone for cron (default: "UTC"):queue- Queue to run on (default: :default):enabled- Whether schedule is active (default: true):durable- Durable instance name (default: Durable)
Examples
{:ok, schedule} = Durable.schedule(MyApp.DailyReport, "0 9 * * *")
{:ok, schedule} = Durable.schedule(
MyApp.Reports,
"0 9 * * MON-FRI",
name: "weekday_report",
workflow: "generate_report",
timezone: "America/New_York"
)
Sends an event to a waiting workflow.
Returns {:error, :not_found} when the run isn't waiting for the event,
unless buffer: true keeps it until the run reaches a wait for it
(wait_for_event, wait_for_any or wait_for_all).
Options
:buffer- Keep the event for a run that isn't waiting for it yet (default:false). A run gets one event per name: if several were kept, it gets the newest.:durable- The Durable instance name (default: Durable)
Examples
:ok = Durable.send_event(workflow_id, "payment_confirmed", %{amount: 99.99})
:ok = Durable.send_event(workflow_id, "article_updated", %{rev: 7}, buffer: true)
@spec start(module(), map(), keyword()) :: {:ok, String.t() | %{id: String.t(), created: boolean()}} | {:error, term()}
Starts a new workflow execution.
Arguments
module- The workflow moduleinput- Initial input data for the workflowopts- Options (optional)
Options
:workflow- The workflow name (defaults to the first workflow in the module):queue- The queue to run the workflow on (default::default):priority- Priority level (higher = more important, default:0):scheduled_at- Schedule execution for a future time:key- A workflow key, such as"article:42": at most one run of this workflow holds a key at a time, so starting it again returns that run instead of creating another. A string of 1 to 255 bytes. Whether a key can be used again after its run finishes is the workflow'sreuse:option. See the Workflow keys guide.:tags- Labels for the run, such as["account:7"], to find runs across workflows withlist_executions(tag: ...)and stop them withcancel_all/2. Child runs don't inherit them; cancelling a run cancels its children anyway:on_duplicate- What to do when the key is taken (the default is the workflow's, else:use_existing)::use_existing- return{:ok, holder_id}:error- return{:error, {:key_taken, holder_id}}:cancel_existing- cancel the running holder and start a new run with this input, returning{:ok, new_id}:run_again- leave one run waiting behind the running holder, with the newest input, returning{:ok, waiting_id}. It runs once the holder ends, ifreuse:lets the key go{:send_event, name}- send this input to the running holder as eventname(kept until it waits for it) and return{:ok, holder_id}
Only
:cancel_existingand:run_againcreate a run; nothing is broadcast or run inline for the others. A finished holder that the workflow'sreuse:keeps answers:cancel_existingand{:send_event, name}with{:error, {:key_taken, holder_id}}.:return-:detailsmakes a success{:ok, %{id: id, created: boolean}}, so a caller can tell a new run from a duplicate (default::id)
Returns
{:ok, workflow_id}for a new run, or the holder's id for a duplicate underon_duplicate: :use_existing{:error, {:key_taken, holder_id}}for a duplicate underon_duplicate: :error{:error, %Ecto.Changeset{}}for an invalid key, and{:error, :key_contended}in the rare case the key changed hands three times while this start ran{:error, :invalid_input}for input that isn't a map
Raises ArgumentError for a :key, :tags or :queue that PostgreSQL can't
store, such as text with a NUL character.
Examples
{:ok, workflow_id} = Durable.start(OrderWorkflow, %{order_id: 123})
# The same article twice: one run
{:ok, id} = Durable.start(ProcessArticle, %{"id" => 42}, key: "article:42")
{:ok, ^id} = Durable.start(ProcessArticle, %{"id" => 42}, key: "article:42")
{:ok, workflow_id} = Durable.start(
OrderWorkflow,
%{order_id: 123},
workflow: "process_order",
queue: :high_priority
)
@spec start_link(keyword()) :: Supervisor.on_start()
Starts a Durable instance.
This function is used when adding Durable to your supervision tree.
Options
:repo- The Ecto repo module (required):name- Instance name (default:Durable):queues- Queue configuration
See Durable.Config for the complete list of options.
Examples
# In your application supervisor
children = [
MyApp.Repo,
{Durable, repo: MyApp.Repo}
]
# With custom queues
{Durable,
repo: MyApp.Repo,
queues: %{
default: [concurrency: 10],
high_priority: [concurrency: 20]
}}
@spec start_many( [{module(), map()} | {module(), map(), keyword()}], keyword() ) :: [ok: String.t() | map(), error: term()]
Starts several runs at once: one {module, input} or {module, input, opts}
per run, with opts (the options of start/3) applying to every item under
the item's own.
All the starts share one transaction, the caller's if it is in one, so they
commit together. Keys are checked for every item, as start/3 checks them,
and each item gets its own result, in order. Two batches can name the same keys
in any order. If the batch's locks can't be taken, nothing is started and
every item gets {:error, reason}.
Examples
Durable.start_many([
{ImportRow, %{"row" => 1}, key: "import:9:row:1"},
{ImportRow, %{"row" => 2}, key: "import:9:row:2"}
], tags: ["import:9"])
#=> [{:ok, id1}, {:ok, id2}]
Triggers a scheduled workflow immediately.
This starts a new workflow execution without waiting for the next scheduled time.
Options
:input- Override the schedule's input:durable- Durable instance name
Examples
{:ok, workflow_id} = Durable.trigger_schedule("daily_report")
Updates a scheduled workflow.
Updatable Fields
:cron_expression- New cron expression:timezone- New timezone:input- New input data:queue- New queue:enabled- Enable/disable
Examples
{:ok, schedule} = Durable.update_schedule("daily_report", cron_expression: "0 10 * * *")