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-management

Workflow definition management

Workflow definition management gives Elsa a durable, versioned description of each workflow. It lets authors save drafts, validate and publish changes, move definitions between systems, turn stored data into executable workflow graphs, and find definitions by identity or metadata. The resulting definition is the hand-off point between authoring and expressions and the workflow engine, while execution and runtime services consume the selected published or latest version through workflow execution and workflow runtime.

Definition lifecycle

Definition identity

A workflow definition has a logical DefinitionId that stays the same across its versions and a version-specific Id that identifies one stored version. The version number and publication flags describe where that version sits in the lifecycle.

ConceptPurpose
Logical definitionGroups all versions of one workflow.
Definition versionCaptures one saved form of that workflow.
Latest versionThe newest version in the logical group.
Published versionThe version selected for normal use.
DraftA version that can change before publication.

The model also carries the workflow contract and its descriptive metadata. Inputs and outputs define the data boundary. Variables hold shared workflow state. Outcomes describe possible results. Options and custom properties carry behavior settings and application data.

References: src/…/WorkflowDefinition.cs• L10-103 src/…/WorkflowDefinitionModel.cs• L10-85

Draft and publication flow

Authoring starts with a new definition or a draft based on an existing definition. Saving a draft creates the next version when the content is new. If the selected version is published, the publisher makes a separate draft so that edits do not change the published version.

Publishing first materializes the draft and validates the resulting workflow. When the management policy rejects validation errors, publication stops and returns those errors. When publication succeeds, the new version becomes both latest and published. The former latest or published versions lose those flags. Retraction removes the published state without deleting the version.

The lifecycle is coordinated by IWorkflowDefinitionPublisher. It also supports reverting an older version by creating a new draft from that version. Reverting allocates a new version number after the highest stored version and does not itself publish the new version.

The following flow shows how author input becomes a version that other services can use.

flowchart LR
    A[Author or import] --> B[Create or load draft]
    B --> C[Save draft]
    C --> D{Publish requested?}
    D -- No --> E[Latest draft]
    D -- Yes --> F[Materialize workflow]
    F --> G[Validate workflow]
    G -- Errors and policy rejects --> H[Return validation errors]
    G -- Accepted --> I[Publish new version]
    I --> J[Retract prior published state]
    J --> K[Published latest version]

References: src/…/WorkflowDefinitionPublisher.cs• L18-27 src/…/WorkflowDefinitionPublisher.cs• L73-125 src/…/WorkflowDefinitionPublisher.cs• L129-175 src/…/WorkflowDefinitionPublisher.cs• L178-238

Definition validation

Validation boundary

Validation runs on the materialized Workflow, not only on the stored text. WorkflowValidator sends a validation notification with a shared error collection. This allows the management system to combine checks from the workflow model and from registered services before publication.

Current checks include duplicate input or output names and invalid output-converter bindings. The latter checks that a converter exists, that its types match the output and destination, and that its settings are valid. Validation errors can identify the affected activity so an author can fix the source definition.

References: src/…/WorkflowValidator.cs• L9-17 src/…/WorkflowDefinitionValidating.cs• L7-12 src/…/ValidateWorkflow.cs• L8-29 src/…/ValidateOutputConverters.cs• L12-106

Definition materialization

Materialization boundary

Materialization converts a stored definition into a Workflow, then builds a WorkflowGraph for lookup and execution. The definition names the materializer that understands its stored representation. This keeps the management model independent from the format used to author or store the workflow.

The registry resolves materializers by name. JSON is the normal representation for definitions created through the management API. Other materializers can reconstruct workflows from typed or CLR-based sources when the matching provider is registered. If a materializer is missing, direct materialization fails. Query paths that use Try return the definition with no graph or skip the graph instead of hiding the stored metadata.

The mapper uses serialized StringData when it is present. It uses OriginalSource only when StringData is absent, which preserves source-only formats without allowing an old file snapshot to hide newer API or Studio edits. Older definitions can still use the serialized StringData representation.

References: src/…/IWorkflowMaterializer.cs• L7-22 src/…/MaterializerRegistry.cs• L4-21 src/…/WorkflowDefinitionService.cs• L20-29 src/…/WorkflowDefinitionService.cs• L59-175 src/…/WorkflowDefinitionMapper.cs• L28-86 src/…/JsonWorkflowMaterializer.cs• L7-37

Workflow definition activities

Activity registry projection

A workflow definition can be exposed as an activity so that another workflow can call it as a reusable step. The activity registry is a live projection of definitions that are marked as usable activities, while the definition store remains the source of truth.

Publication, retraction, and deletion notifications update the local projection. A tenant-scoped registry generation also advances after these changes, which gives other nodes a signal that their view may need reconciliation. Definitions from the current tenant and tenant-agnostic definitions form the visible registry set.

References: src/…/IWorkflowDefinitionActivityRegistryUpdater.cs• L6-25 src/…/RefreshActivityRegistry.cs• L11-26 src/…/RefreshActivityRegistry.cs• L29-115 src/…/WorkflowDefinitionRegistryGeneration.cs• L3-16

Registry reconciliation

Reconciliation refreshes the activity projection from the authoritative definition store. It first invalidates the current tenant's definition cache view, then reads the current descriptors and replaces the visible workflow-definition activities as one protected registry update.

The process keeps the existing registry usable when the store read fails or is cancelled. It also retries when a local add or removal changes the registry during the read, so a stale snapshot does not restore an old descriptor.

References: src/…/IWorkflowDefinitionActivityRegistryReconciler.cs• L3-11 src/…/WorkflowDefinitionActivityRegistryUpdater.cs• L13-21 src/…/WorkflowDefinitionActivityRegistryUpdater.cs• L56-99

Consumer reference propagation

When a reusable workflow definition changes its published version, management can update consuming workflows that point to it. The reference graph supplies the dependency order, so a consumer is updated only after the versions it uses are known. Published consumers keep their published state; draft consumers remain drafts.

The updater changes only JSON-authored consumers automatically. A source format that the JSON materializer cannot rewrite is left unchanged and is reported for manual repair. The update is guarded against re-entry so propagation does not trigger an update loop.

The following flow shows how a published reusable definition moves through its consumers.

flowchart LR
    A[Published referenced definition] --> B[Build reference graph]
    B --> C[Order consuming definitions]
    C --> D[Load or create consumer draft]
    D --> E[Replace referenced version]
    E --> F{Consumer was published?}
    F -- Yes --> G[Publish consumer version]
    F -- No --> H[Save consumer draft]

References: src/…/WorkflowReferenceUpdater.cs• L16-127 src/…/WorkflowReferenceUpdater.cs• L130-195 src/…/WorkflowReferenceUpdater.cs• L197-239

Definition import and export

Import flow

Import accepts a serializable workflow definition model and applies it to an existing logical definition when its DefinitionId is known. Without that ID, it starts a new logical definition. The import path updates the draft's graph and metadata, stores the imported graph as JSON, and removes an older file-source snapshot so the imported model is authoritative. It then saves the result as a draft unless the caller asks for publication.

Import returns the stored definition and any validation errors. API import also applies write permission checks and script authorization before it changes a definition. File import uses the same management boundary for JSON and ZIP workflow-definition files.

References: src/…/IWorkflowDefinitionImporter.cs• L7-16 src/…/WorkflowDefinitionImporter.cs• L11-82 src/…/SaveWorkflowDefinitionRequest.cs• L6-17 src/…/Endpoint.cs• L10-100

Export flow

Export maps a stored version to the public definition model so that another system can restore its workflow contract and graph. A single version is emitted as JSON with the workflow-definition schema marker. Multiple versions are emitted as a ZIP archive.

An export can include consuming workflows. The exporter follows the workflow reference graph and adds the latest version of each consumer. This makes the export useful when a workflow depends on other workflow definitions rather than standing alone.

References: src/…/IWorkflowDefinitionExporter.cs• L7-45 src/…/WorkflowDefinitionExporter.cs• L20-71 src/…/WorkflowDefinitionExporter.cs• L74-97 src/…/WorkflowDefinitionExporter.cs• L145-174 src/…/Endpoint.cs• L8-49

Definition lookup

Version selection

Callers select a definition with a WorkflowDefinitionHandle or a filter. A handle can point to a logical definition with a version rule or to one exact version ID. Version rules include latest, published, latest-or-published, draft, all versions, and a specific version.

The choice matters to downstream services. Runtime use normally needs a stable published version. Authoring needs a draft or latest version. History views need all versions. The same selection model is used by management services and API endpoints, so callers do not need separate lookup rules for each use case.

References: src/…/WorkflowDefinitionHandle.cs• L8-35 src/…/VersionOptions.cs• L15-65 src/…/WorkflowDefinitionFilter.cs• L13-109 src/…/Endpoint.cs• L19-39 src/…/List.cs• L20-39

Metadata queries

IWorkflowDefinitionStore provides one shared query boundary for full definitions, lightweight summaries, paged results, existence checks, distinct definition counts, and name-uniqueness checks. Filters can narrow results by identity, version rule, name or search text, materializer, system status, read-only status, and tenant scope.

The API exposes these queries through read-protected workflow-definition endpoints. List results use summaries and report whether the required materializer is available. A full definition or graph can then be requested when the caller needs its authoring or execution form.

References: src/…/IWorkflowDefinitionStore.cs• L8-203 src/…/WorkflowDefinitionSummary.cs• L11-109 src/…/Endpoint.cs• L13-85 src/…/StaticWorkflowDefinitionLinker.cs• L49-80

Definition storage

The store interface separates lifecycle services from persistence choice. It supports direct and batch writes, deletes, metadata queries, and conditional updates of the latest version. A conditional update loads the current definition, checks the caller's expected snapshot, and saves the replacement only when that snapshot is still current. This prevents one author from silently overwriting another author's change.

The conditional update returns one of three outcomes: Updated with the saved definition, NotFound when no definition matches, or Conflict when another writer changed the latest version first. When an update creates a new draft, the old latest version loses its latest flag in the same operation. Callers should treat the loaded definition as read-only and return a new or cloned definition from the update function.

The repository provides in-memory and EF Core-backed stores, and a cache decorator can sit in front of either store. Cache entries include the tenant and query inputs. Writes invalidate definition and summary results, and each tenant has a separate reconciliation token for refreshing a node's cached view. The in-memory store applies tenant visibility and version-key uniqueness while it performs conditional updates as one critical section.

Persistence keeps the workflow's state collections with the definition and restores them when a definition is read. This lets the management layer query stable metadata while the materializer handles the workflow graph itself. See persistence for the wider storage model.

References: src/…/IWorkflowDefinitionStore.cs• L107-163 src/…/WorkflowDefinitionUpdateResult.cs• L5-37 src/…/MemoryWorkflowDefinitionStore.cs• L97-153 src/…/CachingWorkflowDefinitionStore.cs• L14-21 src/…/CachingWorkflowDefinitionStore.cs• L101-169 src/…/WorkflowDefinitionStore.cs• L20-229

Workflow instance hand-off

Instance persistence boundary

Workflow instance management connects a selected definition version to the state of one running or completed workflow. IWorkflowInstanceManager can create an instance from a workflow state or execution context and save it through the instance store. Its direct create-and-commit operation is a low-level persistence path; it does not evaluate activation rules, so workflow start requests must use the workflow runtime APIs.

The instance record keeps the definition identity and version with execution state, status, correlation data, and time markers. This lets runtime services resume the correct definition version and lets management queries find instances by definition, status, correlation, execution state, incidents, or time.

References: src/…/IWorkflowInstanceManager.cs• L29-48 src/…/IWorkflowInstanceManager.cs• L101-119 src/…/WorkflowInstance.cs• L9-90 src/…/WorkflowInstanceFilter.cs• L41-129

Instance recovery state

The instance store is also the coordination boundary for marking a still-running instance as interrupted. The operation changes the instance to running with an interrupted sub-status and clears its executing marker only when the instance is visible to the current tenant and is not already finished. This protects a terminal completion from being replaced by a drain or recovery action.

The store exposes full instances, summaries, IDs, counts, ordered results, and writes through one contract. These views support runtime recovery and management queries without requiring callers to know which persistence provider is active.

References: src/…/IWorkflowInstanceStore.cs• L13-21 src/…/IWorkflowInstanceStore.cs• L61-130 src/…/IWorkflowInstanceStore.cs• L182-201

Tenant-scoped instance storage

Instance storage applies the current tenant to new records and limits reads and deletes to instances visible to that tenant. Tenant-agnostic instances remain outside that scope. The in-memory store follows the same visibility rule as the other instance-store contracts, so local use does not bypass tenant separation.

Its interrupt operation uses the same critical section as instance writes. It checks tenant visibility and terminal status before changing the state, so a concurrent natural completion cannot be overwritten by an interruption marker.

References: src/…/MemoryWorkflowInstanceStore.cs• L15-27 src/…/MemoryWorkflowInstanceStore.cs• L127-165 src/…/MemoryWorkflowInstanceStore.cs• L169-225 src/…/IWorkflowInstanceStore.cs• L182-201

API boundaries

Authoring interface

The workflow-definition API presents one resource for creating or saving a definition and separate operations for publication, retraction, version history, import, export, lookup, and graph access. Responses include definition metadata and links to the operations that apply to that definition.

Write operations require workflow-definition write permission. Read operations require read permission. Read-only and system definitions limit which changes the API exposes, while script authorization protects expressions embedded in an imported or saved model.

References: src/…/Endpoint.cs• L21-121 src/…/StaticWorkflowDefinitionLinker.cs• L120-166 src/…/Endpoint.cs• L11-33

Change checklist

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

  • Keep DefinitionId, version number, version Id, and latest or published flags aligned across the entity, public model, filters, and version operations.
  • Keep conditional latest-version updates atomic across every persistence provider. Preserve the Updated, NotFound, and Conflict outcomes so callers can distinguish a stale write from a missing definition.
  • Keep import and export mapping symmetric when adding workflow metadata or changing the source representation. Check OriginalSource, StringData, and the materializer name together.
  • When adding a materializer or changing its name, update registration and the API's materializer-availability behavior. Stored definitions with an old name cannot materialize until compatibility is restored.
  • When changing validation rules, preserve the publication contract that returns validation errors and honors the management policy for accepting them.
  • When changing store fields, update both persistence state serialization and state restoration. Query filters and summary projections must remain compatible with the stored fields.
  • When changing a definition write path, preserve cache invalidation and tenant-aware cache keys. A successful conditional update must invalidate the same cached views as other writes.
  • When changing workflow-definition activity handling, keep registry updates and tenant generation changes aligned for publish, retract, update, and delete notifications. Reconciliation must invalidate the tenant view before reading the authoritative store.
  • When changing registry generation storage, preserve tenant normalization and the meaning of IsShared. A local in-memory generation store is suitable for one node or tests, not for cross-node coordination.
  • When changing consumer references, review export dependency discovery and automatic reference propagation so a portable archive includes required definitions and consumers point to the intended published versions.
  • When changing instance creation, keep the low-level manager path separate from runtime activation. Direct persistence must not become an alternate start path that skips activation rules.
  • When changing instance storage, preserve tenant assignment and visibility for single and batch writes. The in-memory store must not expose one tenant's instances to another tenant.
  • When changing interruption handling, preserve the finished-state guard and the binary-compatible allowFinishedCancelled parameter. The operation must not overwrite a concurrent terminal commit.

Important failure modes

TriggerConsequenceGuard
A definition names an unregistered materializer.Full lookup can return an unprocessable result, and graph lookup cannot produce a workflow graph.Register the materializer before importing or loading the definition. Use the availability flag in summary results.
Publication finds validation errors and the management policy rejects them.The new version is not published. The caller receives the validation errors.Treat PublishWorkflowDefinitionResult as the publication decision, not as a best-effort save.
A conditional update uses an old expected snapshot.The latest definition is not overwritten, and the caller receives a conflict outcome.Reload the latest version and ask the author to merge or retry with a current snapshot.
A published definition is edited without creating a draft.Authoring could change the version that downstream runtime services use.Obtain a draft before applying author changes. The publisher creates a new draft for a published selection.
A workflow definition is deleted while it is published.Its published state is retracted before the version is removed.Use the manager's delete path so publication and version flags are repaired.
A stored state payload cannot be restored.Metadata collections fall back to default state and can be missing from the loaded definition.Keep the persistence state format compatible when changing options, variables, inputs, outputs, outcomes, or custom properties.
A caller creates an instance through the low-level manager path when it should start workflow execution.Activation rules are not evaluated, so the instance can bypass the normal runtime start decision.Use the workflow runtime start APIs for execution and reserve direct instance creation for persistence work.
A memory-store write has no tenant applied or a query skips tenant visibility.An instance can be assigned to the wrong tenant or become visible across tenant boundaries.Apply the current tenant to new records and use tenant-aware filtering for every read and delete.
An interruption marks an instance after it has finished.A terminal workflow can be changed back to running and appear recoverable when it is not.Check visibility and finished status inside the same lock as the state change.
A node keeps a cached definition view after another node changes a workflow used as an activity.Registry reconciliation can rebuild from stale data and leave the node with an old activity descriptor.Trigger the tenant reconciliation token before loading descriptors from the authoritative store.
A registry reconciliation replaces descriptors from a stale provider snapshot.A concurrent local add or removal can be undone by an older snapshot.Compare the registry mutation version under the registry lock and retry when it changed.
Registry changes advance only a local generation in a multi-node deployment.Other nodes do not receive a reliable signal to refresh their workflow-definition activity views.Use a shared generation store when nodes must coordinate; the memory store reports IsShared = false.

Key files

FileWhy to read it
src/…/WorkflowDefinition.csDefines the durable identity, version state, metadata, source data, and materializer contract.
src/…/WorkflowDefinitionPublisher.csShows the draft, publish, retract, and revert lifecycle.
src/…/WorkflowDefinitionService.csShows how lookup becomes materialization and a workflow graph.
src/…/WorkflowDefinitionImporter.csShows how an external model becomes a JSON-backed saved draft or published version.
src/…/WorkflowDefinitionExporter.csShows single-definition, archive, and consumer-aware export behavior.
src/…/WorkflowReferenceUpdater.csShows automatic version propagation from reusable definitions to JSON-authored consumers.
src/…/WorkflowDefinitionFilter.csDefines the shared identity, version, metadata, and tenant query language.
src/…/IWorkflowDefinitionStore.csDefines the persistence-independent query, write, and conditional update boundary.
src/…/WorkflowDefinitionUpdateResult.csDefines the outcomes that let callers handle saved, missing, and conflicting updates.
src/…/MemoryWorkflowDefinitionStore.csShows tenant-aware queries, version-key checks, and atomic in-memory updates.
src/…/CachingWorkflowDefinitionStore.csShows tenant-scoped query caching, write invalidation, and reconciliation tokens.
src/…/WorkflowDefinitionActivityRegistryUpdater.csShows how workflow-definition activities are added, removed, and reconciled from the authoritative store.
src/…/RefreshActivityRegistry.csShows which definition lifecycle changes update the activity registry and tenant generations.
src/…/IWorkflowDefinitionRegistryGenerationStore.csDefines the tenant-scoped generation contract used to signal registry changes across nodes.
src/…/MemoryWorkflowDefinitionRegistryGenerationStore.csShows the single-node generation store used by default for memory-backed operation and tests.
src/…/WorkflowDefinitionMapper.csExplains the boundary between stored definitions, source snapshots, public models, and executable workflows.
src/…/IWorkflowInstanceManager.csDefines the boundary between workflow state persistence and runtime activation.
src/…/IWorkflowInstanceStore.csDefines instance queries, persistence operations, and the guarded interruption contract.
src/…/WorkflowInstance.csShows how an execution record binds state and status to a definition version.
src/…/WorkflowInstanceFilter.csDefines the metadata and time-based query language for workflow instances.
src/…/MemoryWorkflowInstanceStore.csShows tenant-aware instance visibility, assignment, and atomic interruption handling.
src/…/Endpoint.csShows the main authoring API boundary and its permission checks.
src/…/WorkflowDefinitionStore.csShows the durable store and how definition state survives reads and writes.