A real-world incident where a scheduled job in a scaled-out service double-charges customers: containment, proving the cause with logs and traces, leader election with a lease, idempotent charges with a per-period key, moving scheduling out of the web tier, and reconciliation.
First I'd contain: disable the billing job itself with its feature flag (scaling to one instance isn't enough while the job is still scheduled), block manual reruns, refund the duplicates and brief finance and support so affected customers hear from us first. Then prove the cause: group charges by customer and billing period and break them down by instance id in Application Insights. The likely story is that every instance runs every BackgroundService, so scaling to three ran the job three times. The fix has two layers. A lease (Azure Blob lease or sp_getapplock) makes one instance the runner. But leases can overlap, so correctness comes from idempotency: a pending charge row keyed customerId:2026-11, unique in the database and passed to the payment provider as its idempotency key. Longer term I'd move the job to a dedicated scheduled host (Container Apps job or timer-triggered Function) and add reconciliation.
"I'd treat it as a customer-impacting incident before I treat it as a bug. Step one is containment: turn the job off with its feature flag, or scale the service to one instance until the fix ships, and confirm no other path is charging. Then I'd get the list of affected customers to finance so refunds go out the same day, and agree the message with support, because people notice double charges on their cards very quickly.
Step two is proving the cause rather than assuming it. I'd query the charges table for customers with more than one charge in the billing period, and in Application Insights look at the job's 'billing run started' logs by
cloud_RoleInstance. If I see three runs starting within seconds, from three instances, at 2 a.m., that confirms it: aBackgroundServiceruns in every instance, and the scale-out multiplied the job. For [example, at company] we [had exactly this after enabling autoscale on an App Service plan; [n] customers were charged twice and we refunded them by 9 a.m.].Step three is the fix, and I'd do it in two layers. The lease layer: before running, an instance takes an Azure Blob lease or a SQL
sp_getapplock; only the holder runs. That removes the wasted work but not the risk, because a paused holder can lose its lease and overlap with a new one. So the correctness layer is idempotency: each charge has a deterministic key,customerIdplus the billing period, with a unique index, and the same key goes to the payment provider. A second run, whether from another instance, a retry or a manual rerun, finds the key and skips. I also write a pending charge row before calling the provider, so a timeout leaves an 'unknown' state to resolve rather than a reason to charge again.Long term, a scheduled job doesn't belong in a scaled-out web app. I'd move it to an Azure Container Apps job or a timer-triggered Function, and add a nightly reconciliation against the provider's settlement report. The lesson: a lease decides who runs; idempotency decides what happens if two run anyway."
| Phase | Actions | Done when |
|---|---|---|
| Contain | Disable job flag or scale to 1; block manual reruns | No new charges from the job |
| Assess | Query duplicates per customer per period; total amount | List of affected customers and amounts |
| Remediate | Refund through the provider; notify support and finance | Refunds issued, comms sent |
| Diagnose | Correlate runs with instance ids; review scaling change | Cause proven with evidence |
| Fix | Lease for single runner + idempotent charge keys | Tests show two concurrent runs charge once |
| Prevent | Move job out of web tier, reconciliation, alerts, post-incident review | Actions owned and dated |
| Layer | Protects against | Doesn't protect against |
|---|---|---|
| Lease / leader election | Wasted duplicate work in normal operation | Pauses past expiry, failover, manual reruns |
| Idempotent charge key | Any duplicate run, retry or rerun | Nothing for the charge itself; still need reconciliation for unknown outcomes |
| Reconciliation | Anything that slipped through | Prevention (it detects after the fact) |
After autoscale took a subscription service from one to three instances, the 2 a.m. billing run executed three times and 1,240 customers were charged twice or three times, about A$61,000 in total. Containment and refunds were finished by 10 a.m. With a blob lease, a unique (CustomerId, Period) index and the provider's idempotency key, a chaos test running five schedulers in parallel produced exactly one charge per customer, and the job later moved to a Container Apps job with no regressions in the following six months.
Checks incident leadership and distributed-systems judgement: containment before diagnosis, evidence over assumptions, and knowing that a lease alone doesn't make money movement safe.
Green flags
Red flags
AddHostedService<T>() registers the service in each process. Three instances means three schedulers, each with its own timer:
02:00:00 instance-a BillingJob: start -> charges customers 1..N
02:00:01 instance-b BillingJob: start -> charges customers 1..N (duplicate)
02:00:01 instance-c BillingJob: start -> charges customers 1..N (duplicate)
The same happens during a deployment slot swap or a rolling update, where old and new instances overlap briefly, even at one instance.
instance-a acquire lease (60 s) ok, renewing every 20 s
instance-a GC pause / CPU throttled for 75 s, renewal missed
lease expires
instance-b acquire lease ok -> starts billing from customer 1
instance-a resumes mid-loop -> still charging customers <- overlap
The fix is to check for lease loss (a CancellationToken that fires when renewal fails) and to make each charge idempotent so overlap does no harm.
Key: {customerId}:{billingPeriod}, for example c-1042:2026-11. Flow per customer:
1. INSERT Charge(Key, Status=Pending) -- unique index on Key
duplicate? -> skip (already charged or in progress)
2. Call provider with Idempotency-Key = Key
3. UPDATE Charge SET Status = Succeeded|Declined
timeout? -> leave Pending; a resolver queries the provider by key later
Because the provider also deduplicates on the key, even a crash between steps 2 and 3 followed by a rerun can't charge twice.
| Host | Single execution? | Notes |
|---|---|---|
| BackgroundService in a scaled web app | No (one per instance) | Needs a lease; competes with request traffic |
| Azure Functions timer trigger | Yes by default (singleton via blob lease on the host's storage) | Watch the execution time limits of your plan |
| Azure Container Apps job (schedule trigger) | Yes, one execution per schedule (configurable parallelism) | Clean separation, retries, history |
| Hangfire / Quartz.NET with a shared store | Yes with clustering (DB locks) | Familiar, but another dependency |
| Kubernetes CronJob | Yes with concurrencyPolicy: Forbid |
Still make the work idempotent |
Every morning compare your charges table with the provider's settlement report: charges you have that the provider doesn't (resolve Pending), charges the provider has twice (refund), charges you don't have (investigate). This is the safety net that catches whatever the design missed.
BackgroundService that logs on a 10-second timer; start three copies on different ports and watch three logs.AzureBlobLeaseDistributedLock against Azurite; confirm only one copy runs, then pause it in the debugger beyond the lease and watch another take over.Charge table with a unique key and run five copies at once; count charges per customer.A billing job that is safe with any number of instances: a blob lease elects the runner, and each charge is idempotent by customer and period.
using Azure.Storage.Blobs;
using Medallion.Threading.Azure;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace Billing;
public sealed class Charge
{
public required string Key { get; init; } // "{customerId}:{yyyy-MM}", unique index
public required string CustomerId { get; init; }
public decimal Amount { get; init; }
public string Status { get; set; } = "Pending";
}
public sealed class BillingDb(DbContextOptions<BillingDb> o) : DbContext(o)
{
public DbSet<Charge> Charges => Set<Charge>();
protected override void OnModelCreating(ModelBuilder b) => b.Entity<Charge>().HasKey(c => c.Key);
}
public interface IPaymentProvider
{
Task<bool> ChargeAsync(string customerId, decimal amount, string idempotencyKey, CancellationToken ct);
}
public sealed class BillingRun(IServiceScopeFactory scopes, BlobContainerClient locks,
TimeProvider time, ILogger<BillingRun> logger)
{
public async Task RunAsync(CancellationToken ct)
{
var period = time.GetUtcNow().ToString("yyyy-MM");
var @lock = new AzureBlobLeaseDistributedLock(locks, $"billing-{period}");
// Layer 1 (efficiency): only one instance runs
await using var handle = await @lock.TryAcquireAsync(cancellationToken: ct);
if (handle is null) { logger.LogInformation("Another instance is billing {Period}", period); return; }
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, handle.HandleLostToken);
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<BillingDb>();
var provider = scope.ServiceProvider.GetRequiredService<IPaymentProvider>();
foreach (var (customerId, amount) in await LoadDueAsync(db, linked.Token))
{
var key = $"{customerId}:{period}";
// Layer 2 (correctness): record intent under a unique key BEFORE charging
db.Charges.Add(new Charge { Key = key, CustomerId = customerId, Amount = amount });
try { await db.SaveChangesAsync(linked.Token); }
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
{
db.ChangeTracker.Clear();
continue; // already charged (or in progress) by another run
}
var charge = await db.Charges.SingleAsync(c => c.Key == key, linked.Token);
try
{
// The provider deduplicates on the same key, so a crash and rerun can't double-charge
charge.Status = await provider.ChargeAsync(customerId, amount, key, linked.Token) ? "Succeeded" : "Declined";
}
catch (TaskCanceledException) when (!linked.IsCancellationRequested)
{
charge.Status = "Unknown"; // resolved later by querying the provider by key
}
await db.SaveChangesAsync(linked.Token);
}
}
private static Task<List<(string, decimal)>> LoadDueAsync(BillingDb db, CancellationToken ct) =>
Task.FromResult(new List<(string, decimal)>()); // query due subscriptions here
}
BackgroundService runs once per application. Why it is wrong: it runs once per process, so scale-out, slot swaps and rolling deployments multiply it. Instead: elect a runner or host the job separately.The deeper lesson is that scaling changed the system's behaviour and nothing told us. I'd add 'what runs on a timer, and what happens with N instances?' to the checklist for any autoscale or deployment-topology change, and make the job's single-execution assumption explicit in code with a lease and a log line naming the runner.
For money, I want three independent safeguards: a single runner, idempotent keys honoured by both us and the provider, and reconciliation. Any one of them can fail; all three failing together is very unlikely. Under the Australian Consumer Law and card-scheme rules, double charges also carry reputational and regulatory weight, so the post-incident review should include how fast refunds went out.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Lease in the web app | Quick fix, small jobs | Shares resources with requests | Long or heavy jobs |
| Container Apps job / Functions timer | Scheduled batch work on Azure | Separate deployment | Sub-second scheduling |
| Hangfire / Quartz clustered | Many jobs, existing SQL store | Another framework to run | One simple nightly job |
| Idempotent keys + reconciliation | Always, for money | Table, provider support, daily job | Never skip for payments |
A distributed lock is really a lease: a time-limited claim that expires so a crashed holder doesn't block everyone forever. That expiry is what makes it dangerous: a holder that pauses (a long GC pause, a VM freeze, a slow network) can lose the lease, carry on, and overlap with the next holder without knowing. Redis SET NX PX is fast but replication is asynchronous, so a failover can hand the same lock to two clients; Redlock adds a majority of nodes but still relies on timing assumptions. SQL Server sp_getapplock and Azure Blob leases are simpler and tied to stores you already trust. For correctness, the protected resource must check a fencing token (a number that only goes up) so stale holders are rejected. Better still, design the lock away with partition ownership, queues, optimistic concurrency or idempotency.
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.
Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.
How to tell it (STAR)
**S:** After we enabled autoscale on our [subscription API], [n] customers were charged two or three times overnight. **T:** As [the on-call lead], I had to stop the damage, get money back to customers and make sure it couldn't recur. **A:** I disabled the job, got refunds out from a duplicate query, proved with Application Insights that each instance had run the BackgroundService, then added a blob lease plus idempotent per-period charge keys shared with the provider. **R:** Refunds were complete by [10 a.m.], a test with five concurrent schedulers produced exactly one charge per customer, and we've had zero duplicate charges in [the following six months].
Last updated 23 Nov 2026.