Skip to content

Build a multi-step workflow ​

This page builds an onboarding workflow: create an account, wait for a manager to approve it, send a welcome email, and send a reminder three days later. It runs as one function, called once per step. Read Workflows for how steps, sleeps and signals work.

A workflow does not change the live site.

Throughout, the distribution is acme-marketing (d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38) and the function runtime is 01JBQZ8XKT4A9WN2CDEFGH5RM7.

1. Write the steps ​

Each call gets the step name, its input, and any signal. Answer with the next step.

js
function answer(value) {
  return { statusCode: 200, body: JSON.stringify(value) };
}

function handler(request, env) {
  const { step, input, signal } = JSON.parse(request.body);
  switch (step) {
    case 'start': {
      env.kv.put(`account:${input.email}`, 'pending', { ifAbsent: true });
      return answer({
        wait: { signal: 'approved', step: 'welcome', timeout_seconds: 7 * 86400, on_timeout: 'expire', input },
      });
    }
    case 'welcome':
      // signal is {name: 'approved', payload: {...}}
      return answer({ sleep: { seconds: 3 * 86400, step: 'remind', input: { ...input, by: signal.payload.by } } });
    case 'remind':
      return answer({ done: { output: { email: input.email, approved_by: input.by } } });
    case 'expire':
      return answer({ fail: { error: `nobody approved ${input.email}` } });
  }
  return { statusCode: 400, body: `unknown step ${step}` };
}
python
import json


def answer(value):
    return {"statusCode": 200, "body": json.dumps(value)}


def handler(request, env):
    event = json.loads(request["body"])
    step, data, signal = event["step"], event["input"], event["signal"]
    if step == "start":
        env.kv.put("account:" + data["email"], "pending", if_absent=True)
        return answer({"wait": {"signal": "approved", "step": "welcome", "timeout_seconds": 7 * 86400,
                                "on_timeout": "expire", "input": data}})
    if step == "welcome":
        return answer({"sleep": {"seconds": 3 * 86400, "step": "remind",
                                 "input": dict(data, by=signal["payload"]["by"])}})
    if step == "remind":
        return answer({"done": {"output": {"email": data["email"], "approved_by": data["by"]}}})
    if step == "expire":
        return answer({"fail": {"error": "nobody approved " + data["email"]}})
    return {"statusCode": 400, "body": "unknown step " + step}

A step can run twice, so the start step writes with ifAbsent and a retried step does no harm (env.kv needs a key-value store grant). Edge carries only input between steps; keep it small.

2. Start a run ​

text
Start a workflow run of function 01JBQZ8XKT4A9WN2CDEFGH5RM7 on acme-marketing named onboard,
with input {"email": "ana@example.com"} and idempotency key ana@example.com.
bash
edge workflows start acme-marketing --function 01JBQZ8XKT4A9WN2CDEFGH5RM7 --name onboard \
  --input '{"email": "ana@example.com"}' --key ana@example.com
bash
curl -s -X POST https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/workflows \
  -H "Authorization: Bearer $EDGE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"script_id": "01JBQZ8XKT4A9WN2CDEFGH5RM7", "name": "onboard",
       "input": {"email": "ana@example.com"}, "idempotency_key": "ana@example.com"}'

The agent runs edge_workflow_start:

json
{
  "run_id": "wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C",
  "name": "onboard",
  "status": "running",
  "step": "start",
  "created": true,
  …
}

Starting again with the same key returns the same run with created: false. A cron can start runs on a schedule with the target {"type": "workflow_start", "script_id": …} (--start-workflow in the CLI).

3. Send the signal ​

After the start step the run is waiting for approved. In the web app, open Distributions, select acme-marketing, and find the run under Workflows: it says Waiting for approved at welcome and has a Send approved button, which sends the signal with no payload. This example reads payload.by, so send it with a payload instead:

text
Send the approved signal to workflow run wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C with payload {"by": "kenji"}.
bash
edge workflows signal wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C --name approved --payload '{"by": "kenji"}'
bash
curl -s -X POST https://api.edge.deca-dev.com/v1/workflows/wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C/signals \
  -H "Authorization: Bearer $EDGE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "approved", "payload": {"by": "kenji"}}'

The agent runs edge_workflow_signal. The answer has delivered: true and the run moves on to welcome. A signal sent before the run waits for it is kept, and delivered is false.

4. Follow it ​

text
Show me workflow run wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C and its steps.
bash
edge workflows get wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C
bash
curl -s https://api.edge.deca-dev.com/v1/workflows/wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C \
  -H "Authorization: Bearer $EDGE_TOKEN"

The agent runs edge_workflow_get. steps lists each step attempt with its status, error and duration. Three days after welcome, the run sleeps through to remind and ends completed with its output.

Subscribe a webhook to workflow.completed and workflow.failed to hear about the end. See Send events to a webhook.

5. Cancel or retry ​

In the web app, the run's row has Cancel while it runs and Retry once it has failed.

text
Cancel workflow run wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C.
bash
edge workflows cancel wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C
edge workflows retry wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C
bash
curl -s -X POST https://api.edge.deca-dev.com/v1/workflows/wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C/cancel \
  -H "Authorization: Bearer $EDGE_TOKEN"
curl -s -X POST https://api.edge.deca-dev.com/v1/workflows/wfr_01M4XC2D3F6G8H1J4K7L0Z2X5C/retry \
  -H "Authorization: Bearer $EDGE_TOKEN"

The agent runs edge_workflow_cancel or edge_workflow_retry. Cancel lets a step that is already running finish and ignores its answer. Retry runs the failed step again with its input and a fresh set of attempts.

6. Start and signal from your own endpoints ​

A function can start and signal runs itself with env.workflow, for example a sign-up form that starts the run and an approval link that sends the signal. Put the branches in the same function, in front of the steps: a function may always start runs of its own script and signal them. To start a different function, add it to this function's workflow_starts first (edge_function_update, see Function runtimes).

js
function handler(request, env) {
  if (request.path === '/_api/signup') {
    const { email } = JSON.parse(request.body);
    const { runId } = env.workflow.start('onboard', { email }, { idempotencyKey: email });
    return { statusCode: 202, body: JSON.stringify({ runId }) };
  }
  if (request.path === '/_api/approve') {
    const { runId, by } = JSON.parse(request.body);
    try {
      env.workflow.signal(runId, 'approved', { by });
    } catch (error) {
      if (error.code === 'run_finished') return { statusCode: 409, body: 'already finished' };
      throw error;
    }
    return { statusCode: 204, body: '' };
  }
  // …the steps from section 1
}
python
import json

def handler(request, env):
    if request["path"] == "/_api/signup":
        email = json.loads(request["body"])["email"]
        started = env.workflow.start("onboard", {"email": email}, idempotency_key=email)
        return {"statusCode": 202, "body": json.dumps({"runId": started["run_id"]})}
    if request["path"] == "/_api/approve":
        body = json.loads(request["body"])
        try:
            env.workflow.signal(body["runId"], "approved", {"by": body["by"]})
        except WorkflowError as error:
            if error.code == "run_finished":
                return {"statusCode": 409, "body": "already finished"}
            raise
        return {"statusCode": 204, "body": ""}
    # …the steps from section 1

Map both paths to the function with a wasm route. env.workflow.get(runId) returns the run's status, step and waiting_for, and output once it completes. A step can start a child run, but it cannot signal its own run: its answer moves the run.

Next ​

Limits lists the step, size and time limits.