Repository navigation
State Machine Deferring Events
A State can defer an event type while it is active. The event is held by the State Machine instead of being processed by the active configuration, then reconsidered when the configuration changes and the event is no longer deferred.
This is different from simply having no transition for an event: a matching deferral is checked before normal transition handling, and a true deferral prevents the current event from triggering a transition in that configuration.
sequenceDiagram
participant Caller
participant Machine as State Machine
participant Active as Active State configuration
Caller->>Machine: Send event
Machine->>Active: Evaluate matching deferral
Active-->>Machine: Defer
Machine-->>Caller: EventStatus.Deferred
Note over Machine: Retain event while any active state still defers it
Active->>Machine: State configuration changes
Machine->>Active: Re-evaluate queued event
Active-->>Machine: No longer deferred
Machine->>Active: Process event normally
Use AddDeferredEvent<TEvent>() in the state definition. When that state is active, incoming events of the registered type are deferred:
public sealed record Submit;
public sealed record PaymentReceived(string TransactionId);The following fragment belongs inside the relevant method or builder callback:
.AddInitialState("AwaitingSubmission", state => state
.AddDeferredEvent<PaymentReceived>()
.AddTransition<Submit>("Processing")
)
.AddState("Processing", state => state
.AddTransition<PaymentReceived>("Completed")
)
.AddState("Completed")If PaymentReceived arrives in AwaitingSubmission, the State Machine stores it and reports EventStatus.Deferred. When Submit moves the machine to Processing, the deferred event is re-evaluated; because that state no longer defers it, the event is dispatched through the normal transition logic and can move the machine to Completed.
Use AddDeferredEvent<TEvent, TDeferralGuard>() for a typed guard, or pass a builder action to AddDeferredEvent<TEvent>() to register guards explicitly. Lambda guards receive an IDeferralContext<TEvent> with the incoming Event, its EventId, headers, and the associated State context:
.AddState("AwaitingSubmission", state => state
.AddDeferredEvent<PaymentReceived>(defer => defer
.AddGuard(context =>
context.Event.TransactionId == "pending")
)
.AddTransition<PaymentReceived>("Reconciled")
)When the guard passes, the event is deferred even though this state also has a transition for that event type. If the guard does not pass, normal transition evaluation proceeds.
Implement IDeferralGuard<TEvent> to encapsulate a reusable deferral predicate.
As with a typed transition guard, its GuardAsync(TEvent) method receives the
event payload and returns Task<bool>. Here, true means defer the event,
not take a transition:
using System.Threading.Tasks;
using Stateflows.StateMachines;
public sealed class AwaitingSubmission : IState;
public sealed class Reconciled : IState;
public sealed class PaymentPending : IDeferralGuard<PaymentReceived>
{
public Task<bool> GuardAsync(PaymentReceived @event) =>
Task.FromResult(@event.TransactionId == "pending");
}This uses the PaymentReceived event declared above. Definition fragment:
.AddInitialState<AwaitingSubmission>(state => state
.AddDeferredEvent<PaymentReceived, PaymentPending>()
.AddTransition<PaymentReceived, Reconciled>())
.AddState<Reconciled>()The type-parameter order is event, deferral guard:
AddDeferredEvent<TEvent, TDeferralGuard>(). The guard must implement
IDeferralGuard<TEvent>, not merely ITransitionGuard<TEvent>. Deferring an
event has no transition effect or target state.
The overload registers the typed guard first, then invokes its optional builder callback to add further predicates:
.AddDeferredEvent<PaymentReceived, PaymentPending>(defer => defer
.AddGuard(context => context.Event.TransactionId.Length > 0))The callback-only form remains available when composing separate guards or configuring a guard instance:
.AddDeferredEvent<PaymentReceived>(defer => defer
.AddGuard<PaymentPending>())When the predicate does not depend on event data, implement the non-generic
IDeferralGuard and its parameterless GuardAsync() method:
using System.Threading.Tasks;
using Stateflows.StateMachines;
public sealed class SubmissionBlocked(IStateContext state) : IDeferralGuard
{
public async Task<bool> GuardAsync()
{
var (found, blocked) = await state.Values.TryGetAsync<bool>("submissionBlocked");
return found && blocked;
}
}Attach it in the same way:
.AddDeferredEvent<PaymentReceived, SubmissionBlocked>()This guard can be reused for different deferred event types. It reads a State-scoped Value each time it is evaluated, rather than capturing a snapshot of the flag.
IDeferralGuard<in TEvent> is contravariant, just like
ITransitionGuard<in TEvent>. A guard can consume an interface or base class
shared by several concrete event types:
using System.Threading.Tasks;
using Stateflows.StateMachines;
public interface IAwaitable
{
bool IsPending { get; }
}
public sealed record PaymentUpdate(bool IsPending) : IAwaitable;
public sealed record InventoryUpdate(bool IsPending) : IAwaitable;
public sealed class StillPending : IDeferralGuard<IAwaitable>
{
public Task<bool> GuardAsync(IAwaitable @event) =>
Task.FromResult(@event.IsPending);
}Inside a state's definition:
.AddDeferredEvent<PaymentUpdate, StillPending>()
.AddDeferredEvent<InventoryUpdate, StillPending>()The declarations still name concrete deferred event types. Reusing an interface-based guard does not broaden which events those declarations match.
One class may implement both IDeferralGuard<TEvent> and
ITransitionGuard<TEvent> when the same predicate is appropriate for both.
IStateMachineGuard<TEvent> is a convenience contract inheriting both;
IStateMachineGuard is its event-independent counterpart. Consider the meaning
of the result at each site: true enables deferral in one and a transition in
the other. Use AddNegatedGuard<TGuard>() when the opposite condition is needed.
Multiple guards on one deferral are combined with AND. Use
AddGuards<TGuard1, TGuard2>() for a typed conjunction or AddGuardExpression
for nested Boolean expressions, including OR. Typed guards can also be mixed
with lambda guards in those expressions.
As with transition guards, a typed deferral guard may implement
IConfigurable<TConfiguration> and receive per-use settings through
.AddGuard<TGuard>(guard => guard.AddConfiguration(value)).
IConfigurable<TConfiguration> is in Stateflows.Common; the
AddConfiguration extension is in Stateflows.Common.Interfaces.
Configuration is applied after construction and before GuardAsync runs.
Use the callback-only AddDeferredEvent<TEvent>(...) form for this configuration:
the callback on AddDeferredEvent<TEvent, TDeferralGuard>(...) configures the
deferral builder, not the already registered guard instance. Adding the same
guard again there registers a second predicate rather than configuring the first.
Deferral guards can constructor-inject application services, IStateContext,
IStateMachineContext, and common behavior/execution contexts. Unlike transition
guards, they have a current state and no ITransitionContext: no transition has
been selected. The typed event is supplied to GuardAsync, while
Stateflows.Common.IExecutionContext supplies execution headers and cancellation.
See Dependency Injection.
Keep guards free of business side effects: a queued event may be evaluated repeatedly before it is released. Use injected services or current Values/Entity reads for conditions, but perform business updates through the appropriate operation after normal event processing resumes.
Deferrals are collected from the active state tree, including active ancestor states and active states in orthogonal regions. If any matching active deferral passes its guard, the event remains deferred. After a later non-deferred event is processed, queued events are checked again against the then-current active deferrals; an event still deferred by another active state stays queued. A configuration change commonly releases an event, but a transition is not required: a later event can cause the machine to re-evaluate the queue against the same configuration.
When an event is no longer deferred, Stateflows reprocesses it as a normal incoming event, so its transitions, guards, and effects are evaluated against the then-current configuration. Applications should therefore make transitions safe for the state in which a deferred event may eventually be replayed.
Stateflows does not allow deferring Completion, Finalize, or time events. Duplicate deferral declarations for the same event on one state are definition errors. Deferral is not an acknowledgment or successful business operation: EventStatus.Deferred means the State Machine accepted the event for later processing, not that a transition consumed it. A deferred event may later be consumed or remain deferred depending on subsequent configurations.
For the builder surface and complete examples, see State. For event-triggered transitions, see Transitions.
Home page Support Code licensed under an MIT-style License. Documentation licensed under CC BY 4.0. © by Mikołaj Milewski, 2026
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