Hangfire

On this page 7

Hangfire is an open-source background job framework for .NET that lets an application enqueue, delay and schedule method calls for execution outside the request thread, with persistent storage guaranteeing that jobs survive process restarts. In scheduling within automation, it fills the role that Sidekiq plays for Ruby or Celery for Python: a job queue, worker runtime and recurring job scheduler combined in one library.

Hangfire runs inside an existing ASP.NET Core application, a Windows service or a console host. It requires no separate broker process in its default setup, because jobs and their state are stored in a database such as SQL Server, PostgreSQL or Redis, and it ships with a built-in monitoring dashboard.

How Hangfire stores and executes jobs

Hangfire works by serializing a method call into a job record, writing it to storage and letting a background server pick it up. The client side, the storage and the server are separate roles that can run in one process or across many machines.

When code calls BackgroundJob.Enqueue(() => SendEmail(id)), Hangfire records the type, method name and serialized arguments, not the delegate itself. A worker later deserializes the record, resolves the type through the configured dependency injection container and invokes the method. For this reason, job arguments should be small, serializable identifiers rather than large objects or open connections.

The table below describes the core components and their responsibilities.

ComponentRoleNotes
Background job clientCreates jobs and writes them to storageUsable from web apps, services or scripts
Job storagePersists jobs, queues, states and locksSQL Server by default, other providers available
Background job serverHosts workers that fetch and run jobsWorker count configurable per server
Recurring job schedulerTurns cron expressions into enqueued jobsRuns inside each server instance
DashboardWeb interface for monitoring and manual actionsMust be protected by authorization
Main components of a Hangfire deployment

Job types supported by Hangfire

Hangfire offers four basic job types in its open-source edition, covering immediate, deferred, periodic and dependent work. Batches, which group many jobs with a shared completion callback, belong to the commercial Hangfire Pro edition.

Job typeAPI entry pointTypical use
Fire-and-forgetBackgroundJob.EnqueueSending a confirmation email after signup
Delayed jobBackgroundJob.ScheduleReminder sent 24 hours after an event
Recurring jobRecurringJob.AddOrUpdateNightly report defined by a cron expression
ContinuationBackgroundJob.ContinueJobWithJob that runs after a parent job succeeds
Batch (Pro)BatchJob.StartNewAtomic group of jobs with one callback
Job types and typical use

Recurring jobs are identified by a stable job identifier, so calling AddOrUpdate on every application start updates the definition instead of creating duplicates. Time zones can be set per recurring job, which matters for schedules that must follow local business hours across daylight saving changes.

Reliability features and job states

Hangfire provides at-least-once execution: a job fetched by a worker that dies is eventually returned to the queue and run again. Each job moves through explicit states, and the transitions are recorded for inspection in the dashboard.

StateMeaningNext step
EnqueuedWaiting in a queue for a free workerMoves to processing
ScheduledWaiting for a future execution timeMoves to enqueued when due
ProcessingBeing executed by a workerEnds as succeeded or failed
SucceededCompleted without exceptionExpires after a retention period
FailedException after all retry attemptsManual requeue or deletion
DeletedRemoved manually or by a filterExpires after a retention period
Common job states in Hangfire

The built-in automatic retry filter retries a failed job 10 times by default with growing delays between attempts. The number of attempts and the behavior on final failure are configurable per job through attributes. Because retries and worker crashes can repeat execution, job methods should be idempotent, for example by checking whether an invoice was already sent before sending it.

Hangfire compared with other schedulers

Hangfire competes with both in-process .NET schedulers and language-specific job queues on other platforms. Its main differentiators are tight .NET integration, persistent storage without a broker and the included dashboard.

ToolPlatformStorage or brokerDistinctive trait
Hangfire.NETSQL Server, PostgreSQL, Redis and othersDashboard and simple setup
Quartz.NET.NETIn-memory or relational job storeRich trigger and calendar model
SidekiqRubyRedisHigh throughput with threads
CeleryPythonRabbitMQ or Redis brokerMature distributed task queue
BullMQNode.jsRedisFlows and rate limiting
Hangfire and comparable tools

Quartz.NET is often preferred when complex calendars and trigger rules are required, whereas Hangfire is favored when the main need is reliable background processing with occasional cron schedules. For enterprise workload automation across many applications, tools such as Control-M operate at a different level.

Practical configuration and common mistakes

A sound Hangfire deployment depends on choosing the right storage, sizing workers and isolating workloads with queues. Storage polling interval, worker count and queue order have the largest influence on throughput and latency.

  • Use named queues to separate critical jobs from bulk work, and order queues by priority on each server.
  • Size worker counts to the job profile: I/O-bound jobs tolerate more workers than CPU-bound jobs.
  • Protect the dashboard with an authorization filter, because by default it is reachable only locally.
  • Avoid passing entities as arguments; pass identifiers and reload current data inside the job.
  • Version job signatures carefully, since queued jobs reference method names that must still exist after a deployment.

A frequent failure mode is renaming or removing a method while jobs that reference it are still queued, which leaves them failing after deployment. Another is placing long-running jobs in the same queue as short user-facing tasks, so that a burst of heavy work delays time-sensitive notifications.

In plain words

Hangfire is a helper for .NET programs that handles work in the background. Some tasks take too long to do while a user waits. Others need to happen later or on a schedule. Hangfire writes each task down in a database and lets background workers do it when the time comes.

Think of it as a to-do list that never gets lost. If the program restarts, the list is still there. If a task fails, Hangfire tries again automatically. A web page shows what is waiting, running or broken.

A real-world example

An online booking platform built on ASP.NET Core must send confirmation emails, generate PDF invoices and remind guests two days before arrival. Doing this inside the web request made checkout slow and lost emails whenever the mail server was briefly unavailable.

The team adds Hangfire with SQL Server storage. Checkout now enqueues a fire-and-forget job for the email, a continuation job for the invoice and a delayed job for the reminder. A recurring job at 02:00 local time cleans up expired reservations. Mail outages now cause automatic retries instead of lost messages, and checkout response time drops noticeably because the request no longer waits for slow external services.