WaitForSignal Step — Human-in-the-Loop Workflows
The built-in WaitForSignal step parks a flow indefinitely until an external HTTP signal is delivered. Use it for approval workflows, content moderation gates, manual QA sign-off, or any "pause until a human (or external system) says go" pattern — without burning a worker thread on a polling loop.
It is the smallest possible primitive that unlocks the entire approval workflow category: ship value in a weekend, not a quarter.
When To Use It vs. Polling
| Pattern | Use case | Mechanism |
|---|---|---|
PollableStepHandler<T> |
Wait for an external system that will eventually respond on its own (job status, file appearance, blob upload completion). | Step re-runs on a fixed cadence; you write the fetch + condition. |
WaitForSignal |
Wait for an external system or human that will push a notification when ready (manager approval, webhook from third party, async batch completion). | Step parks; an HTTP POST wakes it up. |
Rule of thumb: if you'd hit a rate limit polling once a minute, WaitForSignal is the right choice.
Manifest
["wait_for_approval"] = new StepMetadata
{
Type = "WaitForSignal",
RunAfter = new RunAfterCollection { ["submit_request"] = [StepStatus.Succeeded] },
Inputs = new Dictionary<string, object?>
{
["signalName"] = "approval",
["timeoutSeconds"] = 86400 // optional; null/omitted = wait indefinitely
}
}
Fields:
signalName(optional, defaults to"default") — the logical name addressed by the signal endpoint. Must be unique among the parkedWaitForSignalsteps in the same run, so always set it explicitly when a run has more than one waiter. Supplying an explicitly empty or whitespace value fails the step withWaitForSignal step requires a non-empty 'signalName' input.timeoutSeconds(optional) — absolute deadline. When elapsed without delivery, the step transitions toFailedwith a descriptive reason.nullor non-positive values mean "wait forever".allowedRoles(optional, string array) andauthorizationPolicy(optional, policy name) — restrict who may deliver the signal over HTTP. See Restricted signals.
End-to-End Example
public sealed class ApprovalFlow : IFlowDefinition
{
public Guid Id { get; } = new("00000000-0000-0000-0000-000000000007");
public string Version => "1.0";
public FlowManifest Manifest { get; set; } = new()
{
Triggers = new FlowTriggerCollection
{
["manual"] = new TriggerMetadata { Type = TriggerType.Manual }
},
Steps = new StepCollection
{
["submit"] = new StepMetadata
{
Type = "LogMessage",
Inputs = new Dictionary<string, object?> { ["message"] = "Awaiting manager approval" }
},
["wait_for_approval"] = new StepMetadata
{
Type = "WaitForSignal",
RunAfter = new() { ["submit"] = [StepStatus.Succeeded] },
Inputs = new Dictionary<string, object?>
{
["signalName"] = "approval",
["timeoutSeconds"] = 86400
}
},
["finalize"] = new StepMetadata
{
Type = "LogMessage",
RunAfter = new() { ["wait_for_approval"] = [StepStatus.Succeeded] },
Inputs = new Dictionary<string, object?>
{
["message"] = "@steps('wait_for_approval').output.approver"
}
}
}
};
}
From the dashboard, open the run detail page and click Send Signal on the parked WaitForSignal step — the dashboard reads signalName from the step inputs and prompts for the JSON payload. Or POST directly with curl:
curl -X POST http://localhost:5000/flows/api/runs/<runId>/signals/approval \
-H "Content-Type: application/json" \
-d '{"approver":"alice@example.com","approved":true}'
Response on success:
{
"delivered": true,
"stepKey": "wait_for_approval",
"deliveredAt": "2026-05-01T14:33:21+00:00"
}
Downstream steps consume the payload via the same expression syntax used for any step output:
["message"] = "@steps('wait_for_approval').output.approver"
Delivering a Signal In-Process
HTTP is not the only path. IFlowSignalDispatcher is registered by AddFlowOrchestrator and is exactly what the dashboard endpoint calls — inject it when your application (or a test) already has the runId in hand:
public sealed class ApprovalService(IFlowSignalDispatcher signals)
{
public async Task ApproveAsync(Guid runId, string approver)
{
var result = await signals.DispatchAsync(
runId,
"approval",
$$"""{"approver":"{{approver}}","approved":true}""");
// result.Status is Delivered / NotFound / AlreadyDelivered / Expired;
// result.StepKey and result.DeliveredAt are populated on success.
}
}
The returned SignalDeliveryResult carries the same outcomes the HTTP endpoint maps to 200 / 404 / 409 / 410.
An Expired result writes nothing and sends no resume nudge.
IFlowSignalDispatcher performs no authorization — not the operator rule, not a step's
allowedRoles / authorizationPolicy. That is by design: code running in your process is trusted, and
deciding who may approve is your application's job on that path (check the current user before you call
DispatchAsync). Only the HTTP endpoint enforces restrictions.
Endpoint Status Codes
Checked in this order: authentication, authorization, run state, body.
| Status | Meaning |
|---|---|
200 |
Signal delivered. Body includes stepKey and deliveredAt. |
401 |
Not signed in (no session, or a bearer token no scheme accepts). |
403 |
The caller may not deliver this signal — see Security. Also the answer to a caller who is not an operator when the run does not exist, so the endpoint cannot be used to probe run ids. |
404 |
Run does not exist (operators only), or no waiter is registered for that signal name on the run. |
409 |
A signal has already been delivered for this waiter — second delivery rejected. |
410 |
The waiter's timeoutSeconds deadline has passed — the signal is refused and nothing is written. The step fails with its timeout reason (if it has not already). |
400 |
Run is no longer in Running status, or the body is not valid JSON. |
Timeout Patterns
The deadline is absolute. From that instant on the store refuses the signal (SignalDeliveryStatus.Expired,
HTTP 410) — judged by the store's clock: SYSDATETIMEOFFSET() on SQL Server, now() on PostgreSQL, the
registered TimeProvider in memory — even though the step itself is only failed by its safety-net
invocation about a second later. A late signal therefore never resumes a timed-out step. When several
steps wait on the same signal name, an expired waiter is skipped and the oldest live one receives the
signal.
Set timeoutSeconds to fail the step (and therefore the run, unless you wire a recovery branch with a downstream step that runs on [StepStatus.Failed]) after a deadline:
["wait_for_approval"] = new StepMetadata
{
Type = "WaitForSignal",
RunAfter = new() { ["submit"] = [StepStatus.Succeeded] },
Inputs = new Dictionary<string, object?>
{
["signalName"] = "approval",
["timeoutSeconds"] = 3600 // 1 hour
}
},
["escalate_to_director"] = new StepMetadata
{
Type = "NotifyDirector",
RunAfter = new() { ["wait_for_approval"] = [StepStatus.Failed] }
}
The step's FailedReason reads Signal '<name>' not received within <n>s. so it is easy to distinguish from a handler exception in the dashboard.
Multi-Signal Patterns
A run may have multiple WaitForSignal steps, each with its own signalName. They can run in parallel (no runAfter between them) or in sequence.
Both manager and finance must approve: two parallel waiters, both must succeed:
["wait_manager"] = new StepMetadata
{
Type = "WaitForSignal",
Inputs = new Dictionary<string, object?> { ["signalName"] = "manager-approval" }
},
["wait_finance"] = new StepMetadata
{
Type = "WaitForSignal",
Inputs = new Dictionary<string, object?> { ["signalName"] = "finance-approval" }
},
["finalize"] = new StepMetadata
{
Type = "Echo",
RunAfter = new()
{
["wait_manager"] = [StepStatus.Succeeded],
["wait_finance"] = [StepStatus.Succeeded]
}
}
Manager and finance each POST to their respective signal name; only when both have arrived does finalize run.
Security
The signal endpoint is part of the dashboard and is protected the same way — see Securing the dashboard. Delivering a signal changes state, so by default it is an operator action. A step can narrow that to named approvers (restricted signals).
Who may deliver a signal
| Caller | Unrestricted signal | Restricted signal |
|---|---|---|
No authentication configured, Development or AllowAnonymousOperators: true |
200 |
403 |
| No authentication configured, any other environment (read-only) | 403 |
403 |
| Authentication configured, no credentials | 401 |
401 |
| Basic Auth (the shared account) | 200 |
403 |
| Signed in (OIDC session or bearer token) with an operator role | 200 |
200 only if the caller satisfies the restriction |
| Signed in, viewer role only | 403 |
200 only if the caller satisfies the restriction |
| Signed in, no dashboard role | 403 |
200 only if the caller satisfies the restriction |
Anyone, for a run whose flow the dashboard host does not register (default UnregisteredFlowSignals: Deny) |
403 |
403 |
Whatever the caller, a delivered signal cannot resurrect a cancelled or completed run: the run must be in
Running status.
Restricted signals
Add allowedRoles and / or authorizationPolicy to the step:
["wait_finance"] = new StepMetadata
{
Type = "WaitForSignal",
Inputs = new Dictionary<string, object?>
{
["signalName"] = "finance-approval",
["allowedRoles"] = new[] { "finance-approver" }, // any one of them
// ["authorizationPolicy"] = "FinanceLead", // AddAuthorization(o => o.AddPolicy("FinanceLead", …))
["timeoutSeconds"] = 86400
}
}
The endpoint then delivers finance-approval only to a caller who:
- is an identity signed in through
FlowDashboard:Authorization— the OIDC cookie, or any of itsAdditionalAuthenticationSchemessuch as a bearer token. Basic Auth and anonymous callers are always refused, inDevelopmentand withAllowAnonymousOperatorstoo: the shared Basic account has no identity to approve with; - has any of
allowedRoles, matched like the viewer / operator roles (roles/roleclaims,IsInRole, and Keycloak'srealm_access/resource_accessonceAddFlowDashboardKeycloakRolesis registered); - satisfies
authorizationPolicy, when set. With both set, the caller needs both.
Rules worth knowing:
- The operator role does not bypass a restriction, and an approver does not need a viewer or operator role for this endpoint. A finance approver with no dashboard role can approve but cannot list runs.
- Both inputs must be static, and so must the step's
signalName: the endpoint decides which step a signal addresses from the manifest, before it writes anything. A restriction declared in aForEachor other scope applies to every iteration. - The dashboard host must register the flow. The restriction is read from the flows registered (with
AddFlow) in the process that serves the dashboard. A signal for a run of a flow that process does not know is refused for every caller (403, EventId4108): without the manifest the dashboard cannot tell whether it is restricted, so it fails closed. In a split deployment register the same flows on the dashboard host as on the workers. If you cannot,FlowDashboard:Authorization:UnregisteredFlowSignals: OperatorRulerestores the operator rule for such runs — restrictions are then not enforced over HTTP, and startup logs EventId4109(Warning). - When several
WaitForSignalsteps share a signal name, the caller must satisfy every restricted one: the store delivers to whichever waiter is oldest, so the check covers every step the delivery can reach. - Validated at startup.
MapFlowDashboardthrows when a restriction is malformed (allowedRolesnot a non-empty string array, an expression in either input, a non-static or non-ASCIIsignalName) or names a policy that is not registered. A restriction that slips past (flows registered per scope) is refused with403at request time, never delivered. - Audit log. Every restricted delivery logs EventId
4107(Information) with the user, run, signal and step; every refused delivery logs4108(Warning). Startup logs4106(Warning) when flows declare restrictions but identity sign-in is not configured — such signals can then only be delivered in-process. - The page follows suit. Run detail carries a
signalAuthorizationentry for each parked step whose signal is restricted (or whose flow the host does not register):allowedRoles/policyof the step,requirements(every restricted step its signal name reaches),flowUnregisteredandcanSignal.canSignalis computed by the same decision the endpoint makes, shared-name union included, so Send signal is shown only to callers the endpoint would accept — also in view-only mode — and everyone else sees who may approve ("Requires role: finance-approver").
Machine-to-machine: approving with a bearer token
A system that approves on someone's behalf (an ERP, a ticketing workflow) authenticates as a Keycloak service account with the client-credentials grant and presents the access token to the signal endpoint.
In Keycloak, create a client
erp-approvalswith Client authentication on and only Service accounts roles enabled. On its Service account roles tab assign the realm rolefinance-approver. Add an Audience mapper so its access tokens carryaud: flow-dashboard.Register a JWT bearer scheme next to the cookie / OIDC schemes (package
Microsoft.AspNetCore.Authentication.JwtBearer) and list it inAdditionalAuthenticationSchemes:builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie() .AddOpenIdConnect("oidc", o => { /* as in Securing the dashboard */ }) .AddJwtBearer("Bearer", o => { o.Authority = "https://keycloak.example.com/realms/flow-orchestrator"; o.Audience = "flow-dashboard"; o.MapInboundClaims = false; o.TokenValidationParameters.NameClaimType = "preferred_username"; o.TokenValidationParameters.RoleClaimType = "roles"; }); // Turns the token's realm_access.roles into role claims (client roles only for "flow-dashboard"). builder.Services.AddFlowDashboardKeycloakRoles(clientId: "flow-dashboard");"FlowDashboard": { "Authorization": { "AuthenticationScheme": "Cookies", "ChallengeScheme": "oidc", "AdditionalAuthenticationSchemes": [ "Bearer" ] } }Fetch a token and deliver the signal:
TOKEN=$(curl -s -X POST \ https://keycloak.example.com/realms/flow-orchestrator/protocol/openid-connect/token \ -d grant_type=client_credentials -d client_id=erp-approvals -d "client_secret=$ERP_CLIENT_SECRET" \ | jq -r .access_token) curl -X POST https://flows.example.com/flows/api/runs/$RUN_ID/signals/finance-approval \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"approved":true,"approvedBy":"erp"}'
The audit log names the caller as service-account-erp-approvals (Keycloak's preferred_username for a
service account). An expired or forged token gets 401 with the bearer handler's WWW-Authenticate
header — never a redirect to the login page. The same token works on the rest of the API with whatever
viewer / operator roles the service account holds; give it only the approver role if approving is all it
should do.
In-process delivery
IFlowSignalDispatcher is not authorized at all — see Delivering a Signal In-Process.
If your application exposes its own approval endpoint, enforce who may approve there.
Resume Latency
Delivering a signal does not execute the parked step inline. The endpoint persists the payload, then dispatches a resume nudge through the active runtime, and the step wakes when a worker picks that nudge up. How long that takes is a property of the runtime, not of WaitForSignal:
| Runtime | Resume latency after a successful POST |
|---|---|
InMemory (UseInMemoryRuntime()) |
Channel write, picked up immediately |
| Azure Service Bus | Message sent to the flow-steps topic with no ScheduledEnqueueTime, delivered immediately |
Hangfire (UseHangfire()) |
Queue-pickup time — provided the nudge is enqueued rather than scheduled, see below |
On the rare delayed branch described below, each runtime falls back to its deferred primitive instead: a Task.Delay before the channel write, a scheduled Service Bus message, and BackgroundJob.Schedule respectively.
Why Hangfire used to add up to 15 seconds
Hangfire routes delayed work and immediate work through different paths. BackgroundJob.Schedule(...) places the job in the Scheduled set, and DelayedJobScheduler only promotes it to a queue on its poll tick — BackgroundJobServerOptions.SchedulePollingInterval, 15 seconds by default. BackgroundJob.Enqueue(...) goes straight to the queue and skips that window entirely.
Before the fix for #188 the resume nudge always took the delayed path with a 500 ms delay, to sidestep a race: the step registers its waiter — which is what makes delivery possible at all — a few milliseconds before the engine releases its execution claim on the Pending path. A resume that lands inside that window loses TryClaimStepAsync and is dropped silently. On Hangfire that 500 ms intent became 0.5 s + (0–15 s) of real latency, which is what the issue reported.
The dispatcher now reads the step's claim state and picks the path deliberately:
- claim already released — the overwhelming majority of deliveries, where the step has been parked for seconds or longer: dispatched immediately via
EnqueueStepAsync. No scheduled-set poll. - claim still held — the parking invocation has not finished its bookkeeping yet: the short delayed nudge. The nudge can still lose the claim on a loaded multi-worker backend (Hangfire, Service Bus), so it is not the only safety: after releasing its claim, the parking invocation re-reads its own waiter and enqueues the resume itself if a payload has landed (log event 3008). A delivery that saw the claim held committed before that read, so one of the two always wakes the step; a duplicate is absorbed by the claim (#190).
- claim state unreadable (transient storage fault): the delayed path, logged at
Warning— a persistently failing claim store would otherwise silently reinstate the latency this fix removes.
The nudge is dispatched with CancellationToken.None, never the caller's token. The signal is durably persisted before the nudge, so the resume has to outlive the request that delivered it — the dashboard endpoint passes http.RequestAborted, which trips the moment the caller disconnects.
No configuration is required, and SchedulePollingInterval no longer gates signal resume. If you lowered it purely to speed up WaitForSignal, you can put it back — note that it is a global setting affecting every delayed job in your app (step retries, ForEach delays, every polling step) and costs one scheduled-set query per server per tick.
The safety net is not always prompt
If the nudge fails to dispatch (queue outage, broker error), the signal is still durably delivered and the step wakes on the safety-net invocation scheduled when it parked. That invocation is only prompt when the step declares timeoutSeconds — without one the park interval is FlowSignalOptions.IndefiniteParkInterval, 24 hours by default. Set a timeout on any WaitForSignal whose recovery you care about, or shorten the interval globally:
builder.Services.AddFlowOrchestrator(options =>
{
options.Signals.IndefiniteParkInterval = TimeSpan.FromHours(1);
});
Each re-check runs the full step path — a claim and an attempt row (shown as a step.started / step.pending pair in the run timeline) — so a short interval multiplies the run history of every long-parked step.
Observability
The run timeline (dashboard Events drawer, GET /flows/api/runs/{runId}/events, FlowTestRunResult.Events) is derived from the step's attempt rows and shows, for each WaitForSignal step:
step.startedon every invocation (initial park, signal arrival, timeout fire).step.pendingevery time an invocation parks the step. The attempt is closed asPendingbefore its execution claim is released, so it always precedes thestep.completedof the resume that follows. A parked invocation never showsstep.completed.step.completedon successful delivery.step.failedon timeout.
The dashboard run detail page shows the timeline in chronological order, plus the resolved input/output and any handler logs surfaced through IExecutionContext.
Restart Safety
Waiters live in your configured storage (FlowSignalWaiters table for SQL Server, flow_signal_waiters for PostgreSQL, ConcurrentDictionary for in-memory). A process restart does not lose pending waits: when the worker comes back up, FlowRunRecoveryHostedService restores active runs, and the next invocation of the parked step picks up the persisted waiter row. In-memory storage is lost on restart, by design.
Out of Scope
For deliberate simplicity, this primitive does not include:
- HMAC-signed signal endpoints. Authenticate callers with identity sign-in or a bearer token instead (Security).
- Resource-based approval policies.
authorizationPolicyis evaluated without a resource, so a policy cannot see the run, step or payload (for example to forbid the requester from approving their own request). Planned as a follow-up. - Broadcast multi-recipient signals. Each waiter is identified by
(RunId, StepKey); one signal targets one waiter. - Signal cancellation API. Cancel the run instead.
- Long-poll API for callers waiting for delivery confirmation.
- Persistent signal queues for signals that arrive before a step is ready to receive them.
If you find yourself needing one of these, you've outgrown the primitive — consider modeling the workflow as a separate service that triggers FlowOrchestrator, rather than driving FlowOrchestrator from the wait point.