skip to content

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%

answer

  1. ApplicationStopping sends the stop signal
  2. no new fetches once stopping
  3. job token fires after StopTimeout
  4. OperationCanceledException means re-queue
  5. the host's limit still applies

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.

solid answer

~50 s

`AddHangfireServer`'s hosted service hooks the host's lifetime: on `ApplicationStopping` it sends the stop signal, and `StopAsync` waits for the server within the host's own shutdown timeout. Workers stop fetching new jobs at once. Shortly after (`StopTimeout`, half a second by default) the token Hangfire passes to running jobs fires: a `CancellationToken` parameter or `IJobCancellationToken.ShutdownToken`. A job that passes that token to its database and HTTP calls stops quickly with `OperationCanceledException`; Hangfire treats that as an interrupted run, not a failure, and puts the job back on its queue so another server restarts it. A job that ignores the token keeps running until the host gives up and the process exits; then it is in the crash case, waiting for the storage's invisibility timeout. In a marketplace, a payout job should check the token between steps, never in the middle of an external payment call.

code

csharp · 17 lines
csharp
public sealed class ReindexListingsJob(MarketplaceDbContext db, ISearchIndex index)
{
    public async Task RunAsync(long fromListingId, CancellationToken ct)
    {
        var lastId = fromListingId;
        while (true)
        {
            ct.ThrowIfCancellationRequested();     // fires on shutdown or deletion
            var batch = await db.Listings.Where(l => l.Id > lastId)
                .OrderBy(l => l.Id).Take(500).ToListAsync(ct);
            if (batch.Count == 0) return;
            await index.UpsertAsync(batch, ct);
            lastId = batch[^1].Id;
            await db.ReindexCheckpoints.SaveAsync(lastId, ct); // resume point
        }
    }
}

go deeper

for a junior

Remember to give long Hangfire jobs a CancellationToken parameter and pass it to every async call.

for a middle

Explain the stop sequence: no new fetches, the job token firing after StopTimeout, and immediate re-queue of a job that ends with OperationCanceledException.

for a senior

Align Hangfire's timeouts with the host and orchestrator grace period, make long jobs resumable, and place cancellation checks where interruption is safe.

for a principal

Set the deployment contract for background work: maximum job length, resumability, and what a rolling deploy may interrupt.

## Who triggers the stop In ASP.NET Core, `AddHangfireServer` registers `BackgroundJobServerHostedService`. It ties the Hangfire server to the generic host: - it starts the processing server when the host reports **ApplicationStarted**; - on **ApplicationStopping** it sends the server the stop signal; - in `StopAsync` it waits for the server to finish, bounded by the cancellation token the host passes, which reflects the host's own shutdown timeout. The host-level settings (how long the host waits, what a container orchestrator's grace period is) belong to the hosting configuration; Hangfire works inside whatever time the host grants. ## Hangfire's three shutdown phases `SendStop` cancels three token sources inside the processing server: | Phase | When | Effect | |---|---|---| | Stopping | immediately | workers stop fetching; schedulers stop | | Stopped | after `StopTimeout` (500 ms default) | running jobs' cancellation token fires | | Shutdown | after `ShutdownTimeout` (15 s default) | the server abandons its remaining bookkeeping work | Both timeouts are `BackgroundJobServerOptions` properties. ## What a running job sees Hangfire substitutes the token for you: a job method with a `CancellationToken` parameter receives a token that fires in the Stopped phase (and also when the job is deleted or changes state while running, which a watcher checks every few seconds). The older `IJobCancellationToken` exposes the same through `ShutdownToken` and `ThrowIfCancellationRequested()`. Then there are two paths: 1. **The job cooperates.** It passes the token to `SaveChangesAsync`, `HttpClient` calls and loops, so it ends with `OperationCanceledException`. The worker sees the server is stopping, rethrows instead of recording a failure, and re-queues the fetched job, which clears its `FetchedAt` at once (on SQL Server and PostgreSQL alike), so the job goes back to its queue and another server can restart it immediately. It does not count as a failed attempt. 2. **The job ignores the token.** It keeps running while Hangfire and then the host wait. When the host's timeout expires the process exits with the job mid-flight, which is exactly the crash case: the job stays Processing until the storage's invisibility timeout lets another worker fetch it. ## Writing a shutdown-friendly job - Accept a `CancellationToken` and pass `CancellationToken.None` when enqueuing; Hangfire replaces it at run time. - Pass the token to every awaitable call that accepts one. - In long loops (re-indexing 100,000 listings), check it between items and keep progress somewhere durable, so the restarted run continues instead of starting over. - Decide where cancelling is **unsafe**. A seller payout that has called the payment provider must not be abandoned between the charge and recording it; check the token before the external call, not after, and make the job idempotent so a restart can detect the earlier call. ## Deployment checklist 1. Make the orchestrator's grace period at least as long as the host's shutdown timeout, or graceful shutdown never happens. 2. Keep jobs short or resumable, so they fit inside that window. 3. Expect interrupted jobs to run again; that is how a rolling deploy moves work to the new instances.

  • Does an OperationCanceledException during shutdown use up one of the job's automatic retries?
    No. When the server is stopping, the worker rethrows the cancellation instead of electing the Failed state, and the fetched job is re-queued. The job simply runs again later; retry counting applies to failures, not to interrupted runs.
  • Why might every graceful deploy still leave jobs stuck in Processing for minutes?
    If jobs ignore the token, or the orchestrator kills the container before the host's shutdown timeout, the process exits mid-job. Those jobs are recovered only through the storage's invisibility timeout, about 5 minutes on SQL Server and 30 on PostgreSQL defaults.

  • Hangfire waits for every running job to finish before the host stops.
  • A job cancelled by shutdown is marked Failed and consumes a retry.
  • The CancellationToken parameter must be serialized with the job to work.
  • Hangfire kills job threads after ShutdownTimeout.
  • Graceful shutdown makes Hangfire jobs exactly-once.