Introduction
In the previous lesson, we focused on reliable message consumption, acknowledgements, prefetch, and concurrency. This lesson moves to the other side of the workflow: how an API request creates a durable operation record and starts an asynchronous process through RabbitMQ.
Our example is a report-generation request. Instead of generating the report while the HTTP request is open, the API will persist the request in SQL Server and publish a message. A consumer can then process the message independently and update the operation status.
The goal is simple: the API should quickly confirm that the request was accepted, while the long-running work remains observable, retryable, and independent from the request lifetime.
1. Why message contracts matter
A producer and a consumer must agree on the structure and meaning of a message. This agreement is called a message contract. It includes the fields, data types, required values, semantic meaning, and versioning policy of the message.
Sending an EF Core entity directly is usually a poor choice. Entity classes contain persistence concerns and may change when the database model changes. A dedicated messaging DTO is smaller, clearer, and easier to evolve.
A shared contracts project
If the producer and consumer are in the same solution, create a separate class library such as Shared.Contracts. If they are independent services, the contract can be distributed as a versioned package or documented as a stable JSON schema.
namespace Shared.Contracts.Reports;
public sealed record GenerateReportMessage(
Guid OperationId,
Guid CorrelationId,
string ReportType,
DateTimeOffset RequestedAt,
string RequestedBy,
int ContractVersion = 1);OperationId identifies the persisted business operation. CorrelationId connects the HTTP request, database activity, RabbitMQ message, and consumer logs. They do not have to be the same value. One operation may produce multiple messages, and one message may be retried.
2. Designing event metadata
The message body contains business data. Metadata describes how the message was created, transported, and correlated. A practical starting set includes:
- MessageId: The unique identifier of one message instance.
- CorrelationId: The identifier shared by records belonging to one workflow.
- MessageType: The logical name of the event or command.
- OccurredAt: The time at which the message was created.
- ContractVersion: The version of the message schema.
- Source: The service that published the message.
Some teams place these values in RabbitMQ message properties, while others include them in a body envelope. Either approach can work. The important requirement is consistency between producers, consumers, logs, and operational tools.
public sealed record EventEnvelope<T>(
string MessageId,
string MessageType,
string CorrelationId,
DateTimeOffset OccurredAt,
string Source,
int ContractVersion,
T Data);You can generate a correlation ID with a new Guid. For distributed tracing, you may also use the current .NET Activity.TraceId. However, a trace ID and a domain operation ID represent different concepts and should not be confused.
3. Configuring EF Core with SQL Server
The operation record should exist before the consumer starts processing the message. This gives the consumer a durable record that it can update later. Add the EF Core SQL Server provider and design package:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.DesignDefine an operation entity and a database context:
public enum OperationStatus
{
Pending,
Queued,
Processing,
Completed,
Failed
}
public sealed class ReportOperation
{
public Guid Id { get; set; }
public Guid CorrelationId { get; set; }
public string ReportType { get; set; } = null!;
public string RequestedBy { get; set; } = null!;
public OperationStatus Status { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? QueuedAt { get; set; }
public string? ErrorMessage { get; set; }
}
public sealed class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: DbContext(options)
{
public DbSet<ReportOperation> ReportOperations => Set<ReportOperation>();
}Register the context in Program.cs:
var connectionString = builder.Configuration
.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("DefaultConnection was not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));Create and apply the migration:
dotnet ef migrations add CreateReportOperations
dotnet ef database update4. Separating the producer service
The controller should not create RabbitMQ connections, choose queue names, or serialize envelopes. Those responsibilities belong in a separate application or infrastructure service. The controller should call an application service that represents the domain action.
public interface IMessagePublisher
{
Task PublishAsync<T>(
string exchange,
string routingKey,
T data,
Guid correlationId,
CancellationToken cancellationToken = default);
}A simplified publisher using the RabbitMQ .NET client API can look like this:
using System.Text.Json;
using RabbitMQ.Client;
public sealed class RabbitMqMessagePublisher(
IConfiguration configuration) : IMessagePublisher
{
public async Task PublishAsync<T>(
string exchange,
string routingKey,
T data,
Guid correlationId,
CancellationToken cancellationToken = default)
{
var factory = new ConnectionFactory
{
HostName = configuration["RabbitMq:Host"] ?? "localhost",
UserName = configuration["RabbitMq:Username"] ?? "guest",
Password = configuration["RabbitMq:Password"] ?? "guest"
};
await using var connection = await factory.CreateConnectionAsync(cancellationToken);
await using var channel = await connection.CreateChannelAsync(cancellationToken: cancellationToken);
var envelope = new EventEnvelope<T>(
Guid.NewGuid().ToString("N"),
typeof(T).Name,
correlationId.ToString(),
DateTimeOffset.UtcNow,
"Reports.Api",
1,
data);
var body = JsonSerializer.SerializeToUtf8Bytes(envelope);
var properties = new BasicProperties
{
ContentType = "application/json",
DeliveryMode = DeliveryModes.Persistent,
MessageId = envelope.MessageId,
CorrelationId = envelope.CorrelationId,
Type = envelope.MessageType,
Timestamp = new AmqpTimestamp(envelope.OccurredAt.ToUnixTimeSeconds())
};
await channel.BasicPublishAsync(
exchange,
routingKey,
mandatory: false,
basicProperties: properties,
body,
cancellationToken);
}
}For production systems, opening a new connection for every message is inefficient. Prefer a managed, reusable connection and channel strategy. The example is intentionally compact so that the contract and publishing responsibilities remain visible.
5. The application service and API endpoint
Now combine the database insert and message publication in an application service:
public sealed record CreateReportRequest(
string ReportType,
string RequestedBy);
public sealed record CreateReportResponse(
Guid OperationId,
Guid CorrelationId,
string Status);
public sealed class ReportRequestService(
ApplicationDbContext dbContext,
IMessagePublisher publisher)
{
public async Task<CreateReportResponse> CreateAsync(
CreateReportRequest request,
CancellationToken cancellationToken)
{
var operationId = Guid.NewGuid();
var correlationId = Guid.NewGuid();
var now = DateTimeOffset.UtcNow;
var operation = new ReportOperation
{
Id = operationId,
CorrelationId = correlationId,
ReportType = request.ReportType,
RequestedBy = request.RequestedBy,
Status = OperationStatus.Pending,
CreatedAt = now
};
dbContext.ReportOperations.Add(operation);
await dbContext.SaveChangesAsync(cancellationToken);
var message = new GenerateReportMessage(
operationId,
correlationId,
request.ReportType,
now,
request.RequestedBy);
await publisher.PublishAsync(
"reports.exchange",
"report.generate",
message,
correlationId,
cancellationToken);
operation.Status = OperationStatus.Queued;
operation.QueuedAt = DateTimeOffset.UtcNow;
await dbContext.SaveChangesAsync(cancellationToken);
return new CreateReportResponse(
operationId,
correlationId,
operation.Status.ToString());
}
}The endpoint should return 202 Accepted because the operation has been accepted but is not complete:
app.MapPost("/api/reports", async (
CreateReportRequest request,
ReportRequestService service,
CancellationToken cancellationToken) =>
{
var response = await service.CreateAsync(request, cancellationToken);
return Results.Accepted($"/api/reports/{response.OperationId}", response);
});Returning an operation ID and a status URL is more appropriate than returning a completed report. The client can poll the status endpoint or receive a notification when the operation finishes.
6. The atomicity problem
There is an important failure scenario: the database insert may succeed while the RabbitMQ publish fails. The opposite ordering can also create a message without a corresponding database record.
An EF Core transaction covers SQL Server operations. It does not automatically include a RabbitMQ publish. Therefore, writing directly to two independent systems is not fully atomic.
In this lesson, the operation is first saved as Pending and changes to Queued only after publishing succeeds. If publishing fails, the record can remain pending or be marked with a dedicated status such as FailedToPublish.
A more reliable production design is the outbox pattern. The application writes the operation and an outbox message in the same SQL transaction. A separate dispatcher later reads the outbox table and publishes messages to RabbitMQ. This pattern will be developed in a later lesson.
7. Common mistakes
- Sending EF entities as messages: This couples the persistence model to the external communication contract.
- Omitting correlation IDs: Troubleshooting across HTTP, SQL, RabbitMQ, and consumers becomes difficult.
- Marking the operation as completed before processing: Completed should only be set after the consumer finishes successfully.
- Performing long work inside the request: Clients may time out and web server resources remain occupied.
- Embedding RabbitMQ details in controllers: Testing and maintenance become harder.
- Putting secrets in message bodies: Messages may be logged or inspected by operational tools.
- Breaking older consumers with a new schema: Define a contract version and plan backward compatibility.
8. Short practice exercise
Complete the following exercise:
- Create an
InvoiceGenerationMessagecontract. - Add an
InvoiceOperationentity and persist its status in SQL Server. - Make an
/api/invoicesendpoint return202 Accepted. - Add message ID, correlation ID, and contract version to the envelope.
- Keep the operation in
PendingorFailedwhen RabbitMQ publication fails. - Write both operation ID and correlation ID to structured logs.
Conclusion
This lesson divided an API-triggered domain operation into three parts: a durable operation record, a stable message contract, and a RabbitMQ producer service. We used EF Core to persist the operation, added correlation and event metadata for observability, and kept messaging infrastructure outside the controller.
This design allows the API to respond quickly while a consumer performs the long-running work later. We also identified an important limitation: SQL Server and RabbitMQ do not share a native transaction in this flow. For reliable production messaging, the next step is to introduce an outbox, publisher confirms, and stronger recovery strategies.
Sources
- https://www.rabbitmq.com/client-libraries/dotnet-api-guide
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/diagnostics/distributed-tracing-concepts