An ASP.NET Core billing app runs its nightly invoice-reminder BackgroundService on three replicas; why do customers get three reminders, and how do you fix it?
answer
- hosted services are per process
- no cluster coordination in the host
- rolling deploys overlap too
- claim the work in the database
- one worker process, or a scheduler
basics
~20 sEvery replica is its own process whose host starts every registered hosted service, so three loops run three times. Fix it by running the job in one place, or by making each run claim its work in shared storage so duplicates do nothing.
solid answer
~50 s`AddHostedService` registers a singleton per **process**, and the host starts it in every process that runs the app. ASP.NET Core has no notion of a cluster: nothing elects one replica, so with three replicas three loops fire at 02:00 and each sends the reminders. Even with one replica, a rolling deployment briefly runs the old and new process side by side. Fixes, often combined: make the job idempotent by claiming work in the database (a unique row per invoice and reminder date, or a conditional update), so a second run finds nothing; run the loop only in one process, for example a separate `dotnet new worker` deployment with one replica or a configuration switch that registers the service in one place; or use a lease row so only the holder runs. When calendar schedules and retries matter, move the job to a scheduler with shared storage.
code
csharp · 17 linespublic async Task SendDueRemindersAsync(CancellationToken ct)
{
var today = DateOnly.FromDateTime(timeProvider.GetUtcNow().UtcDateTime);
var due = await db.Invoices
.Where(i => i.DueDate < today && i.PaidOn == null)
.Select(i => i.Id)
.ToListAsync(ct);
foreach (var invoiceId in due)
{
// Unique index on (InvoiceId, ReminderDate): only one replica's insert wins.
var claimed = await db.Database.ExecuteSqlAsync(
$"INSERT INTO reminder_claims (invoice_id, reminder_date) VALUES ({invoiceId}, {today}) ON CONFLICT DO NOTHING", ct);
if (claimed == 1)
await mailer.SendReminderAsync(invoiceId, ct);
}
}go deeper
Recall that a hosted service runs inside each process, so every replica of the app starts its own copy of the loop.
Explain why singleton means once per container rather than once per cluster, and how deployment overlap duplicates runs even with one replica.
Design the fix: an idempotent claim in the database as the safety net, fewer runners for efficiency, and logging that shows a duplicate attempt claiming nothing.
Decide when cluster-wide scheduling deserves its own component, such as a dedicated worker or a persistent scheduler, rather than loops in every web replica.
## Why the loop runs once per replica A hosted service is part of the **process**, not of the deployment. `builder.Services.AddHostedService<InvoiceReminderService>()` adds a singleton to that process's container, and when the host starts it starts every registered `IHostedService`. Scale the web app to three replicas and you have three hosts, three singletons and three loops, each with its own `PeriodicTimer` or delay arriving at roughly the same time. Nothing in ASP.NET Core coordinates them: - there is no leader election in the Generic Host; - `HostOptions` settings such as `ServicesStartConcurrently` only order services **inside** one process; - a singleton is single per container, and each replica has its own container. So each loop selects "invoices due today", finds the same rows, and sends the same mail. Duplicates also appear with **one** replica: a rolling deployment starts the new process before stopping the old, a crash-restart can rerun a half-finished batch, and a developer's machine pointed at a shared database is one more loop. ## Options for running it once | Approach | How | Trade-off | |---|---|---| | Idempotent claim | insert a `(InvoiceId, ReminderDate)` row under a unique constraint before sending; skip on violation | works with any number of loops; needs a schema change, and a crash between claim and send drops that reminder unless the claim also records when it was sent | | Conditional update | `UPDATE ... SET RemindedOn = @today WHERE Id = @id AND RemindedOn IS NULL`, send only if one row changed | no new table; the same claim-then-send gap | | Single worker process | move the loop to a separate worker deployment with exactly one replica | clear ownership; a deployment overlap can still double-run without the claim | | Configuration switch | register the hosted service only when a setting such as `Jobs:Enabled` is true, and set it on one instance | cheap; fragile when instances are interchangeable | | Lease in shared storage | a row holding owner and expiry, renewed by the current holder | one runner at a time; must handle expiry and clock skew | | Scheduler with shared storage | a library that stores schedules and locks in a database | adds a dependency; gives retries and a dashboard | ## A robust combination 1. Make the unit of work **idempotent**: claim each invoice before sending, so any extra run is harmless. This is the part that also covers deploy overlap and crash-restart. 2. **Reduce the number of runners** for efficiency: register the loop only in a worker process, or keep it in the web app and accept that every replica checks for work that the claim makes safe. 3. **Observe it**: log how many invoices each run claimed and sent, so a duplicate attempt shows up as a run that claimed zero. ## Spotting it in production - Customers report identical reminders a few seconds apart, one per replica. - The mail log shows the same invoice id sent from different instance names; adding the machine or pod name to the run's log scope makes this visible at once. - After the claim is in place, the duplicates turn into runs that claimed zero invoices, which is the expected, harmless outcome. ## What does not work - Registering with `AddSingleton` instead of `AddHostedService`: still one per process, and a plain singleton is never started. - Choosing different start times per replica: the replicas are interchangeable and restart at random times. - An in-memory flag such as a `static bool`: it lives in one process, so the other replicas never see it. The hosted-service model is per process by design; anything cluster-wide is the application's job, either in its data or in a dedicated scheduler.
- Does moving the loop to a single-replica worker remove the need for idempotency?No. During a rolling deployment the old and new worker processes overlap, and a crash mid-batch means the restarted process sees the same due invoices. The single worker cuts the normal duplicate count to one runner, but only a claim recorded in shared storage makes an extra run harmless.
- Why does a static flag or a singleton field not prevent duplicates across replicas?Both live in one process's memory. Each replica has its own copy, initialised at its own start-up, so a flag set in replica A is invisible to B and C. Coordination has to live where every replica reads the same state: the database, a lease row or a scheduler's store.
Three night guards each carry the same checklist that says lock the gate at 2 a.m.; without a shared logbook where the first one signs "gate locked", every guard walks out and locks it again.
- ASP.NET Core runs a hosted service on only one replica of a deployment
- AddSingleton instead of AddHostedService gives one loop across the cluster
- Setting HostOptions.ServicesStartConcurrently to false stops replicas duplicating the job
- One replica means the job can never run twice
- A static bool marks the job as done for every replica