Wait Primitives

View Source

Suspend workflows to wait for time, events, or human input.

Setup

defmodule MyApp.MyWorkflow do
  use Durable
  use Durable.Helpers
  use Durable.Wait  # Import wait functions
end

Duration Helpers

Use these helpers to specify durations:

seconds(30)   # 30 seconds in ms
minutes(5)    # 5 minutes in ms
hours(2)      # 2 hours in ms
days(1)       # 1 day in ms

Sleep Functions

sleep/1 - Duration-Based Sleep

Suspend the workflow for a specific duration.

workflow "delayed_task" do
  step :start, fn ctx ->
    Logger.info("Starting task")
    {:ok, ctx}
  end

  step :wait, fn ctx ->
    sleep(minutes(30))
    {:ok, ctx}
  end

  step :continue, fn ctx ->
    Logger.info("Resumed after 30 minutes")
    {:ok, ctx}
  end
end

Duration examples:

DurationCode
30 secondssleep(seconds(30))
5 minutessleep(minutes(5))
2 hourssleep(hours(2))
1 daysleep(days(1))

schedule_at/1 - Time-Based Sleep

Suspend until a specific datetime.

step :schedule, fn ctx ->
  # Wake up at midnight UTC
  schedule_at(~U[2025-12-25 00:00:00Z])
  {:ok, ctx}
end

# Or use time helpers
step :wait_until_business_hours, fn ctx ->
  schedule_at(next_business_day(hour: 9))
  {:ok, ctx}
end

step :wait_for_monday, fn ctx ->
  schedule_at(next_weekday(:monday, hour: 9))
  {:ok, ctx}
end

Time Helpers

Use these with schedule_at/1:

HelperDescriptionExample
next_business_day/0,1Next Mon-Frinext_business_day(hour: 9)
next_weekday/1,2Next specific daynext_weekday(:friday, hour: 17)
end_of_day/0,1End of current dayend_of_day()
# Wake up at 9am on the next business day
schedule_at(next_business_day(hour: 9))

# Wake up at 5pm next Friday
schedule_at(next_weekday(:friday, hour: 17))

# Wake up at end of today
schedule_at(end_of_day())

Event Waiting

wait_for_event/2 - Single Event

Suspend until an external system sends an event.

workflow "payment_flow" do
  step :initiate_payment, fn ctx ->
    payment = Payments.create(ctx["amount"])
    {:ok, assign(ctx, :payment_id, payment.id)}
  end

  step :await_confirmation, fn ctx ->
    result = wait_for_event("payment_confirmed",
      timeout: minutes(15),
      timeout_value: "timeout"
    )
    {:ok, assign(ctx, :payment_result, result)}
  end

  step :process_result, fn ctx ->
    case ctx["payment_result"] do
      "timeout" -> handle_timeout()
      %{"status" => "success"} -> handle_success()
      _ -> handle_failure()
    end
    {:ok, ctx}
  end
end

Options:

OptionDescription
:timeoutMax wait time (e.g., minutes(15))
:timeout_valueValue returned on timeout (default nil)

The wait returns :timeout_value exactly as you wrote it: an atom comes back as an atom, a tuple as a tuple. That holds in the step that waits. Once you put the value in the context it is stored as JSON like everything else there, so a later step sees an atom as a string and a tuple as a list. Match on it in the waiting step, or use a string as above.

An event's payload and an input's answer are stored too, so they come back with string keys whatever you sent: %{status: "success"} is read as %{"status" => "success"}.

A wait can't be named after one of the keys Durable keeps for itself (__fail__, __rollback__ and the like): the wait raises ArgumentError, and an event or an input sent under such a name finds no wait.

wait_for_any/2 - First Event Wins

Wait for any one of multiple events. Returns {event_name, payload}.

workflow "order_status" do
  step :await_result, fn ctx ->
    {event, payload} = wait_for_any(["success", "failure", "cancelled"],
      timeout: hours(24),
      timeout_value: {"timeout", nil}
    )
    {:ok, ctx
    |> assign(:result_event, event)
    |> assign(:result_data, payload)}
  end

  step :handle_result, fn ctx ->
    case ctx["result_event"] do
      "success" -> process_success(ctx["result_data"])
      "failure" -> process_failure(ctx["result_data"])
      "cancelled" -> process_cancellation()
      "timeout" -> process_timeout()
    end
    {:ok, ctx}
  end
end

wait_for_all/2 - All Events Required

Wait for all specified events. Returns %{event_name => payload}, with each event's name as a string key.

workflow "multi_approval" do
  step :await_approvals, fn ctx ->
    results = wait_for_all(["manager_approval", "legal_approval", "finance_approval"],
      timeout: days(7),
      timeout_value: "timeout"
    )
    {:ok, assign(ctx, :approvals, results)}
  end

  step :process_approvals, fn ctx ->
    case ctx["approvals"] do
      "timeout" ->
        handle_incomplete_approvals()
      %{} = all_approvals ->
        if Enum.all?(all_approvals, fn {_k, v} -> v["approved"] end) do
          proceed_with_request()
        else
          reject_request()
        end
    end
    {:ok, ctx}
  end
end

Sending Events

From your application code (webhook handler, API endpoint, etc.):

# Send event to resume workflow
Durable.Wait.send_event(
  workflow_id,
  "payment_confirmed",
  %{status: "success", transaction_id: "txn_123"}
)

send_event returns :ok once the waiting run has the event. If nothing is waiting for it, it returns {:error, :not_found} and the event isn't kept, unless you pass buffer: true: then it is handed over when the run reaches a wait_for_event, wait_for_any or wait_for_all for that name. wait_for_any takes the first of its names that has a kept event, and wait_for_all every one it has. Any payload counts as an answer, nil included.

A wait takes one event. A second send_event under the same name, or one that arrives after the wait timed out, returns {:error, :not_found}, so two senders can't both be told they delivered it. An event under another name of a wait_for_any that already has its answer returns :ok and does nothing.

Each wait gets its own answer, so a name can be waited for again: in a later step (a deposit and then the balance, both "payment.succeeded"), or in the same step after the first wait timed out (remind the approver, then ask again). A key in the run's data with the same name as a wait is never taken for its answer.

Cancelling a Wait

To end a wait without an answer, cancel it. The wait returns {:cancelled, reason} and the run carries on from there:

:ok = Durable.cancel_wait(workflow_id, reason: "order withdrawn")

# In the step that waits
case wait_for_event("payment_confirmed", timeout: minutes(15), timeout_value: :timed_out) do
  {:cancelled, reason} -> {:fail, reason}
  :timed_out -> {:fail, "no payment"}
  payment -> {:ok, assign(ctx, :payment, payment)}
end

Only the wait that was open is cancelled: a later wait in the same step waits for its own answer.

A run that waits for the lanes of a parallel block, or for a call_workflow child, has no wait of its own. For such a run the call goes down: every lane or child under it that is waiting has its wait cancelled, and theirs in turn. The block or the call keeps waiting for them to finish. It returns {:error, :not_waiting} for a run that isn't waiting.

Human-in-the-Loop

wait_for_input/2 - Generic Human Input

Suspend until a human provides input.

workflow "approval_flow" do
  step :prepare_request, fn ctx ->
    {:ok, %{request: ctx}}
  end

  step :await_approval, fn ctx ->
    result = wait_for_input("manager_approval",
      type: :approval,
      prompt: "Approve this request?",
      timeout: days(3),
      timeout_value: "auto_rejected"
    )
    {:ok, assign(ctx, :approval, result)}
  end

  step :process_decision, fn ctx ->
    status = case ctx["approval"] do
      "auto_rejected" -> "rejected_timeout"
      %{"approved" => true} -> "approved"
      _ -> "rejected"
    end
    {:ok, assign(ctx, :status, status)}
  end
end

Options:

OptionDescription
:typeInput type (see below)
:promptMessage to show user
:metadataAdditional data for UI
:timeoutMax wait time
:timeout_valueValue on timeout
:on_timeout:resume (default) returns :timeout_value; :fail fails the run
:fieldsField definitions for forms
:choicesOptions for choice inputs

Input types:

TypeUse Case
:approvalSimple yes/no decision
:formStructured data entry
:single_choicePick one option
:free_textOpen text input

Convenience Wrappers

wait_for_approval/2

Wait for an approval decision. It returns the answer as it was given. The dashboard's Inbox answers with %{"approved" => true} or %{"approved" => false}, plus "comment" and "by" when given, so answer the same way from your own code:

step :manager_review, fn ctx ->
  answer = wait_for_approval("expense_approval",
    prompt: "Approve expense for $500?",
    metadata: %{employee: "John", amount: 500},
    timeout: days(3),
    timeout_value: :auto_approved
  )

  approved =
    case answer do
      %{"approved" => approved} -> approved
      :auto_approved -> true
    end

  {:ok, assign(ctx, :approved, approved)}
end

# From your code
Durable.provide_input(workflow_id, "expense_approval", %{"approved" => true})

wait_for_choice/2

Wait for a single choice selection. The answer has been stored, so the chosen value comes back as a string:

step :select_shipping, fn ctx ->
  method = wait_for_choice("shipping_method",
    prompt: "Select shipping method:",
    choices: [
      %{value: "express", label: "Express ($15)"},
      %{value: "standard", label: "Standard (Free)"}
    ],
    timeout: hours(24),
    timeout_value: "standard"
  )
  {:ok, assign(ctx, :shipping, method)}
end

wait_for_text/2

Wait for text input.

step :get_reason, fn ctx ->
  reason = wait_for_text("rejection_reason",
    prompt: "Please provide a reason for rejection:",
    timeout: hours(4),
    timeout_value: "No reason provided"
  )
  {:ok, assign(ctx, :reason, reason)}
end

wait_for_form/2

Wait for form submission.

step :collect_details, fn ctx ->
  result = wait_for_form("equipment_request",
    prompt: "Please specify equipment needs",
    fields: [
      %{name: :laptop, type: :select, options: ["MacBook Pro", "ThinkPad X1"], required: true},
      %{name: :monitor, type: :select, options: ["24 inch", "27 inch", "None"], required: false},
      %{name: :notes, type: :text, required: false}
    ],
    timeout: days(7)
  )
  {:ok, assign(ctx, :equipment, result)}
end

Providing Input

From your application (admin UI, API, etc.):

# Provide human input to resume workflow
Durable.Wait.provide_input(
  workflow_id,
  "manager_approval",
  %{approved: true, comment: "Looks good"}
)

Listing Pending Inputs

Find workflows waiting for human input:

# Get all pending inputs
{:ok, pending} = Durable.Wait.list_pending_inputs()

# Filter by status
{:ok, pending} = Durable.Wait.list_pending_inputs(status: :pending)

# Filter by timeout. The ! form returns the list, and raises on a bad filter
soon = Durable.Wait.list_pending_inputs!(
  timeout_before: DateTime.add(DateTime.utc_now(), 3600)
)

Examples

Multi-Stage Approval

workflow "expense_approval" do
  step :submit, fn ctx ->
    # The input stays as it is: its keys are strings in every step
    {:ok, ctx}
  end

  step :manager_review, fn ctx ->
    if ctx["amount"] > 1000 do
      answer = wait_for_approval("manager_approval",
        prompt: "Approve expense of $#{ctx["amount"]}?",
        timeout: days(2)
      )
      # Nobody answering in time returns nil, the default timeout_value
      {:ok, assign(ctx, :manager_approved, match?(%{"approved" => true}, answer))}
    else
      {:ok, assign(ctx, :manager_approved, true)}
    end
  end

  step :finance_review, fn ctx ->
    if ctx["amount"] > 5000 and ctx["manager_approved"] do
      answer = wait_for_approval("finance_approval",
        timeout: days(3)
      )
      {:ok, assign(ctx, :finance_approved, match?(%{"approved" => true}, answer))}
    else
      {:ok, assign(ctx, :finance_approved, true)}
    end
  end

  step :finalize, fn ctx ->
    if ctx["manager_approved"] and ctx["finance_approved"] do
      Expenses.approve(ctx["expense_id"])
    else
      Expenses.reject(ctx["expense_id"])
    end
    {:ok, ctx}
  end
end

Webhook Integration

workflow "order_fulfillment" do
  step :create_shipment, fn ctx ->
    shipment = Shipping.create(ctx["order_id"])
    {:ok, ctx
    |> assign(:shipment_id, shipment.id)
    |> assign(:tracking_number, shipment.tracking)}
  end

  step :await_delivery, fn ctx ->
    # Wait for webhook from shipping provider
    event = wait_for_event("shipment_delivered",
      timeout: days(14),
      timeout_value: "lost_package"
    )
    {:ok, assign(ctx, :delivery_status, event)}
  end

  step :handle_delivery, fn ctx ->
    case ctx["delivery_status"] do
      "lost_package" ->
        Support.create_ticket("Lost package", ctx["shipment_id"])
      %{"status" => "delivered"} ->
        Orders.mark_complete(ctx["order_id"])
      _ ->
        Logger.warning("Unexpected delivery status")
    end
    {:ok, ctx}
  end
end

# In your webhook controller:
def handle_shipping_webhook(conn, %{"tracking" => tracking, "status" => "delivered"} = params) do
  workflow_id = lookup_workflow_by_tracking(tracking)

  Durable.Wait.send_event(workflow_id, "shipment_delivered", %{
    status: "delivered",
    delivered_at: params["timestamp"]
  })

  json(conn, %{ok: true})
end

Scheduled Reminders

workflow "subscription_renewal" do
  step :check_expiry, fn ctx ->
    subscription = Subscriptions.get(ctx["subscription_id"])
    # Keep what later steps need, in a form JSON holds
    {:ok, ctx
    |> assign(:user_email, subscription.user_email)
    |> assign(:expires_at, DateTime.to_iso8601(subscription.expires_at))}
  end

  step :wait_for_reminder_time, fn ctx ->
    {:ok, expires_at, _offset} = DateTime.from_iso8601(ctx["expires_at"])
    schedule_at(DateTime.add(expires_at, -7, :day))  # 7 days before
    {:ok, ctx}
  end

  step :send_reminder, fn ctx ->
    Mailer.send_renewal_reminder(ctx["user_email"])
    {:ok, ctx}
  end

  step :await_renewal, fn ctx ->
    renewal = wait_for_event("subscription_renewed",
      timeout: days(7),
      timeout_value: "not_renewed"
    )
    {:ok, assign(ctx, :renewal_result, renewal)}
  end

  step :handle_result, fn ctx ->
    case ctx["renewal_result"] do
      "not_renewed" ->
        Subscriptions.expire(ctx["subscription_id"])
      _ ->
        Logger.info("Subscription renewed")
    end
    {:ok, ctx}
  end
end

Parallel Approvals

workflow "contract_approval" do
  step :submit_contract, fn ctx ->
    {:ok, %{contract: ctx}}
  end

  step :await_all_approvals, fn ctx ->
    # Wait for all three departments to approve
    results = wait_for_all(["legal", "finance", "management"],
      timeout: days(5),
      timeout_value: "incomplete"
    )
    {:ok, assign(ctx, :approval_results, results)}
  end

  step :finalize, fn ctx ->
    status = case ctx["approval_results"] do
      "incomplete" -> "timed_out"
      approvals ->
        all_approved = Enum.all?(approvals, fn {_, v} -> v["approved"] end)
        if all_approved, do: "approved", else: "rejected"
    end
    {:ok, assign(ctx, :status, status)}
  end
end

Race Condition Handling

workflow "payment_with_timeout" do
  step :await_payment_or_cancel, fn ctx ->
    # First event wins
    {event, event_data} = wait_for_any(["payment_received", "user_cancelled", "fraud_detected"],
      timeout: hours(1),
      timeout_value: {"timeout", nil}
    )
    {:ok, ctx
    |> assign(:result_event, event)
    |> assign(:result_data, event_data)}
  end

  step :handle_result, fn ctx ->
    case ctx["result_event"] do
      "payment_received" -> complete_order()
      "user_cancelled" -> refund_if_needed()
      "fraud_detected" -> flag_for_review()
      "timeout" -> expire_order()
    end
    {:ok, ctx}
  end
end

Best Practices

Always Handle Timeouts

step :await_response, fn ctx ->
  result = wait_for_input("approval",
    timeout: days(7),
    timeout_value: :timed_out  # Always provide a timeout value
  )

  case result do
    :timed_out -> handle_timeout()
    response -> handle_response(response)
  end
  {:ok, assign(ctx, :response, result)}
end

Use Meaningful Event Names

# Good - descriptive and namespaced
wait_for_event("payment.confirmed")
wait_for_event("shipment.delivered")
wait_for_event("user.verified_email")

# Avoid - too generic
wait_for_event("done")
wait_for_event("event")

Store Data Before Waiting

step :prepare_and_wait, fn ctx ->
  # Save important data before suspending
  ctx = ctx
  |> assign(:prepared_at, DateTime.utc_now())
  |> assign(:request_details, ctx)

  # Now wait
  wait_for_input("approval")
  {:ok, ctx}
end

A step sees the same data however the run got to it, straight from the last step or after a wait, a retry, a snooze, a queue move or a crash: as it is stored, with string keys at every depth. prepared_at above is read as ctx["prepared_at"], and holds ISO 8601 text. What a wait adds, the answer under its name, has a string key too.

Use Convenience Wrappers

# Good - clear intent
wait_for_approval("manager_approval", prompt: "Approve?")
wait_for_choice("priority", choices: [...])
wait_for_text("comments")
wait_for_form("details", fields: [...])

# Also works but less clear
wait_for_input("approval", type: :approval)