A full background job system design: requirements and job-volume estimates, a job table plus Azure Service Bus queues, priorities and per-tenant fairness, a scheduler that is safe on many instances, competing-consumer workers with leases, retries with backoff and dead-lettering, at-least-once delivery with idempotent handlers for exactly-once effects, long jobs, observability, and build vs Hangfire or Durable Functions, on Azure with .NET.
Queues give you at-least-once delivery, so exactly-once effects come from idempotent handlers, not the infrastructure. My design: every job is a row in a jobs table (type, status, attempts, idempotency key) and a message on Azure Service Bus that wakes a worker. Priorities are separate queues with their own worker capacity, and per-tenant fairness stops one big tenant starving the rest. Scheduled jobs come from a single leader (a blob lease) or scheduled messages, never a timer on every instance. Workers are competing consumers with peek-lock, renewing locks and checkpointing long jobs. Failures retry with exponential backoff and jitter, then go to a dead-letter queue with alerting. The trade-off: building gives control; Hangfire or Durable Functions give most of it for free.
"I'd clarify the job mix first: [invoice emails], which must go out once and promptly; [monthly reports] that take up to [20 minutes]; [partner syncs] that hit rate-limited APIs; and scheduled jobs like nightly reminders. Volumes of [about 500,000] jobs a day with spikes at month-end, when one large tenant can enqueue [50,000] invoices at once. Then I'd say the honest thing up front: no queue gives exactly-once delivery. Service Bus gives at-least-once with peek-lock, so I design for duplicates and make the effects idempotent.
The core is a jobs table plus queues. Enqueueing a job inserts a row with a type, payload reference, idempotency key and status, in the same transaction as the business change, through an outbox, and then a message goes on the right queue. Priorities are separate queues,
critical,defaultandbulk, each with its own worker pool, so a report backlog can't delay a password-reset email. For fairness I'd shard bulk work by tenant, for example with Service Bus sessions keyed by tenant id so one tenant's jobs are processed by one consumer at a time and other tenants keep flowing.For example, at [company] we [ran scheduled jobs with a timer in every API instance], and [after scaling to six instances customers got six reminder emails]; [moving to a single leader with a blob lease and idempotency keys] [fixed it the same day].
Workers use peek-lock, renew the lock for long jobs, and checkpoint progress, so a report killed by a deployment resumes instead of starting over. Retries use exponential backoff with jitter, and respect
Retry-Afterfrom partners. After [5] attempts the job dead-letters, the status saysFailed, and someone is alerted with a replay button. For exactly-once effects: invoice sending checks and records 'sent' in the same transaction, and calls to payment or email providers pass our idempotency key so the provider deduplicates too.The mistake I see is building all this before trying Hangfire or Durable Functions. They solve 80% of it; I build only what they can't."
| Type | Requirement | Assumption |
|---|---|---|
| Functional | Enqueue now, delay, or on a CRON schedule | Triggered by API, events, schedules |
| Functional | Priorities, cancellation, status and progress | Visible to users and support |
| Functional | Retries and manual replay | Configurable per job type |
| Non-functional | Critical jobs start within 5 s | Dedicated capacity |
| Non-functional | No customer-visible duplicates | Idempotent effects |
| Non-functional | Jobs up to 30 min survive deploys | Checkpoints, lock renewal |
| Quantity | Arithmetic | Result |
|---|---|---|
| Jobs | 500,000/day | ≈ 6/s avg; month-end ×20 ≈ 120/s |
| Average duration | 2 s (most) to 20 min (reports) | Concurrency ≈ rate × duration |
| Workers for default queue | 6/s × 2 s = 12 concurrent → ×3 headroom | ≈ 36 concurrent handlers |
| Job rows | 500,000 × 1 KB × 30-day retention | ≈ 15 GB, archived after |
API / event handlers ── same tx ──► Jobs table + Outbox ── relay ──► Service Bus queues
├─ critical (ScaleRule: queue length)
Scheduler (single leader via blob lease) ─── CRON due ──► enqueue ├─ default
└─ bulk (sessions by tenant)
│ peek-lock
▼
Workers (Container Apps / AKS, KEDA scaling on queue length)
│ idempotent handler, checkpoints, lock renewal
├──► Partners (idempotency key, Retry-After)
└──► DLQ ──► alert + replay tool
Status API ◄── Jobs table (status, attempts, progress)
| Guarantee | Meaning | How you get it |
|---|---|---|
| At-most-once | May be lost, never repeated | Receive-and-delete; rarely acceptable |
| At-least-once | Never lost, may repeat | Peek-lock, complete after success |
| Exactly-once effect | Repeats are harmless | At-least-once + idempotent handler |
A billing platform running [500,000] jobs a day moved from timers in API instances to Service Bus queues with priority pools and idempotency keys: duplicate customer emails went from [a few hundred a month to zero], critical-job start time stayed under [3 s] during month-end, and reports survived deployments thanks to checkpoints instead of restarting [20-minute] runs.
Checks that the candidate designs a job system that is correct under at-least-once delivery, separates priorities, schedules safely across instances and handles retries, long jobs and poison messages.
Green flags
Red flags
Task.Run in a request as the job systemA worker can finish the work and crash before acknowledging; the broker must redeliver or risk losing it. So the choice is lose-sometimes or repeat-sometimes. Choose repeat, and make repeats harmless.
| Effect | Technique |
|---|---|
| Database change | Unique constraint on the business key, or inbox table of processed job ids in the same transaction |
| Email or SMS | Record 'sent' with the job id before/with sending; provider idempotency key where supported |
| Payment | Provider idempotency key = job id |
| Partner API without idempotency | Look up before create; reconcile; accept rare duplicates and detect them |
A PeriodicTimer in every instance runs the job N times. Options: a leader elected with a blob lease (renew every 15 s; others stand by); a database row lock (sp_getapplock); scheduled messages (ScheduledEnqueueTime) for one-off delays; or a platform scheduler (Container Apps jobs with a cron trigger, Azure Functions timer triggers which use a lease internally). Make each scheduled occurrence idempotent too, keyed by job type + scheduled time, so a leader failover doesn't double-fire.
Separate queues per priority with separate worker pools and scaling rules. A single queue with a priority field doesn't work on FIFO brokers. Fairness across tenants: sessions per tenant on the bulk queue, or a scheduler that pulls round-robin from per-tenant backlogs and caps concurrency per tenant.
Service Bus locks last a limited time, so the processor renews them (MaxAutoLockRenewalDuration). Better still, split long jobs into steps with checkpoints stored in the job row, or use Durable Functions orchestrations, which checkpoint automatically. Handle SIGTERM during deploys: stop taking new work, finish or checkpoint the current one.
Exponential backoff with jitter (1 s, 4 s, 16 s ...) avoids synchronised retry storms. Distinguish transient (timeouts, 429, 503) from permanent errors (validation, 400): permanent errors fail immediately. After max attempts, dead-letter with the reason; a replay tool requeues after a fix.
| Option | Strengths | Limits |
|---|---|---|
| Hangfire | Dashboard, retries, recurring jobs, SQL storage | Throughput limited by storage; licence for Pro features |
| Quartz.NET | Rich scheduling, clustering | Scheduling only, you add queues |
| Durable Functions | Orchestrations, checkpoints, timers | Functions programming model |
| Container Apps jobs | Cron and event-triggered containers | Coarse-grained |
| Custom on Service Bus | Full control, scale | You own everything |
SQS with visibility timeout, EventBridge Scheduler, Step Functions for long workflows, ECS/Fargate or Lambda workers.
BackgroundService timer on three instances and count executions; then add a blob-lease leader.A Service Bus worker with peek-lock, lock renewal, idempotent handling via a processed-jobs table, and transient vs permanent error handling.
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;
namespace Jobs;
public sealed record ProcessedJob(string JobId, DateTimeOffset ProcessedAt);
public sealed class JobsDb(DbContextOptions<JobsDb> o) : DbContext(o)
{
public DbSet<ProcessedJob> Processed => Set<ProcessedJob>();
protected override void OnModelCreating(ModelBuilder b) => b.Entity<ProcessedJob>().HasKey(x => x.JobId);
}
public sealed class PermanentJobException(string message) : Exception(message);
public interface IInvoiceSender { Task SendAsync(Guid invoiceId, string idempotencyKey, CancellationToken ct); }
public sealed class InvoiceWorker(ServiceBusClient client, IServiceScopeFactory scopes, ILogger<InvoiceWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using var processor = client.CreateProcessor("default", new ServiceBusProcessorOptions
{
AutoCompleteMessages = false, // complete only after success
MaxConcurrentCalls = 16,
MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(30) // long jobs keep their lock
});
processor.ProcessMessageAsync += async args =>
{
var jobId = args.Message.MessageId;
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<JobsDb>();
var sender = scope.ServiceProvider.GetRequiredService<IInvoiceSender>();
if (await db.Processed.AnyAsync(p => p.JobId == jobId, args.CancellationToken))
{
await args.CompleteMessageAsync(args.Message); // duplicate delivery: effect already done
return;
}
try
{
var invoiceId = Guid.Parse(args.Message.Body.ToString());
await sender.SendAsync(invoiceId, idempotencyKey: jobId, args.CancellationToken); // provider dedups too
db.Processed.Add(new ProcessedJob(jobId, DateTimeOffset.UtcNow));
await db.SaveChangesAsync(args.CancellationToken);
await args.CompleteMessageAsync(args.Message);
}
catch (PermanentJobException ex)
{
// No point retrying bad input: dead-letter now with a reason.
await args.DeadLetterMessageAsync(args.Message, "Permanent", ex.Message);
}
// Transient exceptions propagate: the lock is abandoned and Service Bus redelivers
// until MaxDeliveryCount, then dead-letters. For backoff, reschedule a copy with a delay instead.
};
processor.ProcessErrorAsync += e => { log.LogError(e.Exception, "Processor error {Source}", e.ErrorSource); return Task.CompletedTask; };
await processor.StartProcessingAsync(stoppingToken);
try { await Task.Delay(Timeout.Infinite, stoppingToken); }
finally { await processor.StopProcessingAsync(); } // stop taking work on SIGTERM
}
}
// Delayed retry with exponential backoff and jitter: schedule a new message instead of hot-looping.
static DateTimeOffset NextAttempt(int attempt, TimeProvider clock) =>
clock.GetUtcNow() + TimeSpan.FromSeconds(Math.Pow(4, attempt)) + TimeSpan.FromMilliseconds(Random.Shared.Next(0, 1000));
// await sender.ScheduleMessageAsync(retryMessage, NextAttempt(attempt, TimeProvider.System), ct);
AddResilienceHandler on the partner's HttpClient); when it opens, reschedule that partner's jobs for later without counting an attempt, and cap concurrency per partner with a bulkhead.Task.Run inside API requests. Why it is wrong: work is lost on recycle and isn't observable. Instead: a durable queue and workers.The two senior points are: be explicit that exactly-once is an effect you engineer with idempotency, and separate capacity by priority so urgent work is never behind bulk work. Then I'd push hard on buy before build; a custom job platform is a product your team must run forever.
External calls are where idempotency gets hard. If a partner API supports idempotency keys, pass the job id. If it doesn't, a timeout leaves you not knowing whether the call worked, so the handler first looks up whether the record already exists (by our reference stored on their side), and a reconciliation job compares both sides daily, raising duplicates for correction or compensation (cancel the duplicate invoice, issue a credit). Under month-end peaks, a per-partner circuit breaker and concurrency cap protect both the partner and your attempt budget.
Storage at volume. At 500,000 jobs a day the jobs table grows by ~15 GB a month; keep it lean (payloads in Blob, not the row), index on (Status, NextAttemptAt), partition or purge completed jobs after 30 days to an archive, and keep the processed-ids table to the redelivery window.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Hangfire on SQL | Small to medium volume, wants a dashboard | Storage load, Pro licence for some features | Hundreds of jobs/s |
| Durable Functions | Multi-step, long-running workflows | Functions model, replay rules | Simple fire-and-forget jobs |
| Service Bus + workers | High volume, priorities, fairness | You build status, scheduling, replay | Small teams with few jobs |
| Container Apps jobs | Cron or event-triggered batch | Coarse, container start time | Sub-second latency |
I measure queue length and age per priority, job start latency, success and retry rates per job type, circuit-breaker open time per partner, DLQ depth, duplicate effects detected by reconciliation, and per-tenant backlog.
An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.
Treat state transitions with business rules as commands: POST /orders/{id}/cancellation (a sub-resource, or /cancel if you prefer verbs for actions) makes intent explicit, lets you validate and authorise that transition, and returns 409 Conflict when it isn't allowed. PATCH {"status":"Cancelled"} looks RESTful but hides intent and invites invalid transitions.
For long-running work, use the asynchronous request-reply pattern: return 202 Accepted with a Location (or Operation-Location) pointing at a status resource and a Retry-After header; a background worker does the job and updates the status (Running, Succeeded, Failed), and the finished status links to the result. The trade-off is extra state and polling versus holding HTTP requests open and hitting gateway timeouts.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
How to tell it (STAR)
**S:** At [company], after we scaled the API to [six] instances, customers got [six] copies of every reminder email. **T:** I had to stop the duplicates fast and make scheduling safe at any scale. **A:** I confirmed every instance ran its own timer, switched the timer off on all but one instance as a stopgap, then built a single-leader scheduler using a blob lease that enqueued jobs to Service Bus, with idempotency keys recorded on each send and separate queues for urgent and bulk work. **R:** Duplicates went to [zero], our email reputation recovered within [two weeks], and we could scale workers independently of the API.
Last updated 23 Nov 2026.