Skip to content
Edit this page

Migrating from Hangfire

Hangfire's API stores a method call: Enqueue(() => sender.SendWelcomeAsync(userId)) records the type, the method and its arguments, and a server calls the method later. Bellhop stores data instead: a job is a record that holds the arguments, and a handler, resolved from dependency injection, does the work. There is no expression-based API in Bellhop and no compatibility package, so each call site moves on its own, and the two libraries can run side by side while it does.

This page takes the common calls one at a time, with the Hangfire code first and the Bellhop code it becomes.

A fire-and-forget job

In Hangfire, an application class enqueues a call to a service:

public sealed class UserRegistration(IBackgroundJobClient jobs)
{
    public void Register(Guid userId)
    {
        jobs.Enqueue<IEmailSender>(sender => sender.SendWelcomeAsync(userId, CancellationToken.None));
    }
}

In Bellhop the call becomes a job type, which holds the arguments and a stable name that is stored with each job:

[JobName("send-welcome-email")]
public sealed record SendWelcomeEmail(Guid UserId) : IJob;

a handler, which calls the same service and is given the job, its context and a cancellation token:

public sealed class SendWelcomeEmailHandler(IEmailSender email) : IJobHandler<SendWelcomeEmail>
{
    public Task HandleAsync(SendWelcomeEmail job, JobContext ctx, CancellationToken ct)
        => email.SendWelcomeAsync(job.UserId, ct);
}

and the call site, which takes IJobClient from dependency injection:

public sealed class UserRegistration(IJobClient jobs)
{
    public async Task RegisterAsync(Guid userId, CancellationToken ct)
    {
        await jobs.EnqueueAsync(new SendWelcomeEmail(userId), ct: ct);
    }
}

The job's name, send-welcome-email, is what the store keeps, so renaming or moving the class does not strand the jobs already stored; the analyzers warn about a job type without [JobName]. Keep a job's arguments small: identifiers rather than whole entities, as with Hangfire.

A delayed job

var jobId = jobs.Schedule<IEmailSender>(sender => sender.SendFollowUpAsync(userId, CancellationToken.None), TimeSpan.FromDays(3));

becomes:

var result = await jobs.ScheduleAsync(new SendFollowUpEmail(userId), TimeSpan.FromDays(3), ct: ct);

ScheduleAsync also takes a DateTimeOffset. A scheduled job can be given a unique key, so scheduling the same follow-up twice keeps one.

A recurring job

A recurring job that Hangfire adds at startup:

recurringJobs.AddOrUpdate<IReportBuilder>(
    "nightly-report",
    reports => reports.BuildNightlyAsync(CancellationToken.None),
    Cron.Daily(3),
    new RecurringJobOptions { TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Sofia") });

is declared on its job type in Bellhop, with its handler beside it:

[JobName("nightly-report")]
[Recurring("nightly-report", "0 3 * * *", TimeMode = TimeMode.Local, TimeZone = "Europe/Sofia")]
public sealed record NightlyReport : IJob;

The time zone is an IANA id, and the schedule is a cron expression; Cron.Daily(3) is 0 3 * * *. Recurring jobs can also be declared with AddRecurring or in the Bellhop:RecurringJobs configuration section, as the concepts page shows. Removing the declaration replaces Hangfire's RemoveIfExists: what happens to a recurring job that no running node declares any more is its OrphanPolicy. Bellhop also decides what to do with runs missed while no node was up (MisfirePolicy) and with a run that falls due while the previous one is still running (OverlapPolicy, which skips it by default).

Continuations

var provisionId = jobs.Enqueue<IAccountProvisioner>(accounts => accounts.ProvisionAsync(userId, CancellationToken.None));
var welcomeId = jobs.ContinueJobWith<IEmailSender>(provisionId, sender => sender.SendWelcomeAsync(userId, CancellationToken.None));

becomes:

var provision = await jobs.EnqueueAsync(new ProvisionAccount(userId), ct: ct);
var welcome = await jobs.ContinueWithAsync(provision.JobId, new SendWelcomeEmail(userId), ContinuationCondition.OnSuccess, ct: ct);

Hangfire runs a continuation once its parent succeeds by default; in Bellhop the condition is given with each call, and OnFailure and OnCompletion are the others. ChainAsync creates a whole chain in one call, and CreateBatchAsync groups jobs into a batch with continuations of its own.

Retries, queues and concurrency

Hangfire's attributes on a service method:

public interface IInvoiceExporter
{
    [AutomaticRetry(Attempts = 3)]
    [Queue("critical")]
    [DisableConcurrentExecution(timeoutInSeconds: 600)]
    Task ExportAsync(CancellationToken ct);
}

become attributes on the job type:

[JobName("export-invoices")]
[Retry(4)]
[Queue("critical")]
[Concurrency("export-invoices")]
public sealed record ExportInvoices : IJob;
  • Retries. Hangfire's Attempts counts retries after the first try; Bellhop's [Retry] counts every attempt, the first included. Three retries are [Retry(4)]. Without an attribute Bellhop makes 5 attempts in all, waiting 10 seconds, 1 minute, 5 minutes and 30 minutes between them (Bellhop:MaxAttempts, Bellhop:RetryDelays). A job out of attempts is dead-lettered: kept for 30 days, shown on the dashboard, and requeued from there. A handler that knows a retry cannot help throws PermanentJobFailureException.
  • Queues. [Queue] moves from the method to the job type. The worker lists the queues it drains, and claims from them in that order: a queue only while every queue before it has nothing to claim, unless the worker gives them weights.
  • Concurrency. [DisableConcurrentExecution] takes a lock while the job runs, and a second run waits for it up to its timeout, then fails. A concurrency key does the same without a lock and without a timeout: a job whose key is held stays enqueued, and is claimed once the running one ends. Its limit is 1 unless the application sets another through IThrottleManager. A key can carry a job's argument, as [Concurrency("export:{CustomerId}")] does, to keep one customer's jobs apart from the others'.

Timeouts and cancellation

Hangfire gives a job no timeout. Bellhop gives every attempt one: 5 minutes by default (Bellhop:DefaultJobTimeout), after which the handler's token is cancelled and the attempt fails with reason Timeout; a handler that ignores its token is abandoned 30 seconds later. Give each job type that can run longer a [Timeout] of its own before you move it, or its runs will start to fail at five minutes.

The handler's ct is cancelled on timeout, when an operator cancels the job, and when the host stops and Bellhop:ShutdownTimeout (30 seconds) has passed with the handler still running, whose job is then handed back to run again. Pass it to every call the handler makes, where a Hangfire job takes a CancellationToken argument that Hangfire fills in itself.

Registration and the dashboard

Hangfire's storage, server and dashboard registrations are replaced by one AddBellhop call, with the store, the jobs and the worker, and the dashboard is mapped as an endpoint:

builder.Services.AddBellhop(bellhop => bellhop
    .UsePostgres(builder.Configuration.GetConnectionString("Default")!)
    .AddJobsFromAssemblyContaining<SendWelcomeEmail>()
    .AddWorker(worker => worker.Queues = ["critical", "default"]));

var app = builder.Build();
app.MapBellhopDashboard("/jobs").RequireAuthorization("Admins");

AddJobsFromAssemblyContaining registers every job type and handler of an assembly. A process that only enqueues registers AddClient() instead of AddWorker. Outside Development the application does not start with a dashboard that has no authorization requirement: map it with the authorization your application already uses, as running in production describes.

Running both while you move

Bellhop keeps its tables in a schema of its own, bellhop by default, so it can share the database Hangfire uses. Nothing converts stored Hangfire jobs: move one call site at a time, and leave the Hangfire server running until its queues are empty and its scheduled jobs have run.

  • New work goes to Bellhop from the moment its call site moves. Jobs Hangfire already holds still run on Hangfire.
  • Recurring jobs move as a pair. Remove the Hangfire recurring job in the same release that declares it in Bellhop, or both run it.
  • Handlers must stay idempotent. Both libraries run a job at least once: after a crash, a job may run again. Bellhop's unique keys stop a second job being created for the same work; they do not stop one job from running twice.
  • Remove Hangfire once its dashboard shows no enqueued, scheduled, processing or recurring jobs.

Where to go next: getting started for a whole application, concepts for each feature named here, and the option reference for every setting and its default.