API guide

RunFlow API guide

This guide is written for coding agents and the people who set them up. It shows how to run containers, workflows, timers and webhooks through the REST API, and you can copy any code block as it is.

REST API at https://runflow.rodmena.co.uk. Send your API key as the Bearer token.

What RunFlow does #capabilities

Pause and resume

Pausing freezes a running container with its memory intact, and resuming continues it from the same point. You can watch its CPU and memory over HTTP throughout.

The Python "training loop" below keeps its state only in process memory. If it carries on from the same epoch after a resume, the state survived the pause.

# set up your environment
export KEY="rak_..."
export BASE="https://runflow.rodmena.co.uk"

# 1) Submit a simulated training job that streams progress
TID=$(curl -s -X POST $BASE/api/v1/runs -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{
  "image":"python:3.12-slim",
  "command":["python","-u","-c","import time\nloss=1.0\nfor epoch in range(1,21):\n    time.sleep(1)\n    loss*=0.95\n    print(f\"epoch {epoch}/20 loss={loss:.4f}\",flush=True)"],
  "timeout_seconds":60,"cpu_limit":0.5,"memory_limit_mb":128,"name":"pause-resume-demo"}' | jq -r .track_id)

# 2) watch the logs and the CPU use
curl -s "$BASE/api/v1/runs/$TID/logs?stream=stdout" -H "Authorization: Bearer $KEY" | jq -r '.lines[-3:][]'
curl -s "$BASE/api/v1/runs/$TID/utilization"        -H "Authorization: Bearer $KEY" | jq '.samples[-1]'

# 3) pause it mid-training: the logs stop, state=paused, CPU drops to 0
curl -s -X POST "$BASE/api/v1/runs/$TID/pause"  -H "Authorization: Bearer $KEY"

# 4) resume: it continues from the epoch where it stopped
curl -s -X POST "$BASE/api/v1/runs/$TID/resume" -H "Authorization: Bearer $KEY"

# 5) collect the result when it finishes
curl -s "$BASE/api/v1/runs/$TID/result" -H "Authorization: Bearer $KEY" | jq

What you should see:

StepObserved
mid-runepoch 8/20 loss=0.6634, cpu_percent > 0%, X-Log-Source: redis
after pausestate paused, frozen at epoch 8
6s later, still pausedstill epoch 8, with no CPU in use
after resumeepoch 9/20 loss=0.6302. Because the loss carries on from its value before the pause, the process kept its memory.

Authentication #auth

Send your API key as a Bearer token. A key is rak_ followed by 43 characters. The auth service issues keys and shows each one once, when it is created, and RunFlow keeps nothing from which a key could be recovered.

If you do not have a key, do not make one up. A person can get a free key by emailing runflow-freepass@mail.rodmena.co.uk from the address it should belong to, and runflow-freepass+rotate@mail.rodmena.co.uk replaces a leaked one. Because the key comes back to that mailbox, an agent cannot get one by itself. Free keys are restricted, and GET /api/v1/usage shows what yours allows. For a key on this node, or a standard or pro key, contact RODMENA. Runs, logs and metadata are scoped to your key's tenant.

Authorization: Bearer <your-api-key>
ResponseMeaning
401 Missing bearer tokenThe request has no Authorization header.
401 Invalid API keyThe key has a shape RunFlow does not accept, such as a malformed key or a bare UUID. It is refused without a call to the auth service.
401 Unknown API keyThe shape is valid, but the key is not registered or holds no permissions.
401 Tenant-UUID API keys are no longer accepted…The key uses the format retired on 31 July 2026. The message names the fix.
403The key is valid but lacks the permission the endpoint needs.
503The auth service could not be reached and the request was not authorised. Retry it, and do not treat it as a 401.

The auth service grants permissions per key. The run permissions are:

runflow_run_submit   # POST /api/v1/runs
runflow_run_read     # GET /api/v1/runs, /{track_id}, /result, /logs, /utilization, /tenant/quotas
runflow_run_control # POST /pause, /resume, /stop, /kill
runflow_run_delete   # DELETE /api/v1/runs/{track_id}
runflow_tenant_admin # PUT /api/v1/tenant/quotas
Finding your API key. Check the environment variables you were given, or ask the person you work for.
curl https://runflow.rodmena.co.uk/api/v1/tenant/quotas \
  -H "Authorization: Bearer $API_KEY"

Quick Start #quickstart

Three calls take a job from submit to result.

1

Check health

No key is needed. The response reports the service and its dependencies.

curl https://runflow.rodmena.co.uk/health
# {"status":"healthy","postgres":"up","redis":"up","docker":"up","workers":{"total":4,"busy":0}}
2

Submit a hello-world Docker run

API_KEY=rak_...   # your API key, see Authentication above
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "print(\"hello from runflow\")"],
    "timeout_seconds": 60
  }'
# {"track_id":"01KY0XX71BMX0B88C3A189S2K7","status":"scheduled","eligible_start":"2026-07-20T23:31:17Z","clamped":false}
3

Poll the status, then fetch the result and logs

TRACK=01KY0XX71BMX0B88C3A189S2K7

# status: poll until the state is terminal
curl -s https://runflow.rodmena.co.uk/api/v1/runs/$TRACK \
  -H "Authorization: Bearer $API_KEY" | python3 -m json.tool

# result: available when the state is "exited", "failed", "timeout" or "killed"
curl -s https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/result \
  -H "Authorization: Bearer $API_KEY" | python3 -m json.tool

# logs: stdout only here, use stream=both for both
curl -s "https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/logs?stream=stdout" \
  -H "Authorization: Bearer $API_KEY" | python3 -m json.tool

Workflows at a glance #overview

A workflow is a directed acyclic graph of container nodes, submitted in one request. RunFlow starts each node as its own run once the node's dependencies are met, and you do not need a separate orchestrator.

POST   /api/v1/workflows                   # submit a DAG (nodes + edges)
GET    /api/v1/workflows                   # list workflows
GET    /api/v1/workflows/{id}              # status + per-node state
GET    /api/v1/workflows/{id}/nodes/{ref}  # one node's detail
GET    /api/v1/workflows/{id}/result       # per-node outcomes when terminal
GET    /api/v1/workflows/{id}/events       # event log (replay/subscribe by ?since=)
POST   /api/v1/workflows/{id}/cancel       # cancel the whole graph
POST   /api/v1/workflows/{id}/pause|resume # halt / continue the graph
POST   .../nodes/{ref}/retry|approve|reject # retry a stage; decide an approval gate

The Workflows section has the states, engine rules and request models, and examples 4g to 4j can be copied as they are.

The same operations are available over MCP. Connect an MCP client to https://runflow.rodmena.co.uk/mcp (streamable HTTP, Authorization: Bearer <api-key>), which offers 66 tools.

Examples #examples

4a. Hello-world Docker run

Minimal run: pull python:3.12-slim, run a one-liner, exit.

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "print(\"hello from runflow\")"],
    "timeout_seconds": 60
  }'

4b. Python script with environment variables

This run reads a URL from an environment variable, fetches it and prints the HTTP status and content type. The keys and values in env become environment variables in the container.

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "import os,urllib.request; r=urllib.request.urlopen(os.environ[\"TARGET_URL\"]); print(r.status, r.headers[\"content-type\"])"],
    "env": {"TARGET_URL": "https://api.github.com/repos/python/cpython"},
    "timeout_seconds": 30,
    "tags": ["probe", "github"]
  }'

Use tags for free-form labels that you can filter on when listing runs. Values in env must be strings.

4c. Data processing with resource limits

This run sets CPU and memory limits and a name. Runs have no stdin. Pass data in environment variables or in the command itself.

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "import json,os; data={\"a\":1,\"b\":2,\"c\":3}; print(json.dumps({\"count\":len(data),\"keys\":list(data.keys()),\"sum\":sum(data.values())}))"],
    "env": {"PYTHONDONTWRITEBYTECODE": "1"},
    "timeout_seconds": 120,
    "cpu_limit": 1.0,
    "memory_limit_mb": 512,
    "name": "summarize-input",
    "tags": ["etl", "summary"]
  }'

RunFlow clamps cpu_limit, memory_limit_mb and timeout_seconds to your tenant’s quotas, and the response then carries "clamped": true.

4d. Fetch the Hacker News top stories

An agent can hand a data fetch like this one to RunFlow. The script reads the five top stories from the Hacker News API and prints their titles.

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "import urllib.request, json\ntop5=json.loads(urllib.request.urlopen(\"https://hacker-news.firebaseio.com/v0/topstories.json\").read())[:5]\nfor i,sid in enumerate(top5):\n    title=json.loads(urllib.request.urlopen(f\"https://hacker-news.firebaseio.com/v0/item/{sid}.json\").read()).get(\"title\")\n    print(f\"{i+1}. {title}\")"],
    "timeout_seconds": 30,
    "name": "hn-top-5",
    "tags": ["agent", "data-fetch"]
  }'

4e. Scheduling, one-time and recurring

A) One-time run. scheduled_start is an ISO-8601 instant in UTC, written with the trailing Z. A time in the past is clamped to now. The run waits in scheduled and is dispatched once that time arrives and a worker is free.

# schedule a run 60 seconds from now
WHEN=$(date -u -d '+60 seconds' +%Y-%m-%dT%H:%M:%SZ)

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "import datetime;print(\"ran at\", datetime.datetime.now(datetime.timezone.utc).isoformat())"],
    "scheduled_start": "'"${WHEN}"'",
    "timeout_seconds": 30,
    "name": "scheduled-one-time"
  }'

B) Recurring runs (cron). There are three ways to repeat work.

Do not use scheduled_start as a timer. A deferred run spends a max_daily_runs slot on the day you submit it, and when its time comes it still needs a worker, an image pull and a container just to call back. It holds no concurrency slot while it waits in scheduled. A timer (POST /api/v1/timers) sends a signed webhook at the time you give, and a pending timer uses no worker and no daily run.

# example crontab entry (run 'crontab -e', then add it):
# 5 9 * * * (runs at 09:05 every day)
5 9 * * * curl -s -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
  -d '{"image":"python:3.12-slim","command":["python","-c","print(\"daily job\")"],"name":"daily-job"}' \
  >> $HOME/runflow-daily.log 2>&1

4f. Control: pause, resume, stop, kill

# pause a running container
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/pause \
  -H "Authorization: Bearer $API_KEY"

# resume
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/resume \
  -H "Authorization: Bearer $API_KEY"

# graceful stop (SIGTERM + grace period)
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/stop \
  -H "Authorization: Bearer $API_KEY"

# force kill (SIGKILL)
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs/$TRACK/kill \
  -H "Authorization: Bearer $API_KEY"

4g. Workflow: an ETL DAG with fan-out, fan-in and a quality gate

One POST submits the whole graph. Each node is a run with its own track_id, and RunFlow starts it when its dependencies are met. This graph extracts data, splits the work between two transforms that run in parallel, merges the results and checks data quality. It then publishes the result or raises an alert.

curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "nightly-etl",
    "tags": ["etl"],
    "failure_policy": "continue",
    "nodes": [
      {
        "ref": "extract",
        "image": "python:3.12-slim",
        "command": ["python","-c","import json;print(json.dumps({\"rows\":1200,\"nulls\":5}))"],
        "cpu_limit": 0.5, "memory_limit_mb": 128, "timeout_seconds": 120
      },
      {
        "ref": "transform-eu",
        "image": "python:3.12-slim",
        "inputs_from": ["extract"],
        "command": ["python","-c","import json,os;d=json.loads(os.environ[\"RUNFLOW_INPUT_EXTRACT\"]);print(json.dumps({\"region\":\"eu\",\"rows\":d[\"rows\"]//2,\"nulls\":d[\"nulls\"]//2}))"]
      },
      {
        "ref": "transform-us",
        "image": "python:3.12-slim",
        "inputs_from": ["extract"],
        "command": ["python","-c","import json,os;d=json.loads(os.environ[\"RUNFLOW_INPUT_EXTRACT\"]);print(json.dumps({\"region\":\"us\",\"rows\":d[\"rows\"]//2,\"nulls\":d[\"nulls\"]-d[\"nulls\"]//2}))"]
      },
      {
        "ref": "load",
        "image": "python:3.12-slim",
        "inputs_from": ["transform-eu","transform-us"],
        "command": ["python","-c","import json,os;a=json.loads(os.environ[\"RUNFLOW_INPUT_TRANSFORM_EU\"]);b=json.loads(os.environ[\"RUNFLOW_INPUT_TRANSFORM_US\"]);print(json.dumps({\"loaded\":a[\"rows\"]+b[\"rows\"],\"nulls\":a[\"nulls\"]+b[\"nulls\"]}))"]
      },
      {
        "ref": "quality-gate",
        "image": "python:3.12-slim",
        "inputs_from": ["load"],
        "retries": 1,
        "retry_backoff_seconds": 5,
        "command": ["python","-c","import json,os,sys\nd=json.loads(os.environ[\"RUNFLOW_INPUT_LOAD\"])\nrate=100.0*d[\"nulls\"]/d[\"loaded\"]\nif rate>1.0: sys.exit(1)\nprint(json.dumps({\"passed\":True,\"null_rate\":round(rate,2),\"rows\":d[\"loaded\"]}))"]
      },
      {
        "ref": "publish",
        "image": "python:3.12-slim",
        "inputs_from": ["quality-gate"],
        "command": ["python","-c","import json,os;q=json.loads(os.environ[\"RUNFLOW_INPUT_QUALITY_GATE\"]);print(json.dumps({\"published\":True,\"rows\":q[\"rows\"]}))"]
      },
      {
        "ref": "alert",
        "image": "python:3.12-slim",
        "command": ["python","-c","print(\"paging data-oncall\")"]
      }
    ],
    "edges": [
      {"from": "extract",      "to": "transform-eu", "condition": "on_success"},
      {"from": "extract",      "to": "transform-us", "condition": "on_success"},
      {"from": "transform-eu", "to": "load",         "condition": "on_success"},
      {"from": "transform-us", "to": "load",         "condition": "on_success"},
      {"from": "load",         "to": "quality-gate", "condition": "on_success"},
      {"from": "quality-gate", "to": "publish",      "condition": "on_success"},
      {"from": "quality-gate", "to": "alert",        "condition": "on_failure"}
    ]
  }'

The response is 202 {"workflow_id": "01K...", "status": "pending"}. Requests name an edge’s source "from", and responses call it from_ref. transform-eu and transform-us run at the same time, and load waits for both. If the gate passes, publish runs and alert is marked skipped. If it fails, alert runs and publish is skipped. Each node prints JSON on its last line, which reaches the next node as RUNFLOW_INPUT_<REF> (see Message passing).

4h. Workflow: monitor it

You can read the live graph, the event log and the final result.

WF=01K...  # workflow_id from the submit response

# live graph: each node's state, attempt count and current track_id
curl -s https://runflow.rodmena.co.uk/api/v1/workflows/$WF \
  -H "Authorization: Bearer $API_KEY" | jq '.nodes[] | {ref, state, attempt}'

# event log: replay from the start
curl -s "https://runflow.rodmena.co.uk/api/v1/workflows/$WF/events?since=0" \
  -H "Authorization: Bearer $API_KEY" | jq -r '.[] | "\(.id) \(.node_ref // "workflow") -> \(.to_state)"'

# ...then subscribe: re-poll with the highest id you have seen
curl -s "https://runflow.rodmena.co.uk/api/v1/workflows/$WF/events?since=93" \
  -H "Authorization: Bearer $API_KEY"

# per-node detail: each attempt's track_id, for pulling that run's logs
curl -s https://runflow.rodmena.co.uk/api/v1/workflows/$WF/nodes/quality-gate \
  -H "Authorization: Bearer $API_KEY" | jq '{state, attempt, attempts, output}'

# final result: per-node outcomes (409 not_terminal while still running)
curl -s https://runflow.rodmena.co.uk/api/v1/workflows/$WF/result \
  -H "Authorization: Bearer $API_KEY" | jq

A node’s logs are its run’s logs. Take a track_id from attempts and call GET /api/v1/runs/{track_id}/logs. Workflows have no log endpoint of their own.

4i. Workflow control: pause, resume, retry a failed stage, cancel

# pause the graph: no NEW nodes are launched; in-flight nodes run to completion
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/pause \
  -H "Authorization: Bearer $API_KEY"

# resume
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/resume \
  -H "Authorization: Bearer $API_KEY"

# fix the cause, then re-run a failed stage AND everything downstream of it.
# Works on an already-terminal workflow: it goes back to running.
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/nodes/quality-gate/retry \
  -H "Authorization: Bearer $API_KEY"
# -> {"status":"ok","message":"Retrying quality-gate (+2 downstream)"}

# cancel everything: in-flight node runs are killed, the rest marked cancelled
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/cancel \
  -H "Authorization: Bearer $API_KEY"

4j. Workflow: an approval gate

A node with "type":"approval" runs no container and needs no image. Its branch waits at waiting_approval, and the workflow stays active, until you approve or reject it. On the free, standard and pro tiers the gate is rejected automatically after 1 hour, 1 day and 7 days. Approving it follows on_success, and rejecting it follows on_failure.

curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "deploy-with-signoff",
    "nodes": [
      {"ref": "build",  "image": "python:3.12-slim",
       "command": ["python","-c","print(\"built\")"]},
      {"ref": "signoff", "type": "approval"},
      {"ref": "deploy", "image": "python:3.12-slim",
       "command": ["python","-c","print(\"deploying\")"]},
      {"ref": "discard", "image": "python:3.12-slim",
       "command": ["python","-c","print(\"discarded\")"]}
    ],
    "edges": [
      {"from": "build",   "to": "signoff", "condition": "on_success"},
      {"from": "signoff", "to": "deploy",  "condition": "on_success"},
      {"from": "signoff", "to": "discard", "condition": "on_failure"}
    ]
  }'

# ship it (deploy runs, discard is skipped)
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/nodes/signoff/approve \
  -H "Authorization: Bearer $API_KEY"

# or don't (discard runs, deploy is skipped)
curl -X POST https://runflow.rodmena.co.uk/api/v1/workflows/$WF/nodes/signoff/reject \
  -H "Authorization: Bearer $API_KEY"

Because a rejected gate is a failed node, the workflow ends failed even when rejection was the intended outcome. failure_policy does not change that verdict. If your caller treats the reject path as success, check whether the gate is the only entry in failed_nodes.

Scheduling #scheduling

Each run gets an eligible_start when you submit it. That is the earliest time it may start, worked out from scheduled_start and the tenant’s working-hours calendar. The scheduler checks once a second and dispatches eligible runs to free workers. A run is not refused at submit for lack of capacity. It waits for a worker, for up to max_queue_seconds.

Contract change (v2). Reaching the concurrency quota no longer returns 429. The run is accepted and queued, and only max_daily_runs still returns 429 at once. If you relied on that 429 for backpressure, poll scheduling_info.queue_position.

How eligible_start is computed

eligible_start = working_hours_clamp(max(scheduled_start, now))

RunFlow does not look at capacity, meaning the worker pool and the concurrency quota, at submit time. A run at the concurrency limit is accepted and waits in scheduled until a worker is free. If it waits longer than max_queue_seconds past eligible_start, it ends as failed with reason queue_timeout.

Working hours calendar

Set working_hours_tjp in the tenant’s quotas to limit when runs may start. The value is a TaskJuggler (TJP) shift definition. A run is dispatched only when its eligible_start falls inside the shift. With a Monday to Friday, 09:00 to 18:00 shift, a run submitted at 18:30 on Friday gets an eligible_start of Monday 09:00.

# set working hours with PUT /api/v1/tenant/quotas
curl -X PUT https://runflow.rodmena.co.uk/api/v1/tenant/quotas \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "working_hours_tjp": "shift shift_def \"Business Hours\" { workinghours mon - fri 09:00 - 18:00 }"
  }'

# submit on Friday at 17:55 (inside the shift): eligible_start = Friday 17:55
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "print(\"within hours\")"],
    "scheduled_start": "2025-07-18T17:55:00Z"
  }'

# submit on Friday at 18:30 (outside the shift): eligible_start = Monday 09:00
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "print(\"after hours\")"],
    "scheduled_start": "2025-07-18T18:30:00Z"
  }'

Expiry: expires_at as an absolute deadline

Pass an optional expires_at (an ISO-8601 UTC instant) to set an absolute deadline. If the run has not started by then, RunFlow fails it as expired and does not dispatch it. It works separately from scheduled_start, which sets when a run may start, and from max_queue_seconds, which is a window measured from eligible_start. Use it for time-sensitive work you would drop sooner than run late, such as a call that must not go out at night.

# run it only if it can start before the deadline
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python", "-c", "print(\"on time\")"],
    "expires_at": "2026-07-24T22:00:00Z"
  }'
# if still `scheduled` at 22:00:00Z: state=failed, reason=expired, not dispatched

scheduling_info in run status

Every GET /api/v1/runs/{track_id} response includes a scheduling_info object:

{
  "scheduling_info": {
    "eligible_start": "2026-07-21T10:00:00Z",
    "working_hours_applied": false,
    "queue_position": 3,
    "estimated_start": "2026-07-21T10:00:30Z"
  }
}

What happens when the pool is full

# 4 workers, 4 runs already running, submit a 5th
curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "python:3.12-slim", "command": ["python", "-c", "print(5)"]}'

# response: 202 Accepted, not 429
{"track_id": "01KY...", "status": "scheduled", "eligible_start": "2026-07-21T..."}

# check scheduling_info for the queue position
curl -s https://runflow.rodmena.co.uk/api/v1/runs/01KY... \
  -H "Authorization: Bearer $API_KEY" | python3 -m json.tool
# "scheduling_info": {"queue_position": 1, "estimated_start": "..."}

# when a running run exits, the 5th is dispatched on the next scheduler tick

Quotas and limits

max_concurrent_runs limits how many of a tenant’s runs can be in pulling, running or paused at once, and RunFlow checks it at dispatch. max_daily_runs limits submissions per UTC day and is checked at submit, with a 429. cpu_limit, memory_limit_mb and timeout_seconds are clamped to the tenant’s maximums, and the response carries "clamped": true when any of them was reduced.

# check your quotas
curl https://runflow.rodmena.co.uk/api/v1/tenant/quotas \
  -H "Authorization: Bearer $API_KEY"

# update quotas (needs the runflow_tenant_admin permission)
curl -X PUT https://runflow.rodmena.co.uk/api/v1/tenant/quotas \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "max_concurrent_runs": 5,
    "max_daily_runs": 200,
    "max_timeout_seconds": 3600,
    "max_queue_seconds": 600
  }'

Run Lifecycle #lifecycle

A run moves through these states. Poll GET /api/v1/runs/{track_id} until state is terminal.

scheduled -> queued -> pulling -> running -> exited | failed | timeout | killed | v paused -> (resume) -> running
StateCategoryMeaning
scheduledactiveSubmitted, waiting for eligible_start or a free worker slot.
queuedactiveSlot acquired, waiting in the worker queue.
pullingactiveDocker is pulling the image.
runningactiveContainer is executing.
pausedactiveContainer paused via POST /pause. Resume with /resume.
exitedterminalContainer exited 0 or was stopped gracefully.
failedterminalContainer exited non-zero, or the worker failed to start it.
timeoutterminalRun exceeded timeout_seconds and was killed.
killedterminalRun force-killed via POST /kill.

Control endpoints: POST /pause, POST /resume, POST /stop (graceful SIGTERM + grace), POST /kill (SIGKILL). All return 204 No Content on success.

Workflows (DAG) #workflows

A workflow is a directed acyclic graph of nodes joined by conditional edges, submitted in one POST /api/v1/workflows. The engine checks once a second and starts each node when its incoming edges are satisfied. Each node is an ordinary run with one track_id. The quotas, working-hours rules and container hardening on this page apply to it, and its logs, results and utilisation come from the /api/v1/runs/{track_id}/* endpoints.

Worked examples: 4g submit, 4h monitor, 4i control, 4j approval gate.

Workflow states

pending -> running -> succeeded | failed | cancelled | v paused -> (resume) -> running
StateCategoryMeaning
pendingactiveAccepted, not yet picked up by an engine tick.
runningactiveAt least one node is running, retrying or awaiting approval.
pausedactivePaused via POST /pause. No new nodes launch, and in-flight nodes finish.
succeededterminalNothing left to run and no node ended failed.
failedterminalNothing left to run and at least one node ended failed. See failed_nodes.
cancelledterminalCancelled via POST /cancel.

A workflow is terminal only when no node is running, retrying or waiting_approval. An approval gate keeps it active until someone decides the gate or its tier’s approval wait runs out.

Node states

StateCategoryMeaning
pendingactiveWaiting on upstream nodes.
runningactiveIts run is dispatched (the run has its own lifecycle above).
retryingactiveAttempt failed, waiting out retry_backoff_seconds before the next one.
waiting_approvalactiveApproval gate parked until /approve or /reject.
succeededterminalRun exited 0 (or gate approved).
failedterminalRun exited non-zero with retries exhausted (or gate rejected).
skippedterminalIts branch was not taken, or its dependencies can never be satisfied.
cancelledterminalThe workflow was cancelled before this node finished.

Edge conditions

An edge fires based on the upstream node's terminal state. A node launches when every incoming edge is satisfied (nodes with no incoming edges are roots and start immediately).

ConditionFires when upstream is
on_success (default)succeeded
on_failurefailed
alwayssucceeded or failed

always is not unconditional. An upstream node that ends skipped or cancelled satisfies no condition, always included, and the skip carries on down the graph. A node with any unsatisfiable incoming edge is itself marked skipped.

failure_policy

ValueBehaviour
fail_fast (default)After any node fails, no further forward node is launched. Nodes on a failure path (any incoming on_failure or always edge) still run, so cleanup and alerting still fire. Remaining pending nodes are drained to skipped.
continueBranches the failure does not affect keep running to the end. Use it when one branch failing should not stop the others.

Under either policy the workflow ends failed if any node failed. continue changes how much of the graph runs. Check failed_nodes in the result.

Message passing between nodes

Nodes exchange small JSON payloads and share no volumes.

inputs_from does not create a dependency edge. It only says where to read output from. A node that reads inputs_from: ["extract"] without a matching edge may start before extract finishes and see nothing, so declare the edge as well. Each ref in inputs_from must exist, or the submit fails with 400 invalid_graph.

Retries

Each node has its own retries (0 to 10, default 0) and retry_backoff_seconds (default 10). A failed attempt puts the node in retrying. After the backoff, RunFlow dispatches a new run with a new track_id, and the node detail endpoint lists each attempt in attempts. When the retries run out, the node becomes failed and its on_failure edges fire. The backoff stays the same between attempts.

POST /nodes/{ref}/retry retries by hand. It resets that node and everything downstream of it to pending, and moves a terminal workflow back to running. Use it once you have fixed the cause. The node must be terminal, or the call returns 409 node_not_terminal.

Limits

Two tenant quotas apply on top of the run quotas. max_nodes_per_workflow defaults to 50, and going over it returns 400 too_many_nodes. max_concurrent_workflows defaults to 10, and going over it returns 429 workflow_quota_exceeded. Each node also takes a run slot and counts towards max_daily_runs, so a 6-node workflow spends 6 of your daily runs.

WorkflowSubmitRequest — POST /api/v1/workflows body

{
  "name": "nightly-etl",               // optional, max 128 chars
  "tags": ["etl"],                     // default [], free-form labels
  "failure_policy": "fail_fast",       // fail_fast (default) | continue
  "nodes": [ /* NodeSpec, at least 1 */ ],
  "edges": [ /* EdgeSpec, default [] */ ]
}

NodeSpec — one node

{
  "ref": "transform-eu",               // required, unique within the workflow, max 128 chars
  "type": "container",                 // container (default) | approval
  "image": "python:3.12-slim",         // required for container nodes; omit for approval
  "command": ["python", "-c", "..."],   // default []
  "env": {"KEY": "value"},              // default {}, string values only
  "inputs_from": ["extract"],           // default [], upstream refs to inject as RUNFLOW_INPUT_*
  "retries": 0,                        // default 0, range 0-10
  "retry_backoff_seconds": 10,          // default 10, fixed (not exponential)
  "cpu_limit": null,                    // per-node; clamped to tenant quota
  "memory_limit_mb": null,              // per-node; clamped to tenant quota
  "timeout_seconds": null               // per-node; clamped to tenant quota
}

RunFlow ignores unknown keys in a node without an error. A typo such as max_retries for retries returns 202, and the node never retries. If a node does not behave as configured, check its field names against the list above.

EdgeSpec — one dependency

{
  "from": "extract",                    // required, upstream ref. NOTE: "from", not "from_ref"
  "to": "transform-eu",                // required, downstream ref
  "condition": "on_success"           // on_success (default) | on_failure | always
}

Requests use "from", and responses echo edges back as "from_ref"/"to_ref".

WorkflowStatus — GET /api/v1/workflows/{workflow_id}

{
  "workflow_id": "01KY2NQ63B95DZ7SYD741W3S45",
  "tenant_id": "...",
  "name": "nightly-etl",
  "state": "running",                  // pending|running|paused|succeeded|failed|cancelled
  "failure_policy": "continue",
  "submitted_at": "...",
  "started_at": "...",                 // null until the first node launches
  "finished_at": "...",                // null until terminal
  "tags": [...],
  "nodes": [{
    "ref": "quality-gate",
    "type": "container",
    "state": "running",                // see Node states above
    "attempt": 1,
    "current_track_id": "01KY...",    // pull logs via /api/v1/runs/{track_id}/logs
    "exit_code": null
  }],
  "edges": [{"from_ref":"load","to_ref":"quality-gate","condition":"on_success"}]
}

WorkflowNodeDetail — GET /api/v1/workflows/{workflow_id}/nodes/{ref}

{
  "ref": "quality-gate",
  "state": "failed",
  "attempt": 2,
  "attempts": ["01KY2H7ZJN...", "01KY2H85EV..."],  // track_id per attempt, oldest first
  "current_track_id": "01KY2H85EV...",
  "output": {...},                            // parsed from the last stdout line
  "started_at": "...",
  "finished_at": "..."
}

WorkflowResult — GET /api/v1/workflows/{workflow_id}/result (terminal only)

{
  "workflow_id": "...",
  "state": "succeeded",                 // succeeded|failed|cancelled
  "duration_seconds": 5.08,
  "nodes": [{
    "ref": "quality-gate",
    "final_state": "succeeded",
    "exit_code": 0,
    "attempts": 1,                     // count, not the id list
    "output": {"passed": true}
  }],
  "failed_nodes": []                        // refs that ended failed
}

Returns 409 not_terminal while the workflow is still active.

WorkflowEvent — GET /api/v1/workflows/{workflow_id}/events

id is a cursor that only increases. Replay from ?since=0, then poll again with the highest id you have seen. Query: since (default 0), limit (default 200).

[{
  "id": 89,                              // cursor — pass back as ?since=89
  "workflow_id": "...",
  "node_ref": "quality-gate",            // null for workflow-level events
  "kind": "node",                       // node | workflow
  "to_state": "running",
  "detail": {"attempt": 1},              // e.g. {"attempt":N} or {"has_output":true}
  "created_at": "2026-07-21T15:46:44Z"
}]

Workflow Templates #templates

Register a DAG once, then run it by id, or by a name you choose, with only its parameters. A template run substitutes the parameters and then takes the same path as POST /api/v1/workflows. Graph validation, the image allowlist, resource clamping, metering and container hardening apply to it unchanged.

Register it

Declare the parameters, then write ${{ name }} wherever a value should be substituted. A call that breaks the declaration gets a 422 before any container starts.

curl -X POST https://runflow.rodmena.co.uk/api/v1/templates \
  -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' \
  -d '{
    "name": "summarise-repo",                 // optional; ^[a-z][a-z0-9-]{1,62}$, unique to YOUR tenant
    "params": [
      {"name": "repo",  "type": "string", "required": true,
       "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"},
      {"name": "model", "type": "enum", "enum": ["glm-5.2", "gpt-4o-mini"], "default": "glm-5.2"},
      {"name": "LLM_KEY", "type": "string", "required": true, "secret": true}
    ],
    "definition": {                                // the same body as POST /workflows
      "name": "summarise-${{ repo }}",
      "nodes": [
        {"ref": "fetch", "image": "python:3.12-slim", "timeout_seconds": 60,
         "command": ["python", "-c", "..."],
         "env": {"SOURCE_URL": "https://api.github.com/repos/${{ repo }}"}},
        {"ref": "summarise", "image": "python:3.12-slim", "inputs_from": ["fetch"],
         "command": ["python", "-c", "..."],
         "env": {"LLM_MODEL": "${{ model }}", "LLM_API_KEY": "${{ LLM_KEY }}"}}
      ],
      "edges": [{"from": "fetch", "to": "summarise", "condition": "on_success"}]
    }
  }'
# 201 -> {"template_id":"01KYD...","name":"summarise-repo","version":1, ...}

Run it

curl -X POST https://runflow.rodmena.co.uk/api/v1/templates/summarise-repo/run \
  -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' \
  -d '{"params": {"repo": "rodmena-limited/RunFlow", "LLM_KEY": "sk-..."}}'
# 202 -> {"workflow_id":"01KYD...","template_id":"01KYD...","version":1,"status":"pending"}

# from here on it is an ordinary workflow
curl .../api/v1/workflows/$WF          # state + per-node progress
curl .../api/v1/workflows/$WF/result   # each node's JSON output
curl ".../api/v1/workflows?template_id=$TID"   # every run of this template

A run can also take version to pin a version, name to override the workflow name, tags to add to the definition’s tags, scheduled_start to hold back the whole graph, and webhook.

Parameters

Names, versions, limits

Over MCP the template tools are runflow_create_template, runflow_list_templates, runflow_get_template, runflow_update_template, runflow_delete_template and runflow_run_template. They take the same arguments and follow the same permissions and tenant scoping.

Two endpoints send a signed webhook without running a container, so neither spends run quota. POST /api/v1/timers wakes you once at a given instant. POST /api/v1/schedules fires on a cron expression in an IANA timezone, once per occurrence, with daylight-saving changes handled. After downtime a schedule fires the most recent missed occurrence, states the delay in fire_delay_seconds and records how many occurrences it dropped. A template trigger (POST /api/v1/templates/{ref}/triggers) also runs on cron, and it starts a stored workflow.

Outbound Webhooks #webhooks

Register a delivery target and RunFlow POSTs a signed JSON envelope to it when a run, workflow or node changes state. The events are the lifecycle events the /events cursor shows. Delivery is at least once, so deduplicate on event_id. Failed deliveries are retried with growing delays, and you can list and redeliver them. The dispatcher refuses targets on private networks (see Egress safety).

Two ways to register

Inline, for one resource. Add a webhook object to a run or workflow submit body. It applies to that resource only.

curl -X POST https://runflow.rodmena.co.uk/api/v1/runs \
  -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' \
  -d '{
    "image": "python:3.12-slim",
    "command": ["python","-c","print(\"done\")"],
    "webhook": {"url": "https://me.example.com/hooks/run1", "events": ["run.terminal"]}
  }'

Tenant endpoint, kept until you delete it. Register it once and filter by event. RunFlow generates a 32-byte secret, returns it once, and signs each delivery with it.

curl -X POST https://runflow.rodmena.co.uk/api/v1/webhooks \
  -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' \
  -d '{"url": "https://me.example.com/hooks/runflow", "events": ["run.failed", "node.waiting_approval"]}'
# -> 201 {"endpoint_id":"01K...","secret":"a1b2...(64 hex chars)","url":"https://me.example.com/hooks/runflow","events":["run.failed","node.waiting_approval"],...}

If an endpoint and an inline webhook both match an event, each gets its own delivery with its own attempt budget.

Event catalog

ResourceEventsAliasWildcard
runrun.scheduled, run.queued, run.pulling, run.running, run.paused, run.resumed, run.stopping, run.exited, run.failed, run.timeout, run.killedrun.terminal (= exited | failed | timeout | killed)run.*
workflowworkflow.running, workflow.paused, workflow.resumed, workflow.succeeded, workflow.failed, workflow.cancelledworkflow.terminalworkflow.*
nodenode.running, node.retrying, node.waiting_approval, node.succeeded, node.failed, node.skipped, node.cancelled—node.*
any* matches every lifecycle event. webhook.test is deliverable only via POST /api/v1/webhooks/{id}/test and is never emitted by lifecycle.

A subscription’s events list is a union. RunFlow enqueues a delivery when the event matches any literal, alias or wildcard in it, and only one delivery per subscription and event when several patterns match.

Envelope

{
  "event_id": "01K...",                  // ULID; stable across attempts + redelivery (dedupe on this)
  "event_type": "run.exited",
  "occurred_at": "2026-07-21T10:00:00Z",
  "tenant_id": "...",
  "resource": {"type": "run", "id": "01K..."},
  "data": { ... },                       // see data shape below
  "delivery": {"delivery_id": 42, "attempt": 1, "endpoint_id": "01K...|null"},
  "truncated": false                     // true if result_summary or data.nodes were trimmed to fit max_webhook_payload_bytes
}

For a run event, data carries {track_id, state, name, tags, image, submitted_at, started_at, finished_at, workflow_id, node_ref, env} with env redacted. For a run.terminal event, a result block is added: {exit_code, duration_seconds, stdout_bytes, stderr_bytes, result_summary} (last 1 KB of stdout). For a workflow event, data carries {workflow_id, state, name, failure_policy, tags, nodes, failed_nodes}. For a node event, {workflow_id, ref, state, attempt, current_track_id, exit_code, output}.

Headers

HeaderValue
Content-Typeapplication/json
X-RunFlow-Eventthe concrete event type (e.g. run.exited)
X-RunFlow-Event-Idthe ULID event_id from the envelope
X-RunFlow-Deliverythe numeric delivery_id
X-RunFlow-Attemptthe attempt number (1-based)
X-RunFlow-TimestampUnix seconds, bound into the signature
X-RunFlow-Signaturesha256=<hex> = HMAC-SHA256(key, "<timestamp>.<raw body>") where key = bytes.fromhex(secret) (see the note below), or none for an inline webhook with no secret
User-AgentRunFlow/<version>

Hex-decode the secret before you HMAC with it. A secret RunFlow generates is 32 random bytes, given to you once as 64 hex characters. The HMAC key is the 32 raw bytes (bytes.fromhex(secret)), and the 64-character string will not work. Keying with the string produces a well-formed signature that never matches ours, and every delivery then fails your check while your code looks correct. A secret you supply is used as the key exactly as written, with no decoding. GET /api/v1/webhooks/{id} reports which kind you hold in secret_origin: generated, supplied, or unknown for endpoints registered before RunFlow recorded it. Rotation always generates a new secret, so a supplied-secret endpoint becomes generated when rotated and the decoding rule changes with it.

If your verifier reproduces this reference vector, it will verify real deliveries. The dummy secret has the shape RunFlow generates, 64 hex characters.

secret     = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
key        = bytes.fromhex(secret)                  # 32 bytes
timestamp  = 1700000000
raw body   = {"event":"webhook.test","data":{"hello":"world"}}
signed     = "1700000000." + raw body               # note the "." separator

X-RunFlow-Signature: sha256=17737c4354daa76a95234accecd925dbb898813f8ae49c30be40f563c141a079

# Keying with the 64-character STRING instead of its decoded bytes gives:
#   sha256=ffa67b3ea6d46819da436a844b11096bc763ea2c20e278e0cb38b69e149013c1
#
# For a GENERATED secret (this vector) that is the mistake. For a SUPPLIED
# secret it is the CORRECT and only derivation. Which one applies depends
# on where the secret came from.

There is no origin-independent wrong derivation. Do not turn the line above into a receiver rule such as “reject the verbatim-keyed digest”, because that rejects every legitimate supplied secret. Decide by origin when you configure the endpoint, since either you created the secret or RunFlow did, and key each secret one way only. A receiver that tries both derivations accepts no extra callers, and it hides this documented mistake behind a valid signature.

Hash the raw request body bytes. Re-serialising the parsed JSON can reorder keys or change whitespace, and the digest will then differ.

Zero-gap secret rotation. rotate-secret generates the new value, so you cannot install it in advance, and deliveries between the swap and your redeploy fail verification. To rotate with no gap, supply the secret yourself. Generate a value, install it in your receiver, send PATCH /api/v1/webhooks/{id} with {"secret": "…"}, and retire the old value afterwards. Because you install it before RunFlow switches, no valid signature is refused.

Keep the derivation with the secret. A supplied secret is keyed verbatim, whatever it looks like. If you generate 64 hex characters and supply them, the value looks generated and parses as hex, and it must still be keyed verbatim. A receiver that hex-decodes it derives a different key and fails without an obvious error. Record the derivation in your own config when you install the secret, and land that config change together with the PATCH.

Verifying the signature (Python)

import hmac, hashlib

def verify(raw_body: bytes, signature_header: str, shared_secret: bytes) -> bool:
    if signature_header == "none":
        return True  # inline webhook opted out of signing
    if not signature_header.startswith("sha256="):
        return False
    timestamp = ...  # from X-RunFlow-Timestamp header
    expected = hmac.new(shared_secret, f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature_header.removeprefix("sha256="), expected)

During a rotation your receiver holds two valid secrets, the new one and the previous one, for the grace period. The function above accepts only one. Check every candidate and combine the results with a bitwise OR, without returning early on the first match:

def verify_any(raw_body: bytes, signature_header: str, secrets: list[bytes]) -> bool:
    ok = False
    for secret in secrets:            # NO early return, NO ordering heuristic
        ok |= verify(raw_body, signature_header, secret)
    return ok

An early exit over a set of secrets leaks, through response timing, which secret matched. That holds whether the order comes from a hint in the payload, a cache or a most-recently-used rule. Checking every candidate leaks nothing, and it stays safe if someone later tries to speed it up. In particular, do not order by delivery.endpoint_id from the request body. The sender controls that body until the HMAC checks out, so it can serve as a hint and never as a trust decision.

Retry schedule & delivery states

A 2xx response marks the delivery delivered. A 408, 429 or 5xx, a timeout or a transport failure is retried after 10s, 1m, 5m, 30m, which makes 5 attempts in all and a retry budget of 36m10s. Any other 4xx marks the delivery dead at once, because the receiver has rejected the payload. RunFlow does not follow a 3xx redirect and counts it as a failed attempt. An endpoint is disabled automatically (active=false, disabled_reason="dead_without_success_24h") when it has 20 dead deliveries within 24 hours and no successful one in that window. One delivered webhook in the window prevents the disable. A webhook.endpoint_degraded notice goes out earlier, when the 24-hour dead count reaches 5, whether or not there were successes. Re-enable an endpoint with PATCH {"active": true}. The rule counts a 24-hour window. consecutive_failures is reported for information only, because any single success resets it to zero and an endpoint that fails now and then never builds a long streak.

A non-retryable 4xx ends the delivery. It gets no second attempt, and the event reaches you again only if you redeliver it. The usual cause is a route that is up and checks the wrong thing, such as a signature check against the wrong secret, auth middleware that has not been exempted, or a replay guard keyed on something that changes per attempt. Each of those answers 401, and RunFlow treats 401 as final.

Choose the metric you alert on with care. consecutive_failures counts a delivery that dies on its first attempt, and a single success resets it to zero. An endpoint that fails intermittently keeps returning to 0 and never trips a streak threshold, so that field alone cannot show flapping. Alert on tenant.delivery_dead and dead_deliveries_total instead. The cumulative counter and last_dead_delivery_at are not cleared by a success or by re-activation.

Bring the route up first, check that it accepts a request you signed yourself, and register the endpoint last. Each attempt is signed when it is sent. Only the body and X-RunFlow-Event-Id stay the same across retries, so a freshness window measures transit time only, and a replay guard keyed on the signature rejects legitimate retries.

StateMeaning
pendingEnqueued, waiting for the dispatcher to claim it.
deliveringClaimed, with an HTTP attempt in flight.
deliveredA 2xx was returned.
deadAttempt budget exhausted or a non-retryable response.

Delivery listings read oldest first. GET /api/v1/webhooks/{endpoint_id}/deliveries orders by ascending delivery id, and limit cuts from the front, so ?limit=100 returns the first hundred deliveries. Page forward with ?since=<last id seen>. To find out what happened recently, read last_dead_delivery_at, dead_deliveries_total and updated_at on the endpoint record.

Unknown query parameters get a 400 that names the supported ones, on every route that takes query parameters, so a misspelled filter cannot return unfiltered results. The filter is called state_filter, and state is refused.

Replay a terminal delivery with POST /api/v1/webhooks/deliveries/{delivery_id}/redeliver. It creates a new delivery that reuses the original event_id, so your deduplication still works. Delivery is at least once, and receivers must be idempotent on event_id.

Egress safety (SSRF)

RunFlow sends HTTPS requests to URLs that tenants supply. These rules stop the dispatcher being used to reach private networks.

Inline webhook per resource (FR-WH-17)

An inline webhook applies only to the resource it was submitted with. Leave out secret to deliver unsigned, with X-RunFlow-Signature: none. Unknown keys inside the webhook object are rejected with 422, so a misspelled secret cannot produce unsigned deliveries.

Usage & limits #usage

GET /api/v1/usage reports what your key is allowed to do and, on a metered tier, how much of it is left. Call it before you plan a batch of work, to avoid a 429 halfway through. It needs runflow_run_read.

curl https://runflow.rodmena.co.uk/api/v1/usage \
  -H "Authorization: Bearer $API_KEY"
{
  "tier": "free",          // null on an unmetered (standard) key
  "metered": true,
  "limits": {
    "memory_limit_mb": 256,
    "cpu_cores": 0.5,
    "timeout_seconds": 60,
    "concurrent_runs": 1,
    "daily_runs": 100,
    "workflow_nodes": 5,
    "retention_days": 3
  },
  "allowed_images": ["python:3.12-slim", "alpine:latest", "..."],
  "expires_at": "2026-10-23T03:24:39Z",
  "usage": [
    {"policy": "runflow-free-runs-daily", "used": 7,
     "limit": 100, "remaining": 93,
     "resets_at": "2026-07-26T00:00:00Z"}
  ]
}

Notes for agents. allowed_images is null when any image is allowed. When it is a list, any other image returns 403 image_not_allowed. A rate-limit policy reports "used": null because a token bucket has no window total, so do not add that field up. On a metered key a run is charged its full timeout_seconds when it starts and refunded the unused part when it finishes. remaining therefore dips while a run is in flight and recovers afterwards, and a realistic timeout keeps the dip small.

Endpoint Reference #endpoints

MethodPathDescriptionPermissionNotes
GET/pingLiveness probe—No auth. Returns {"message":"PONG"}
GET/healthReadiness probe—No auth. Returns service + dependency status JSON
GET/metricsPrometheus exposition—No auth. Allowed from the local host and the estate's monitoring host only. text/plain
POST/api/v1/runsSubmit a runrunflow_run_submitBody: RunSubmitRequest. Returns RunSubmitResponse (202)
GET/api/v1/runsList runsrunflow_run_readQuery: state_filter, tag, limit (default 100, max 1000), offset
GET/api/v1/runs/{track_id}Run statusrunflow_run_readReturns RunStatus
GET/api/v1/runs/{track_id}/resultRun resultrunflow_run_readReturns RunResult. Only available when state is terminal
GET/api/v1/runs/{track_id}/logsLogsrunflow_run_readQuery: stream=stdout|stderr|both (default both), since=N (offset; null=tail last N), limit (default 1000, max 1000). Returns LogResponse
GET/api/v1/runs/{track_id}/utilizationCPU/mem/net samplesrunflow_run_readQuery: from_ts, to_ts (ISO-8601). Returns UtilizationResponse
POST/api/v1/runs/{track_id}/pausePauserunflow_run_controlReturns 204
POST/api/v1/runs/{track_id}/resumeResumerunflow_run_controlReturns 204
POST/api/v1/runs/{track_id}/stopGraceful stop (SIGTERM + grace)runflow_run_controlReturns 204
POST/api/v1/runs/{track_id}/killForce kill (SIGKILL)runflow_run_controlReturns 204
POST/api/v1/buildsBuild a Dockerfile at a commit and push itrunflow_submit_buildBuild nodes only. Body: BuildSubmitRequest. Returns {track_id} (202)
GET/api/v1/buildsList buildsrunflow_list_buildsQuery: state_filter, tag, limit, offset
GET/api/v1/builds/{track_id}Build status and resultrunflow_get_buildbuild_result has the pushed ref and verified digest
POST/api/v1/builds/{track_id}/killKill a buildrunflow_kill_buildStops the build unit. Nothing is pushed
GET/api/v1/tenant/quotasTenant quotasrunflow_run_readReturns TenantQuotas
POST/api/v1/workflowsSubmit a DAGrunflow_workflow_submitBody: WorkflowSubmitRequest. Returns {workflow_id, status} (202)
GET/api/v1/workflowsList workflowsrunflow_workflow_readQuery: state_filter, tag, template_id, limit (default 50), offset
POST/api/v1/templatesRegister a workflow templaterunflow_template_writeBody: definition + params + optional name. Returns the stored template (201)
GET/api/v1/templatesList your templatesrunflow_template_readQuery: limit, offset
GET/api/v1/templates/{ref}Template + parameter contractrunflow_template_read{ref} = template_id or name. Query: version. Definition is redacted
PATCH/api/v1/templates/{ref}Rename/describe, or publish a new versionrunflow_template_writeA new definition or params publishes a new version. "name": null clears the name
DELETE/api/v1/templates/{ref}Delete a templaterunflow_template_writeFrees the name and the quota slot. Workflows it launched keep running
POST/api/v1/templates/{ref}/runRun a template with parametersrunflow_template_run + runflow_workflow_submitBody: params, version, name, tags, scheduled_start, webhook. Returns {workflow_id, template_id, version} (202)
POST/api/v1/templates/{ref}/triggersAttach a cron to a templaterunflow_template_writeBody: cron + timezone. Fires the template unattended
GET/api/v1/templates/{ref}/triggersList a template's triggersrunflow_template_readIncludes next_fire_at
POST/api/v1/timersSchedule a one-shot wakerunflow_timer_writeBody: fire_at + opaque payload. Delivers timer.fired and starts no container
GET/api/v1/timersList timersrunflow_timer_readstate_filter, label_filter. Cap counts PENDING only
DELETE/api/v1/timers/{timer_id}Cancel a pending timerrunflow_timer_write409 if it already fired
POST/api/v1/schedulesRegister a recurring cronrunflow_timer_writeBody: cron + timezone. Delivers schedule.fired and starts no container
GET/api/v1/schedulesList schedulesrunflow_timer_readIncludes next_fire_at
PATCH/api/v1/schedules/{id}Enable or disable a schedulerunflow_timer_writeDisabling frees the quota slot and keeps the fire ledger
DELETE/api/v1/schedules/{id}Delete a schedulerunflow_timer_writeRemoves it and its fire history
GET/api/v1/schedules/{schedule_id}/firesFire ledger for a schedulerunflow_timer_readPer-occurrence outcome, deliveries_enqueued, fire_delay_seconds
GET/api/v1/triggersList every template triggerrunflow_template_readAcross all your templates
GET/api/v1/triggers/{trigger_id}One triggerrunflow_template_readIncludes next_fire_at and disable reason
GET/api/v1/triggers/{trigger_id}/firesFire ledger for a triggerrunflow_template_readWhich occurrence produced which workflow
POST/api/v1/workflows/{workflow_id}/nodes/{ref}/retryRetry a failed noderunflow_workflow_controlResets the node and its downstream
POST/api/v1/workflows/{workflow_id}/nodes/{ref}/approveApprove a gate noderunflow_workflow_controlLets the workflow continue past the gate
POST/api/v1/workflows/{workflow_id}/nodes/{ref}/rejectReject a gate noderunflow_workflow_controlEnds the gate as failed, and the workflow ends failed
GET/api/v1/auditYour audit logrunflow_run_readOperator actions and refusals recorded against your tenant
GET/api/v1/workflows/{workflow_id}Live graph + per-node staterunflow_workflow_readReturns WorkflowStatus
GET/api/v1/workflows/{workflow_id}/nodes/{ref}One node's detailrunflow_workflow_readReturns WorkflowNodeDetail, incl. every attempt's track_id
GET/api/v1/workflows/{workflow_id}/resultPer-node outcomesrunflow_workflow_readReturns WorkflowResult. 409 not_terminal while active
GET/api/v1/workflows/{workflow_id}/eventsEvent log (replay/subscribe)runflow_workflow_readQuery: since (cursor, default 0), limit (default 200)
POST/api/v1/workflows/{workflow_id}/pausePause the graphrunflow_workflow_controlOnly from pending/running, else 409 not_pausable
POST/api/v1/workflows/{workflow_id}/resumeResume the graphrunflow_workflow_controlOnly from paused, else 409 not_paused
POST/api/v1/workflows/{workflow_id}/cancelCancel the graphrunflow_workflow_controlKills in-flight node runs. 409 already_terminal if finished
POST.../workflows/{workflow_id}/nodes/{ref}/retryRe-run a stage + downstreamrunflow_workflow_controlNode must be terminal, else 409 node_not_terminal. Revives a terminal workflow
POST.../workflows/{workflow_id}/nodes/{ref}/approveApprove a gaterunflow_workflow_controlThe node succeeds and its on_success edges fire
POST.../workflows/{workflow_id}/nodes/{ref}/rejectReject a gaterunflow_workflow_controlThe node fails and its on_failure edges fire
POST/api/v1/webhooksRegister a webhook endpointrunflow_webhook_adminBody: WebhookCreateRequest. Returns WebhookCreateResponse (201), incl. one-time secret
GET/api/v1/webhooksList the tenant's endpointsrunflow_webhook_readNever returns the secret
GET/api/v1/webhooks/{endpoint_id}One endpointrunflow_webhook_read404 for not-found-or-not-yours
PATCH/api/v1/webhooks/{endpoint_id}Partial update (merge)runflow_webhook_adminactive:true resets consecutive_failures
DELETE/api/v1/webhooks/{endpoint_id}Delete + cancel pending deliveriesrunflow_webhook_admin—
POST/api/v1/webhooks/{endpoint_id}/testEnqueue a synthetic webhook.test. An optional body {"event_type":"…"} rehearses a real event through the endpoint's filter. The payload carries "test": true inside the signed body, and a type the endpoint does not subscribe to is refused with 422. Answer a rehearsal with a 2xx. A non-2xx counts towards auto-disable like any delivery, so refusing rehearsals can disable the endpointrunflow_webhook_adminReturns {delivery_id, event_type}
POST/api/v1/webhooks/{endpoint_id}/rotate-secretRotate the signing secretrunflow_webhook_adminReturns the new secret exactly once
GET/api/v1/webhooks/{endpoint_id}/deliveriesEndpoint deliveriesrunflow_webhook_readQuery: state_filter, since, limit
GET/api/v1/webhooks/deliveries/{delivery_id}One deliveryrunflow_webhook_read404 for not-found-or-not-yours
POST/api/v1/webhooks/deliveries/{delivery_id}/redeliverRe-enqueue (reuse event_id)runflow_webhook_adminReturns the new delivery_id
GET/api/v1/runs/{track_id}/deliveriesDeliveries for a runrunflow_webhook_read—
GET/api/v1/workflows/{workflow_id}/deliveriesDeliveries for a workflowrunflow_webhook_read—

Workflow permissions are separate from run permissions. A key holding only runflow_run_* cannot submit or control workflows. Run endpoints still work on individual node runs, so runflow_run_read is enough to fetch a node’s logs.

Request / Response Models #models

RunSubmitRequest — POST /api/v1/runs body

{
  "image": "python:3.12-slim",          // required, Docker image ref (host/path[:tag|@digest])
  "command": ["python", "-c", "..."],   // default [], command args
  "env": {"KEY": "value"},              // default {}, injected as container env vars (string values only)
  "scheduled_start": null,              // ISO-8601 or null (ASAP)
  "timeout_seconds": null,             // null=use default; clamped to quota max_timeout_seconds
  "cpu_limit": null,                     // cores, clamped to quota max_cpu_cores
  "memory_limit_mb": null,               // MB, clamped to quota max_memory_mb
  "name": "optional-label",             // max 128 chars
  "tags": ["tag1", "tag2"]              // default [], free-form labels
}

RunSubmitResponse — 202

{
  "track_id": "01KY0XX71BMX0B88C3A189S2K7",   // ULID
  "status": "scheduled",
  "eligible_start": "2026-07-20T23:31:17Z",
  "clamped": false                       // true if requested limits were reduced to quota
}

RunStatus — GET /api/v1/runs/{track_id}

{
  "track_id": "...",
  "tenant_id": "...",
  "state": "running",                   // scheduled|queued|pulling|running|paused|exited|failed|timeout|killed
  "image": "...",
  "command": [...],
  "env": {...},
  "submitted_at": "...",
  "eligible_start": "...",
  "started_at": "...",                  // null until running
  "finished_at": "...",                 // null until terminal
  "exit_code": 0,                       // null until terminal
  "container_id": "...",
  "worker_id": "...",
  "cpu_limit": 1.0,
  "memory_limit_mb": 512,
  "timeout_seconds": 60,
  "name": "...",
  "tags": [...],
  "stdout_file": "/var/log/runflow/...stdout",
  "stderr_file": "/var/log/runflow/...stderr",
  "events": [{"ts":"...","from_state":"...","to_state":"...","reason":"...","payload":{}}],
  "scheduling_info": {                        // see Scheduling section
    "eligible_start": "2026-07-21T10:00:00Z",
    "working_hours_applied": false,
    "queue_position": 3,                   // null if not scheduled
    "estimated_start": "2026-07-21T10:00:30Z"  // soft estimate, null if no history
  }
}

RunResult — GET /api/v1/runs/{track_id}/result (terminal only)

{
  "track_id": "...",
  "exit_code": 0,
  "status": "exited",                   // exited|failed|timeout|killed
  "started_at": "...",
  "finished_at": "...",
  "duration_seconds": 12.34,
  "stdout_bytes": 1024,
  "stderr_bytes": 0,
  "stdout_file": "...",
  "stderr_file": "...",
  "result_summary": "..."
}

LogResponse — GET /api/v1/runs/{track_id}/logs

{
  "lines": ["line1", "line2"],
  "next_since": 2,                       // pass as ?since=2 for the next page
  "eof": true                            // false = more lines may arrive (run still active)
}

UtilizationResponse — GET /api/v1/runs/{track_id}/utilization

{
  "samples": [
    {
      "timestamp": "2026-07-20T23:31:18Z",
      "cpu_percent": 12.5,
      "memory_mb": 128.4,
      "memory_limit_mb": 512,
      "net_rx_bytes": 1024,
      "net_tx_bytes": 2048
    }
  ]
}

TenantQuotas — GET /api/v1/tenant/quotas, PUT /api/v1/tenant/quotas

{
  "max_concurrent_runs": 10,          // max runs in {pulling,running,paused} simultaneously
  "max_daily_runs": 100,            // max submissions per UTC day (still rejected at submit)
  "max_timeout_seconds": 86400,
  "max_cpu_cores": 4.0,
  "max_memory_mb": 4096,
  "max_queue_seconds": 3600,        // max wait after eligible_start before queue_timeout
  "working_hours_tjp": null,         // TJP shift definition, see Scheduling section
  "retention_days": 30,
  "max_nodes_per_workflow": 50,     // exceeded -> 400 too_many_nodes
  "max_concurrent_workflows": 10,    // exceeded -> 429 workflow_quota_exceeded
  "max_webhook_endpoints": 10,       // exceeded -> 429 webhook_quota_exceeded
  "max_webhook_payload_bytes": 262144 // 256 KiB; result_summary then data.nodes truncated to fit
}

PUT requires runflow_tenant_admin permission. Only the quotas fields you include are updated.

curl -X PUT https://runflow.rodmena.co.uk/api/v1/tenant/quotas \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "max_concurrent_runs": 5,
    "max_queue_seconds": 1800,
    "working_hours_tjp": "shift shift_def \"Office\" { workinghours mon - fri 09:00 - 18:00 }"
  }'

Errors #errors

Standard error envelope (FastAPI default):

{
  "detail": "human-readable message"
}
StatusMeaning
400Bad request, such as an invalid image reference, malformed JSON or an expires_at in the past (expires_at_in_past)
401No/invalid bearer token
403Permission denied (missing RBAC permission)
404Run not found (wrong track_id or not owned by tenant)
409Conflict, such as a result requested before the run has finished, or pause or resume in the wrong state
422Validation error (Pydantic schema mismatch, invalid TJP shift)
429Daily quota exceeded (daily_quota_exceeded) or rate limited (per-tenant sliding window). Reaching the concurrency quota no longer returns 429 (see Scheduling).
500Internal server error

Workflow-specific detail codes

StatusdetailCause
400invalid_image:<ref>That node's image isn't a valid Docker reference.
400invalid_graphA cycle, a duplicate ref, an edge pointing at a missing ref, or an inputs_from naming a node that doesn't exist.
400too_many_nodesMore nodes than max_nodes_per_workflow.
409not_terminal/result requested while the workflow is still active.
409already_terminal/cancel on a finished workflow.
409not_pausable/pause when the workflow isn't pending or running.
409not_paused/resume on a workflow that isn't paused.
409node_not_terminal/retry on a node that is still active.
409not_an_approval_node/approve or /reject on a container node.
409not_awaiting_approvalThe gate isn't in waiting_approval (already decided, or not reached yet).
429workflow_quota_exceededAlready at max_concurrent_workflows.
400invalid_webhook_urlWebhook URL is not absolute, not https, or contains userinfo.
400unknown_event_typeWebhook events entry is not a catalog member, alias, or wildcard.
422(pydantic)Inline webhook object contained an unknown key (FR-WH-22).
429webhook_quota_exceededAlready at max_webhook_endpoints.

Node-level failures are not HTTP errors. A node whose injected inputs exceed 64 KB fails with output {"error":"inputs_too_large"}. Read it from the node detail or result endpoint.