Introduction
MassTransit saga state machines help developers coordinate long-running business workflows across multiple services. They are commonly used for order processing, payment collection, inventory reservation, shipment management, customer onboarding, and other processes that involve several independent operations.
A saga is not a short-lived operation that starts and finishes within a single HTTP request. It may remain active for several minutes, hours, or even days while waiting for messages from other services. During that time, the application responsible for processing the saga may need to be updated, restarted, or deployed with a new version.
This creates an important deployment challenge.
Imagine an order-processing application that has 10,000 active saga instances. The current application version uses three states: Submitted, PaymentProcessing, and Completed. A new release introduces an additional InventoryReserved state and changes the payment workflow.
The deployment may appear successful because the new application starts without errors. However, existing saga instances were created using the previous workflow definition. Some may still be waiting for messages that the new version handles differently. Others may contain state values or business properties that the new version no longer expects.
A deployment that ignores these existing workflows can cause messages to be rejected, saga instances to become stuck, or business operations to execute incorrectly.
This is why saga deployments require more planning than ordinary application deployments.
In this article, we will explore how to update MassTransit saga applications safely. We will cover message contract compatibility, state machine changes, database migrations, rolling deployments, in-flight workflow handling, and practical deployment strategies for production systems.
Why Saga Deployments Are Different
In a typical web application, a deployment replaces the application code with a newer version. Existing HTTP requests usually finish using the old application instance, while new requests are handled by the new version.
A saga works differently because its state survives beyond the lifetime of an application instance.
For example, consider an order saga that starts on Monday and waits for a payment confirmation. The application may be deployed several times before that confirmation arrives on Wednesday.
The saga instance remains in the database throughout those deployments. When the payment confirmation eventually arrives, the currently running application version processes it.
This means that the new application version must understand the state and messages produced by earlier versions.
Several areas need attention:
Message contracts: Existing messages may still be stored in queues or delivered by other services.
Saga state: Existing database records may contain states and properties created by an older application version.
State machine behavior: A new version may handle events differently from the version that created the saga.
Database schema: New properties or changed mappings may require database migrations.
Deployment timing: Old and new application instances may run simultaneously during a rolling deployment.
External dependencies: Other services may continue publishing messages using the previous contract version.
A safe deployment must consider all these areas together.
Understanding In-Flight Saga Instances
An in-flight saga instance is a workflow that has started but has not yet reached its intended completion point.
Consider the following order-processing workflow:
Order Submitted
|
v
Inventory Reserved
|
v
Payment Processing
|
v
Shipment Created
|
v
Order Completed
Suppose the application currently has 5,000 orders in PaymentProcessing when a new release is deployed.
The new release introduces a fraud-verification step:
Order Submitted
|
v
Inventory Reserved
|
v
Fraud Verification
|
v
Payment Processing
|
v
Shipment Created
|
v
Order Completed
New orders should follow the updated workflow. However, the existing 5,000 orders have already passed inventory reservation and are waiting for payment processing.
The application must decide how to handle them.
There are several possible approaches:
Allow existing workflows to continue using compatible behavior while new workflows use the updated process.
Migrate existing saga instances into the new workflow state when a safe mapping exists.
Complete existing workflows using the old process before introducing the new behavior.
Run separate workflow versions when the old and new processes must coexist independently.
The correct approach depends on the business requirements. The important point is that existing saga instances should never be assumed to have the same history as newly created instances.
Keeping Message Contracts Backward Compatible
Message contracts define the communication structure between services. In MassTransit, messages are represented by .NET classes, records, or interfaces.
When one service publishes a message, another service may consume it immediately or much later. The consumer must be able to understand the message structure that was published.
This becomes important during deployments because different service versions may run at the same time.
Consider the original OrderSubmitted contract:
namespace OrderManagement.Contracts;
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber,
decimal Amount);
The application later needs to capture the customer's delivery preference.
A simple backward-compatible change is to add an optional property:
namespace OrderManagement.Contracts;
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber,
decimal Amount)
{
public string? DeliveryPreference { get; init; }
}
The new application can read DeliveryPreference when it is available. Messages produced by older applications may not contain this property.
The application should therefore handle the missing value safely.
For example:
var preference =
context.Message.DeliveryPreference ?? "Standard";
This approach is useful when the message serializer and all participating consumers can handle the additive change.
However, adding a property is not automatically safe in every situation. Compatibility depends on the serializer, message contract type, required fields, and how existing consumers process missing values.
Test the old and new contract versions together before deploying the change.
Avoid Renaming Existing Message Properties
Suppose the original contract contains:
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber);
A new release changes OrderNumber to ReferenceNumber:
public record OrderSubmitted(
Guid CorrelationId,
string ReferenceNumber);
This can break existing consumers because they expect the original property name.
A safer approach is to introduce the new property while retaining the old one during a transition period.
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber)
{
public string? ReferenceNumber { get; init; }
}
During the transition, producers can populate both properties. Consumers can prefer ReferenceNumber when available and fall back to OrderNumber.
Once all producers and consumers have been updated, the old property can be removed through a separate contract migration.
This approach is commonly called an expand-and-contract change. It avoids requiring every service to be deployed at exactly the same time.
Avoid Changing Message Namespaces Without a Migration Plan
MassTransit uses message type information that includes the message's namespace and type name.
For example, these are different message types:
namespace OrderManagement.Contracts;
public record OrderSubmitted(Guid CorrelationId);
namespace OrderManagement.Contracts.V2;
public record OrderSubmitted(Guid CorrelationId);
Even though both records have the same class name and property, they have different type identities.
Changing a namespace or message type name can affect message routing and consumer compatibility. It should not be treated as a simple code organization change.
If a new contract is required, introduce it intentionally and configure the communication between the old and new versions.
Introducing Versioned Message Contracts
Sometimes a message needs a major structural change that cannot be handled safely through optional properties.
For example, the old contract may contain a single Amount property, while the new business process requires separate currency and payment details.
Instead of changing the old contract in place, introduce a new contract version.
namespace OrderManagement.Contracts.V1;
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber,
decimal Amount);
The new contract can contain the additional information:
namespace OrderManagement.Contracts.V2;
public record OrderSubmitted(
Guid CorrelationId,
string OrderNumber,
decimal Amount,
string Currency,
string PaymentMethod);
The application can temporarily support both versions.
For example, a compatibility consumer can receive the old contract and convert it into an internal application command or the new contract.
using MassTransit;
using OrderManagement.Contracts.V1;
using OrderManagement.Contracts.V2;
public class OrderSubmittedV1Consumer :
IConsumer<OrderSubmitted>
{
public async Task Consume(
ConsumeContext<OrderSubmitted> context)
{
var oldMessage = context.Message;
var newMessage =
new OrderManagement.Contracts.V2.OrderSubmitted(
oldMessage.CorrelationId,
oldMessage.OrderNumber,
oldMessage.Amount,
"USD",
"Default");
await context.Publish(newMessage);
}
}
This example illustrates a compatibility adapter. In a real application, use explicit type aliases or fully qualified names because both contracts contain a type named OrderSubmitted.
The adapter converts the old message into the new representation. The new workflow can then process the versioned contract without requiring every existing producer to change immediately.
There are several important considerations.
First, do not assume that the example's default currency or payment method is correct for every business. A conversion must use valid business rules. If the old message does not contain enough information to construct a valid new message, the application must retrieve that information from an authoritative source or reject the migration.
Second, avoid allowing multiple producers to publish both versions independently without a clear ownership and routing strategy. Otherwise, the same business operation may be processed twice.
Third, define a retirement plan for the old contract. Compatibility code should not remain indefinitely without an owner or migration deadline.
Managing State Machine Changes Safely
Message compatibility is only one part of saga deployment. The state machine itself may also change.
Consider an existing state machine:
public class OrderStateMachine :
MassTransitStateMachine<OrderState>
{
public State Submitted { get; private set; } = null!;
public State Processing { get; private set; } = null!;
public State Completed { get; private set; } = null!;
public OrderStateMachine()
{
InstanceState(x => x.CurrentState);
// Event and state behavior configuration
}
}
The new version introduces a ReviewPending state.
public State ReviewPending { get; private set; } = null!;
Adding a new state is not necessarily a problem for existing records. However, developers must understand how existing saga instances will behave after the deployment.
For example, an existing saga may still be in Processing. The new state machine must continue handling the events that are valid for that state.
If the new implementation removes the Processing behavior or changes its meaning, old workflows may become stuck.
Keep Existing State Behavior During the Transition
When introducing a new state, retain the existing state definitions and event behavior until all affected saga instances have been handled.
For example, the updated state machine might allow both the old and new paths:
Initially(
When(OrderSubmitted)
.Then(context =>
{
context.Saga.OrderNumber =
context.Message.OrderNumber;
})
.TransitionTo(ReviewPending)
);
During(Processing,
When(PaymentCompleted)
.TransitionTo(Completed)
);
During(ReviewPending,
When(ReviewApproved)
.TransitionTo(Processing)
);
This is only a simplified illustration. A complete implementation must define the relevant events, correlation rules, and behavior for all active states.
The important principle is that existing saga instances must continue to have valid event-handling paths after the deployment.
Be Careful When Renaming States
Saga state is persisted as part of the saga instance. Depending on the repository and state property mapping, the stored state may be represented by a state name or another configured representation.
Suppose the existing state is named PaymentProcessing, and the new application renames it to PaymentPending.
The new application may not recognize existing records that still contain the previous state value.
Instead of renaming a persisted state directly, consider retaining the old state and transitioning existing instances into the new state through a controlled migration.
A database migration or application-level migration may be appropriate, but it must be designed around the actual persistence provider and state mapping.
Never assume that changing a property name or state name in C# automatically updates existing saga records correctly.
Treat Finalization Carefully
MassTransit state machines have a built-in Final state. A workflow that has completed should transition to Final when the instance is ready to be finalized.
For example:
During(Processing,
When(PaymentCompleted)
.Publish(context =>
new OrderCompleted(
context.Saga.CorrelationId))
.Finalize()
);
SetCompletedWhenFinalized();
This configuration marks the saga as completed and allows the repository to remove finalized instances according to its configured behavior.
During a deployment, changing when a saga is finalized can have important consequences. If older versions remove completed instances but newer versions need them for additional processing, the workflow design must be reviewed before changing the finalization behavior.
If completed workflow information is required for reporting or audit purposes, store it in an appropriate business or audit data store rather than depending on a finalized saga instance remaining permanently available.
Applying Database Migrations Without Breaking Active Sagas
Saga state is stored in a repository, so changes to the saga model may require database schema changes.
Consider the existing saga class:
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public string OrderNumber { get; set; } = string.Empty;
}
The new version adds a PaymentReference property.
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public string OrderNumber { get; set; } = string.Empty;
public string? PaymentReference { get; set; }
}
The new application expects the database to contain the PaymentReference column.
If the application is deployed before the database migration is applied, saga persistence may fail when it tries to read or write the new property.
A safer deployment uses an expand-and-contract database migration.
Expand Phase
First, add the new column without removing or changing existing columns.
For example, an Entity Framework Core migration might contain:
migrationBuilder.AddColumn<string>(
name: "PaymentReference",
table: "OrderState",
type: "nvarchar(100)",
maxLength: 100,
nullable: true);
The new column is nullable so existing saga records remain valid.
The old application can continue working because it does not depend on the new column.
Application Deployment Phase
Deploy the new application version after the database schema has been expanded.
The new application can read and write PaymentReference while existing saga instances continue using their previous data.
If the new property is required for all workflows, the application should handle records where the property is still null.
For example, an existing workflow may need to retrieve the payment reference from the payment service before continuing.
Data Backfill Phase
If existing saga records need a value for the new property, populate it through a controlled backfill process.
A backfill may retrieve the payment reference from another database or service and update the saga record.
Do not populate business-critical values with arbitrary defaults simply to satisfy a non-null database constraint.
Contract Phase
After all application versions and workflows no longer depend on the old schema, remove obsolete columns or constraints through a separate migration.
This final phase should happen only after verifying that old application instances, background jobs, and compatibility consumers no longer require the previous schema.
The expand-and-contract approach is safer than combining column removal, renaming, and application changes into a single deployment.
Handling Rolling Deployments
A rolling deployment gradually replaces old application instances with new instances.
For example, an application may run four instances behind a load balancer. During deployment, the platform updates one instance at a time while the remaining instances continue processing messages.
This approach reduces downtime, but it introduces a compatibility challenge for saga applications.
For example:
Instance A runs version 1.
Instance B runs version 1.
Instance C runs version 2.
Instance D runs version 2.
Both versions may receive messages for the same saga endpoint.
If the old and new versions have different state-machine behavior, the same saga instance could be processed differently depending on which version receives the message.
This is particularly dangerous when one version understands a new state or contract while another version does not.
Keep Mixed Versions Behaviorally Compatible
During a rolling deployment, the old and new application versions should be compatible with the same message contracts and persisted saga states.
A safe rolling deployment usually follows these principles:
Add database changes before deploying code that requires them.
Keep existing message properties available.
Retain behavior for states that may exist in the database.
Avoid changing message routing unexpectedly.
Do not remove old event handlers while old messages may still arrive.
Verify that both application versions can safely process the same supported messages.
If the state machine behavior changes significantly, simply running both versions against the same queue may not be safe.
Use Versioned Endpoints When Workflows Must Be Isolated
Sometimes the new workflow cannot safely coexist with the old workflow.
For example, version 1 may process payments through an old provider, while version 2 uses a completely different payment process.
In that situation, separate endpoints or queues may be appropriate.
The architecture could look like this:
Order Submission
|
-----------------------
| |
v v
Workflow V1 Workflow V2
| |
Old Payment New Payment
| |
v v
Old Shipment New Shipment
New orders can be routed to the new workflow, while existing orders continue through the old workflow.
This requires an explicit routing strategy. The application must know which workflow version owns each order, and subsequent messages must be delivered to the correct endpoint.
For example, a saga instance can store a WorkflowVersion property:
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public string OrderNumber { get; set; } = string.Empty;
public int WorkflowVersion { get; set; }
}
When the saga starts, the application records the workflow version:
Initially(
When(OrderSubmitted)
.Then(context =>
{
context.Saga.OrderNumber =
context.Message.OrderNumber;
context.Saga.WorkflowVersion = 2;
})
.TransitionTo(Submitted)
);
This property can help the application identify the workflow version associated with an order.
However, storing a version number alone does not automatically create separate state-machine behavior. The application must explicitly implement the required routing and state-handling rules.
For workflows with substantially different behavior, separate state machines and endpoints may be easier to maintain than one large state machine containing many version-specific conditions.
Draining Messages Before Deployment
Another useful deployment strategy is to drain or pause message processing before replacing an application version.
A controlled deployment might follow these steps:
Stop accepting new work for the affected workflow.
Allow currently executing message operations to finish.
Check whether messages remain in the queue.
Verify that important in-flight workflows have reached safe checkpoints.
Deploy the new application version.
Resume message processing.
Monitor message failures, saga errors, and workflow progress.
Draining messages can reduce the chance of old and new application versions processing the same workflow during a transition.
However, it is not always practical to wait until every saga instance completes. Some workflows may remain active for days because they depend on customer approvals or external services.
In such cases, the application needs backward-compatible state-machine behavior or an explicit migration strategy.
Also, pausing consumers does not necessarily stop producers from publishing new messages. A deployment plan must account for message arrival from other services and the broker's delivery behavior.
Creating a Controlled Saga Migration Process
When a new version changes the meaning or structure of persisted saga state, a migration may be required.
Consider an existing workflow with these states:
Submitted
Processing
Completed
The new version introduces:
Submitted
InventoryReserved
PaymentProcessing
Completed
Existing instances in Processing may need to be mapped into one of the new states.
Before migrating them, determine what Processing meant in the old workflow.
If it represented an order with reserved inventory and pending payment, it may be possible to map it to PaymentProcessing.
However, if the old state did not record whether inventory was reserved, the migration cannot safely assume that inventory reservation has completed.
A migration should use authoritative business information to determine the correct state.
Identify the Affected Saga Instances
Start by identifying the records that require migration.
For example, query saga instances using their current persisted state.
SELECT
CorrelationId,
CurrentState,
OrderNumber
FROM OrderState
WHERE CurrentState = 'Processing';
The actual table and state-column names depend on the Entity Framework mapping and database configuration.
This query is only an example. Confirm the generated database schema before running migration queries.
Define Explicit State Mapping Rules
Create a documented mapping between old and new states.
Old state | New state | Migration condition |
|---|
Submitted | Submitted | No change required |
Processing | PaymentProcessing | Inventory reservation is confirmed |
Processing | InventoryReserved | Payment has not started |
Completed | Completed | No change required |
The conditions in this table are business-specific. A migration should not assign a new state based only on the old state name if the old workflow did not record enough information.
Perform the Migration Safely
For a small number of records, an application-level migration service may be appropriate.
For larger datasets, a controlled database migration or background migration job may be more practical.
The migration process should:
Process records in manageable batches.
Avoid changing saga instances while they are actively being processed.
Use transactions where appropriate.
Record which instances were migrated.
Be safe to resume after an interruption.
Validate the resulting state before allowing further processing.
Avoid directly modifying saga state records while application instances are consuming messages unless the migration process has a clear concurrency and coordination strategy.
A database update that changes CurrentState without considering the state machine's business rules can create a workflow that appears valid in the database but cannot complete correctly.
Testing Deployment Compatibility
Before deploying a new saga version, test it against data and messages created by the previous version.
A normal unit test verifies the behavior of the new state machine. A deployment compatibility test verifies that the new state machine can continue processing existing workflows.
These tests should cover several scenarios.
Test Old Messages With New Consumers
Create a message using the old contract shape and verify that the new consumer can process it.
For example, if DeliveryPreference was added as an optional property, verify that the new consumer handles messages where it is missing.
Test Existing Saga States
Create saga instances that represent every important state from the previous release.
Then deliver the events that those instances are expected to receive.
Verify that the new state machine can process them and reach the correct outcome.
Test New Messages With Compatible Consumers
If the deployment includes a rolling upgrade, verify that older consumers can safely handle the messages produced by the new application.
If they cannot, do not assume that a rolling deployment is safe. Introduce a compatibility adapter, versioned contract, or isolated endpoint.
Test Database Migration and Rollback
Apply the migration to a database containing representative saga records.
Verify that existing instances remain readable and that the new application can update them.
Also test the rollback plan. A database migration may not be reversible after new application code starts writing data in the new format.
A safer approach is to keep database changes backward compatible until the application rollout is complete.
Test In-Flight Workflow Completion
Create a saga instance using the old workflow, persist it, and then start the new application version.
Publish the next expected event and verify that the workflow continues correctly.
This is one of the most valuable deployment tests because it directly represents what happens when a production application is upgraded while business workflows are still active.
Practical Deployment Checklist
Before deploying a new MassTransit saga version, review the following areas.
Message Contracts
Existing message namespaces and type names remain compatible.
New properties are handled safely when missing.
Required contract changes have an explicit versioning plan.
Old messages can still be consumed during the transition.
Producers and consumers have a coordinated retirement plan for old contracts.
Saga State Machine
Existing persisted states are still recognized.
Existing events continue to have valid behavior.
New states have clear entry and exit conditions.
Finalization behavior has been reviewed.
In-flight workflows have a documented migration or compatibility strategy.
Database
Required columns are added before the new application depends on them.
Existing saga records remain readable.
Data backfills use valid business information.
Database migrations are tested against realistic data.
Schema rollback limitations are understood.
Deployment
Old and new instances can safely process the supported messages during rollout.
Endpoint and queue routing changes are intentional.
Message consumers can be paused or drained when necessary.
In-flight workflows are monitored after deployment.
A rollback plan exists for application and database changes.
Common Deployment Mistakes to Avoid
Removing Old Event Handlers Too Early
An older saga instance may still be waiting for an event handled by the previous state machine version.
Removing that behavior can leave the workflow unable to progress.
Retain compatible event handling until affected workflows have completed or been migrated.
Renaming Persisted States Without Migrating Records
Changing a state name in C# does not automatically update existing database records.
If the new application cannot recognize the stored state, messages may fail to update the saga.
Use a controlled migration or retain the old state during the transition.
Deploying a New Database Schema After the Application
If the new application expects a column that does not yet exist, saga persistence can fail immediately.
Apply backward-compatible schema changes before deploying code that depends on them.
Assuming Rolling Deployment Is Always Safe
Running old and new versions simultaneously can cause inconsistent behavior when they implement different state-machine rules.
Ensure that both versions can safely process the same messages and persisted states before using a rolling deployment.
Deleting Old Messages Without Investigation
A message that appears outdated may still be required to complete an in-flight business workflow.
Inspect the affected messages and saga instances before purging queues or deleting stored data.
Changing Workflow Behavior Without Testing Existing Records
Testing only newly created saga instances is not sufficient.
Always include tests that start from states created by the previous application version.
Conclusion
Deploying MassTransit saga applications requires careful planning because saga instances can remain active across multiple application releases. A new version must understand the messages, persisted states, and business progress created by previous versions.
Backward-compatible message contracts, controlled state-machine changes, expand-and-contract database migrations, and carefully planned rolling deployments help prevent problems with in-flight workflows.
For small changes, maintaining compatibility with existing messages and saga states may be sufficient. For major workflow changes, separate workflow versions or a controlled migration process may be more appropriate.
The most important practice is to treat persisted saga state as long-lived business data rather than temporary application information. Before deploying a new version, verify that existing workflows can continue, new workflows can start correctly, and database changes do not make older records unusable.
A deployment is successful only when both new and existing business workflows continue to behave correctly after the application has been updated.
Join the conversation! Your thoughts help the community grow.