LESSON 10 OF 14

10. Hangfire Setup and Fire-and-Forget Jobs

Integrate Hangfire with SQL Server in an ASP.NET Core Web API, secure the Dashboard, and design observable fire-and-forget jobs.

50 dk 43

Introduction

In the previous lessons, we examined reliable RabbitMQ consumption, failure handling, retries, and idempotent processing. In this lesson, we will approach background work with a different tool: Hangfire. Hangfire is a .NET library that persists background jobs in storage, provides a server component to process them, and exposes a web interface for monitoring job execution.

Our goals are to add Hangfire to an ASP.NET Core Web API, use SQL Server as persistent job storage, protect the Dashboard, and move work that does not need to finish during the HTTP request into the background. The examples will queue a welcome email and a report-generation operation.

Fire-and-forget does not mean that the job runs immediately or that it is guaranteed to run only once. The API stores the job and returns a job identifier. A Hangfire Server later picks up the job through a worker. The HTTP request therefore does not wait for an email provider or a long report query to finish.

Hangfire’s core components

Storage

Storage contains the job definition, arguments, state transitions, exception details, and scheduling information. In this lesson, SQL Server is the storage provider. Persistence means that work is not tied only to the memory of the current web process and can be recovered after an application restart.

Client

The client creates a job and writes it to storage. In an ASP.NET Core application, this is commonly done with BackgroundJob.Enqueue or the injected IBackgroundJobClient. The call does not execute the target method synchronously. It serializes the method information and arguments as a background job.

Server

The server monitors storage and processes enqueued jobs. In ASP.NET Core, it is registered with AddHangfireServer. If the server is not running, jobs can remain persisted but will not be processed.

Dashboard

The Dashboard displays states such as Enqueued, Processing, Succeeded, Failed, and Deleted. It is useful for operations and troubleshooting, but it should not be exposed anonymously. Job arguments and exception details may contain sensitive information.

Installing the NuGet packages

From the directory containing the existing Web API project, add the integration packages:

dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
dotnet add package Microsoft.Data.SqlClient

Use package versions that are compatible with the Hangfire release selected for your application. The ASP.NET Core package provides host integration, while the SQL Server package supplies the persistent storage implementation.

Configuring SQL Server storage

Add a connection string to appsettings.json. Do not commit production passwords to source control. Use User Secrets, environment variables, or a managed secret store instead.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost,1433;Database=AsyncCourse;User Id=sa;Password=YourStrongPassword1!;TrustServerCertificate=True;",
    "HangfireConnection": "Server=localhost,1433;Database=HangfireDb;User Id=sa;Password=YourStrongPassword1!;TrustServerCertificate=True;"
  }
}

A separate Hangfire database keeps job tables operationally distinct from application tables. A small development project may use the same database, but production deployments should consider permissions, backups, growth, and maintenance independently.

Register Hangfire in Program.cs:

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

var hangfireConnection =
    builder.Configuration.GetConnectionString("HangfireConnection")
    ?? throw new InvalidOperationException("HangfireConnection is missing.");

builder.Services.AddControllers();
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        // Configure JWT validation for the real application.
    });
builder.Services.AddAuthorization();

builder.Services.AddHangfire(configuration => configuration
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(
        hangfireConnection,
        new SqlServerStorageOptions
        {
            PrepareSchemaIfNecessary = true,
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero
        }));

builder.Services.AddHangfireServer(options =>
{
    options.WorkerCount = 5;
});

builder.Services.AddScoped<IEmailSender, EmailSender>();
builder.Services.AddScoped<IReportGenerator, ReportGenerator>();
builder.Services.AddScoped<NotificationJob>();
builder.Services.AddScoped<ReportJob>();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.UseHangfireDashboard(
    "/hangfire",
    new DashboardOptions
    {
        Authorization = new[] { new AdminDashboardAuthorizationFilter() }
    });

app.MapControllers();
app.Run();

During the first connection, Hangfire can create the required SQL Server objects. For production, evaluate this behavior together with your deployment and database-migration process. If PrepareSchemaIfNecessary is disabled, schema creation and upgrades must be handled by another controlled process.

Securing Dashboard access

Changing the Dashboard path is not an authorization mechanism. The application should require authentication and an appropriate role or policy. The following filter allows only authenticated users with the Admin role to access the Dashboard.

using Hangfire.Dashboard;

public sealed class AdminDashboardAuthorizationFilter
    : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var httpContext = context.GetHttpContext();

        return httpContext.User.Identity?.IsAuthenticated == true
            && httpContext.User.IsInRole("Admin");
    }
}

Test the selected authentication scheme, role claims, HTTPS configuration, and reverse-proxy behavior. Restricting access to local requests may be acceptable during development, but shared test and production environments should not leave the Dashboard anonymous.

Creating the first fire-and-forget job

A job class should not capture the current HttpContext, an open database connection, or an object that cannot be serialized reliably. Pass small, stable values such as identifiers and dates. When the job executes, it can resolve scoped services through dependency injection.

public interface IEmailSender
{
    Task SendAsync(string recipient, string subject, string body,
        CancellationToken cancellationToken = default);
}

public sealed class NotificationJob(
    IEmailSender emailSender,
    ILogger<NotificationJob> logger)
{
    public async Task SendWelcomeEmailAsync(Guid userId)
    {
        logger.LogInformation(
            "Preparing welcome email. UserId: {UserId}", userId);

        // A real implementation would load user data from a repository.
        var recipient = $"user-{userId}@example.test";
        await emailSender.SendAsync(
            recipient,
            "Welcome",
            "Your account was created successfully.");

        logger.LogInformation(
            "Welcome email sent. UserId: {UserId}", userId);
    }
}

Queue the job from a controller:

using Hangfire;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/users")]
public sealed class UsersController(
    IBackgroundJobClient backgroundJobClient) : ControllerBase
{
    [HttpPost("{userId:guid}/welcome-email")]
    public IActionResult QueueWelcomeEmail(Guid userId)
    {
        var jobId = backgroundJobClient.Enqueue<NotificationJob>(
            job => job.SendWelcomeEmailAsync(userId));

        return Accepted(new
        {
            JobId = jobId,
            Message = "The email job was queued."
        });
    }
}

Returning HTTP 202 Accepted clearly communicates that the request was accepted but the work is not complete. Returning 200 is technically possible, but it may lead clients to assume that the email was already delivered.

Queueing a report-generation job

For a long-running report, it is usually better to create a job and let the client query its progress or result later instead of generating the file inside the request.

public sealed class ReportJob(
    IReportGenerator reportGenerator,
    ILogger<ReportJob> logger)
{
    public async Task GenerateSalesReportAsync(
        DateOnly startDate,
        DateOnly endDate,
        Guid requestedBy)
    {
        logger.LogInformation(
            "Sales report started. Start: {Start}, End: {End}, User: {User}",
            startDate, endDate, requestedBy);

        var filePath = await reportGenerator.GenerateAsync(
            startDate,
            endDate,
            requestedBy);

        logger.LogInformation(
            "Sales report completed. Path: {Path}", filePath);
    }
}
[HttpPost("reports/sales")]
public IActionResult QueueSalesReport(
    [FromBody] SalesReportRequest request,
    [FromServices] IBackgroundJobClient jobs)
{
    var requestedBy = Guid.Parse(User.FindFirst("sub")!.Value);

    var jobId = jobs.Enqueue<ReportJob>(
        job => job.GenerateSalesReportAsync(
            request.StartDate,
            request.EndDate,
            requestedBy));

    return Accepted(new { JobId = jobId });
}

public sealed record SalesReportRequest(
    DateOnly StartDate,
    DateOnly EndDate);

Prefer passing identifiers and date ranges rather than a large report object, an entire user entity, or an EF Core object graph. The job can load current data when it starts. This also keeps serialized job data smaller and easier to evolve.

Job states and failure behavior

A job commonly moves through these states:

  • Enqueued: The job is waiting in a queue for a worker.
  • Processing: A worker is currently executing the job.
  • Succeeded: The method completed successfully.
  • Failed: The method ended with an exception and may be retried.
  • Deleted: The job was removed or deleted by an operator.

When a job throws an exception, Hangfire retry behavior may run. Therefore, design the job as if it can execute more than once. Email delivery, payment calls, and external webhooks need an idempotency key, a delivery record, or a provider-side unique message identifier to avoid duplicate side effects.

Use structured logging rather than writing only to the console:

public sealed class EmailSender(
    ILogger<EmailSender> logger) : IEmailSender
{
    public async Task SendAsync(
        string recipient,
        string subject,
        string body,
        CancellationToken cancellationToken = default)
    {
        logger.LogInformation(
            "Sending email. Recipient: {Recipient}, Subject: {Subject}",
            recipient, subject);

        await Task.Delay(250, cancellationToken);

        // Call the external email provider here.
        logger.LogInformation("Email provider call completed.");
    }
}

Common mistakes

  • Forgetting the server: AddHangfire configures Hangfire, but AddHangfireServer is required to process jobs in the same application.
  • Leaving the Dashboard anonymous: Job arguments and stack traces may expose sensitive data.
  • Capturing request-scoped objects: HttpContext may no longer be valid after the request ends.
  • Keeping long database transactions open: This can create locks and timeouts. Keep job units focused and reasonably small.
  • Ignoring retries: Repeated external calls can create duplicate emails, records, or webhooks.
  • Passing secrets as arguments: Job data may be visible in the Dashboard, so do not pass passwords or access tokens.
  • Assuming one application instance is enough: In production, monitor the server, SQL Server connectivity, application restarts, and whether queued jobs resume correctly.

Practice exercise

  1. Add the Hangfire ASP.NET Core and SQL Server packages to the project.
  2. Configure a separate SQL Server connection for Hangfire.
  3. Register AddHangfire and AddHangfireServer.
  4. Create a NotificationJob that waits for three seconds and writes a structured log.
  5. Queue the job from a controller and return HTTP 202 with the job identifier.
  6. Restrict Dashboard access to users in the Admin role.
  7. Throw a controlled exception from the job and inspect the Failed state and retry history.
  8. Finally, design an idempotency check so that running the same job twice for one user does not create a duplicate operation.

Conclusion

In this lesson, we connected Hangfire’s SQL Server storage, client, server, and Dashboard components inside an ASP.NET Core Web API. Fire-and-forget jobs allowed us to move email delivery and report generation outside the API response. However, fire-and-forget does not mean exactly-once execution. Persistent storage, retries, and process-recovery behavior mean that job code must tolerate repeated execution.

In the next stage, we will use delayed, recurring, and continuation jobs to build workflows that depend not only on immediate execution, but also on time and the result of another job.

Sources