skip to content

Hangfire

Hangfire runs .NET background jobs from persistent storage: fire-and-forget, delayed, continuation and recurring jobs, worker servers and a dashboard. Interviewers ask what survives a restart.

on this pageshow

explore

questions

18

With Hangfire, what is the difference between BackgroundJob.Enqueue, BackgroundJob.Schedule and RecurringJob.AddOrUpdate, and when do you use each?

level: juniorimportance: must knowfreq 72%

answer

  1. three job kinds plus continuations
  2. Enqueue returns the job id string
  3. Schedule takes TimeSpan or DateTimeOffset
  4. AddOrUpdate stores a definition, not a job
  5. Cron.Daily() means midnight UTC

basics

~20 s

BackgroundJob.Enqueue creates a fire-and-forget job that runs as soon as a worker is free; BackgroundJob.Schedule creates a job that runs after a delay or at a set time; RecurringJob.AddOrUpdate registers a cron schedule that creates a new job at every occurrence.

solid answer

~40 s

All three write to Hangfire's storage and return at once, so the request never runs the work itself. `BackgroundJob.Enqueue(() => ...)` creates a **fire-and-forget** job in the Enqueued state and returns its id as a `string`; a worker on any Hangfire server listening to its queue picks it up. `BackgroundJob.Schedule(() => ..., TimeSpan.FromHours(1))` (or a `DateTimeOffset`) creates a **delayed** job in the Scheduled state, which the server's scheduler moves to the queue once the time has passed: the shop's abandoned-cart reminder an hour after a cart goes idle. `RecurringJob.AddOrUpdate("nightly-sales-report", () => ..., Cron.Daily(2))` creates no job at all: it stores a **recurring job** definition, an id plus a cron expression, and each occurrence creates a fresh background job. The fourth kind, `BackgroundJob.ContinueJobWith(parentId, ...)`, waits for a parent job to finish.

code

csharp · 20 lines
csharp
// Program.cs (Hangfire 1.8, after AddHangfire and AddHangfireServer)
using Hangfire;

app.MapPost("/orders/{orderId:int}/confirm", (int orderId, IBackgroundJobClient jobs) =>
{
    // fire-and-forget: a worker sends the e-mail
    var jobId = jobs.Enqueue<IOrderMailer>(m => m.SendConfirmationAsync(orderId));
    return Results.Accepted(value: new { jobId });
});

app.MapPost("/carts/{cartId:guid}/idle", (Guid cartId, IBackgroundJobClient jobs) =>
{
    // delayed: remind the shopper in one hour
    jobs.Schedule<ICartReminder>(r => r.RemindAsync(cartId), TimeSpan.FromHours(1));
    return Results.NoContent();
});

// recurring: one stored definition, a new job every night at 02:00 UTC
app.Services.GetRequiredService<IRecurringJobManager>()
    .AddOrUpdate<ISalesReportService>("nightly-sales-report", s => s.BuildAsync(), Cron.Daily(2));

go deeper

for a junior

Name the three kinds and the call for each: Enqueue for now, Schedule for later, AddOrUpdate with an id and a cron for repeating work, and say that each returns before the work runs.

for a middle

Explain that every call only writes a record to storage, that Schedule depends on a polling scheduler, and that a recurring job is a definition which spawns ordinary jobs.

for a senior

Show how you pick between them for real flows: cancellable delayed jobs that still guard themselves, recurring definitions registered idempotently, and when a hosted service is the simpler tool.

for a principal

Frame Hangfire as durable, storage-backed work distribution, and weigh its operational cost against in-process loops or a message broker for the shop's workload.

## What a Hangfire job is A **Hangfire background job** is a method call recorded in persistent storage (SQL Server, PostgreSQL, Redis and others): the type, the method, its parameter types and its serialized arguments. The **client** side writes that record; in ASP.NET Core it is the static `BackgroundJob` / `RecurringJob` classes or the injected `IBackgroundJobClient` / `IRecurringJobManager`. The **server** side, added with `AddHangfireServer`, runs workers that fetch jobs from storage and invoke the method. Because the job is stored before anything runs, it survives an application restart, a deploy or a crash, and it can run on a different machine from the one that created it. That is the point of using Hangfire instead of `Task.Run` or an unawaited task inside an endpoint, whose work lives only in one process's memory. ## The four ways to create work | API | Kind | State it is created in | When the method runs | Returns | |---|---|---|---|---| | `BackgroundJob.Enqueue` | fire-and-forget | Enqueued | as soon as a worker is free | the job id (`string`) | | `BackgroundJob.Schedule` | delayed | Scheduled | after a `TimeSpan`, or at a `DateTimeOffset` | the job id | | `BackgroundJob.ContinueJobWith` | continuation | Awaiting | after a parent job finishes | the job id | | `RecurringJob.AddOrUpdate` | recurring | none: it stores a definition | each cron occurrence creates a new job | `void` | The lambda you pass is an **expression tree**, not a delegate Hangfire calls later: Hangfire reads which method it names and evaluates the arguments right away. ## Fire-and-forget: `Enqueue` Use it when the caller should not wait for slow or unreliable work: sending the order-confirmation e-mail after checkout, resizing product images, calling a payment provider's slow reconciliation API. The endpoint returns as soon as the job row is written, and the returned id can be logged or stored to look the job up later. ## Delayed: `Schedule` Use it when the work belongs to a moment relative to an event. In an online shop the classic case is the **abandoned-cart reminder**: when a cart goes idle, schedule a reminder for one hour later. Two details matter: - The time is a lower bound, not an appointment. A server-side scheduler checks for due jobs on a polling interval (`BackgroundJobServerOptions.SchedulePollingInterval`, 15 seconds by default) and then enqueues them, where they wait for a free worker. - You can cancel it. Keep the id `Schedule` returned and call `BackgroundJob.Delete(jobId)` when the customer checks out first. The reminder job itself should still re-check the cart when it runs, because the delete can race with a worker that has just picked the job up. ## Recurring: `AddOrUpdate` Use it for calendar-driven work: the **nightly sales report**, a weekly stock-level export, an hourly cache warm-up. `RecurringJob.AddOrUpdate` stores a definition under an id you choose, with a cron expression such as `Cron.Daily(2)` (the string `"0 2 * * *"`). It does not run anything when called; each time the cron fires, the recurring-job scheduler creates an ordinary background job from the definition, and that job is processed, retried and listed like any other. In Hangfire 1.8 every overload without an explicit recurring job id is `[Obsolete]`, and the schedule is read in UTC unless `RecurringJobOptions.TimeZone` says otherwise. ## Choosing between them 1. The user must not wait, and the work must not be lost: `Enqueue`. 2. The work belongs to a later moment tied to one event: `Schedule`, keeping the id if it may need cancelling. 3. The work belongs to the calendar, not to an event: a recurring job. 4. The work must follow another job: `ContinueJobWith`. 5. The loop is in-process, needs no persistence and no dashboard: a plain hosted service, not Hangfire at all. What ties all four together is that the caller only **creates** a record; the decision of when and where the method runs belongs to the Hangfire servers reading the same storage.

  • Why not just call Task.Run from the endpoint instead of BackgroundJob.Enqueue?
    Work started with `Task.Run` exists only in that process's memory: a restart, a deploy or a crash loses it, nothing retries it, and no other instance can pick it up. `Enqueue` writes the job to storage first, so it survives restarts, can run on any Hangfire server, and is retried and visible like every other job.
  • How do you cancel the abandoned-cart reminder if the customer checks out within the hour?
    Store the id that `Schedule` returned, for example on the cart row, and call `BackgroundJob.Delete(jobId)` (or `IBackgroundJobClient.Delete`) at checkout; it moves the job to Deleted and returns whether the state change happened. Keep a guard in the job too, re-reading the cart and exiting if it was checked out, because a worker may already have started it.

  • BackgroundJob.Enqueue runs the lambda straight away on the thread pool, like Task.Run.
  • A fire-and-forget Hangfire job is lost if the app restarts before it runs.
  • BackgroundJob.Schedule fires at exactly the second you asked for.
  • RecurringJob.AddOrUpdate runs the job once immediately and then on the schedule.
  • Cron.Daily() runs at midnight in the server's local time zone.
open as a page

In an ASP.NET Core 10 app, how do you wire Hangfire with AddHangfire, a PostgreSQL job storage and AddHangfireServer, and what does each call do?

level: juniorimportance: must knowfreq 62%

basics

~20 s

AddHangfire configures Hangfire globally, sets the job storage (UsePostgreSqlStorage for PostgreSQL) and registers the job clients. AddHangfireServer adds a hosted service that runs a processing server: workers that execute jobs plus the schedulers, all reading the same storage.

open as a page

With Hangfire, why should a job method take an order id rather than the Order entity, and what happens to its arguments at enqueue time?

level: middleimportance: must knowfreq 58%

basics

~20 s

Hangfire evaluates a job's arguments and serializes them to JSON in storage when the job is created, so an entity becomes a stale, bulky snapshot. Passing the id lets the job load current data when it actually runs.

open as a page

With Hangfire, how does [AutomaticRetry] behave by default, and how do you stop a flaky payout job from retrying for days on errors that will never succeed?

level: middleimportance: must knowfreq 50%

basics

~20 s

AutomaticRetryAttribute is global: a throwing job is retried 10 times with growing delays, about 4.5 hours in all, then left Failed. A method-level [AutomaticRetry] with fewer Attempts or ExceptOn for permanent errors stops pointless retries.

open as a page

With Hangfire on ASP.NET Core, why does the dashboard work on a developer machine but return 401 once deployed, and how do you secure it properly?

level: middleimportance: must knowfreq 52%

basics

~10 s

DashboardOptions.Authorization defaults to LocalRequestsOnlyAuthorizationFilter, which admits only loopback or same-IP requests, so a deployed dashboard answers 401. Replace it with your own IDashboardAuthorizationFilter, or map it with MapHangfireDashboardWithAuthorizationPolicy and an ASP.NET Core policy.

open as a page

With Hangfire on SQL Server or PostgreSQL, what happens to a job whose server process dies mid-execution, and which storage option decides when it runs again?

level: seniorimportance: must knowfreq 42%

basics

~20 s

The job stays in Processing while its queue row remains marked as fetched. Once the storage's invisibility timeout passes, another worker fetches it and runs it again from the start: 5 minutes by default on SQL Server, 30 minutes on Hangfire.PostgreSql.

open as a page

In Hangfire, which states can a background job be in, how does it move between them, and which ones expire on their own?

level: juniorimportance: should knowfreq 48%

basics

~20 s

A job starts Enqueued, Scheduled or Awaiting, becomes Processing on a worker, and ends Succeeded, Failed or Deleted. Succeeded and Deleted are final and expire after a day; Failed stays until someone requeues or deletes it.

open as a page

With Hangfire, how does BackgroundJob.ContinueJobWith chain two jobs, and what happens to the continuation when the parent job fails?

level: middleimportance: should knowfreq 35%

basics

~20 s

ContinueJobWith(parentId, ...) creates a job in the Awaiting state that is enqueued when the parent reaches Succeeded. A failed parent leaves it waiting, because Failed is not a final state; a deleted parent deletes it under the default options.

open as a page

In an ASP.NET Core app using Hangfire, why inject IBackgroundJobClient instead of calling the static BackgroundJob class, and how do you unit-test the enqueue?

level: middleimportance: should knowfreq 40%

basics

~20 s

IBackgroundJobClient comes from DI bound to the storage AddHangfire configured, and a test can replace it. Enqueue and Schedule are extension methods over Create(Job, IState), so a test verifies Create with an EnqueuedState or ScheduledState.

open as a page

With Hangfire 1.8, why does RecurringJob.AddOrUpdate take an explicit recurring job id, and what happens when it runs at every startup?

level: middleimportance: should knowfreq 45%

basics

~20 s

The id is the recurring job's key in storage: AddOrUpdate creates or overwrites the definition with that id, so calling it at every startup never duplicates it. Hangfire 1.8's id-less overloads, which derived the id from type and method, are obsolete.

open as a page

For Hangfire 1.8, how do the SQL Server, PostgreSQL and Redis storages differ, and which options set pickup latency and schema creation?

level: middleimportance: should knowfreq 30%

basics

~20 s

Hangfire.SqlServer is maintained with Hangfire itself; Hangfire.PostgreSql and Hangfire.Redis.StackExchange are community packages, and Hangfire.Pro.Redis is commercial. Pickup latency comes from QueuePollInterval (sub-second on SQL Server, 15 s on PostgreSQL unless EnableLongPolling); PrepareSchemaIfNecessary creates the schema.

open as a page

With Hangfire on ASP.NET Core, what happens to running jobs when the host shuts down gracefully, and how should a long job use its CancellationToken?

level: middleimportance: should knowfreq 35%

basics

~20 s

On shutdown the Hangfire server stops fetching, then cancels running jobs' CancellationToken. A job that stops by throwing OperationCanceledException is re-queued immediately for another server; a job that ignores the token is cut off when the process exits and recovered later.

open as a page

With Hangfire, how do BackgroundJobServerOptions.WorkerCount and Queues work, and how does [Queue("critical")] keep a marketplace's payout jobs ahead of e-mails?

level: middleimportance: should knowfreq 45%

basics

~20 s

A Hangfire server runs WorkerCount workers (default min(cores x 5, 20)) that fetch only from the queues in Queues (default "default"). [Queue("critical")] puts a method's jobs on that queue; a dedicated server listening only to critical guarantees payouts their own workers.

open as a page

With Hangfire, a nightly sales report must run at 04:00 shop time and only once after a server outage; which RecurringJobOptions settings achieve that, and what are their defaults?

level: seniorimportance: should knowfreq 30%

basics

~10 s

RecurringJobOptions.TimeZone, default UTC, decides whose 04:00 the cron means. MisfireHandling, default Relaxed, makes a gap of missed occurrences produce one job; Strict creates one job per missed occurrence and Ignorable creates none.

open as a page

With Hangfire, what does [DisableConcurrentExecution(timeoutInSeconds)] actually guarantee, and when is a dedicated queue with one worker the better tool?

level: seniorimportance: should knowfreq 30%

basics

~20 s

[DisableConcurrentExecution] holds a storage distributed lock while the job method runs, so runs sharing a lock resource never overlap. It does not skip duplicates: the second run waits on its worker and fails into retries after the timeout.

open as a page

With Hangfire, when can a seller-payout job's method run more than once, and how do you write it so a second run pays nobody twice?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A Hangfire job reruns on every automatic retry, after a crash or expired invisibility timeout, and on a manual requeue. The payout job checks its recorded state first and sends the provider a key that stays stable across runs.

open as a page

When several Hangfire servers share one PostgreSQL database, what stops two of them running the same job or recurring occurrence, and how do Hangfire's distributed locks work?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Each queue row is claimed atomically, so only one worker fetches a job, and every server's schedulers take a storage-level distributed lock before promoting delayed or recurring jobs. The lock is a SQL Server application lock, a PostgreSQL lock-table row or a Redis key.

open as a page

With Hangfire, how do job filters such as IClientFilter, IServerFilter and IElectStateFilter work, and how would you add one that alerts when a payout job finally fails?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Job filters are Hangfire's hooks around creation (IClientFilter), execution (IServerFilter) and state changes (IElectStateFilter, IApplyStateFilter). Apply one as a JobFilterAttribute on a method or class, or globally with config.UseFilter; a final-failure alert fits IApplyStateFilter.

open as a page