Skip to content

Orleans Runtime

Mikołaj Milewski edited this page Oct 27, 2026 · 1 revision

Orleans Runtime

Every Stateflows host must configure a runtime; registering services and behavior definitions alone is not sufficient. Stateflows.Runtimes.Orleans is the supported distributed runtime for Microsoft Orleans silos and is the recommended choice for new applications. The core package still contains a transitional in-process Legacy runtime, but it is scheduled for removal; Orleans is intended to be the only runtime thereafter. Configure exactly one runtime per host. State Machines, Activities, Actions, and Entities use the same Orleans grain contract; a behavior instance is addressed by its tenant and BehaviorId, so applications do not generate a separate Orleans grain type for every behavior definition.

Register behavior definitions and the runtime

Install Stateflows.Runtimes.Orleans, register definitions with builder.Services.AddStateflows(...), and add the runtime to the Orleans silo builder with AddStateflowsRuntime(). Do not call AddLegacyRuntime() in this host:

using Orleans.Hosting;
using Stateflows;
using Stateflows.StateMachines;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddStateflows(stateflows => stateflows
    .AddStateMachines(machines => machines
        .AddStateMachine<Order>()));

builder.Host.UseOrleans(silo => silo
    .UseLocalhostClustering()
    .AddMemoryGrainStorageAsDefault()
    .UseInMemoryReminderService()
    .AddStateflowsRuntime());

using var host = builder.Build();
await host.RunAsync();

The Orleans package is published as Stateflows.Runtimes.Orleans and provides the silo integration. The application still registers behavior definitions through the usual Stateflows builders. Configure a cluster, Orleans grain storage, and an Orleans reminder service as required by your deployment; the in-memory providers above are suitable only for development or tests.

Storage and reminders

Behavior state is owned by its Orleans behavior grain. The runtime does not use a separate Stateflows storage provider to hydrate or dehydrate behavior contexts. Persistent state is stored using Orleans grain storage and includes behavior context, pending time events, event receipts and publication outbox, notification history/subscriptions/deliveries, and the behavior instance index.

The runtime requires both an Orleans grain storage provider and a reminder service/table. If AddStateflowsRuntime is called without a StorageProviderName, it uses Orleans' default grain storage provider. To select a named provider, register that Orleans provider and set the exact name in runtime options:

builder.UseOrleans(silo => silo
    .AddAdoNetGrainStorage("workflow-storage", options =>
    {
        options.Invariant = "Microsoft.Data.SqlClient";
        options.ConnectionString = connectionString;
    })
    .UseAdoNetReminderService(options =>
    {
        options.Invariant = "Microsoft.Data.SqlClient";
        options.ConnectionString = connectionString;
    })
    .AddStateflowsRuntime(options =>
        options.StorageProviderName = "workflow-storage"));

Reminder storage is configured through Orleans separately from StorageProviderName. An explicit storage provider name must be nonempty and is not silently replaced with the default. Configure storage and reminders before starting the silo; runtime configuration validation reports missing providers during startup. Keep provider selection consistent across silos. Switching providers or renaming persisted state does not migrate existing records.

Use durable storage and a durable reminder table in production. The memory providers lose their data when their silo shuts down. For safe failover, use a grain storage provider that supports ETag-based concurrency, so an activation from a failed silo cannot overwrite state committed by its replacement.

Behavior hosting, tenant identity, and startup

Each behavior grain is identified by tenant plus BehaviorId. Different silos may register different behavior classes, but definitions must be fixed before the silo starts; adding or changing definitions at runtime is not supported. Behavior code is not distributed by Orleans runtime registration: each silo must deploy compatible assemblies, dependencies, and event/response types for any behavior definitions it hosts.

Default instances are initialized for configured tenants when their hosting silo starts. Orleans hosting does not automatically dispatch the shared Startup event and does not use startup-triggered context scanning or startup indexes. The Startup event remains available for explicit use; legacy startup-index data is unused by this runtime.

The IStateflowsStorage bridge is intentionally grain-scoped: reading or writing behavior contexts outside their owning behavior grain is unsupported. For discovery, use GetAllContextIdsAsync and then interact with each behavior by sending events or requests, rather than trying to retrieve its in-memory context.

Cluster discovery and placement

Silos advertise the behavior classes and definition versions they host. Each silo discovers the capabilities of active silos asynchronously and refreshes them periodically. Locators can therefore take a short time to discover newly started remote definitions; discovery is eventually consistent, and failed capability reads are retried.

Orleans placement is filtered so behavior activations land only on silos that host that behavior class. During rolling upgrades, silos that host every registered definition version are preferred, allowing existing instances to run their persisted version while new instances use the newest version. If no silo hosts every version, the runtime logs an incompatible-deployment warning and places on silos hosting the newest version. If a persisted version is not registered on the selected silo, that activation fails explicitly instead of running under a different version.

When no active silo is known to host a behavior class, sends fail with an error indicating that no eligible silo hosts the behavior. Its persisted state is left intact; the behavior can become available again when a hosting silo returns. Remote behavior discovery does not verify that same-named definitions with the same version have compatible code or schemas.

Scheduling, notifications, and resource limits

Stateflows time events use Orleans reminders; behavior state does not need to be periodically scanned by a separate Stateflows scheduler. Durable notification delivery and retries also use Orleans-backed state and reminders.

AddResource(...).SetMaxConcurrentBehaviorExecutions(...) and SetResourceName(...) are enforced independently on each silo across the instances and behavior classes assigned to that resource. Executions awaiting another behavior retain their permit; awaited dependency chains should use separate resources or enough capacity to avoid permit exhaustion. Optional queue-length and wait-time limits can shed load before permit waiters accumulate.

An execution rejected by admission limits, or arriving while the silo is stopping, returns EventStatus.Overloaded. It is not executed, committed, or recorded as received, so a caller may retry. Reminder-driven work treats overload as retryable. On graceful shutdown, waiting executions are rejected and already-running executions are allowed to finish and commit, bounded by the host's shutdown timeout. Abrupt process termination cannot drain in-flight work.

Observability

Stateflows.Extensions.OpenTelemetry integrates the runtime with OpenTelemetry. It exports per-resource behavior execution counts, durations, running and waiting gauges, as well as the Stateflows.Orleans meter for persistence, reminder, index, publication, discovery, and admission failures. Configure exporters through the application's OpenTelemetry setup. The waiting gauge counts work waiting for a local Stateflows resource permit; it is not Orleans mailbox depth, which should be monitored through Orleans' own metrics.

See the OpenTelemetry guide for instrumentation setup and the runtime source for Orleans-specific implementation details.

Overview
Installation
Runtimes
   Orleans runtime
Concepts
   Events and Structural Events
   Messaging Patterns
   Validation
   Scheduling
   Observability
Behaviors
   Behavior Values
   Dependency Injection
   Behavioral Groups
   State Machines
       Concepts
           State Identity
           In-State Event Deferrals
           Evaluation of Transitions
           Exception Handling
       Building blocks
           Regions
           States
               State
               Composite State
               Orthogonal State
               Final State
           Pseudostates
               Choice
               Junction
               Fork
               Join
               History
           Transitions
               Transition
               Default Transition
               Internal Transition
   Activities
       Concepts
           Exception Handling
           Implicit Fork and Join
           Tokens
       Building blocks
           Nodes
               Action Node
               Decision Node
               Merge Node
               Initial Node
               Final Node
               Input Node
               Output Node
               Fork Node
               Join Node
               Accept Event Action Node
               Send Event Action Node
               Publish Event Action Node
               Time Event Action Node
               Data Store Node
               Structured Activity Node
               Iterative Activity Node
               Parallel Activity Node
           Flows
               Data Flow
               Control Flow
   Actions
   Entities
       Fields
       Mutations
       Projections
Extensions
   ClearScript
   FluentValidation
   JSON definitions
   Minimal APIs
   OneOf
   OpenTelemetry
   PlantUML
   Scheduling

Clone this wiki locally