
Every backend eventually grows work that should not happen inside a request: sending notifications, rebuilding a report, importing a file, calling a slow third party, retrying something that failed. Moving it to the background is the easy decision. The harder ones are where the work lives while it waits, and what happens to it when a process dies halfway through.
I have used three answers in real projects: a hosted service inside the application, Hangfire, and a small queue table in the application's own database, claimed under leases. This note compares them, and then goes through the parts that matter whichever one you pick: idempotency, retries, shutdown and observability.
The rule that comes first: at least once
Any background job system that survives crashes will sometimes run a job twice. A worker can finish the work and die before it records that it finished; a lease can expire while a slow job is still running; a retry can follow a timeout that was not really a failure. Systems that promise exactly-once delivery are usually describing at-least-once delivery plus deduplication.
So the design starts with the handler, not the queue. Each job should be safe to run again:
- Upsert on a natural key instead of inserting, so a repeated write overwrites itself.
- Record the effect with the job id in the same transaction as the effect, and check it first, so a second run sees that the work is done.
- Pass an idempotency key to external APIs that support one, such as payment and messaging providers.
- Deduplicate on enqueue with a unique key, when the same event can produce the same job twice.
The only place where you get exactly-once for free is when the job's effects and its completion live in the same database transaction. That is one of the real arguments for a queue in your own database, and I will come back to it.
Option one: a hosted service
ASP.NET Core can run long-lived background work in the same process through BackgroundService. Combined with a bounded Channel<T>, it makes a simple in-memory queue:
public sealed class ReportQueue
{
private readonly Channel<Guid> _channel = Channel.CreateBounded<Guid>(
new BoundedChannelOptions(1_000) { FullMode = BoundedChannelFullMode.Wait });
public ValueTask EnqueueAsync(Guid id, CancellationToken ct) => _channel.Writer.WriteAsync(id, ct);
public IAsyncEnumerable<Guid> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
public sealed class ReportWorker(ReportQueue queue, IServiceScopeFactory scopes, ILogger<ReportWorker> log)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var id in queue.ReadAllAsync(stoppingToken))
{
await using var scope = scopes.CreateAsyncScope(); // a fresh DbContext per item
try
{
var builder = scope.ServiceProvider.GetRequiredService<ReportBuilder>();
await builder.BuildAsync(id, stoppingToken);
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{
log.LogError(ex, "Report {ReportId} failed", id);
}
}
}
}
A hosted service is a singleton, so scoped services such as a DbContext must come from a scope created per item, never from the constructor. The try/catch matters too: since .NET 6, an unhandled exception in a BackgroundService stops the whole host by default. The filter lets only shutdown end the loop; a timeout inside the handler, which also surfaces as a cancellation exception, is logged like any other failure.
The weakness is that the queue lives in memory. A deployment, a crash or a scale-down loses whatever was waiting. That is fine for work that is cheap to lose or easy to redo, like warming a cache. On a market-data pipeline I worked on with a small team, live records were buffered in memory and written to PostgreSQL in batches, using upserts on a natural key, so a record seen twice simply overwrote itself. A recurring job looked for gaps in the stored series and fetched what was missing, so a buffer lost on restart was repaired later. If I built it again, I would replace its timer callbacks with a BackgroundService reading a channel, so flushes could never overlap and shutdown could drain the buffer.
Option two: Hangfire
Hangfire stores jobs in persistent storage, such as SQL Server or Redis, with PostgreSQL available through a community package. It retries failures, schedules recurring jobs with CRON expressions and ships with a dashboard. In the same market-data pipeline, Hangfire ran the recurring work, with its storage in the same PostgreSQL database as the data: a calendar import every fifteen minutes and the gap check every few hours.
builder.Services.AddHangfire(config =>
config.UseSqlServerStorage(builder.Configuration.GetConnectionString("Jobs")));
builder.Services.AddHangfireServer();
// in a handler, with IBackgroundJobClient injected: pass an id, not the entity
jobs.Enqueue<ReportBuilder>(b => b.BuildAsync(reportId, CancellationToken.None));
// at startup, with IRecurringJobManager: an explicit id, a CRON expression and a time zone
recurring.AddOrUpdate<GapChecker>("gap-check", g => g.RunAsync(CancellationToken.None),
"0 */4 * * *", new RecurringJobOptions { TimeZone = TimeZoneInfo.Utc });
Hangfire is the fastest way to get durable jobs with retries and a screen to look at them, and most of its sharp edges come from one fact: a job is a serialized method call. The method's arguments are stored as JSON, so pass small identifiers, not entities. Each stored job also records the type name, the method name and the parameter types, so the method's signature becomes a contract with every job already in storage; rename it in one deployment and the jobs enqueued before it can no longer find their method. The CancellationToken.None in the expression is a placeholder that Hangfire replaces with a token that fires when the server shuts down or the job is deleted. Failed jobs are retried automatically with growing delays, ten times by default, which is one more reason for idempotent handlers; [AutomaticRetry(Attempts = 3)] changes the count per job. And the dashboard answers only local requests until you add an authorization filter; put it behind real authentication before exposing it.
Option three: a lease queue in PostgreSQL
The third option is a table, a claim query and a worker loop. It sounds like reinventing Hangfire, and partly it is, but it buys two things. A job can be inserted in the same transaction as the business change that caused it, so there is never an order without its confirmation job, or a job for an order that rolled back. And you control the semantics completely: what a retry means, what a dead job looks like, which tenant a job runs in.
An early version of the workflow engine in a multi-tenant platform I am building worked this way. Worker processes polled a ready queue in the database and claimed items under a lease, so several workers could run at once. An item whose lease expired went back to the queue, and after a maximum number of attempts it was failed instead of retried forever. A database transaction was never held open across an outbound call: claim and commit, execute, then commit the result. Here is the PostgreSQL form of that design:
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id text NOT NULL,
kind text NOT NULL,
payload jsonb NOT NULL,
idempotency_key text,
status text NOT NULL DEFAULT 'ready', -- ready, done, dead
attempts int NOT NULL DEFAULT 0,
run_at timestamptz NOT NULL DEFAULT now(),
lease_id uuid,
leased_until timestamptz,
last_error text,
traceparent text,
UNIQUE (tenant_id, idempotency_key)
);
CREATE INDEX jobs_due ON jobs (run_at) WHERE status = 'ready';
-- claim: $1 = batch size, $2 = lease length (a TimeSpan, sent as interval)
WITH picked AS (
SELECT id FROM jobs
WHERE status = 'ready' AND run_at <= now()
AND (leased_until IS NULL OR leased_until < now())
ORDER BY run_at
LIMIT $1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs j
SET lease_id = gen_random_uuid(), leased_until = now() + $2, attempts = j.attempts + 1
FROM picked
WHERE j.id = picked.id
RETURNING j.id, j.tenant_id, j.kind, j.payload, j.attempts, j.lease_id, j.traceparent;
FOR UPDATE SKIP LOCKED is what lets many workers run the same query without blocking each other: a row another worker is claiming at this moment is skipped instead of waited for. The row lock ends when the claim statement commits, a few milliseconds later; from then on the lease protects the job. If the worker dies, leased_until passes and the job becomes claimable again, with its attempt count already raised.
The lease_id is a fencing token. Every later update about the job includes it, so a worker that lost its lease, because it was paused or slow, cannot overwrite the result of the worker that took over:
-- done
UPDATE jobs SET status = 'done', lease_id = NULL, leased_until = NULL
WHERE id = $1 AND lease_id = $2;
-- failed: back off, or give up after the last attempt ($3 = max attempts, $4 = delay, $5 = error)
UPDATE jobs
SET status = CASE WHEN attempts >= $3 THEN 'dead' ELSE 'ready' END,
run_at = now() + $4, last_error = $5, lease_id = NULL, leased_until = NULL
WHERE id = $1 AND lease_id = $2;
If an update affects zero rows, the worker has learned that its lease is gone; it logs that and moves on. Long jobs extend their lease periodically with the same WHERE clause. And when a job's only effects are writes to this same database, they can go into the same transaction as the "done" update: if that update matches no row, the worker rolls the transaction back, and a job that lost its lease leaves no trace. That is the exactly-once case from the start of this note. In a multi-tenant system the queue table is deliberately not tenant-owned, because a worker claims across tenants; each job then runs inside its own tenant scope, so the query filters and row-level security from the previous note apply to the work itself.
Retries and backoff
Not every failure deserves a retry. I classify errors first: timeouts, connection failures and HTTP 408, 429, 502, 503 and 504 are transient; a validation error or a missing record is permanent and goes straight to dead, where retrying would only repeat it. Transient failures back off exponentially with a cap and some random jitter, for example 5 seconds times 2 to the power of the attempt, at most an hour, plus up to 20 percent. Without jitter, a hundred jobs that failed together during an outage retry together the moment it ends, and the outage comes back.
The attempt limit also protects against poison jobs. A job that crashes the worker never records a failure, but its lease keeps expiring and its attempt count keeps rising, so it reaches dead without taking the queue down with it.
Shutting down without losing work
When the host stops, it cancels the stoppingToken and waits up to HostOptions.ShutdownTimeout for background services to finish. The worker loop should stop claiming immediately, let the job in progress finish if it can, and hand back the rest:
foreach (var job in claimed)
{
if (stoppingToken.IsCancellationRequested)
{
await ReleaseAsync(job); // clears the lease now, instead of after it expires
continue;
}
await RunAsync(job, stoppingToken);
}
Release, completion and failure updates use their own short timeout rather than the stopping token, so they still run while the host is shutting down. The shutdown timeout has to fit inside whatever kills the process after it: Kubernetes, for example, sends SIGTERM and waits 30 seconds by default before SIGKILL. If the process is killed anyway, nothing is lost; the lease expires and another worker picks the job up. Graceful shutdown makes recovery fast, and the lease makes it certain.
Observability
A queue that fails quietly is worse than one that fails loudly. Three signals cover most of what I need:
- Age of the oldest due job. A better alert than queue length, because it measures what users feel. A long queue that drains fast is fine; a short queue with a job waiting for an hour is not.
- Dead jobs. Their count and the newest
last_error, on a dashboard and an alert. - Duration and outcome per job kind, as a histogram from a
Meter, exported with OpenTelemetry.
SELECT count(*) FILTER (WHERE status = 'ready' AND run_at <= now()) AS due,
count(*) FILTER (WHERE status = 'dead') AS dead,
now() - min(run_at) FILTER (WHERE status = 'ready' AND run_at <= now()) AS oldest_due
FROM jobs;
Every log line a job writes should carry the job id, its kind, the attempt and the tenant, using the log context techniques from the Serilog note. And the traceparent column connects the job to the request that created it: store Activity.Current?.Id when enqueuing, parse it with ActivityContext.TryParse when running, and start the job's activity with that parent. In a trace viewer the job then appears under the request, even when it ran ten minutes later on another machine.
Choosing
My rule of thumb is short. Use a hosted service for work that is cheap to lose or rebuilds itself. Use Hangfire when you want durable jobs, retries, recurring schedules and a dashboard this week, and you can live with jobs being serialized method calls. Build a lease queue when jobs must be enqueued atomically with your data, when you need control over tenancy and retry semantics, or when you would rather own a hundred lines of SQL than another moving part. All three are at-least-once, so whichever you choose, write the handler as if it will run twice, because one day it will.
The next note steps back from single jobs to the shape of a whole application: a modular monolith in .NET 10, with module boundaries, contracts between modules and architecture tests that keep them honest.
If you are untangling background work that loses jobs, runs them twice or hides its failures, that is the kind of backend work I take on.
This note is also available in Persian: read the Persian version.
