skip to content

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%

answer

  1. at-least-once, never exactly-once
  2. the queue row stays fetched
  3. SlidingInvisibilityTimeout = 5 minutes
  4. PostgreSQL InvisibilityTimeout = 30 minutes
  5. UseSlidingInvisibilityTimeout is off by default

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.

solid answer

~50 s

Hangfire processes jobs **at least once**. A worker marks the job's queue row as fetched, moves the job to Processing and runs it; only after recording the result does it remove the row. If the process dies in between, the row stays fetched and the job shows as Processing until the **invisibility timeout** expires and another worker fetches it again, re-running the method from the beginning. On Hangfire.SqlServer that is `SlidingInvisibilityTimeout`, 5 minutes by default: a live worker refreshes the row every minute, so a crashed job returns after about 5 minutes whatever its length. Hangfire.PostgreSql 1.21 uses `InvisibilityTimeout`, 30 minutes, measured from the fetch because `UseSlidingInvisibilityTimeout` is off by default; a healthy job running longer than 30 minutes is therefore fetched and run a **second time** while still running. Turn sliding on, and make jobs safe to repeat.

code

csharp · 10 lines
csharp
builder.Services.AddHangfire(config => config
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UsePostgreSqlStorage(
        c => c.UseNpgsqlConnection(connectionString),
        new PostgreSqlStorageOptions
        {
            // keep long jobs' rows alive; crashed jobs return after the timeout
            UseSlidingInvisibilityTimeout = true,
            InvisibilityTimeout = TimeSpan.FromMinutes(5)
        }));

go deeper

for a junior

Remember that a Hangfire job interrupted by a crash runs again later on another server, so it may execute more than once.

for a middle

Explain fetch, Processing, perform and acknowledge, and the invisibility timeout that returns an abandoned job: 5 minutes sliding on SQL Server, 30 minutes on PostgreSQL.

for a senior

Spot the PostgreSQL long-job duplicate, choose timeouts from job length and recovery goals, and make every job safe to repeat.

for a principal

Weigh recovery speed against duplicate-execution risk across storages, and set the at-least-once contract every job author must honour.

## How a worker processes a job A Hangfire worker handles one job in four steps: 1. **Fetch.** It atomically marks one row of the storage's job queue as fetched (`FetchedAt` set to now), so other workers skip it. 2. **Processing.** It changes the job's state to Processing, naming its server and worker. 3. **Perform.** It runs the job method. 4. **Acknowledge.** It records the new state (Succeeded, Failed, Scheduled for retry) and removes the queue row. Hangfire's own source comments the gap between steps 2 and 4: the job may or may not have run, so it must be re-queued to guarantee it is performed **at least once**. Exactly-once is not on offer. ## What a crash leaves behind If the process is killed (out-of-memory, a node failure, a container killed without a graceful stop) during step 3: - the queue row keeps its `FetchedAt` value; - the job stays in the **Processing** state, still naming the dead server; - no worker touches it while the row counts as fetched. The **server watchdog** on the surviving servers removes the dead server's entry after `ServerTimeout` (5 minutes) without heartbeats. That is bookkeeping only; what brings the job back is the storage's **invisibility timeout**: once `FetchedAt` is older than it, the row is fetchable again, a worker picks it up, moves the job to Processing again (Processing is an accepted starting state) and runs the method from the start. ## The storages compared | Storage | Option | Default | How it is measured | |---|---|---|---| | Hangfire.SqlServer 1.8 | `SlidingInvisibilityTimeout` | 5 min | refreshed by live workers every timeout/5 (1 min) | | Hangfire.PostgreSql 1.21 | `InvisibilityTimeout` | 30 min | from the fetch, unless `UseSlidingInvisibilityTimeout = true` | | Hangfire.Redis.StackExchange | `InvisibilityTimeout` | 30 min | checked by its fetched-jobs watcher | On SQL Server the old fixed `InvisibilityTimeout` option is `[Obsolete]`: with the sliding timeout a long job keeps its row alive, and a crashed one comes back within minutes. ## The PostgreSQL trap With Hangfire.PostgreSql's defaults the 30 minutes run from the moment of fetch and nothing extends them. A healthy job that runs 45 minutes (the marketplace's nightly settlement export, say) becomes fetchable again at minute 30, and a second worker starts it while the first is still running. Two fixes: - set `UseSlidingInvisibilityTimeout = true` in `PostgreSqlStorageOptions`, so live jobs keep refreshing their row (it relies on storage processes, so it does not work on a server with `IsLightweightServer = true`); - or raise `InvisibilityTimeout` above the longest job, accepting slower recovery after a crash. ## Graceful stop is different When the host shuts down cleanly, a job that stops on its cancellation token is **re-queued immediately** (its row's `FetchedAt` is cleared), so another server can start it at once. Only a hard kill leaves the row to the timeout. ## What this means for job code - Every job can run twice, partially or fully: crash recovery, long jobs on PostgreSQL defaults, and automatic retries all re-run the method from the top. - Design payouts and e-mails to be repeatable: check whether the payout was already executed before calling the gateway, use idempotency keys with external APIs, and write results in a way that tolerates a second run. - Pick the timeout from your longest job and your acceptable recovery delay, not from the defaults.

  • Why does the dead server's job still show as Processing for a while?
    The Processing state is only replaced when a worker re-fetches the job (after the invisibility timeout) or a final state is recorded. The watchdog removing the dead server after `ServerTimeout` (5 minutes) cleans up the server list; it does not move jobs.
  • Does lowering SlidingInvisibilityTimeout to 1 minute make crash recovery faster without risk?
    Faster, yes: live workers refresh at a fifth of the timeout. The cost is more frequent keep-alive writes, and a worker that stalls (a long garbage-collection pause, a blocked database connection) for longer than the timeout lets the job be fetched again. Keep it comfortably above any realistic pause.

A library book checked out with a due date: while the borrower keeps renewing it (sliding timeout), nobody else gets it; if the borrower disappears, the book returns to the shelf when the loan expires. With a fixed loan and no renewals, a slow reader still holding it at the due date finds a second copy has been handed to someone else.

  • When a server crashes, Hangfire marks its running jobs as Failed straight away.
  • Hangfire guarantees each job runs exactly once.
  • The server watchdog re-queues the dead server's jobs.
  • With Hangfire.PostgreSql defaults, a long-running job can never be picked up twice.
  • SQL Server storage still relies on a fixed 30-minute InvisibilityTimeout.

Assumes Hangfire 1.8.25 (SqlServerStorageOptions.SlidingInvisibilityTimeout 5 min, InvisibilityTimeout obsolete) and Hangfire.PostgreSql 1.21 (InvisibilityTimeout 30 min, UseSlidingInvisibilityTimeout false).