📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design a background job system for a SaaS platform: jobs such as sending invoices, generating reports and syncing with partner APIs are triggered by users, by events and on schedules, some are urgent and some can wait, they fail and must be retried, and some must never run twice in a way the customer can see. Walk me through scheduling, queues and priorities, workers, retries, and how you get exactly-once effects.

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.

Senior SystemDesign Advanced azure-service-bus background-jobs idempotency retries scheduling system-design

🎯 Key points

  • Clarify: job types, volumes, latency expectations per priority, max job duration, schedules, which effects must not repeat
  • Job record in a database (status, attempts, idempotency key = job id, payload ref) plus a Service Bus message whose MessageId is that job id
  • Priorities as separate queues with dedicated worker capacity (Service Bus has no message priority); per-tenant fairness via sessions or round-robin
  • Scheduler on many instances: a single leader via a blob lease or a platform scheduler; delays and retries via ScheduledEnqueueTime / ScheduleMessageAsync
  • Workers are competing consumers with peek-lock; lock renewal for long jobs; checkpoints so a restarted job resumes
  • Retries with exponential backoff and jitter, honouring Retry-After; a circuit breaker per partner pauses that partner's jobs instead of burning attempts
  • Exactly-once delivery doesn't exist: at-least-once plus idempotent handlers (provider idempotency keys, unique constraints, inbox table, look-up-before-create)
  • Build vs buy: Hangfire, Quartz.NET, Durable Functions or Container Apps jobs before building your own

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, default and bulk, 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-After from partners. After [5] attempts the job dead-letters, the status says Failed, 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."


Requirements

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

Capacity estimate

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

High-level design

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)

Delivery semantics

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

Production example

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.

🔍 What the interviewer is checking

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

  • States that exactly-once effects come from idempotent handlers
  • Separate priority queues and per-tenant fairness
  • Single-leader or platform scheduling, not per-instance timers
  • Backoff with jitter, error classification, DLQ and replay
  • Considers Hangfire or Durable Functions before building

Red flags

  • Claims the broker guarantees exactly-once
  • Timers in every instance
  • Infinite immediate retries
  • Task.Run in a request as the job system

📚 Learn in depth

1. Why exactly-once delivery is impossible

A 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.

2. Making effects idempotent

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

3. Scheduling on many instances

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.

4. Priorities and fairness

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.

5. Long-running jobs

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.

6. Retries and poison jobs

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.

7. Build vs buy

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

8. AWS mapping

SQS with visibility timeout, EventBridge Scheduler, Step Functions for long workflows, ECS/Fargate or Lambda workers.

Try it yourself

  1. Run a BackgroundService timer on three instances and count executions; then add a blob-lease leader.
  2. Kill a worker after doing the work but before completing the message, and prove the handler is idempotent.
  3. Enqueue 10,000 bulk jobs for one tenant and 10 for another; measure the second tenant's wait with and without sessions.
  4. Implement backoff with jitter and plot retry times for 100 failing jobs.
  5. Build the same flow in Hangfire and compare effort.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Assuming the queue gives exactly-once delivery. Why it is wrong: crashes between work and acknowledgement cause redelivery. Instead: at-least-once plus idempotent handlers.
  • Mistake: A timer in every instance for scheduled jobs. Why it is wrong: scaling to N instances runs each job N times. Instead: a single leader (blob lease), scheduled messages or a platform scheduler, and idempotent occurrences.
  • Mistake: One Service Bus queue with a priority property. Why it is wrong: Service Bus (like SQS standard and FIFO queues) has no message priority, so urgent jobs wait behind bulk ones. Brokers with priority support (RabbitMQ priority queues) still let a flood of high-priority work starve the rest. Instead: separate queues with dedicated, independently scaled capacity.
  • Mistake: No per-tenant fairness. Why it is wrong: one tenant's 50,000 jobs delay everyone for hours. Instead: sessions per tenant or round-robin scheduling with caps.
  • Mistake: Retrying immediately and forever. Why it is wrong: retry storms overload partners and poison jobs block workers. Instead: exponential backoff with jitter, max attempts and a DLQ.
  • Mistake: Retrying every job independently while a partner is down. Why it is wrong: thousands of jobs exhaust their attempts in minutes and all dead-letter during a short outage at month-end. Instead: a circuit breaker per partner (Polly via 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.
  • Mistake: Retrying permanent errors. Why it is wrong: wasted capacity and delayed alerts. Instead: classify errors and dead-letter permanent ones straight away.
  • Mistake: Generating a new idempotency key on each attempt. Why it is wrong: the provider sees every retry as a new request and sends twice. Instead: use the job id created at enqueue time, the same across all retries.
  • Mistake: Long jobs without checkpoints or lock renewal. Why it is wrong: the lock expires, another worker starts the same job, and deploys restart 20-minute jobs. Instead: lock renewal, checkpoints or Durable Functions.
  • Mistake: Running jobs with Task.Run inside API requests. Why it is wrong: work is lost on recycle and isn't observable. Instead: a durable queue and workers.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says handlers must be idempotent Why: Checks idempotency keys and concurrent duplicates
    How to answer

    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.

  2. When: Candidate mentions users checking job progress Why: Checks exposing long-running jobs over HTTP with 202 and a status resource
    How to answer

    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.

  3. When: Candidate mentions the outbox Why: Checks enqueueing a job reliably in the same transaction as the business change
    How to answer

    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.

🛠 Real-world problems: how you handle them

Scaling out the API sent every scheduled reminder six times
Situation
A [SaaS appointment] platform; scheduled reminder emails ran from a `PeriodicTimer` inside each [ASP.NET Core] instance; scaled from [1 to 6] instances for a [launch].
Signals
Customers reported [six] identical reminders; email provider bounce and complaint rates spiked; provider warned about sender reputation.
Investigation
Logs grouped by instance showed every instance running the same schedule; job counts multiplied by instance count; no idempotency on sends.
Resolution
Immediate: disabled the timer on all but one instance via configuration. Long term: moved scheduling to a single leader holding a blob lease, enqueued jobs to Service Bus, added idempotency keys (reminder id + scheduled time) recorded with each send, and split critical and bulk queues.
Prevention
Integration test running the scheduler on three instances asserting one execution; alert on duplicate sends detected by a nightly query; design checklist item 'what happens with N instances?'.

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.

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me