Introducing a new way to review your PRs.

Read the announcement

elsa-workflows / elsa-core

The Workflow Engine for .NET

View on GitHub

32 documents · Updated Oct 7, 2026

docs / workflow-runtime

Workflow runtime dispatch and recovery

The workflow runtime turns start requests, external signals, and scheduled work into workflow execution. It controls when an instance may start, how work reaches an instance, how execution state is saved, and how interrupted work returns to the dispatch path. It supports local execution and clustered execution with shared locks and durable state. See the workflow engine, workflow execution, and persistence pages for the neighboring system boundaries.

Runtime boundary

The runtime is the service boundary between workflow management and the workflow engine. Workflow management supplies a workflow definition. The runtime selects or creates an instance, sends execution work, resumes waiting work, and returns the resulting state to the engine and its callers. The runtime feature registers these services for the module host and provides the dispatch, stimulus, queue, state, and recovery services used by the host.

The main client contract is IWorkflowClient. It groups instance creation, execution, cancellation, state transfer, existence checks, and deletion behind one interface. LocalWorkflowClient performs the work on the current host. DistributedWorkflowClient keeps the same contract while adding a lock around instance execution and deletion.

References: src/…/IWorkflowClient.cs• L6-53 src/…/LocalWorkflowClient.cs• L18-29 src/…/DistributedWorkflowClient.cs• L13-24 src/…/WorkflowRuntimeFeature.cs• L38-71

Dispatch lifecycle

Workflow starts

The start path resolves a workflow graph, checks whether its activation rule allows a new instance, and asks the workflow client to create and run it. A start request carries the context that caused the start, such as correlation data, input, parent identity, and trigger information. A refused activation returns CannotStart and does not persist an instance.

Activation rules prevent duplicate live instances. The correlated singleton rule limits one running instance for a definition and correlation ID. The correlation rule limits one running instance for a correlation ID across definitions. The activation gate holds the strategy-scoped lock from the check until the new instance is saved, so two concurrent starts cannot both pass an empty-state check. Built-in strategies have tenant-aware lock scopes. Custom strategies do not receive an assumed lock scope.

References: src/…/DefaultWorkflowStarter.cs• L16-50 src/…/WorkflowActivationGate.cs• L22-108 src/…/CorrelatedSingletonStrategy.cs• L7-30 src/…/CorrelationStrategy.cs• L7-30

Workflow dispatch

Dispatch separates accepting work from running the target instance. The dispatch handler maps a definition or instance command to either a create-and-run request or a resume request. A stimulus command follows the same boundary but sends the event to the stimulus router. The runtime can send dispatch work through a background channel. A transactional outbox keeps dispatch caused by a workflow execution until the parent state commit succeeds.

The dispatch outbox is durable and supports recovery from a partial write. It stores the item, an ordered lookup entry, and an ID lookup entry. A recovery marker remains while the item is being written. If a process stops during that write, a later read can rebuild the ordered lookup. The store also migrates older records into the current layout. That migration is scoped to the active tenant and records completion per tenant, so one tenant cannot hide unfinished legacy work for another tenant.

The DispatchWorkflow activity creates one child instance and can either complete after dispatch or wait for the child result. BulkDispatchWorkflows applies the same model to a set of items. It tracks each child through a parent bookmark and completes only after all children report a result. This gives parent workflows a controlled choice between fire-and-forget work and parent-child coordination.

If a child dispatch is accepted but its activation rule refuses the new instance, the runtime sends an internal denial notification. The parent wait path then receives a completion-shaped result with CannotStart, instead of waiting for a child instance that does not exist.

The following diagram shows how a request becomes a workflow run and how a waiting parent receives a child result.

flowchart LR
    Request[Start or dispatch request] --> Gate[Activation check]
    Gate -->|Allowed| Client[Workflow client]
    Gate -->|Denied| Denial[Activation-denied route]
    Client --> Run[Create or resume execution]
    Request --> Outbox[Background or transactional outbox]
    Outbox --> Client
    Run --> Commit[Persist execution state]
    Commit --> Child[Child completion notification]
    Child --> Parent[Resume parent bookmark]
    Denial --> Parent

References: src/…/DispatchWorkflowRequestHandler.cs• L36-96 src/…/KeyValueWorkflowDispatchOutboxStore.cs• L10-44 src/…/KeyValueWorkflowDispatchOutboxStore.cs• L66-88 src/…/KeyValueWorkflowDispatchOutboxStore.cs• L212-261 src/…/DispatchWorkflow.cs• L79-169 src/…/BulkDispatchWorkflows.cs• L111-149 src/…/ResumeDispatchWorkflowActivity.cs• L22-80 src/…/ResumeBulkDispatchWorkflowActivity.cs• L23-82

Stimulus and bookmark processing

Stimulus routing

A stimulus is an external value that can start a workflow or continue one that is waiting. StimulusSender hashes the activity type and stimulus into a lookup key. It first starts workflows whose triggers match when the request is not tied to a known instance. It then resumes matching bookmarks. When no bookmark exists, it queues the request so a bookmark created shortly after the signal can consume it.

The bookmark queue separates signal intake from instance execution. A queue item stores the tenant and the bookmark match data. Enqueueing also signals the tenant-specific worker. The worker restores the captured tenant context before it processes the queue and limits rapid repeated processing. A periodic task signals the worker as a reliability measure, so a missed in-memory signal does not prevent a later queue check. Items that cannot be delivered within the configured limit move to dead-letter storage. Expired active items also move to dead-letter storage before removal.

The runtime registers queue processing and purge tasks as part of its recurring work. The memory queue store applies the current tenant to reads and deletes. Other store implementations must provide the same tenant boundary for clustered or durable operation.

References: src/…/StimulusSender.cs• L19-43 src/…/StimulusSender.cs• L87-134 src/…/StoreBookmarkQueue.cs• L8-38 src/…/BookmarkQueueSignaler.cs• L7-57 src/…/BookmarkQueueWorker.cs• L49-120 src/…/MemoryBookmarkQueueStore.cs• L36-68 src/…/TriggerBookmarkQueueRecurringTask.cs• L7-31 src/…/WorkflowRuntimeFeature.cs• L347-365 src/…/WorkflowRuntimeFeature.cs• L407-413

Trigger matching

A trigger is a condition that allows an incoming stimulus to start a workflow. The runtime indexes trigger identity so a stimulus can find the matching published workflow graph. Trigger matching keeps the activity type and stimulus hash together. Tenant and workflow identity remain part of the lookup scope. This lets definition refresh replace trigger records without leaving an old trigger set active beside the new one.

References: src/…/WorkflowRuntimeFeature.cs• L313-341 src/…/StimulusSender.cs• L46-80

Workflow-as-activity registry

The workflow-as-activity registry makes selected workflow definitions available as activities in the runtime. A definition reload updates the local registry and advances a tenant-scoped generation for both the current tenant and shared tenant-agnostic definitions. In a distributed deployment, each node polls the shared generations and reconciles its local registry when a change is visible.

The runtime also performs periodic full reconciliation. This gives nodes a recovery path when a change signal is missed while avoiding work when the shared generations are unchanged.

References: src/…/RefreshActivityRegistry.cs• L10-41 src/…/RefreshWorkflowDefinitionActivityRegistryTask.cs• L9-45 src/…/WorkflowRuntimeFeature.cs• L407-413

Parent workflow resumption

Child completion uses the bookmark path to continue a waiting parent. A finished child emits its output and status as resume input. The runtime hashes the parent activity route and places a resume item on the bookmark queue. An activation denial uses the same parent route but reports CannotStart, so both normal completion and refusal reach the waiting activity through one contract.

References: src/…/ResumeDispatchWorkflowActivity.cs• L22-80 src/…/ResumeBulkDispatchWorkflowActivity.cs• L23-82

State and control

Execution state

Each execution cycle produces a new workflow state. The workflow client loads the saved instance and its definition graph, passes them to the workflow runner, and returns status, sub-status, bookmarks, incidents, and optional output. A separate commit boundary persists the workflow state with its runtime records. The runtime tracks each active execution cycle until that commit completes, so shutdown coordination cannot treat a cycle as finished before its state is durable. The next dispatch or resume therefore starts from the last durable state rather than from an in-memory runner.

Cancellation follows the execution path. It runs the workflow cancellation action, saves the resulting state, and can be used before deletion. This matters because deletion must not remove an active instance without first stopping its execution.

References: src/…/LocalWorkflowClient.cs• L75-124 src/…/LocalWorkflowClient.cs• L139-186 src/…/LocalWorkflowClient.cs• L189-232 src/…/ExecutionCycleTrackingMiddleware.cs• L5-9 src/…/ExecutionCycleTrackingMiddleware.cs• L27-35 src/…/IWorkflowClient.cs• L33-53

Graceful shutdown

Graceful shutdown enters drain, pauses registered ingress sources in parallel, and waits for active execution cycles to reach zero. Each source has a bounded pause period. A source that does not pause can be force-stopped when it supports that action.

When the deadline expires, or an operator requests a force drain, the runtime cancels active cycles and records still-running instances as Interrupted. It leaves finished and cancelled instances unchanged, then writes a WorkflowInterrupted event for affected instances. It waits for normal commits before this recovery mark when possible. This keeps the final durable state aligned with the shutdown result.

Pause and drain control the boundary at different strengths. Administrative pause blocks new intake and can persist across reactivation. Drain is a one-way operation for the current runtime generation, so resume does not clear an active drain. The runtime records the generation so a later activation can identify work interrupted by the prior generation.

The quiescence signal is the single source of truth for whether a runtime accepts new work. It keeps administrative pause and drain as separate reasons, exposes the active execution-cycle count, and makes state reads safe while transitions are serialized. Administrative pause can be session-scoped or can survive a host restart or shell reactivation through the key-value store. Startup restores that state on every node or shell activation when across-reactivation persistence is enabled.

Pause persistence uses a host-scoped key. During startup, the runtime also adopts a visible legacy pause record and removes the old record so an upgrade does not leave stale tenant-scoped state that can later restore a pause unexpectedly. If persistence fails during pause or resume, the signal restores the in-memory pause fields and reports the failure to the caller.

The following diagram shows how administrative pause state moves between runtime memory and durable storage across a runtime generation boundary.

flowchart LR
    Admin[Pause or resume request] --> Signal[Quiescence signal]
    Signal --> Memory[In-memory runtime state]
    Signal -->|AcrossReactivations| Store[Key-value store]
    Store --> Init[Startup or shell activation]
    Init --> Signal
    Signal --> Intake[Ingress and dispatch acceptance]

References: src/…/DrainOrchestrator.cs• L20-30 src/…/DrainOrchestrator.cs• L103-177 src/…/DrainOrchestrator.cs• L198-264 src/…/DrainOrchestrator.cs• L266-286 src/…/DrainOrchestrator.cs• L383-503 src/…/DrainOrchestrator.cs• L505-617 src/…/QuiescenceSignal.cs• L129-175 src/…/QuiescenceSignal.cs• L220-261 src/…/QuiescenceSignal.cs• L274-359 src/…/InitializePauseStateStartupTask.cs• L7-25 src/…/InitializePauseStateShellInitializer.cs• L7-40 src/…/WorkflowRuntimeFeature.cs• L281-311

Runtime administration

Runtime administration provides one domain service for pause, resume, force drain, and status queries. Transport layers use this service instead of implementing their own control and audit rules. Pause is idempotent. A force drain uses the same drain protocol with no waiting deadline and returns a structured outcome.

The status view combines quiescence state, ingress source state, and the active execution-cycle count. This gives operators one view of whether the runtime accepts work, whether ingress has paused, and whether recovery work may remain.

References: src/…/IWorkflowRuntimeAdminService.cs• L3-40 src/…/IDrainOrchestrator.cs• L10-17 src/…/WorkflowRuntimeAdminService.cs• L12-64 src/…/WorkflowRuntimeFeature.cs• L283-311

Interrupted workflow recovery

Recovery changes an interrupted execution back into normal dispatch. On activation, the startup task scans running instances with the Interrupted sub-status and requeues them through the normal restarter. It restores tenant context before restarting tenant-owned work and processes the scan in bounded batches.

This startup scan is separate from the timeout-based liveness task. The startup scan handles rows explicitly marked Interrupted, while the liveness task handles rows that still report execution with a stale update time. A failed startup requeue remains available to the liveness path instead of stopping the scan for other instances. Terminal Finished+Interrupted rows are not requeued.

Recovery is therefore a continuation of dispatch, not a separate execution mode. The restarted instance returns to the workflow client and follows the same load, run, and commit path as a normal resume. This lets a host failure or forced drain recover durable work without creating a second workflow instance.

References: src/…/IInterruptedRecoveryScanner.cs• L3-22 src/…/InterruptedRecoveryScanner.cs• L39-80 src/…/RecoverInterruptedWorkflowsStartupTask.cs• L7-19 src/…/WorkflowRuntimeFeature.cs• L301-306 src/…/WorkflowRuntimeFeature.cs• L407-413 src/…/LocalWorkflowClient.cs• L189-232

Distributed runtime

Instance coordination

The distributed client uses the local client for instance work and adds a per-instance distributed lock around create-and-run, run, and delete operations. A newly created instance is locked during its first run because that run can dispatch work that tries to resume its parent. Transient lock-acquisition errors are retried with delay and jitter. A lock release failure is logged while the lock provider remains responsible for releasing the lock when the connection ends.

Activation checks use a related strategy-scoped lock. The lock stays held through the instance save, which closes the race between checking for a running instance and making the new instance visible. In a cluster, both this gate and instance execution must use a lock provider shared by all nodes.

References: src/…/DistributedWorkflowClient.cs• L26-132 src/…/WorkflowActivationGate.cs• L22-65 src/…/WorkflowActivationLease.cs• L3-59

Shared runtime resources

Clustered nodes must share the durable resources that describe workflow progress. These resources include workflow instances, bookmarks, bookmark queues, triggers, execution records, and the dispatch outbox. Shared locks also coordinate work that must have one active processor, such as instance execution and queue handling. The local feature defaults to memory stores and a file-system lock provider, so those defaults are suitable for one host only.

The distributed feature can replace the local runtime client and queue worker with coordinated services. The important system property is shared visibility: every node must see the same state and must use the same lock scope. Without it, two nodes can accept the same logical work or resume an instance from stale state. Tenant-specific queue signals and queue reads must also remain aligned, so one tenant cannot process another tenant's work.

Runtime serialization is part of this shared-state contract. The runtime registers stable aliases for persisted bookmark payloads, stimuli, results, interruption data, and activation strategies. Concrete workflow types also receive aliases when they are concrete, non-generic implementations. Legacy names remain available for built-in activation strategies, so stored runtime data can continue to resolve after type names change.

References: src/…/WorkflowRuntimeFeature.cs• L83-116 src/…/WorkflowRuntimeFeature.cs• L381-414 src/…/DistributedWorkflowClient.cs• L13-24 src/…/BookmarkQueueSignaler.cs• L31-47 src/…/MemoryBookmarkQueueStore.cs• L61-68 src/…/WorkflowRuntimeTypeAliasRegistrar.cs• L11-39

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to activation checks must preserve the lock from strategy evaluation through instance persistence. Review both the activation gate and every built-in strategy scope.
  • Changes to child dispatch must keep the parent resume route aligned with the activation-denied notification. Check single-child and bulk-child paths together.
  • Changes to stimulus hashing or bookmark matching must keep activity type, stimulus hash, correlation, instance, and tenant scope consistent across direct delivery and queued delivery.
  • Changes to queue signaling or recurring triggering must preserve both prompt processing and periodic recovery of missed in-memory signals. Check tenant capture and tenant-scoped queue reads together.
  • Changes to queue or outbox delivery must preserve the boundary between accepting work and the commit that makes the source state durable.
  • Changes to dispatch outbox keys or migration logic must preserve item lookup, ordered lookup, recovery lookup, deletion cleanup, and per-tenant legacy-scan state as one contract.
  • Changes to shutdown ordering must keep terminal commits ahead of execution-cycle release and forced Interrupted persistence.
  • Changes to drain persistence must preserve the rule that terminal Finished and user-cancelled rows are not promoted back to Running or Interrupted.
  • Changes to pause persistence must keep the host-scoped key, legacy-row adoption, tenant context, and rollback behavior aligned across pause, resume, startup, and shell activation.
  • Changes to pause-state initialization must run on every node and every shell activation when across-reactivation persistence is enabled. A single cluster winner is not enough because each node has its own in-memory signal.
  • Changes to distributed runtime mode must replace both local stores and local lock scope with shared durable resources. Check activation locks, instance locks, queue coordination, and tenant scope together.
  • Changes to workflow definition reloads must update the local workflow-as-activity registry and its tenant and tenant-agnostic generations. Check the reload handler and the recurring reconciliation task together.
  • Changes to runtime serialization aliases must preserve names for stored payloads, activation strategies, and concrete workflow types. Treat legacy aliases as data-compatibility contracts.
  • Changes to workflow client responses must keep CannotStart distinct from a persisted instance result. Parent waiters depend on that distinction.

Important failure modes

TriggerConsequenceGuard
Activation is checked without holding its strategy lock until the instance is savedConcurrent starts can both see no running instance and create duplicatesUse IWorkflowActivationGate and dispose its lease only after persistence
A child dispatch is denied but no denial route reaches the parent bookmarkThe parent can wait for a child instance that was never createdCarry the internal route and send DispatchWorkflowActivationDenied
A stimulus arrives before its bookmark exists and is not queuedA valid event can be lost before the workflow reaches its wait pointEnqueue unmatched resume requests in the bookmark queue
A queue signal is lost and no recurring trigger runsA queued bookmark can wait until another event arrivesKeep the periodic queue trigger enabled and tenant-scoped
A dispatch from a workflow is delivered before the parent commitA host failure can leave the child request without durable parent stateUse the transactional outbox boundary
A dispatch outbox write stops after the item is saved but before its index is completeThe item can disappear from normal ordered readsKeep the recovery marker and rebuild indexes during the next scan
Legacy outbox scan state is shared across tenantsOne tenant can skip migration work because another tenant marked its scan completeStore and read the scan-complete marker in the active tenant scope
A persisted runtime payload has no stable or legacy type aliasA later node cannot restore a bookmark, stimulus, result, or strategyRegister stable aliases and keep legacy names for stored data
A drain releases an execution cycle before the terminal commitForced interruption can overwrite or race with a normal resultRelease the cycle after commit and persist Interrupted last
Drain promotes a finished or user-cancelled row to InterruptedRecovery can requeue work that has a terminal resultMark only still-running rows and leave terminal rows unchanged
A persisted administrative pause is restored on only one cluster nodeOther nodes can keep accepting new work while the paused node rejects itRun pause-state initialization on every node and use the shared key-value store
A pause or resume write fails after the in-memory transitionRuntime state and durable state can disagree across reactivationSerialize persistence and revert the pause fields when the write fails
Legacy pause state is read under the wrong tenant or left on the old keyAn upgrade can miss the pause or restore stale state laterCheck the default and ambient tenant scopes, then adopt and remove the legacy row
A distributed node uses a node-local workflow-definition generation storeIts workflow-as-activity registry can remain stale after another node reloads a definitionUse a shared generation store and keep periodic full reconciliation enabled
Cluster nodes use separate stores or non-shared locksNodes can run the same instance or consume stale bookmark stateUse shared durable runtime stores and one shared lock provider
A lock acquisition fails for a transient reason and is not retriedTemporary infrastructure faults can reject otherwise valid workUse the distributed client's bounded transient retry policy

Key files

FileWhy to read it
src/…/WorkflowRuntimeFeature.csShows the runtime service graph, stores, dispatchers, queue workers, and recovery tasks for the module host
src/…/IWorkflowRuntimeAdminService.csDefines the administrative pause, resume, force-drain, and status boundary
src/…/DrainOrchestrator.csShows the shutdown phases and the rules for force cancellation and interrupted-state persistence
src/…/QuiescenceSignal.csShows the runtime pause and drain state boundary, persisted administrative pause, and legacy-state migration
src/…/IQuiescenceSignal.csDefines the runtime-wide acceptance, drain, pause, and persisted-state lifecycle contract
src/…/InitializePauseStateStartupTask.csShows why persisted pause state must be restored on every node at host startup
src/…/InitializePauseStateShellInitializer.csShows why shell-aware hosts restore pause state on every shell activation
src/…/ExecutionCycleTrackingMiddleware.csShows how execution cycles connect workflow commits to drain tracking
src/…/IInterruptedRecoveryScanner.csDefines the startup recovery scope and its separation from liveness recovery
src/…/InterruptedRecoveryScanner.csShows how interrupted instances return to normal dispatch with tenant context
src/…/LocalWorkflowClient.csShows the high-level path from instance state to workflow run, cancellation, and persistence
src/…/DefaultWorkflowStarter.csShows how a start request becomes a create-and-run request
src/…/WorkflowActivationGate.csShows how activation rules become serialized, tenant-aware start decisions
src/…/DispatchWorkflowRequestHandler.csShows how definition dispatch, instance resume, and stimulus commands enter the runtime
src/…/KeyValueWorkflowDispatchOutboxStore.csShows durable outbox item storage, recovery markers, ordered indexes, tenant-scoped migration, and cleanup
src/…/StimulusSender.csShows how one stimulus can start workflows, resume bookmarks, or enter the queue
src/…/BookmarkQueueWorker.csShows tenant-aware queue wake-up and processing
src/…/TriggerBookmarkQueueRecurringTask.csShows periodic signaling that protects queued stimuli from missed wake-ups
src/…/RefreshActivityRegistry.csShows how definition reloads update the workflow-as-activity registry and its tenant generations
src/…/RefreshWorkflowDefinitionActivityRegistryTask.csShows how clustered nodes detect shared definition changes and reconcile local activity registries
src/…/WorkflowRuntimeTypeAliasRegistrar.csShows the stable serialization names that let runtime state survive type-name changes and restarts
src/…/DispatchWorkflow.csShows the parent-child dispatch contract for one child workflow
src/…/BulkDispatchWorkflows.csShows fan-out dispatch and completion tracking for many child workflows
src/…/ResumeDispatchWorkflowActivity.csShows how child completion and activation denial resume one waiting parent
src/…/ResumeBulkDispatchWorkflowActivity.csShows the corresponding resume path for bulk child dispatch
src/…/DistributedWorkflowClient.csShows per-instance locking and transient lock retry for clustered execution