Skip to main content
Version: 2.0

Workflows

Workflows let you chain jobs into a directed acyclic graph (DAG). Steps run scheduled jobs, route by expressions, wait for events, people or time, run other workflows (once or for every item of a list) and let an AI agent work; the engine coordinates execution order, data passing, branching and failure handling.

What Is a Workflow?​

A workflow is a named, versionable pipeline made up of:

ConceptDescription
StepA node in the DAG: a Task that runs a job, or one of the other node types
EdgeA directed connection from one step to another
RunA single execution instance of the workflow
InputThe job data of a step, with expressions that read the results of earlier steps

Core Concepts​

Node Types​

Every step in a workflow is one of these node types:

TypeDescription
TaskDispatches a scheduled job. This is the primary building block.
ConditionEvaluates an expression and routes execution through a true or false port. Does not run a job.
SwitchRoutes execution through the port of the first case whose expression is true, or default. Does not run a job.
MergeJoins branches: waits for all of them, for any of them, or for a number of them. Does not run a job.
DelayWaits for a number of seconds or until a date. Does not run a job.
WaitForEventWaits for an event sent to the API, or until its timeout. Does not run a job.
ApprovalWaits for people to approve or reject, or until its timeout. Does not run a job.
SubWorkflowRuns another workflow of the project and waits for that run. Does not run a job itself.
ForEachRuns another workflow of the project once for every item of a list, some at a time, and waits for all of them.
AgentAn AI agent: a model that uses jobs, workflows and tools of MCP servers until it answers.

Condition, Switch, Merge and Delay are virtual nodes: they control flow without dispatching any job. WaitForEvent, Approval, SubWorkflow, ForEach and Agent wait: they stay Running until what they wait for happens, without holding a worker.

Edges and Ports​

Edges connect nodes and define execution order. They can carry optional source ports for conditional routing:

Step A ──────────────────► Step B         (unconditional)

Condition ──── true ────► Step B
└── false ────► Step C (conditional)
NodePorts
Tasksuccess, error
Conditiontrue, false
Switchone per case, default
Merge, Delayout
WaitForEventreceived, timeout
Approvalapproved, rejected, timeout
SubWorkflowsuccess, error
ForEachdone, error
Agentsuccess, error

An edge without a port follows every outcome except a failure: on a Task, SubWorkflow and Agent that is success, on a ForEach done. A port that does not exist is rejected on save.

A step whose incoming edges all come from branches that were not taken is skipped, and so is everything after it, up to a step that another branch also leads to.

Runs​

Each time a workflow is triggered (manually or by cron), a WorkflowRun is created. It tracks:

  • Overall status (Pending → Running → Completed / Failed / PartiallyCompleted / Cancelled)
  • Start/end time, total duration
  • Individual step statuses: one JobOccurrence per Task step, and a step run for every step and node
  • Trigger reason
  • For a run that a SubWorkflow, ForEach or Agent step started: parentRunId, parentStepId and depth (the list has parentRunId). Such runs are in the run lists too.

The run page follows a running workflow live. The panel under the graph has a Timeline of when each step ran and the Logs and output of the step selected in the graph or the timeline; large outputs open in chunks. A connection shows how many items its source step returned: the length of a JSON array, or 1 for any other result.


Workflow Settings​

When creating or editing a workflow, the following settings are available:

SettingDescription
NameDisplay name (required)
DescriptionOptional human-readable description
TagsComma-separated labels for filtering
ActiveWhether the workflow can be triggered
Cron Expression6-field cron for automatic scheduling (e.g. 0 0 9 * * * = daily at 9:00 AM). Leave empty for manual-only.
Failure StrategyHow the engine handles step failures (see below)
Max Step RetriesNumber of times the engine runs a failed step again before its failure counts, with either failure strategy
Max Retry-AfterNumber of times a step may be rerun at the time its job asked for (see Retry at a Specific Time). Default 10. Not counted against Max Step Retries.
Time ZoneIANA time zone of the cron expression, for example Europe/Istanbul. Default UTC.
Schedule InputThe input of scheduled runs
Overlap PolicyWhat happens to a run that is due while as many runs as allowed are active (see Overlapping Runs). Default Allow.
Max Concurrent RunsHow many runs may be active at once, with Skip and Queue. Empty = 1
Deadline (seconds)A run that has not finished this long after it was due raises the alert WorkflowDeadlineMissed, once. The run goes on.
Timeout (seconds)Maximum total duration. The run is cancelled if exceeded. null = no timeout.
Expose as Tool (exposeAsTool)Whether AI clients (the MCP server, agents) may start the workflow as a tool, with its description and input schema. Off by default. Not versioned.

Overlapping Runs​

PolicyBehavior when the limit is reached
AllowRuns overlap freely. There is no limit.
SkipThe run does not start. A manual, MCP or webhook trigger is rejected; a scheduled run appears in the history as Cancelled with the reason.
QueueThe run stays Pending and starts when another one has finished, in the order the runs were due.

Failure Strategies​

StrategyBehavior
Stop on First FailureThe entire workflow stops when any step fails. Running steps are cancelled, pending steps are skipped and the run is Failed.
Continue on FailureIndependent parallel branches keep running. Only steps that depend on the failed step, directly or through other steps, are skipped. That includes a Merge node with a failed branch, unless it waits for any or a number of branches and has enough without it.

With both strategies a step has failed once its retries are used up: those of its policy, or the workflow's Max Step Retries.

An edge from the error port of a Task, SubWorkflow, ForEach or Agent handles its failure, with either strategy: the run goes on along that edge, the steps after success are skipped, and the run does not fail because of this step.

With Continue on Failure, a Condition node right after a step can handle its failure: if the expression reads that step's status or error (for example {{ steps.load.status == 'Failed' }}), the condition is evaluated and routes to its true or false port instead of being skipped.


Step Settings​

Each Task step has the following configuration:

SettingDescription
Step NameLabel shown in the DAG builder and run history
JobWhich scheduled job this step executes
Delay (seconds)Wait this many seconds after dependencies complete before dispatching
KeyThe name expressions use for this step
InputJob data of this step, merged over the job's own data (see Step Keys and Input)

Condition steps additionally have a Condition Expression field (see Condition Nodes).


Run Input​

The Run Workflow dialog has a form for the input, made from the input schema (required fields first), or a JSON editor.

A run can have an input: JSON that is passed when it is triggered and that expressions read as input. It is stored with the run.

The workflow's inputSchema is a JSON Schema the input must match. Supported keywords: type, properties, required, additionalProperties, items, enum, const, pattern, minLength, maxLength, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minItems, maxItems, uniqueItems, minProperties, maxProperties, and annotations such as title and default (which is not applied). Any other keyword is rejected on save. Without a schema every JSON value is accepted.

  • Manual trigger and MCP: input of the trigger request, also with executeAt.
  • Cron schedule: the workflow's scheduleInput. It is checked when the schedule, its input or the schema is saved.
  • An input that does not match is rejected; the message names the fields, never the values. The largest input is 256 KB. A missing input counts as {} for the check.

Step Keys and Input​

Every step has a key: 1 to 50 lowercase letters, digits and underscores, starting with a letter, unique in the workflow. Expressions name steps by it. A new step sent without a key gets one made from its name; an existing step must be sent with its key.

A Task step's input is a JSON object merged over the job's own data. Texts in it may hold expressions:

{
"amount": "{{ steps.extract_prices.result.price }}",
"title": "Invoice for {{ steps.extract_prices.result.item.name }}",
"smtpPassword": "{{secret:smtp-password}}"
}

A step's job data is built in this order; later entries overwrite earlier ones:

  1. The job's own data
  2. The step's input. Objects are merged, everything else (lists included) is replaced
  3. stepJobData sent when the run was triggered (top-level keys)

{{secret:name}} stays in the job data and is resolved at dispatch. Data of other steps cannot bring in a secret reference: that fails the step.

Input is checked when the workflow is saved: it must be an object, every expression must parse, and it may only name steps that come before this one. At run time an input that cannot be evaluated fails the step.


Step Policy​

A Task step may have a policy:

{ "maxAttempts": 5, "backoff": "exponential", "backoffSeconds": 10, "maxBackoffSeconds": 300, "timeoutSeconds": 60, "retryOn": "any" }
FieldDescription
maxAttemptsAttempts, the first one included (1 to 100)
backofffixed, or exponential: doubles every time
backoffSecondsWait before the second attempt. 0 = none
maxBackoffSecondsLongest wait of an exponential backoff (at most 7 days)
timeoutSecondsTime limit of one attempt. Empty uses the job's
retryOnany, or transient: timeouts, lost workers and failed dispatches only
  • With a policy the engine owns the retries and the workflow's Max Step Retries does not apply. The worker makes no retries of its own for the step (worker SDK versions released with Milvaion 2.0; an older worker still makes its own).
  • A permanent job error (PermanentJobException and its equivalents) is never retried, with or without a policy.

Condition Nodes​

A Condition node has one expression in its configuration and routes execution through its true or false port:

{ "expression": "{{ steps.check_stock.result.count > 0 && steps.check_stock.status == 'Completed' }}" }
  • The text must be exactly one {{ … }}.
  • The expression must give true, false or null (which counts as false). Anything else, or an expression that cannot be evaluated, fails the condition step, and the failure strategy applies. It never defaults to true. A failed condition is not retried.

Switch, Merge and Delay Nodes​

{ "cases": [ { "port": "small", "expression": "{{ steps.load.result.count < 10 }}" }, { "port": "large", "expression": "{{ steps.load.result.count >= 1000 }}" } ] }
{ "mode": "any" }
{ "mode": "count", "count": 2 }
{ "seconds": 60 }
{ "until": "{{ steps.load.result.publishAt }}" }
  • Switch: the cases are tried in order; expressions follow the rules of conditions. Port names have the form of step keys.
  • Merge: all (the default) waits until every branch has ended and goes on if at least one was taken. any and count go on as soon as enough branches have arrived; the others keep running.
  • Delay: seconds is a number or an expression, until an ISO 8601 date or an expression. The wait counts from the end of the step before. A date that has passed does not wait.
  • In the expressions of these nodes and of conditions, now() is the time the node became ready.

WaitForEvent Nodes​

{ "eventName": "order.paid", "correlation": "{{ input.orderId }}", "timeoutSeconds": 86400 }
  • eventName is required: 1 to 100 characters, no expressions. correlation is optional: a text or an expression, evaluated once when the node starts to wait (at most 200 characters). timeoutSeconds is optional, 1 to a year; without it the node waits until the run ends.

  • An event is sent with POST /api/v1/workflows/events (Trigger permission; MCP tool send_workflow_event):

    { "eventName": "order.paid", "correlation": "o-1", "payload": { "amount": 50 } }

    It reaches the waiting nodes of the caller's project with that name, and with that correlation; a node without a correlation takes any event of the name. The answer is how many nodes took it. An event is taken once; an event for which nobody waits is dropped. The payload is at most 256 KB.

  • The node then takes received, and steps.<key>.result is the payload. Without an event it takes timeout when the time is up, with no result.

  • A correlation that cannot be evaluated fails the node. The run detail shows a waiting node as Running with eventName, correlation and wakeAt.

In the builder, Wait for event is under Flow control. Its panel has the event name, the correlation (with the field picker) and an optional timeout; its card shows the event and correlation and has the ports received and timeout. An edge without a port follows both.

On the run page a waiting node is shown as Waiting, with when its timeout ends. Selecting it shows the event, the correlation, since when it waits and when it times out; a finished one shows whether it received the event or timed out, and the payload as its output. Users with the Trigger permission get Send event there: the name and correlation are filled in from the node, and the payload is optional JSON. Like the API call, the event reaches every waiting node of the project with that name and correlation, not only the selected one. The page checks a waiting run every few seconds, so an event sent from elsewhere shows up without a reload.

Approval Nodes​

{
"title": "Pay {{ steps.invoice.result.total }}",
"message": "Invoice {{ steps.invoice.result.number }}",
"form": { "type": "object", "required": ["reference"], "properties": { "reference": { "type": "string" } } },
"approverRoles": ["finance"],
"allowLinkDecision": false,
"channels": ["Finance mail"],
"timeoutSeconds": 172800
}
  • title is required; title and message may hold expressions, evaluated when the node starts to wait. form is an optional JSON Schema (the keywords of the run input) the approver fills in to approve. approverRoles names the roles that may answer, for the installation or in the project of the run; super admins are no exception. allowLinkDecision (default false) lets whoever holds a link answer without signing in; an approval needs roles or this. channels names notification channels of the project, or global ones. timeoutSeconds: 1 to a year.
  • When the node starts to wait, every channel gets the title, the message and a link (see Approval Links). A link without a timeout works 30 days. A channel that fails is logged; the approval can still be answered in Milvaion. The link of an e-mail channel names its addresses; a channel whose address is a secret (a webhook URL, a bot token) is named by the channel name.
  • The run detail shows, on the step run of an Approval, approval: { title, message, channels, sentTo: [{ channel, address, sentAt }] } to anybody who may read the run: the evaluated text and the channels that took the message (address only for e-mail channels). Who may answer and the form are only in the approvals list.
  • In Milvaion: PATCH /api/v1/workflows/approvals { workflowId?, runId? } lists the approvals of the project that the signed-in user holds an approver role of: { approvalId, runId, workflowId, workflowName, stepKey, title, message, form, approverRoles, startedAt, expiresAt }. POST /api/v1/workflows/approvals/respond { approvalId, approved, comment, form } answers; the form is checked against the schema when it approves.
  • An approval is answered once. The node then takes approved or rejected, and steps.<key>.result is { approved, comment, form, respondedBy (user or link), userName, channel, address, respondedAt }; for a link, channel and address are those the link was sent to. Without an answer it takes timeout; an answer after that is refused.

In the builder, Approval is under Flow control. Its panel has the title and message (with the field picker), the approver roles and the notification channels (picked from the lists, or typed), Allow answers through links without signing in with a warning of what that allows, the approval form (edited like the input schema, by field or as JSON) and an optional timeout. The panel says so when nobody could answer. The card shows the title and who answers, and has the ports approved, rejected and timeout; an edge without a port follows all three.

Approvals in the menu lists the approvals that wait for the signed-in user, with their number beside it. Each shows the title and message as asked, the workflow and step, since when it waits and the time left, and the form to approve. Approve stays disabled until the required fields of the form are filled; rejecting needs no form. A comment is optional.

On the run page a waiting approval is shown as Awaiting approval. Selecting it shows what it asks, the approver roles, the channels and when it times out; an approver answers it there with the same form as in the inbox. Others see why they cannot. Everyone who can read the run sees the title and message as they were asked, the channels and where the message was sent (approval of the step run). An answered approval shows who answered (the user, or the link with its channel), when, the comment and the form.


SubWorkflow Nodes​

{ "workflowId": "0193a0b0-0000-7000-8000-000000000001", "version": 3 }

The step's Input (with expressions, like a Task's) is the input of the run it starts.

  • workflowId names a workflow of the same project; version is optional and defaults to the published version when the step starts. The node has no timeoutSeconds: the run it starts has the timeout of its own workflow.
  • When the node starts, the engine starts a run of that workflow with the input; the run follows the overlap policy of its workflow. The run records parentRunId, parentStepId and depth; the step run records childRunId. Runs can be nested 5 deep.
  • When that run completes (or partially completes), the node takes success and steps.<key>.result holds the results of its last steps (the steps no edge leaves), by key: { "<key>": <result>, … }. When it fails, is cancelled or times out, the node fails with its error and takes error.
  • A run that cannot start fails the node at once: the workflow does not exist in this project, is not active, has no such version or no steps, a Task has no job, the input does not fit its schema, or the nesting is too deep.
  • When the run that started it ends (it is cancelled, fails or times out), the run started by the step is cancelled too.
  • An error edge handles the failure, as on a Task: the run does not fail because of it.

In the builder, Sub-workflow is under Actions. Its panel picks the workflow (from the workflows of the project, without the one being edited) and the version: the one published when the step starts, or a fixed one. The input is edited like a Task's, and offers the fields of that version's input schema; the panel names its required fields. The card shows the workflow and the version.

On the run page, a Sub-workflow step links to the run it started (Open its run, and in the step list). A run started by one says so above its details, with a link to the step and the run that started it. In the runs of a workflow, such a run is marked Sub-run of with a link to that run. /workflow-runs/<runId> opens any run by its id.


ForEach Nodes​

{ "workflowId": "0193a0b0-0000-7000-8000-000000000001", "items": "{{ steps.load.result.orders }}", "concurrency": 5 }

The step's Input is the input of the run of each item, and reads the item as item and its position (from 0) as index: { "orderId": "{{ item.id }}" }. Without an Input, an item that is an object is the input itself, and any other item is given as { "item": … }.

  • items is one expression that gives a list, evaluated when the node starts; at most 1000 items. concurrency (1–50, default 5) is how many runs of items may be active at once; the next item starts when one ends. workflowId and version are as on a SubWorkflow, and there is no timeoutSeconds.
  • Every item is a step run of the node with its number (from 1) as its iteration, and the run detail lists them under the step: iterations: [{ iteration, status, childRunId, error, startedAt, endedAt }]. The run of an item has parentRunId and parentStepId, and the item's number is stored with it; the item lists its childRunId.
  • When every item has ended, steps.<key>.result is the list of the results of their runs (as on a SubWorkflow: the results of their last steps, by key), in the order of the items, with null for an item whose run failed. All succeeded: the node takes done. One failed: the node fails with n of m items failed. Item k: <error>, takes error, and has the same result.
  • An item whose run cannot start (its input does not fit the workflow's schema, the workflow is not active, …) fails alone; the other items still run. A list without items gives done at once with [].
  • When the run of the node ends, the runs of its items that are still active are cancelled.

In the builder, For each is under Actions. Its panel picks the workflow and version like a Sub-workflow, and has Items (one expression; against the last run it says how many items it gives and shows the first), At a time (the concurrency) and the input of each run. In that input the field picker offers item (with the fields of the first item of the last run), index, the run input and the steps before; the previews read the first item as item and 0 as index. The card shows the workflow, the version and how many at a time.

On the run page the card shows how many items ended and failed (4/10 · 1 failed). Selecting the step shows a progress bar and every item with its status, a link to its run, how long it took and its error; the page checks the run every few seconds while items run. In the step list the row says how many items ended.


Agent Nodes​

{
"connection": "main",
"model": "",
"instructions": "Check the orders in the input and refund the duplicates.",
"tools": [
{ "kind": "Job", "name": "refund", "id": "0193a0b0-0000-7000-8000-000000000002" },
{ "kind": "Workflow", "name": "lookup", "id": "0193a0b0-0000-7000-8000-000000000003" },
{ "kind": "Mcp", "name": "crm", "url": "https://mcp.example.com", "mcpTools": ["find_customer"], "headers": { "Authorization": "{{secret:crm}}" } }
],
"maxTurns": 10,
"maxTokens": 100000,
"approveTools": ["refund"]
}

The configuration is checked when the workflow is saved. The instructions take no expressions: what earlier steps produced goes into the step's Input, which is evaluated once, when the node starts, and given to the model as data. approveTools names the tools whose calls wait for a decision; without it every call waits, [] lets every call run.

  • The engine starts the node; the agent service (one instance at a time per node) runs it. Every model call and every tool call is stored as a step run of the node, with its index + 1 as its iteration, before the next one is made, so a restart goes on from the last one.
  • A job tool starts an occurrence of the job. The model's arguments (a JSON object, never evaluated) are merged into the job's data like a step's input: objects are merged, everything else is replaced. They may add fields, but may change a field the job's data has only when the tool's inputSchema names it under properties; a call that would change another one is not run, so the model cannot, for example, send an HTTP job to another address. The occurrence is not a step of the run; when it ends the agent goes on. A workflow tool starts a run of the workflow (a child run, ended with the node's run) with the arguments as its input. A call started again finds what it started.
  • A call that waits for a decision stays until someone with the permission to trigger workflows decides: POST /api/v1/workflows/agents/decisions { stepRunId, index, approve }. A call is decided once.
  • When the agent answers, the node takes success and steps.<key>.result is { text } (with json when the answer is JSON). When it fails, it takes error. A failure that may pass (the provider is down) is tried again later, up to 5 times.
  • The run detail shows, on the step run of the node, agent: { stepRunId, iterations: [{ index, kind, status, model, text, toolCalls, toolName, arguments, result, decidedBy, inputTokens, outputTokens }], awaitingApproval: [index], tokens }.

In the builder, Agent is under Actions. Its panel picks the AI connection (from AI Connections) and the model (the connection's default, or one of its models), takes the instructions as fixed text and the input like a Task's, and lists the tools: a job (picked from the jobs), a workflow (picked from the workflows) or an MCP server (its address, the tools the agent may use and headers, where a value may be a secret reference). Each tool has a name and Ask before a call. Decisions chooses between every call waiting for a decision (no approveTools, the default) and only the marked tools; the panel says so when no call would wait. Limits sets the turns, the tokens in all and per answer. MCP servers are called only when the API allows them (MilvaionConfig:Agents:AllowedMcpServers). The panel offers those addresses to pick from (GET /api/v1/workflows/agents/mcp-servers, Update permission; an entry with a user name, a query or a fragment is left out, since those may carry a key), and Another address… for one that is typed, with a note that it is not allowed yet. Without any allowed server the address is typed.

On the run page the card shows the tokens used and Awaiting decision while a call waits. Selecting the step shows the agent as a conversation: the tools it started with, every model turn with its text, the calls it asked for and its tokens, and every tool call with its arguments, result, status and who decided it. Users with the Trigger permission approve or refuse a waiting call there; a refused call is not run and the model is told so.

Expose as Tool is in the builder's settings, with a note on what it allows.


Expressions​

Expressions read the results of earlier steps in a step's input and configuration. The API evaluates one against sample data:

POST /api/v1/workflows/expressions/preview
Content-Type: application/json

{
"template": "Order {{ input.id }}: {{ sum(steps.fetch.result.items[*].price) }}",
"context": {
"input": { "id": 7 },
"steps": { "fetch": { "result": { "items": [ { "price": 10 }, { "price": 5 } ] }, "status": "Completed" } }
}
}

The answer has value, type (string, number, boolean, object, array, null) and error. A template that is exactly one {{ … }} keeps the value's JSON type; otherwise the results are put into the text.

PartAvailable
Rootsinput, steps.<key>.result, steps.<key>.status, steps.<key>.error, run.id, run.startedAt, item, index
Paths.name, ["name"], [0], [-1], [*], [?(expression)]
Operators== != > >= < <=, &&, ||, !, + - * / %, ??, condition ? a : b
Textlength, lower, upper, trim, replace, split, join, contains, startsWith, endsWith, substring
Lists and objectslength, first, last, contains, map, filter, sum, min, max, avg, sort, unique, keys, values
ConversiontoJson, fromJson, toNumber, toString, default, base64, sha256
Time and idsnow, formatDate, addSeconds, uuid
  • Inside map(list, …), filter(list, …) and [?(…)], item and index are the current element and its position.
  • After [*] and [?(…)], the rest of the path applies to each element, and elements without it are left out. Use first(…) or parentheses to work with the list itself.
  • A missing property or list element is null. Property names match exactly first, then ignoring case.
  • Conditions need true, false or null (which counts as false). == is case-sensitive and does not convert types.
  • default(a, b) replaces null and empty text; a ?? b replaces only null.
  • Dates are ISO 8601 and are handled in UTC; formatDate takes a .NET format.
  • {{secret:name}} is not an expression and stays as it is. A result that contains a secret reference the template does not have is an error.
  • Limits: 10 000 evaluation steps, a result of 1 MB, a template of 64 KB, 100 levels of nesting.

Execution Engine​

The Workflow Engine runs as a background service inside the Milvaion API. It is woken when something happens to a run and also polls at MilvaionConfig:WorkflowEngine:PollingIntervalSeconds. A second service, the agent service, runs the Agent nodes (see Agent Nodes); both follow MilvaionConfig:WorkflowEngine:Enabled.

Execution Loop​

Every API instance runs the engine, and they share the work. A run is looked at when something happens to it: a step finished, the run was triggered, a timer of the run is due (a Delay node, a retry, a timeout, a deadline). The run is then marked with nextEvaluationAt, and an instance claims it.

On a signal, or every PollingIntervalSeconds (5):
1. Check cron-scheduled workflows → trigger due ones (a slot is claimed in the database, so it fires once)
2. Claim up to BatchSize (100) marked runs with FOR UPDATE SKIP LOCKED, for ClaimSeconds (60)
3. For each run:
a. Apply the overlap policy, the timeout, retry-after reruns, step retries and the failure strategy
b. Evaluate virtual nodes (Condition, Switch, Merge, Delay) in dependency order; their outcomes are recorded and not evaluated again.
Waiting nodes start to wait (their correlation, approval text, input or items are evaluated once), and SubWorkflow and ForEach start their runs
c. Skip steps that can no longer run; find Task steps whose dependencies are all satisfied
4. Evaluate the input of the ready steps and build their job data
5. In one transaction, only for the runs this instance still holds: save runs, steps, step runs and logs
6. Publish the ready steps, then give the runs back with the time they are due again
Every SweepIntervalSeconds (30):
Mark runs nobody looked at for that long, and runs whose claim expired

A run is never worked on by two instances at once. An instance that stops gives its runs back, or they come back when its claim expires. A step that was saved as dispatched but not published, because the instance stopped in between, is published by the next instance that takes the run. Only when an instance dies after publishing a step and before recording it can a step be published twice; the worker skips an attempt it already finished.

Each step and node of a run has a step run (WorkflowStepRuns): status, port, attempt, times, error and the occurrence of a Task step. Clients get WorkflowRunUpdated over SignalR (/hubs/jobs) for every change: { runId, workflowId, status, stepKey, stepStatus }, where stepKey is null for a change of the run itself. A connection gets the runs of its project; SubscribeToWorkflowRun(runId) and UnsubscribeFromWorkflowRun(runId) follow one run.

Large Outputs​

A node's output (an event payload, an answer, the results of a Sub-workflow or ForEach) larger than 256 KB is kept in the payload store instead of its step run, which then holds a reference (db:<id>). So is a node's stored input over 256 KB, such as the inputs of the items of a ForEach. Expressions, the run page and the API read it as if it were in the step run. The store is a table in the database, and its rows are deleted with their run.

Step Lifecycle​

Pending → (dependencies satisfied) → Delayed (if delay > 0)
→ Running (dispatched to worker)
→ Completed | Failed | Skipped | Cancelled
Failed with retries left → Pending, or Delayed (backoff) → Running
Failed with retry-after → Delayed (until the requested time) → Running

Run Status Transitions​

StatusMeaning
PendingRun created, engine has not processed it yet. A run triggered for later stays here until its scheduled time.
RunningAt least one step is active
CompletedEvery step that ran completed. Steps on branches that were not taken are skipped and do not change this.
PartiallyCompletedA step failed while at least one succeeded (Continue on Failure), a failure was handled by an error edge, or steps were skipped because a step they depend on failed
FailedA step failed with Stop on First Failure; or, with Continue on Failure, steps failed and none succeeded; or the remaining steps can never run
CancelledRun was cancelled manually or due to a timeout, or the run whose step started it ended

Zombie Detection​

Task steps that are Running and have not received a heartbeat within their ZombieTimeoutMinutes threshold are detected and marked as zombie/failed, preventing runs from getting stuck indefinitely. A dispatched step that no worker has picked up is measured from its dispatch time, not from when the run was created, so long waits before dispatch (a scheduled run, slow upstream steps, a retry-after) don't count against it. Pending and Delayed steps are never treated as zombies.

Retry at a Specific Time​

Sometimes a step can't run now but you know when it can: an API quota resets at 11:00 UTC, a rate limit window ends, a partner system is down for planned maintenance. Retrying with backoff would just burn attempts. Instead the job throws a retry-after error carrying the time:

// .NET
throw new RetryAfterException(DateTime.UtcNow.Date.AddHours(11), "YouTube upload quota used up");
// Node.js
import { RetryAfterError } from '@milvasoft/milvaion-worker';

throw new RetryAfterError(new Date('2026-11-15T11:00:00Z'), 'YouTube upload quota used up');

Every SDK has it (Python RetryAfterError, Go milvaion.RetryAfter(...), Java and PHP RetryAfterException, Rust JobError::retry_after(...), Ruby Milvaion::RetryAfterError); see Workers in Other Languages.

What happens:

  1. The worker doesn't retry the job itself and doesn't send it to the dead letter queue. It reports the occurrence as Failed with the requested time.
  2. The engine puts the step in Delayed until that time, then dispatches it again. A time that has already passed dispatches it right away. Other steps and the run carry on as usual; the run stays Running.
  3. These reruns are counted apart from Max Step Retries, and they don't count towards the job's auto-disable threshold or raise a failure alert. Max Retry-After (default 10) caps them per step and run; once it is used up, the step's failure is handled like any other failure.

The workflow's Timeout still applies while a step waits, so leave room for the longest wait you expect.

In a standalone job (not a workflow step) a retry-after error ends the occurrence as Failed with no retry.


Triggering Workflows​

Manual Trigger​

Workflows can be triggered from the Milvaion Portal (the Trigger button on the Workflows list or detail page) or via the API:

POST /api/v1/workflows/workflow/trigger
Content-Type: application/json

{
"workflowId": "0195f0c2-...",
"reason": "Publish post 42",
"input": { "postId": 42 },
"stepJobData": { "<stepId>": "{\"postId\": 42}" }
}

input is the run input. stepJobData is optional: per-step job data for this run, merged on top of the job's and the step's own data. It is applied after the step's input. Each value must be a JSON object; anything else is rejected, and fails the step if an older run still holds it.

Scheduled Run (Once, at a Given Time)​

Add executeAt (UTC) to start the run once at that time instead of right away. This is what you want for "publish this post at 18:00", with no extra one-time job in between. In the portal, pick a time under Run At in the Run Workflow dialog; it is in your local time. Over the API:

POST /api/v1/workflows/workflow/trigger

{
"workflowId": "0195f0c2-...",
"reason": "Publish post 42",
"executeAt": "2026-11-15T18:00:00Z",
"stepJobData": { "<stepId>": "{\"postId\": 42}" }
}

The response carries the run id and scheduledAt. Until its time the run stays Pending; the run list and run page show when it will start. Before it starts you can:

  • Move it: Reschedule on the run page or in the workflow's run list, or over the API:

    PUT /api/v1/workflows/workflow/run/schedule

    { "workflowRunId": "0195f0c3-...", "executeAt": "2026-11-15T20:00:00Z" }

    A run that has already started (or was never scheduled) can't be moved. A time in the past starts it right away.

  • Cancel it: POST /api/v1/workflows/workflow/cancel with { "workflowRunId": "..." }, the same as cancelling a running run. Its steps are marked Skipped.

executeAt more than 5 minutes in the past is rejected. Over MCP, trigger_workflow takes executeAt and stepJobData, and reschedule_workflow_run moves a scheduled run.

Webhook​

The workflow page manages its webhook triggers under Webhook Triggers: add, edit, disable, renew the address and delete. The address is shown once, with a curl example, when a trigger is added or renewed.

A webhook trigger starts a workflow with POST /hooks/{token}; the JSON body is the run's input. The token is the credential and decides the project. It is shown once, when the trigger is created or rotated; only its SHA-256 is stored.

Request under /api/v1/workflows/workflowPermission
GET triggers?workflowId=Detail
POST triggers { workflowId, name, secretName, responseTimeoutSeconds, rateLimitPerMinute }, returns { id, token, path }Update and Trigger
PUT triggers { triggerId, name, isEnabled, secretName, responseTimeoutSeconds, rateLimitPerMinute }, each as { value, isUpdated }Update and Trigger
POST triggers/rotate { triggerId }, returns { id, token, path }. The old token stops working right awayUpdate and Trigger
DELETE triggers?triggerId=Update

Signature. With secretName (a database secret of the project) every request must be signed. Choosing, changing or removing the secret of a trigger also needs SecretManagement.Update, as for AI and connector connections:

  • X-Milvaion-Timestamp: Unix time in seconds, at most 5 minutes from now.
  • X-Milvaion-Signature: sha256= and the hex HMAC-SHA256 of {timestamp}.{body}.

A signed request is accepted once. One that started no run may be sent again.

Answer. 202 with { runId, status }. With responseTimeoutSeconds (1 to 60) the request waits for the run: if it finishes in time the answer is 200 with { runId, status, results }, where results has the results of the completed Task steps that no other step follows, by step key. status may be Failed.

StatusMeaning
400The body is not valid JSON.
401The signature is missing or wrong, or the timestamp is too old.
404Unknown or disabled token, or the project is archived.
409The signed request was already accepted.
413The body is larger than MilvaionConfig:Webhooks:MaxBodyBytes (256 KB).
415The body is not application/json.
422The run was not created: the input does not match the schema, the workflow is not active, or its overlap policy is Skip.
429More than rateLimitPerMinute (60) requests of the trigger, or MilvaionConfig:RateLimiting:WebhookPermitPerMinute (600) of the client address, in a minute. Each API instance counts on its own.
503The secret cannot be read.

An empty body counts as {}. At most MilvaionConfig:Webhooks:MaxWaitingRequests (50) requests wait at a time; above it the answer is 202. The API writes no tokens, bodies or signatures to its logs and traces. A reverse proxy writes the path, and so the token, to its access log: turn that off for /hooks/.

Rerun​

On the run page, Run Again reruns a finished run, and Run again from here in the panel of a selected step reruns it from that step. Both ask which version to use. A kept step links to the execution whose result it keeps.

POST /api/v1/workflows/runs/rerun (Trigger permission; MCP tool rerun_workflow_run) runs a finished run again as a new run with the same input and stepJobData.

FieldMeaning
runIdThe finished run.
fromStepIdStep to start again from. Completed and skipped steps keep their result unless they depend on this step or on one that did not complete. Without it every step runs.
useOriginalVersiontrue uses the workflow version of the run, false the published one. Default: true with fromStepId, otherwise false.
reasonTrigger reason.

Kept steps are copied into the new run with their times, so a Delay after a kept step may already be over. Their reusedFromOccurrenceId is the occurrence that ran; the new run's rerunOfRunId is the run it repeats. The workflow must be active, the input must match the schema of the version that is used, and the overlap policy applies.

Workflow List​

The list shows the last 20 runs of each workflow as a strip, the newest on the right, the average duration of the completed ones among them, and when the workflow runs next: the earlier of its schedule and a run triggered for later. Schedules are looked up 30 days ahead.

Cron Schedule​

Set a Cron Expression on the workflow. The engine automatically triggers the workflow when the cron schedule fires:

0 0 9 * * *       → Every day at 09:00 in the workflow's time zone
0 */30 * * * * → Every 30 minutes
0 0 0 * * MON → Every Monday at midnight

Uses the 6-field cron format (seconds included). See Core Concepts — Cron Expressions for full reference.


Building a Workflow (Step-by-Step)​

1. Open the Builder​

Navigate to Workflows → click Create Workflow, or open an existing workflow and click Edit. The visual builder is the only editor; links to the older form editor (/workflows/new, /workflows/<id>/edit) open it too.

2. Configure Workflow Settings​

Fill in the name, optional cron expression, and choose a failure strategy in Settings.

Input Schema describes the input a run starts with as a JSON Schema. Edit it field by field (name, type, description, required) or as JSON; keywords the field editor does not show are kept. A schema that is not a JSON object cannot be saved. The order of the fields is not stored.

3. Add Nodes​

Click Add Step in the toolbar (or press Ctrl+K) to open the node palette. Search it or pick from its categories:

  • Task — runs a job
  • Condition — routes by an expression
  • Switch — routes by the first case that is true
  • Merge — joins branches: all, any, or a number of them
  • Delay — waits for a number of seconds or until a date
  • Wait for event and Approval — wait for an event or for people
  • Sub-workflow and For each — run another workflow, once or for every item
  • Agent — lets a model call jobs, workflows and MCP tools (see Agent Nodes)

The + beside a node's output opens the same palette and connects the new node to that output.

4. Connect Nodes​

Drag from the output on the right of one node to the input on the left of another to create an edge. A Task has an error port for handling its failure, a Condition true and false, a Switch one per case and default. Without dragging, select a step and use Connect to a step in its panel.

A connection that would make a loop is refused while you draw it, and saving a workflow that has one tells you which steps it runs through.

Click an edge to change where it starts or ends, its port, or its label.

Auto Layout in the toolbar arranges the steps from left to right in the order they run. Undo brings the old arrangement back.

Note in the toolbar puts a note on the canvas. Double-click it, or press Enter while it is selected, to write; drag it to move it and drag its corner to resize it. Notes lie behind the steps, are stored with the workflow, also show on its page, and do not affect runs.

5. Configure Each Step​

Click a node to open its panel. The middle column holds the parameters:

  • Step Name and Key. The key of a new step follows its name until the step is saved. Renaming a key renames it in the expressions of the other steps.
  • Task: the Job, its Input, a Delay and an optional retry policy. The input is edited field by field or as JSON.
  • Condition and Switch: an expression per condition or case, exactly one {{ … }}. Comparison writes one for you. Renaming a case takes its connections along.
  • Merge: when it goes on. Delay: how long, or until when.

The Input column shows what the Task steps before this one return, and the Output column what this step returns. Both have a schema, a table and a JSON view, and either can be collapsed. Values come from the workflow's last finished run, which is named above them; a step that returned nothing in it has no values.

Drag a field from the schema or table into any text that may hold expressions to insert steps.<key>.result.<field>. Dropped beside the input fields it becomes a new one. With the keyboard, press Ctrl+Space in such a text, or use the button in its corner, and pick the field from the list; it also offers each step's status and error, and the fields of the run input from the input schema.

Under a text, its expressions are previewed while you type, evaluated by the API with the data of the last run. A server without the preview endpoint is named as such.

A workflow that cannot be saved names the step and opens it.

6. Save​

A new workflow is created with Save. An existing one is saved with Save draft (Ctrl+S): new runs keep the published version, and the toolbar shows Draft. Publish saves what is unsaved, shows what changes against the published version, and publishes it on confirmation; Discard draft throws the draft away. Settings such as the schedule take effect when they are saved (see Draft and Publish).

Until then the toolbar shows Unsaved changes, and leaving the page asks first. Every edit can be undone and redone, including moving nodes, changes in the panels and workflow settings.

ShortcutAction
Ctrl+SSave, as a draft for an existing workflow
Ctrl+ZUndo
Ctrl+Shift+Z or Ctrl+YRedo
Ctrl+KOpen the node palette
Ctrl+C / Ctrl+VCopy and paste the selected step
EnterWrite in the selected note
DeleteDelete the selected steps, notes and edges

On macOS use Cmd instead of Ctrl.


Versioning​

The definition has a schemaVersion; the current one is 2. A version 1 definition (data mappings, job data overrides, @status/$.field conditions) is upgraded when it is read, and stored in the new shape when the API starts. Data mappings and overrides appear as input; until that input is edited, the step keeps their rules: a value that cannot be found fails the step, a skipped source step is left out, and the override replaces top-level keys. Older workflow versions are upgraded the same way.

A save that changes the steps, the edges, the input schema, the notes, the failure strategy, the retry limits or the timeout creates a new version. The name, description and tags are labels, and the cron expression, time zone, overlap policy, concurrent run limit, deadline and schedule input decide when runs start, not what they do: changing them, or Active, applies right away without a version. Versions do not store them; older versions that do are compared and restored without them. Moving steps or notes on the canvas is saved and published too, but is no new version on its own: the layout is left out of the comparison, as it is of the diff. Older versions are stored as snapshots in Workflow.Versions. This allows you to:

  • See when the DAG definition changed
  • Compare what a historical run was executing against

A run executes the steps and edges of the workflow version that was current when it was triggered. Failure strategy, retry limits and timeout are read from the workflow as it is now, so changing them also affects runs in progress.

Steps and edges can be changed at any time. Runs that are pending or running, including one scheduled for later, keep their version.

Draft and Publish​

Request (permission)What it does
PUT /api/v1/workflows/workflow with publish: false (Update)Saves steps, edges, inputSchema and notes as a draft. A draft may be incomplete: only names, temp ids and cycles are checked. Other fields, such as the schedule, take effect right away. Without publish, or with true, the definition takes effect for new runs; a draft stays as it is.
POST /api/v1/workflows/workflow/publish { workflowId } (Update)Checks the draft like a save and makes it the published version. A draft that equals the published definition makes no version.
DELETE /api/v1/workflows/workflow/draft?workflowId= (Update)Throws the draft away.
POST /api/v1/workflows/workflow/restore { workflowId, version } (Update)Copies the definition of an earlier version into the draft, replacing it. The name and schedule settings stay as they are.
GET /api/v1/workflows/workflow/diff?workflowId=&from=&to= (Detail)Settings, steps and edges that differ. from and to are a version number, published (default of from) or draft (default of to).

In the panel, Compare and Restore beside each version in the version history show what differs from the published version and copy that version into the draft.

The published version is the workflow's version. The draft is in the draft field of the workflow detail, and hasDraft of the list says whether there is one.


Limitations​

LimitationDetail
No cyclesThe DAG must be acyclic. The builder refuses a connection that would make a loop, and the API rejects a definition that has one.
Delay (seconds) of a stepOnly Task steps have it. Use a Delay node in front of other nodes.
Result sizeStep results are stored in PostgreSQL as JSON. Node outputs and inputs over 256 KB go to the payload store; results of Task steps stay in their occurrence. Very large results (> a few MB) may impact performance.
NestingRuns started by SubWorkflow, ForEach and Agent steps can be nested 5 deep. A ForEach takes at most 1000 items.

  • Implementing Jobs — Write jobs that return typed results for use in expressions
  • Core Concepts — Job, Occurrence, Worker fundamentals
  • Reliability — Retry, timeout, and zombie detection details
  • Configuration — WorkflowEngine section for polling interval and enable/disable