Introduction
Distributed applications rarely complete every operation immediately. A service may receive a request, perform some processing, and publish a response several seconds later. Another service may depend on an external provider that takes minutes to respond. Sometimes, the expected response never arrives because a service is unavailable, a message is delayed, or an external system fails.
These situations create an important problem for long-running business workflows. An application cannot wait forever for another service to respond. It needs a reliable way to determine when an operation has taken too long and what should happen next.
Consider an order-processing application. When a customer places an order, the application reserves inventory and requests payment. The Payment Service sends a payment request to an external payment provider. Normally, the provider returns a success or failure response. However, the provider might become unavailable, or the response might be delayed because of a network problem.
If the order-processing workflow waits indefinitely, the order may remain in a pending state. The inventory reservation may also remain active, preventing other customers from purchasing the same products.
The application needs a timeout mechanism. If payment is not confirmed within the expected period, the workflow should take an appropriate action, such as checking the payment status, cancelling the order, or releasing the inventory reservation.
The Saga pattern helps coordinate these long-running operations, while MassTransit provides state machine scheduling capabilities that allow a saga to schedule messages for future delivery.
In this article, we will build on the MassTransit Saga State Machine implementation and learn how to handle timeouts and delayed events in ASP.NET Core. We will create a payment timeout workflow, schedule a timeout message, cancel it when payment succeeds, and handle the case where the timeout arrives before the expected response. We will also discuss scheduler configuration, duplicate messages, late responses, persistence, and production considerations.
Why Do Distributed Workflows Need Timeouts?
A timeout defines how long an application is willing to wait for an expected operation or response.
Timeouts are important because distributed systems cannot assume that every service will respond successfully. A request may be delayed, a consumer may stop processing messages, or an external dependency may become unavailable.
Consider this order-processing sequence:
The customer submits an order.
The Order Service starts the saga.
The saga requests inventory reservation.
The Inventory Service confirms the reservation.
The saga sends a payment request.
The Payment Service contacts an external provider.
The payment provider does not respond within the expected time.
At this point, the saga is waiting for PaymentCompleted or PaymentFailed. Without a timeout, the workflow may remain in WaitingForPayment indefinitely.
A timeout allows the saga to detect that the expected response has not arrived within the configured period.
However, a timeout does not necessarily mean that the operation itself failed. It only means that the application did not receive the expected response within the allowed time.
This distinction is extremely important.
For example, the payment provider may have successfully charged the customer, but its response may have been lost because of a network interruption. If the saga assumes that every timeout means payment failure and immediately sends another payment request, the customer could be charged twice.
A reliable timeout workflow should therefore distinguish between the following situations:
The operation failed and the failure response arrived.
The operation succeeded, but the response arrived late.
The operation is still being processed.
The operation completed, but the response was lost.
The operation never reached the external service.
The application cannot determine the final result.
The correct recovery action depends on the business operation and the information available from the participating service.
Understanding Scheduled Messages in MassTransit
MassTransit supports scheduled messages that can be delivered after a specified delay.
Instead of keeping a worker thread active while waiting, the application asks the configured message scheduler to deliver a message in the future.
For example, when a saga starts payment processing, it can schedule a PaymentTimeoutExpired message for delivery after five minutes.
The message is not intended to report that payment failed. It simply tells the saga that the configured waiting period has expired.
When the scheduled message arrives, the state machine checks its current state and executes the corresponding behavior.
The basic workflow looks like this:
Payment Requested
|
v
Schedule Payment Timeout
|
v
Waiting For Payment
|
+----------------------+
| |
v v
Payment Completed Timeout Expired
| |
v v
Cancel Timeout Check Payment Status
| |
v v
Continue Order Recover or CompensateThis approach is more reliable than using Task.Delay inside a consumer or storing a timer in application memory.
A consumer should not remain active for several minutes simply to wait for a response. It should complete its current message processing operation and allow the broker and scheduler to manage future delivery.
MassTransit supports different scheduling approaches, including transport-based delayed delivery and scheduler-based integrations such as Quartz.NET and Hangfire. The appropriate option depends on the transport, required scheduling duration, cancellation requirements, and operational infrastructure.
Understanding the Difference Between a Timeout and a Retry
Timeouts and retries solve different problems.
A retry repeats an operation after a failure. A timeout determines when the application should stop waiting for an expected response or take another action.
Consider a Payment Service that cannot connect to an external provider.
If the connection fails temporarily, the service may retry the request. It can use a retry policy with increasing delays between attempts.
A timeout is different. It controls how long the Order Service waits for the payment result before executing the next workflow decision.
Feature | Retry | Timeout |
|---|---|---|
Main purpose | Repeat an operation after a failure | Detect that an expected response has not arrived in time |
Typical trigger | Temporary exception or unsuccessful attempt | Expiration of a configured waiting period |
Main action | Execute the operation again | Continue, investigate, or compensate |
Example | Retry a failed payment-provider connection | Check payment status after five minutes |
These mechanisms can work together.
For example, the Payment Service may retry temporary connection failures for a limited period. At the same time, the Order Saga may have a timeout that determines when the business workflow should investigate the payment status.
The retry policy should not exceed the business timeout without a deliberate reason. Otherwise, the payment service may still be retrying an operation after the order workflow has already started cancellation.
Building a Payment Timeout Workflow
We will create a simplified order-processing saga that waits for a payment result.
The workflow will follow these steps:
The application receives SubmitOrder.
The saga sends ProcessPayment.
The saga schedules PaymentTimeoutExpired for five minutes later.
The saga moves to WaitingForPayment.
If PaymentCompleted arrives first, the saga cancels the scheduled timeout.
If PaymentFailed arrives first, the saga handles the failure.
If PaymentTimeoutExpired arrives first, the saga requests the payment status.
The saga continues or starts compensation after receiving the status result.
This example uses RabbitMQ for message delivery and MassTransit for workflow coordination. The payment provider itself is represented by a separate service that publishes payment results.
Step 1: Create the Project and Install Packages
Create an ASP.NET Core Web API project:
dotnet new webapi -n SagaTimeoutApi
cd SagaTimeoutApiInstall MassTransit with RabbitMQ support:
dotnet add package MassTransit.RabbitMQFor a durable saga repository using SQL Server, install the Entity Framework Core integration and SQL Server provider:
dotnet add package MassTransit.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.DesignThe RabbitMQ package provides message transport integration. The Entity Framework packages allow the application to store saga instances in SQL Server.
The timeout itself will be represented as a scheduled message. RabbitMQ delayed delivery requires the appropriate delayed-message transport support and broker configuration. We will configure that later.
Step 2: Define the Message Contracts
Create a folder named Contracts.
Create OrderMessages.cs:
public record SubmitOrder(
Guid OrderId,
Guid CustomerId,
decimal Amount);
public record OrderAccepted(
Guid OrderId);
public record OrderCancelled(
Guid OrderId,
string Reason);SubmitOrder starts the order workflow. OrderAccepted and OrderCancelled represent the final business outcomes.
Create PaymentMessages.cs:
public record ProcessPayment(
Guid OrderId,
Guid CustomerId,
decimal Amount,
Guid PaymentOperationId);
public record PaymentCompleted(
Guid OrderId,
Guid PaymentOperationId,
string TransactionId);
public record PaymentFailed(
Guid OrderId,
Guid PaymentOperationId,
string Reason);
public record CheckPaymentStatus(
Guid OrderId,
Guid PaymentOperationId);
public record PaymentStatusConfirmed(
Guid OrderId,
Guid PaymentOperationId,
bool IsPaid,
string? TransactionId);
public record PaymentStatusUnknown(
Guid OrderId,
Guid PaymentOperationId,
string Reason);
public record RefundPayment(
Guid OrderId,
Guid PaymentOperationId,
string TransactionId);
public record PaymentRefunded(
Guid OrderId,
Guid PaymentOperationId);These contracts represent the commands and events used by the payment workflow.
ProcessPayment requests a payment operation. PaymentCompleted confirms that the payment was successful, while PaymentFailed communicates a known business failure.
CheckPaymentStatus is especially important. It allows the saga to investigate the result of an operation when the original response has not arrived.
For example, the payment provider may have processed the payment successfully, but the Payment Service may have failed before publishing PaymentCompleted. The status check gives the application an opportunity to discover the actual result before deciding whether to retry, refund, or cancel the order.
PaymentOperationId identifies one specific payment operation. It should remain the same when checking the status of that operation. It should also be used as an idempotency key by the Payment Service and, where supported, by the external payment provider.
Create TimeoutMessages.cs:
public record PaymentTimeoutExpired(
Guid OrderId);
public record PaymentStatusCheckTimeoutExpired(
Guid OrderId);These messages represent scheduled timeout events.
PaymentTimeoutExpired tells the saga that the initial payment waiting period has expired.
PaymentStatusCheckTimeoutExpired can be used when the application also wants to limit how long it waits for the payment status investigation.
Keeping separate message types for different timeout purposes makes the workflow easier to understand. It also prevents one timeout from being confused with another when the saga has multiple scheduled operations.
Step 3: Create the Saga Instance
Create a folder named Sagas and add OrderState.cs:
using MassTransit;
public class OrderState : 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 Guid PaymentOperationId { get; set; }
public string? PaymentTransactionId { get; set; }
public string? FailureReason { get; set; }
public Guid? PaymentTimeoutTokenId { get; set; }
public Guid? StatusTimeoutTokenId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public byte[] RowVersion { get; set; } = [];
}The saga instance stores the information required to manage one order workflow.
CorrelationId identifies the saga instance. In this example, it will use the OrderId so that every message for an order can be routed to the same workflow.
CurrentState stores the current state of the workflow.
PaymentOperationId identifies the payment operation. It is generated when the saga starts payment processing and remains unchanged during status checks.
PaymentTransactionId stores the transaction identifier returned by the payment provider. It may be required when issuing a refund.
PaymentTimeoutTokenId stores the identifier of the scheduled payment timeout. MassTransit uses this token to identify the scheduled message when the saga needs to cancel it.
StatusTimeoutTokenId serves the same purpose for the payment status check timeout.
These token properties are nullable because a timeout may not yet have been scheduled, may already have been delivered, or may have been cancelled.
The token identifiers should be persisted with the saga instance. If the application restarts, it must still have the information needed to manage outstanding scheduled messages.
Step 4: Define the Saga States and Events
Create OrderStateMachine.cs.
We will use the following states:
WaitingForPayment: The payment command has been sent and the saga is waiting for a result.
CheckingPaymentStatus: The original payment timeout expired, and the saga is investigating the payment result.
WaitingForRefund: The payment succeeded, but the order cannot continue and a refund is required.
Completed: The payment workflow succeeded.
Cancelled: The order workflow ended without a successful payment.
The state machine will also declare the events it can receive.
using MassTransit;
public class OrderStateMachine :
MassTransitStateMachine<OrderState>
{
public State WaitingForPayment { get; private set; }
= null!;
public State CheckingPaymentStatus { get; private set; }
= null!;
public State WaitingForRefund { get; private set; }
= null!;
public State Completed { get; private set; }
= null!;
public State Cancelled { get; private set; }
= null!;
public Event<SubmitOrder> SubmitOrder { get; private set; }
= null!;
public Event<PaymentCompleted> PaymentCompleted { get; private set; }
= null!;
public Event<PaymentFailed> PaymentFailed { get; private set; }
= null!;
public Event<PaymentStatusConfirmed> PaymentStatusConfirmed
{ get; private set; } = null!;
public Event<PaymentStatusUnknown> PaymentStatusUnknown
{ get; private set; } = null!;
public Event<PaymentRefunded> PaymentRefunded { get; private set; }
= null!;
public Schedule<OrderState, PaymentTimeoutExpired>
PaymentTimeout { get; private set; } = null!;
public Schedule<OrderState, PaymentStatusCheckTimeoutExpired>
StatusTimeout { get; private set; } = null!;
public OrderStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => SubmitOrder,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentCompleted,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentStatusConfirmed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentStatusUnknown,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentRefunded,
x => x.CorrelateById(
context => context.Message.OrderId));
Schedule(
() => PaymentTimeout,
x => x.PaymentTimeoutTokenId,
schedule =>
{
schedule.Delay =
TimeSpan.FromMinutes(5);
schedule.Received = e =>
e.CorrelateById(
context => context.Message.OrderId);
});
Schedule(
() => StatusTimeout,
x => x.StatusTimeoutTokenId,
schedule =>
{
schedule.Delay =
TimeSpan.FromMinutes(2);
schedule.Received = e =>
e.CorrelateById(
context => context.Message.OrderId);
});
ConfigureInitialBehavior();
ConfigurePaymentBehavior();
ConfigureStatusBehavior();
ConfigureRefundBehavior();
ConfigureCompletedBehavior();
SetCompletedWhenFinalized();
}
private void ConfigureInitialBehavior()
{
Initially(
When(SubmitOrder)
.Then(context =>
{
context.Saga.OrderId =
context.Message.OrderId;
context.Saga.CustomerId =
context.Message.CustomerId;
context.Saga.Amount =
context.Message.Amount;
context.Saga.PaymentOperationId =
Guid.NewGuid();
context.Saga.CreatedAt =
DateTime.UtcNow;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<ProcessPayment>(
new
{
context.Saga.OrderId,
context.Saga.CustomerId,
context.Saga.Amount,
context.Saga.PaymentOperationId
}))
.Schedule(
PaymentTimeout,
context => context.Init<PaymentTimeoutExpired>(
new
{
context.Saga.OrderId
}))
.TransitionTo(WaitingForPayment));
}
private void ConfigurePaymentBehavior()
{
During(
WaitingForPayment,
When(PaymentCompleted)
.Then(context =>
{
context.Saga.PaymentTransactionId =
context.Message.TransactionId;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Unschedule(PaymentTimeout)
.Publish(context =>
context.Init<OrderAccepted>(
new
{
context.Saga.OrderId
}))
.TransitionTo(Completed),
When(PaymentFailed)
.Then(context =>
{
context.Saga.FailureReason =
context.Message.Reason;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Unschedule(PaymentTimeout)
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason = context.Message.Reason
}))
.TransitionTo(Cancelled),
When(PaymentTimeout.Received)
.Publish(context =>
context.Init<CheckPaymentStatus>(
new
{
context.Saga.OrderId,
context.Saga.PaymentOperationId
}))
.Schedule(
StatusTimeout,
context => context.Init<
PaymentStatusCheckTimeoutExpired>(
new
{
context.Saga.OrderId
}))
.TransitionTo(CheckingPaymentStatus));
}
private void ConfigureStatusBehavior()
{
During(
CheckingPaymentStatus,
When(PaymentStatusConfirmed)
.Unschedule(StatusTimeout)
.If(
context => context.Message.IsPaid,
paid => paid
.Then(context =>
{
context.Saga.PaymentTransactionId =
context.Message.TransactionId;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<OrderAccepted>(
new
{
context.Saga.OrderId
}))
.TransitionTo(Completed),
unpaid => unpaid
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason =
"Payment was not completed."
}))
.TransitionTo(Cancelled)),
When(PaymentStatusUnknown)
.Then(context =>
{
context.Saga.FailureReason =
context.Message.Reason;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Unschedule(StatusTimeout)
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason =
"Payment status could not be confirmed."
}))
.TransitionTo(Cancelled),
When(StatusTimeout.Received)
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason =
"Payment status check timed out."
}))
.TransitionTo(Cancelled));
}
private void ConfigureRefundBehavior()
{
During(
WaitingForRefund,
When(PaymentRefunded)
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason =
context.Saga.FailureReason
?? "Order was cancelled."
}))
.TransitionTo(Cancelled));
}
private void ConfigureCompletedBehavior()
{
During(
Completed,
Ignore(PaymentCompleted),
Ignore(PaymentFailed),
Ignore(PaymentStatusConfirmed),
Ignore(PaymentStatusUnknown));
}
}
Join the conversation! Your thoughts help the community grow.