skip to content

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%

answer

  1. WorkerCount = min(cores x 5, 20)
  2. Queues defaults to only "default"
  3. names: lowercase, digits, _ and -
  4. [Queue] re-applied on every enqueue
  5. a dedicated server for critical work

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.

solid answer

~50 s

`BackgroundJobServerOptions.WorkerCount` is the number of worker threads in one server, `Math.Min(Environment.ProcessorCount * 5, 20)` by default, and `Queues` is the list of queues those workers fetch from, `["default"]` unless you change it. A job sits on exactly one queue: `[Queue("critical")]` on the method (or its class) puts it there every time it is enqueued, including retries; names may hold only lowercase letters, digits, `_` and `-`. A job on a queue no server listens to stays Enqueued forever. Listing `["critical", "default"]` on one server does **not** give strict priority: Hangfire.PostgreSql's fetch query orders by queue *name*, and SQL Server's does not order by your list at all. For a marketplace, the reliable shape is a second `AddHangfireServer` with `Queues = ["critical"]` and its own workers, so seller payouts never wait behind a burst of thumbnail and e-mail jobs.

code

csharp · 20 lines
csharp
// Marketplace on Hangfire 1.8 + PostgreSQL: two servers in one worker process
builder.Services.AddHangfireServer(options =>
{
    options.ServerName = $"{Environment.MachineName}:critical";
    options.Queues = ["critical"];
    options.WorkerCount = 4;          // reserved for payouts
});

builder.Services.AddHangfireServer(options =>
{
    options.ServerName = $"{Environment.MachineName}:default";
    options.Queues = ["default"];      // e-mails, thumbnails, re-indexing
});

public sealed class PayoutJobs(IPayoutGateway gateway)
{
    [Queue("critical")]
    public Task PaySellerAsync(long payoutId, CancellationToken ct)
        => gateway.ExecuteAsync(payoutId, ct);
}

go deeper

for a junior

Remember that servers only process the queues they list, that the default queue is "default", and that [Queue] on a method chooses its queue.

for a middle

Explain the WorkerCount default, queue name rules, why [Queue] survives retries, and why listing order is not a priority guarantee.

for a senior

Design isolation with dedicated servers per queue, size workers by job type, and keep queue names in sync between code and server configuration.

for a principal

Decide which business flows deserve reserved capacity, and whether that reservation belongs in Hangfire queues or in separate deployments.

## Workers and queues A Hangfire **processing server** owns a fixed pool of **workers**. Each worker loops: fetch one job from storage, run it, record the result, repeat. Two `BackgroundJobServerOptions` properties shape that pool: | Option | Default | Meaning | |---|---|---| | `WorkerCount` | `Math.Min(Environment.ProcessorCount * 5, 20)` | concurrent jobs this server runs; must be positive | | `Queues` | `["default"]` | the only queues its workers fetch from; must not be empty | The defaults suit I/O-bound jobs that wait on databases and HTTP calls. CPU-heavy jobs (image processing, report rendering) want fewer workers than that; a server with 20 workers on a two-core box will thrash. ## Putting a job on a queue Every job is enqueued into exactly one **queue**, `default` unless something says otherwise: - **`[Queue("critical")]`** on the job method or its class. It is a job filter that rewrites the queue every time the job enters the Enqueued state, so automatic retries and manual requeues go back to the same queue. The name can include format placeholders filled from the job's arguments. - **Queue-taking overloads** such as `IBackgroundJobClient.Enqueue("critical", () => ...)`, which store the queue on the job itself. They need storage support; SQL Server and PostgreSQL storage both declare it. Queue names must consist of lowercase letters, digits, underscores and dashes. Anything else (`"Critical"`, `"payouts.eu"`) is rejected when the job is enqueued: the `ArgumentException` surfaces wrapped in a `BackgroundJobClientException` from the creating call. ## The trap: a queue nobody listens to Adding `[Queue("critical")]` without adding `"critical"` to some server's `Queues` sends those jobs into a queue no worker reads. They are created normally and then wait, Enqueued, indefinitely. Treat a queue name as a contract between the code that enqueues and the servers that listen. ## Why list order is not priority It is tempting to write `Queues = ["critical", "default"]` and expect critical jobs first. The order in which a worker picks among several queues is decided by the storage's fetch query: - **Hangfire.PostgreSql** selects candidates `ORDER BY fetchedat NULLS FIRST, queue, jobid`, i.e. by queue **name**. `critical` happens to sort before `default`; a queue called `payouts` would not. - **Hangfire.SqlServer** takes the first available row for any of the listed queues with no ordering by your list. Even where critical jobs come first, they still compete for the same workers: if all 20 are busy with five-minute report jobs, a payout waits. ## Isolation with dedicated servers The dependable pattern is one server per class of work. Each `AddHangfireServer` call registers another server in the same process (or put them in different processes): 1. A **critical** server: `Queues = ["critical"]`, a small `WorkerCount`, reserved for payouts and payment captures. 2. A **general** server: `Queues = ["default"]`, more workers, for e-mails, thumbnails and search re-indexing. 3. Optionally, give each a `ServerName` so the two are easy to tell apart when inspecting servers. Now a flood of e-mail jobs can saturate the general workers without touching the payout path, and capacity per class is an explicit number. ## Sizing notes - Total concurrency is the sum of `WorkerCount` across every server on every instance; the database must sustain that many concurrent job transactions. - Scaling out adds instances, each with its own workers, all fetching from the same queues.

  • A job carries [Queue("critical")] but you enqueue it with IBackgroundJobClient.Enqueue("default", ...); where does it go?
    To `critical`. `QueueAttribute` is a state-election filter that runs when the job enters Enqueued and overwrites the queue on that state, so the attribute wins over the queue passed at creation, and it keeps winning on retries and requeues.
  • How would you size WorkerCount for CPU-bound image-processing jobs?
    Below the default. The default of five workers per core, capped at 20, assumes jobs mostly wait on I/O. For CPU-bound work start near the core count on a dedicated server and queue, then measure throughput and CPU rather than adding workers blindly.

  • Queues = ["critical", "default"] guarantees critical jobs always run first.
  • A job with [Queue("critical")] runs even if no server lists that queue.
  • WorkerCount defaults to the number of processor cores.
  • Queue names are case-insensitive, so "Critical" is accepted.
  • Retried jobs fall back to the default queue.