skip to content

Storage & Servers

Wiring Hangfire into an app: AddHangfire with a job storage, AddHangfireServer workers and queues, and several servers sharing one database. Interviewers probe what happens when a server dies mid-job.

on this pageshow

explore

questions

6

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%

answer

  1. client side versus processing side
  2. UsePostgreSqlStorage with UseNpgsqlConnection
  3. SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
  4. AddHangfireServer adds a hosted service
  5. PrepareSchemaIfNecessary defaults to true

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.

solid answer

~40 s

`builder.Services.AddHangfire(config => config.SetDataCompatibilityLevel(CompatibilityLevel.Version_180).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString)))` sets Hangfire's global configuration and storage and registers `JobStorage`, `IBackgroundJobClient` and `IRecurringJobManager` as singletons: that is everything an app needs to **create** jobs. `builder.Services.AddHangfireServer()` registers a hosted service that, once the host has started, runs a **processing server**: a pool of workers fetching jobs from the storage, the delayed and recurring job schedulers, heartbeats and the watchdog. The two are independent: a web API can only enqueue while a separate worker service runs the servers, as long as both point at the same database. The packages are `Hangfire.AspNetCore` (which brings `Hangfire.NetCore` and `Hangfire.Core`) plus a storage package such as `Hangfire.PostgreSql`, which creates its `hangfire` schema on startup unless `PrepareSchemaIfNecessary` is turned off.

code

csharp · 18 lines
csharp
// Program.cs: Hangfire 1.8 on PostgreSQL (Hangfire.AspNetCore + Hangfire.PostgreSql)
using Hangfire;
using Hangfire.PostgreSql;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Hangfire");

builder.Services.AddHangfire(config => config
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString)));

// Omit this line in a process that should only enqueue jobs
builder.Services.AddHangfireServer();

var app = builder.Build();
app.Run();

go deeper

for a junior

Remember the pair: AddHangfire sets up storage and the clients that create jobs, AddHangfireServer starts the workers that run them.

for a middle

Explain what the processing server contains (workers, schedulers, heartbeat, watchdog), the default WorkerCount and queue, and the schema PrepareSchemaIfNecessary creates.

for a senior

Choose the layout: client-only web nodes, dedicated worker processes, schema deployment without DDL rights, and a compatibility level that matches every server in the fleet.

for a principal

Decide whether background processing shares the web tier's scaling and failure domain or lives in its own deployable, and what the shared database means for both.

## Two roles, one storage Hangfire splits background processing into two roles that only meet in the **job storage**, a database Hangfire owns tables (or keys) in: - The **client** creates jobs: it serializes a method call and writes it to storage. Any process with the storage configured can be a client. - The **server** processes jobs: it runs workers that fetch jobs from the storage queues and execute them, plus background processes that promote delayed jobs, fire recurring jobs and clean up. In ASP.NET Core both roles are configured on the service collection, by two different calls. ## `AddHangfire`: configuration and clients `AddHangfire(Action<IGlobalConfiguration>)`, or the overload that also receives the `IServiceProvider`, does three things: 1. Runs your configuration chain against Hangfire's global configuration. The usual chain for a new 1.8 app is `SetDataCompatibilityLevel(CompatibilityLevel.Version_180)` (the newest stored data format), `UseSimpleAssemblyNameTypeSerializer()` (type names without assembly versions, so payloads survive version bumps), `UseRecommendedSerializerSettings()` and the storage call. 2. Sets the **storage**. For PostgreSQL that is `UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString))` from Hangfire.PostgreSql 1.21; the older overloads taking a connection string directly are `[Obsolete]` ("Will be removed in 2.0"). For SQL Server it is `UseSqlServerStorage(connectionString, options)` from Hangfire.SqlServer. 3. Registers singletons: `JobStorage`, `IBackgroundJobClient`, `IRecurringJobManager`, their factories and the job activator that resolves job classes from DI scopes. ## `AddHangfireServer`: the processing server `AddHangfireServer()` registers a hosted service (`BackgroundJobServerHostedService`). When the host has started, it creates a processing server with these parts: - **Workers**, `WorkerCount` of them (by default `Math.Min(Environment.ProcessorCount * 5, 20)`), listening to the queues in `Queues` (by default only `default`). - The **delayed job scheduler**, which moves due Scheduled jobs to their queue every `SchedulePollingInterval` (15 s). - The **recurring job scheduler**, which creates jobs from recurring definitions. - **Heartbeats and the server watchdog**, which announce the server every 30 s and remove servers that stopped announcing. - Storage maintenance, such as deleting expired jobs. Overloads take an `Action<BackgroundJobServerOptions>` (or one with the `IServiceProvider`) and an explicit `JobStorage`. Each call adds one more server, so a process can host several with different queues. ## Typical layouts | Layout | Web API process | Worker process | |---|---|---| | Single app | `AddHangfire` + `AddHangfireServer` | none | | Split roles | `AddHangfire` only, enqueues | `AddHangfire` + `AddHangfireServer` | | Scaled out | several instances, any mix | several instances; all share the database | Whatever the layout, every process must use the **same storage** and be able to load the job types it executes. ## Schema and connection - `PrepareSchemaIfNecessary` is `true` by default for both SQL Server and PostgreSQL storage: the first start creates or upgrades Hangfire's schema (`HangFire` on SQL Server, `hangfire` on PostgreSQL). If the application account may not run DDL, set it to `false` and apply Hangfire's install scripts during deployment. - Keep Hangfire's tables in their own schema, usually in the application database or a dedicated one; they are not managed by EF Core migrations. The dashboard is a third, separate piece, mapped onto the HTTP pipeline; it is neither required for processing nor added by these two calls.

  • The web API enqueues a job but nothing ever runs it; what do you check first?
    Whether any process calls `AddHangfireServer` against the same storage, and whether that server listens to the job's queue. `AddHangfire` alone only creates jobs; without a server, or with servers on another database, schema or queue, jobs stay Enqueued indefinitely.
  • Why call SetDataCompatibilityLevel(CompatibilityLevel.Version_180) in a new app?
    It tells Hangfire to write the 1.8 data format instead of the older format kept for compatibility. A new installation has no older servers reading the storage, so it should start on the newest format; mixed fleets upgrade the level only after every server runs 1.8.

  • AddHangfire alone starts processing jobs in the background.
  • Every web instance must run AddHangfireServer, or its jobs are lost.
  • Hangfire's tables are created by EF Core migrations.
  • Calling AddHangfireServer twice registers the same server twice and is an error.
  • The dashboard has to be mapped for jobs to be processed.
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

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

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