Introduction
In the previous lessons, we used RabbitMQ to publish and consume messages, and we explored Hangfire fire-and-forget, delayed, recurring, and continuation jobs separately. In real systems, these technologies are often used together. The important design question is not simply how to add both libraries, but which responsibility belongs to each one.
In this lesson, we will use a report-processing scenario. A client submits a report request to the API. The API stores the request and publishes a ReportRequested event through RabbitMQ. A report service consumes that event and creates a Hangfire job instead of performing the long-running operation inside the consumer. The Hangfire job generates the report, updates its status, and publishes a ReportCompleted event through RabbitMQ.
This design allows RabbitMQ to provide loosely coupled communication between services. Hangfire provides persistence, retries, monitoring, and scheduling for work that belongs inside an application.
Assigning Responsibilities Correctly
| Component | Main responsibility | Example |
|---|---|---|
| ASP.NET Core API | Accept the request and return quickly | Create a report request |
| RabbitMQ | Transport events between services | Carry the ReportRequested event |
| RabbitMQ consumer | Receive the event and start application work | Create a Hangfire job |
| Hangfire | Persist, retry, schedule, and execute application jobs | Generate the report |
| Database | Store state, idempotency data, and results | Update request status |
RabbitMQ is not a job scheduler designed to manage when and how many times application code should run. Hangfire is not an inter-service event bus. RabbitMQ makes an event available to another service or application; Hangfire focuses on reliably executing work inside an application.
End-to-End Workflow
- The client sends a
POST /api/reportsrequest. - The API creates a
ReportRequestrecord with the initial statusQueued. - The API publishes a
ReportRequestedmessage to RabbitMQ. - A publisher confirm verifies that the broker accepted the message.
- The consumer receives the message and stores a report job in Hangfire storage.
- Hangfire Server fetches the job and executes
GenerateReportJob. - The job generates the report, updates the result, and sets the status to
Completed. - The job publishes a
ReportCompletedevent through RabbitMQ. - A notification service consumes the event and sends an email or application notification.
The API does not wait for report generation. It only confirms that the request was accepted. The client can later query the report status or react to a completion notification.
Message Contracts
The boundary between RabbitMQ and Hangfire should use small and stable message contracts. Instead of passing a large report object to a Hangfire job, pass an identifier and load the current data when the job runs.
public sealed record ReportRequestedEvent(
Guid MessageId,
Guid RequestId,
int UserId,
string ReportType,
DateTimeOffset RequestedAt);
public sealed record ReportCompletedEvent(
Guid MessageId,
Guid RequestId,
int UserId,
string DownloadUrl,
DateTimeOffset CompletedAt);MessageId identifies the message, while RequestId identifies the business workflow. If the same message is delivered again, MessageId can support message-level idempotency. If the same report job is scheduled more than once, RequestId can support business-level idempotency.
Publishing the Event from the API
RabbitMQ client details should not be embedded directly in controllers. An application-level abstraction keeps the API independent from broker-specific implementation details.
public interface IEventBus
{
Task PublishAsync<T>(T message, string routingKey,
CancellationToken cancellationToken);
}
public sealed record CreateReportRequest(string ReportType);
app.MapPost("/api/reports", async (
CreateReportRequest request,
AppDbContext db,
IEventBus eventBus,
CancellationToken cancellationToken) =>
{
var report = new ReportRequest
{
Id = Guid.NewGuid(),
UserId = 42,
ReportType = request.ReportType,
Status = ReportStatus.Queued,
CreatedAt = DateTimeOffset.UtcNow
};
db.ReportRequests.Add(report);
await db.SaveChangesAsync(cancellationToken);
var message = new ReportRequestedEvent(
Guid.NewGuid(), report.Id, report.UserId,
report.ReportType, DateTimeOffset.UtcNow);
await eventBus.PublishAsync(
message, "report.requested", cancellationToken);
return Results.Accepted($"/api/reports/{report.Id}",
new { report.Id, report.Status });
});This example exposes the distributed transaction problem between the database and RabbitMQ. The database write can succeed while message publishing fails. In production systems, consider an outbox pattern. With an outbox, the event is stored in the same database transaction as the business record, and a separate publisher later forwards outbox records to RabbitMQ.
Creating a Hangfire Job from the Consumer
The consumer should receive the message and hand the work to the application job system. It should not generate the report itself. Long-running work inside the consumer occupies consumer capacity and makes scaling more difficult.
public sealed class ReportRequestedConsumer(
IBackgroundJobClient jobs,
AppDbContext db,
ILogger<ReportRequestedConsumer> logger)
{
public async Task HandleAsync(
ReportRequestedEvent message,
CancellationToken cancellationToken)
{
var alreadyScheduled = await db.ReportRequests
.AnyAsync(x => x.Id == message.RequestId
&& x.JobCreatedAt != null,
cancellationToken);
if (alreadyScheduled)
{
logger.LogInformation(
"Report job already exists for {RequestId}",
message.RequestId);
return;
}
var jobId = jobs.Enqueue<ReportJob>(
job => job.ExecuteAsync(
message.RequestId,
CancellationToken.None));
await db.ReportRequests
.Where(x => x.Id == message.RequestId)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.JobId, jobId)
.SetProperty(x => x.JobCreatedAt,
DateTimeOffset.UtcNow),
cancellationToken);
}
}In the actual consumer, acknowledge the RabbitMQ message only after the Hangfire job has been successfully stored. If job creation fails, the message should remain unacknowledged and follow the retry or dead-letter flow discussed earlier in the course.
There is still a race condition: the Hangfire job can be created successfully, then the process can terminate before the database update completes. RabbitMQ may redeliver the message. Therefore, the job itself must also be idempotent and must use RequestId as its business key.
Implementing the Hangfire Job
A Hangfire job should receive a small identifier, load current data from the database, and remain safe when executed more than once.
public sealed class ReportJob(
IServiceScopeFactory scopeFactory,
ILogger<ReportJob> logger)
{
public async Task ExecuteAsync(
Guid requestId,
CancellationToken cancellationToken)
{
await using var scope =
scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
var generator = scope.ServiceProvider
.GetRequiredService<IReportGenerator>();
var eventBus = scope.ServiceProvider
.GetRequiredService<IEventBus>();
var request = await db.ReportRequests
.SingleOrDefaultAsync(x => x.Id == requestId,
cancellationToken);
if (request is null)
{
logger.LogWarning("Report request not found: {RequestId}",
requestId);
return;
}
if (request.Status == ReportStatus.Completed)
return;
request.Status = ReportStatus.Processing;
await db.SaveChangesAsync(cancellationToken);
var file = await generator.GenerateAsync(
request.ReportType, cancellationToken);
request.Status = ReportStatus.Completed;
request.DownloadUrl = file.Url;
request.CompletedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync(cancellationToken);
await eventBus.PublishAsync(
new ReportCompletedEvent(
Guid.NewGuid(), request.Id, request.UserId,
file.Url, DateTimeOffset.UtcNow),
"report.completed", cancellationToken);
}
}As with hosted services, scoped service lifetimes matter in Hangfire jobs. A long-lived singleton should not directly hold a scoped dependency such as DbContext. Create a scope while the job is running, or use Hangfire’s dependency-injection integration correctly.
Failure and Retry Strategies
This architecture can contain two retry layers:
- RabbitMQ retry: Used when the consumer cannot create the Hangfire job.
- Hangfire retry: Used when the job exists but report generation or an external service call fails.
Retrying the same failure without limits at both layers can create a retry storm. For example, the consumer may repeatedly try to create a Hangfire job while Hangfire repeatedly retries a failed report operation. The resulting behavior can be difficult to diagnose.
Use a limited retry policy for transient network failures. Permanent data errors should move to a failed state and require investigation. On the RabbitMQ side, track redelivery attempts and route messages to a dead-letter queue after a defined limit. On the Hangfire side, monitor retry count, exception type, and the most recent failure time.
Publishing a Completion Notification
When the report job completes, publishing a ReportCompleted event is usually more flexible than calling the notification service directly. An email service, web notification service, and audit service can subscribe to the same event using separate queues.
report.events exchange
├── report.requested → report-worker queue
├── report.completed → notification queue
└── report.completed → audit queueHangfire continuations are also useful when the next operation belongs to the same application. For example, file cleanup or a local index update can be a continuation. If independent services need to know that the report completed, RabbitMQ is the better boundary.
Common Mistakes
- Generating the report inside the consumer: The consumer remains busy and delivery capacity decreases.
- Passing large objects to Hangfire: Job arguments are serialized, increasing storage size and creating a risk of stale data. Pass an identifier and load current data inside the job.
- Acknowledging too early: Acknowledging before the Hangfire job is stored can cause message loss if the process stops.
- Leaving both retry systems unlimited: The same failure may repeat continuously in two different systems.
- Ignoring repeated execution: A report file, email, or external API call may be produced more than once.
- Treating RabbitMQ storage and Hangfire storage as the same thing: RabbitMQ transports messages; Hangfire storage tracks job state and processing.
- Dropping correlation identifiers: Troubleshooting becomes difficult when the API request, RabbitMQ message, and Hangfire job cannot be connected.
Practice Exercise
Implement the following workflow:
- Add
Status,JobId, andCorrelationIdfields to theReportRequesttable. - Publish a
ReportRequestedevent fromPOST /api/reports. - Make the RabbitMQ consumer create a
GenerateReportJobin Hangfire. - Prevent the job from processing a request that has already completed.
- Publish a
ReportCompletedevent after successful processing. - Create a notification consumer that logs the event or calls a fake email service.
- Stop the consumer after receiving the message but before creating the job, then verify redelivery and duplicate protection.
At the end of the exercise, answer this question: If the Hangfire job is created but the database update fails immediately afterward, which source should your idempotency check rely on?
Conclusion
Using RabbitMQ and Hangfire together creates a powerful asynchronous workflow, but the boundaries must be designed deliberately. RabbitMQ transports events between services, the consumer receives an event and starts application work, and Hangfire persists, processes, and retries the job. Completion events can be published through RabbitMQ so that notification and audit services remain independent.
The most important principles are to give each component one clear responsibility, acknowledge messages at the correct point, keep job arguments small, implement idempotency, limit retries, and preserve correlation information. In the next lesson, we will evaluate this design from the perspective of observability, performance, and production deployment.
Sources
- https://www.rabbitmq.com/docs/consumers
- https://www.rabbitmq.com/docs/confirms
- https://www.rabbitmq.com/docs/reliability
- https://docs.hangfire.io/en/latest/background-methods/calling-methods-in-background.html
- https://docs.hangfire.io/en/latest/background-methods/passing-arguments.html
- https://docs.hangfire.io/en/latest/best-practices.html
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0