Introduction
Business workflows rarely follow the same path for every request. A simple purchase request may need approval from a department manager, while a high-value purchase may require additional approval from finance. A customer support request may go directly to a technical team, while another request may need to pass through billing or security first.
These differences make workflow routing an important part of enterprise application development. Instead of defining one fixed sequence of operations, an application should be able to select the next step based on the request data, business rules, customer information, or the result of an earlier operation.
This approach is known as dynamic workflow routing.
In a message-driven application, dynamic routing becomes more challenging because different services may be responsible for different steps. The application must decide which service should receive a message, remember which route was selected, handle failures, and continue the workflow when a response arrives.
MassTransit Sagas provide a useful way to coordinate these long-running processes. A saga stores the current workflow state and reacts to messages as the process moves between services. Instead of keeping the entire workflow inside one API request, the application can process each step independently.
In this article, we will build a dynamic order-processing workflow using ASP.NET Core, MassTransit, RabbitMQ, and Entity Framework Core. The application will select different processing routes based on order information, send messages to the appropriate services, and continue the workflow based on their responses.
Understanding Dynamic Workflow Routing
Dynamic workflow routing means selecting the next operation or service at runtime instead of following a fixed sequence.
Consider an e-commerce application that receives orders from different customers. The application may use the following rules:
Order condition | Processing route |
|---|---|
Standard order | Inventory and payment |
High-value order | Risk verification, inventory, and payment |
International order | Customs validation, inventory, and payment |
High-risk international order | Risk verification, customs validation, inventory, and payment |
A traditional workflow might always execute the same sequence:
Order Submitted
|
v
Risk Verification
|
v
Customs Validation
|
v
Inventory Check
|
v
Payment Processing
|
v
Order CompletedThis design works, but it performs unnecessary operations for orders that do not require them. A domestic standard order should not need customs validation. A low-value order may not need additional risk verification.
With dynamic routing, the application evaluates the order and selects the required steps.
For example, a standard domestic order may follow this route:
Order Submitted
|
v
Inventory Check
|
v
Payment Processing
|
v
Order CompletedA high-value international order may follow a different route:
Order Submitted
|
v
Risk Verification
|
v
Customs Validation
|
v
Inventory Check
|
v
Payment Processing
|
v
Order CompletedThe important difference is that the workflow is selected using business information available when the order is submitted.
Why Use MassTransit Sagas for Dynamic Routing?
A simple routing decision can be implemented using conditional statements in an API or message consumer. However, a business workflow may involve several services, long processing times, and multiple asynchronous responses.
For example, risk verification may take a few seconds, while customs validation may take several minutes. Inventory and payment services may also experience temporary failures.
If all the logic is placed inside one consumer, the implementation can become difficult to maintain. The consumer must understand every possible route, track completed operations, and determine what to do after each failure.
A MassTransit saga separates workflow coordination from individual business operations.
The saga is responsible for:
Determining which workflow route should be followed.
Storing the selected processing steps.
Tracking the current step.
Publishing messages to the required services.
Receiving responses from those services.
Moving to the next step.
Handling failures and cancellation.
Recording the final workflow status.
Each service remains responsible for its own business operation. The risk service verifies an order, the customs service validates international shipping information, the inventory service checks stock, and the payment service processes the payment.
This separation allows each service to be developed, deployed, and maintained independently.
Designing the Order Processing Architecture
Our example will contain the following components.
ASP.NET Core API receives new orders.
Workflow routing service determines the required processing steps.
MassTransit saga manages the order-processing lifecycle.
Risk verification consumer checks high-value or suspicious orders.
Customs validation consumer checks international orders.
Inventory consumer verifies product availability.
Payment consumer processes the payment.
Entity Framework Core stores the saga state.
RabbitMQ transports messages between components.
The workflow will use sequential routing to keep the example understandable. Each operation must complete successfully before the saga starts the next operation.
The architecture looks like this:
ASP.NET Core API
|
v
Order Submitted
|
v
Workflow Router
|
v
MassTransit Saga
|
Select Processing Step
|
+----------+-----------+
| | |
v v v
Risk Customs Inventory
Verification Validation Check
| | |
+----------+-----------+
|
v
Payment
|
v
Order CompletedThe diagram represents the possible processing operations. The actual saga executes only the steps selected for a particular order.
Creating the ASP.NET Core Project
Create a new ASP.NET Core Web API project.
dotnet new webapi -n DynamicOrderWorkflow
cd DynamicOrderWorkflowInstall the required NuGet packages.
dotnet add package MassTransit
dotnet add package MassTransit.RabbitMQ
dotnet add package MassTransit.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServerWe will use RabbitMQ as the message broker and SQL Server to persist saga state.
For a production application, keep the API, saga coordinator, and business consumers logically separated. They can initially run in one ASP.NET Core application, but separating them into independently deployable services may be useful as the system grows.
Defining Workflow Steps
The first step is to define the operations that may be included in an order-processing workflow.
public enum WorkflowStep
{
RiskVerification = 1,
CustomsValidation = 2,
InventoryCheck = 3,
PaymentProcessing = 4
}Each step represents a business operation handled by a specific consumer.
We also need an overall workflow status.
public enum WorkflowStatus
{
Pending = 0,
Processing = 1,
Completed = 2,
Failed = 3,
Cancelled = 4
}These enums make the workflow easier to understand and help prevent the application from relying on loosely defined string values.
Creating the Order Model
Define the order information received by the API.
public record CreateOrderRequest(
decimal Amount,
string Currency,
string Country,
bool IsHighRisk);The order contains the amount, currency, destination country, and risk information.
In a real application, risk classification should come from a trusted risk assessment service or server-side business rules. Do not allow clients to mark their own orders as low-risk simply by changing a request property.
We also need an internal order model that can be used by the workflow.
public class Order
{
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; } = string.Empty;
public string Country { get; set; } = string.Empty;
public bool IsHighRisk { get; set; }
public DateTime CreatedAtUtc { get; set; }
}The order ID will be used to correlate messages with the correct saga instance.
Creating the Workflow Routing Service
The routing service determines which steps are required for an order.
Keeping this logic outside the saga makes the business rules easier to test and change.
Create an interface.
public interface IWorkflowRoutingService
{
List<WorkflowStep> GetRoute(Order order);
}Implement the routing service.
public class WorkflowRoutingService : IWorkflowRoutingService
{
public List<WorkflowStep> GetRoute(Order order)
{
var route = new List<WorkflowStep>();
if (order.IsHighRisk || order.Amount > 5000)
{
route.Add(WorkflowStep.RiskVerification);
}
if (!string.Equals(
order.Country,
"US",
StringComparison.OrdinalIgnoreCase))
{
route.Add(WorkflowStep.CustomsValidation);
}
route.Add(WorkflowStep.InventoryCheck);
route.Add(WorkflowStep.PaymentProcessing);
return route;
}
}This service applies the routing rules in one place.
For example, consider an order worth $7,500 with Canada as its destination. The routing service returns the following sequence:
RiskVerification
CustomsValidation
InventoryCheck
PaymentProcessingA domestic order worth $500 with no additional risk requirements follows a shorter route:
InventoryCheck
PaymentProcessingThis design makes it possible to introduce additional routing conditions without rewriting the entire saga.
For example, an organization may later add fraud screening for certain product categories or require manual review for customers with a particular account status.
The routing service should return a deterministic route based on trusted order information. If business rules change later, an order already in progress should normally continue using the route selected when it was submitted.
Defining Message Contracts
MassTransit uses messages to communicate between the API, saga, and processing services.
The first message indicates that a new order has been submitted.
public record OrderSubmitted(
Guid OrderId,
Guid CustomerId,
decimal Amount,
string Currency,
string Country,
List<WorkflowStep> Route);The saga uses this message to create a workflow instance and store the selected route.
We also need a message to start a processing operation.
public record ProcessWorkflowStep(
Guid OrderId,
WorkflowStep Step,
decimal Amount,
string Currency,
string Country);Each processing consumer returns a result message.
public record WorkflowStepCompleted(
Guid OrderId,
WorkflowStep Step,
bool IsSuccessful,
string? ErrorMessage);Finally, define messages for the completed and failed workflows.
public record OrderWorkflowCompleted(
Guid OrderId,
Guid CustomerId);
public record OrderWorkflowFailed(
Guid OrderId,
WorkflowStep FailedStep,
string Reason);These contracts allow the saga to communicate with different services without depending on their internal implementation.
For larger systems, consider using separate request and response contracts for each business operation. A shared generic contract is convenient for a simple example, but dedicated contracts often provide better validation and clearer ownership when services evolve independently.
Creating the Saga State
The saga must remember the selected route and the current processing step.
Create the saga state class.
using MassTransit;
public class OrderWorkflowState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public Guid OrderId { get; set; }
public Guid CustomerId { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; } = string.Empty;
public string Country { get; set; } = string.Empty;
public List<WorkflowStep> Route { get; set; } = new();
public int CurrentStepIndex { get; set; }
public WorkflowStep CurrentStep { get; set; }
public WorkflowStatus Status { get; set; }
public string? FailureReason { get; set; }
}The CorrelationId uniquely identifies the saga instance. We will use the order ID as the correlation ID.
The Route property stores the processing steps selected by the routing service. The CurrentStepIndex identifies the operation currently being executed.
For example, the saga state for a high-value international order may look like this:
OrderId: 1001
CurrentStepIndex: 1
Route:
0 - RiskVerification
1 - CustomsValidation
2 - InventoryCheck
3 - PaymentProcessing
CurrentStep: CustomsValidation
Status: ProcessingThis means risk verification has already completed and customs validation is currently running.
Persisting this information is important because the workflow may remain active while the application is restarted or individual services are temporarily unavailable.
Implementing the MassTransit Saga State Machine
The state machine coordinates the workflow.
We need to handle two main events:
OrderSubmitted starts a new workflow.
WorkflowStepCompleted reports the result of the current operation.
Create the state machine.
using MassTransit;
public class OrderWorkflowStateMachine
: MassTransitStateMachine<OrderWorkflowState>
{
public State Processing { get; private set; } = null!;
public State Completed { get; private set; } = null!;
public State Failed { get; private set; } = null!;
public Event<OrderSubmitted> OrderSubmitted { get; private set; } = null!;
public Event<WorkflowStepCompleted> WorkflowStepCompleted
{ get; private set; } = null!;
public OrderWorkflowStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => OrderSubmitted, x =>
x.CorrelateById(context => context.Message.OrderId));
Event(() => WorkflowStepCompleted, x =>
x.CorrelateById(context => context.Message.OrderId));
Initially(
When(OrderSubmitted)
.Then(context =>
{
var message = context.Message;
var state = context.Saga;
state.OrderId = message.OrderId;
state.CustomerId = message.CustomerId;
state.Amount = message.Amount;
state.Currency = message.Currency;
state.Country = message.Country;
state.Route = message.Route;
state.CurrentStepIndex = 0;
state.Status = WorkflowStatus.Processing;
})
.IfElse(
context => context.Message.Route.Count > 0,
binder => binder
.ThenAsync(async context =>
{
await StartCurrentStep(context);
})
.TransitionTo(Processing),
binder => binder
.ThenAsync(async context =>
{
await CompleteWorkflow(context);
})
.Finalize())
);
During(Processing,
When(WorkflowStepCompleted)
.If(
context =>
context.Message.Step == context.Saga.CurrentStep,
validStep =>
{
validStep.IfElse(
context => context.Message.IsSuccessful,
success => success
.ThenAsync(async context =>
{
await MoveToNextStep(context);
}),
failure => failure
.ThenAsync(async context =>
{
await FailWorkflow(context);
})
.TransitionTo(Failed)
);
})
);
SetCompletedWhenFinalized();
}
private static async Task StartCurrentStep(
BehaviorContext<OrderWorkflowState> context)
{
var state = context.Saga;
state.CurrentStep = state.Route[state.CurrentStepIndex];
await context.Publish(
new ProcessWorkflowStep(
state.OrderId,
state.CurrentStep,
state.Amount,
state.Currency,
state.Country));
}
private static async Task MoveToNextStep(
BehaviorContext<OrderWorkflowState, WorkflowStepCompleted> context)
{
var state = context.Saga;
state.CurrentStepIndex++;
if (state.CurrentStepIndex >= state.Route.Count)
{
await CompleteWorkflow(context);
return;
}
state.CurrentStep = state.Route[state.CurrentStepIndex];
await context.Publish(
new ProcessWorkflowStep(
state.OrderId,
state.CurrentStep,
state.Amount,
state.Currency,
state.Country));
}
private static async Task CompleteWorkflow(
BehaviorContext<OrderWorkflowState> context)
{
var state = context.Saga;
state.Status = WorkflowStatus.Completed;
await context.Publish(
new OrderWorkflowCompleted(
state.OrderId,
state.CustomerId));
await context.Finalize();
}
private static async Task FailWorkflow(
BehaviorContext<OrderWorkflowState, WorkflowStepCompleted> context)
{
var state = context.Saga;
state.Status = WorkflowStatus.Failed;
state.FailureReason = context.Message.ErrorMessage;
await context.Publish(
new OrderWorkflowFailed(
state.OrderId,
state.CurrentStep,
state.FailureReason ?? "Processing failed."));
}
}
Join the conversation! Your thoughts help the community grow.