Many business applications contain processes that cannot be completed automatically. Some operations require a person to review information, approve a request, reject an application, or provide additional details before the workflow can continue.
Examples include employee leave requests, purchase approvals, expense reimbursements, loan applications, insurance claims, and document reviews.
A simple application might handle these processes using database records and a few API endpoints. However, as the workflow becomes more complex, managing its state, notifications, deadlines, and responses across multiple services can become difficult.
Consider a purchase approval workflow. An employee submits a purchase request. The system checks the request, sends it to a manager, waits for a decision, and then either approves or rejects it. If the manager does not respond within the required time, the system may need to send a reminder or escalate the request to another manager.
This process can take hours or days. The application must remember the current status, identify the person responsible for the next action, and continue the workflow when an approval or rejection arrives.
MassTransit saga state machines provide a useful approach for implementing these long-running workflows. A saga can maintain the request state, react to messages, publish notifications, and coordinate different services without keeping an HTTP request open while waiting for a person.
In this article, we will build a purchase approval workflow using MassTransit and ASP.NET Core. We will define message contracts, create a saga state machine, handle approval and rejection decisions, expose an API for submitting requests, and discuss how to protect and operate the workflow in production.
Why Human Approval Workflows Need a Saga
A human approval process is different from a normal automated operation because the next step depends on a decision made by a person.
For example, an employee may submit a purchase request on Monday, but the manager may not review it until Wednesday. During that period, the application must preserve the request information and remember that approval is still pending.
A normal HTTP request cannot remain active for several days while waiting for a manager. The application needs a mechanism that can store the workflow state and continue processing when a decision arrives.
A saga provides this capability.
Instead of executing the entire process in one operation, the application divides it into separate message-driven steps.
A purchase approval workflow might contain the following stages:
An employee submits a purchase request.
The application creates a purchase approval saga.
The saga publishes an approval request notification.
The manager reviews the request.
The manager approves or rejects the request.
The saga validates the decision and updates its state.
The application notifies the employee about the result.
If the manager does not respond, the workflow can also send reminders or escalate the request according to business rules.
The saga remains active while the approval is pending. It does not need to keep a worker thread or HTTP connection open during this period.
Understanding the Workflow Architecture
Before writing code, let's understand the components involved in the application.
We will use four main components:
ASP.NET Core API: Accepts purchase requests and approval decisions.
MassTransit: Handles message publishing and consumption.
Purchase approval saga: Stores the current workflow state and coordinates the process.
Notification service: Sends notifications to employees and managers.
The API should not directly manage every workflow transition. Its responsibility is to accept and validate requests, then publish the appropriate messages.
The saga handles the business process and decides what should happen next.
<AsyncImage query="software architecture diagram human purchase approval workflow ASP.NET Core API MassTransit saga message broker notification service manager employee clean technical architecture illustration" aspectRatio="16:9" width="100%" />
The overall flow looks like this:
Employee
|
| Submit Purchase Request
v
ASP.NET Core API
|
| PurchaseSubmitted
v
MassTransit Message Broker
|
v
Purchase Approval Saga
|
| ApprovalRequested
v
Notification Service
|
| Manager receives notification
v
Manager
|
| Approve or Reject
v
ASP.NET Core API
|
| PurchaseApproved / PurchaseRejected
v
MassTransit Message Broker
|
v
Purchase Approval Saga
|
+------> Approved
|
+------> Rejected
|
v
Employee NotificationThis architecture separates the approval process from the user interface and notification implementation.
For example, the manager could respond through a web application, a mobile application, or an internal administrative portal. As long as the application publishes the correct decision message, the saga can continue the workflow.
Creating the ASP.NET Core Project
Start by creating a new ASP.NET Core Web API project.
dotnet new webapi -n PurchaseApprovalApi
cd PurchaseApprovalApiInstall the required MassTransit packages:
dotnet add package MassTransit
dotnet add package MassTransit.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServerFor this example, we will use RabbitMQ as the message transport and Entity Framework Core with SQL Server for saga persistence.
The database will store approval workflow instances so that requests remain available after application restarts.
The notification service will be represented by a message consumer. In a real application, this consumer could call an email provider, push notification service, or internal notification API.
Creating Message Contracts
Message contracts describe the information exchanged between the API, saga, and other services.
We need several messages for the purchase approval workflow.
Create a file named PurchaseMessages.cs.
public record PurchaseSubmitted
{
public Guid CorrelationId { get; init; }
public string RequestNumber { get; init; } = string.Empty;
public string EmployeeId { get; init; } = string.Empty;
public string ManagerId { get; init; } = string.Empty;
public decimal Amount { get; init; }
public string Description { get; init; } = string.Empty;
}
public record PurchaseApproved
{
public Guid CorrelationId { get; init; }
public string ManagerId { get; init; } = string.Empty;
public string Comments { get; init; } = string.Empty;
public DateTime DecisionAt { get; init; }
}
public record PurchaseRejected
{
public Guid CorrelationId { get; init; }
public string ManagerId { get; init; } = string.Empty;
public string Reason { get; init; } = string.Empty;
public DateTime DecisionAt { get; init; }
}
public record ApprovalRequested
{
public Guid CorrelationId { get; init; }
public string RequestNumber { get; init; } = string.Empty;
public string EmployeeId { get; init; } = string.Empty;
public string ManagerId { get; init; } = string.Empty;
public decimal Amount { get; init; }
public string Description { get; init; } = string.Empty;
}
public record PurchaseApprovalCompleted
{
public Guid CorrelationId { get; init; }
public string RequestNumber { get; init; } = string.Empty;
public string EmployeeId { get; init; } = string.Empty;
public string ManagerId { get; init; } = string.Empty;
public DateTime CompletedAt { get; init; }
}
public record PurchaseApprovalFailed
{
public Guid CorrelationId { get; init; }
public string RequestNumber { get; init; } = string.Empty;
public string EmployeeId { get; init; } = string.Empty;
public string Reason { get; init; } = string.Empty;
}Let's understand the purpose of these messages.
PurchaseSubmitted represents a new purchase request. It contains the request identifier, employee information, manager information, purchase amount, and description.
PurchaseApproved represents a decision made by the manager. It contains the manager identifier, approval comments, and decision time.
PurchaseRejected represents a rejection decision. It includes a reason so that the employee can understand why the request was rejected.
ApprovalRequested is an outgoing event that tells the notification service that a manager needs to review a purchase.
PurchaseApprovalCompleted and PurchaseApprovalFailed represent the final business outcomes of the workflow. Other services can consume these events to update reports, notify employees, or perform additional operations.
Notice that every message related to the same purchase workflow contains a CorrelationId. MassTransit uses this identifier to locate the correct saga instance.
The correlation identifier should be generated when the purchase request is created and reused throughout the workflow. Do not generate a new identifier when publishing the approval or rejection decision.
Creating the Saga State Instance
The saga needs to remember the purchase request information and its current state.
Create a file named PurchaseApprovalState.cs.
using MassTransit;
public class PurchaseApprovalState :
SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public string RequestNumber { get; set; } = string.Empty;
public string EmployeeId { get; set; } = string.Empty;
public string ManagerId { get; set; } = string.Empty;
public decimal Amount { get; set; }
public string Description { get; set; } = string.Empty;
public string? DecisionComments { get; set; }
public DateTime SubmittedAt { get; set; }
public DateTime? DecisionAt { get; set; }
}The PurchaseApprovalState class implements SagaStateMachineInstance.
The CorrelationId property identifies the workflow. CurrentState stores its current state, such as PendingApproval, Approved, or Rejected.
The remaining properties store information required to process the request.
For example, the saga needs ManagerId to verify that the person submitting a decision is the manager assigned to the request. It also needs EmployeeId so that the employee can receive the final result.
The DecisionComments property stores the manager's approval comments or rejection reason. DecisionAt records when the decision was made.
In a production application, the saga instance should be persisted in a database. This allows the workflow to continue after an application restart.
Creating the Purchase Approval State Machine
Now we can create the state machine that coordinates the approval process.
Create a file named PurchaseApprovalStateMachine.cs.
using MassTransit;
public class PurchaseApprovalStateMachine :
MassTransitStateMachine<PurchaseApprovalState>
{
public State PendingApproval { get; private set; } = null!;
public State Approved { get; private set; } = null!;
public State Rejected { get; private set; } = null!;
public Event<PurchaseSubmitted> PurchaseSubmitted { get; private set; }
= null!;
public Event<PurchaseApproved> PurchaseApproved { get; private set; }
= null!;
public Event<PurchaseRejected> PurchaseRejected { get; private set; }
= null!;
public PurchaseApprovalStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => PurchaseSubmitted,
x => x.CorrelateById(context =>
context.Message.CorrelationId));
Event(() => PurchaseApproved,
x => x.CorrelateById(context =>
context.Message.CorrelationId));
Event(() => PurchaseRejected,
x => x.CorrelateById(context =>
context.Message.CorrelationId));
Initially(
When(PurchaseSubmitted)
.Then(context =>
{
context.Saga.RequestNumber =
context.Message.RequestNumber;
context.Saga.EmployeeId =
context.Message.EmployeeId;
context.Saga.ManagerId =
context.Message.ManagerId;
context.Saga.Amount =
context.Message.Amount;
context.Saga.Description =
context.Message.Description;
context.Saga.SubmittedAt =
DateTime.UtcNow;
})
.Publish(context =>
new ApprovalRequested
{
CorrelationId =
context.Saga.CorrelationId,
RequestNumber =
context.Saga.RequestNumber,
EmployeeId =
context.Saga.EmployeeId,
ManagerId =
context.Saga.ManagerId,
Amount =
context.Saga.Amount,
Description =
context.Saga.Description
})
.TransitionTo(PendingApproval));
During(PendingApproval,
When(PurchaseApproved)
.If(context =>
context.Message.ManagerId ==
context.Saga.ManagerId,
approved => approved
.Then(context =>
{
context.Saga.DecisionComments =
context.Message.Comments;
context.Saga.DecisionAt =
context.Message.DecisionAt;
})
.Publish(context =>
new PurchaseApprovalCompleted
{
CorrelationId =
context.Saga.CorrelationId,
RequestNumber =
context.Saga.RequestNumber,
EmployeeId =
context.Saga.EmployeeId,
ManagerId =
context.Saga.ManagerId,
CompletedAt =
context.Message.DecisionAt
})
.TransitionTo(Approved)));
During(PendingApproval,
When(PurchaseRejected)
.If(context =>
context.Message.ManagerId ==
context.Saga.ManagerId,
rejected => rejected
.Then(context =>
{
context.Saga.DecisionComments =
context.Message.Reason;
context.Saga.DecisionAt =
context.Message.DecisionAt;
})
.Publish(context =>
new PurchaseApprovalFailed
{
CorrelationId =
context.Saga.CorrelationId,
RequestNumber =
context.Saga.RequestNumber,
EmployeeId =
context.Saga.EmployeeId,
Reason =
context.Message.Reason
})
.TransitionTo(Rejected)));
During(Approved,
Ignore(PurchaseApproved),
Ignore(PurchaseRejected));
During(Rejected,
Ignore(PurchaseApproved),
Ignore(PurchaseRejected));
}
}Let's understand the important parts of this implementation.
The state machine defines three states: PendingApproval, Approved, and Rejected.
It also defines three events. PurchaseSubmitted starts the workflow, while PurchaseApproved and PurchaseRejected represent decisions made by the manager.
The Initially section handles a new purchase request. It copies the incoming request information into the saga instance, records the submission time, publishes ApprovalRequested, and moves the workflow to PendingApproval.
Publishing ApprovalRequested allows another service to notify the manager. The saga does not need to know whether the notification is sent through email, a mobile push notification, or an internal dashboard.
The approval and rejection behaviors are active only while the saga is in PendingApproval.
An important detail is the ManagerId check. The state machine compares the manager identifier in the incoming message with the manager assigned to the saga.
If the identifiers match, the decision is accepted and the workflow moves to the corresponding final state. If they do not match, the configured behavior does not execute the approval or rejection transition.
This check is useful as an additional business safeguard, but it is not a replacement for authentication and authorization. The API must independently verify the identity of the manager before publishing a decision message.
The final state behaviors ignore additional approval or rejection events. This prevents a completed workflow from processing another decision through the same transition.
For a production application, you may prefer to finalize completed saga instances or retain them for auditing. That decision depends on how long the application needs to support delayed messages, reporting, and operational recovery.
Configuring Saga Persistence with Entity Framework Core
A human approval workflow may remain active for several days. Storing saga information only in memory would be unsafe because an application restart could remove pending approval information.
We will use Entity Framework Core with SQL Server to persist the saga.
First, create the saga mapping.
Join the conversation! Your thoughts help the community grow.