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

📚 Interview question

Your nightly billing job runs inside an ASP.NET Core service as a BackgroundService. After the service was scaled from one instance to three, some customers were charged twice overnight. Walk me through how you would contain the incident, prove the cause, and fix it so the job is safe however many instances run, using leases and idempotency.

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.

Senior RealWorldScenario Advanced background-services distributed-systems idempotency incident-response leader-election payments

🎯 Key points

  • Contain first: disable the billing job itself with its feature flag (not just scale down), block manual reruns, refund duplicates, brief finance and support
  • Prove it: correlate charge records per customer per period with instance ids (cloud_RoleInstance) in Application Insights
  • Root cause: every instance runs every BackgroundService; scaling multiplies the job
  • A lease (Azure Blob lease, sp_getapplock) elects one runner, but alone is not enough for money
  • Record intent first: a pending charge row whose unique key is customerId + billing period, the same key passed to the payment provider
  • Resolve unknown outcomes (timeouts) by querying the provider by key; if the lease can't be acquired, skip and alert rather than retry in a loop
  • Move scheduling out of the request-serving API into a dedicated scheduled host: Azure Container Apps job, Functions timer trigger or a single-replica worker
  • Prevent: reconciliation against the provider's report, an alert on more than one charge per customer per period, tests that run two schedulers concurrently, customer comms standards

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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: a BackgroundService runs 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, customerId plus 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."


Incident timeline I'd follow

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

Lease vs idempotency

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)

Production example

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.

🔍 What the interviewer is checking

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

  • Disables the job and remediates (refunds, customer and staff comms) before deep debugging.
  • Proves the cause with data: duplicates by customer and instance id.
  • Combines a lease with idempotent per-period keys passed to the provider.
  • Moves scheduling to a dedicated host, adds reconciliation and job metrics (runs per period, charges per customer, unknown outcomes).
  • Can discuss alternatives to locking: single-replica workers, partitioned work queues, Service Bus sessions.

Red flags

  • 'Just set instance count to one.'
  • A lease or a lock as the only fix.
  • No mention of refunds, customers or reconciliation.

📚 Learn in depth

1. Why every instance runs the job

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.

2. Why a lease alone isn't enough

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.

3. Idempotent charges

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.

4. Where scheduled work should live

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

5. Reconciliation

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.

Try it yourself

  1. Run an ASP.NET Core app with a BackgroundService that logs on a 10-second timer; start three copies on different ports and watch three logs.
  2. Add AzureBlobLeaseDistributedLock against Azurite; confirm only one copy runs, then pause it in the debugger beyond the lease and watch another take over.
  3. Add the Charge table with a unique key and run five copies at once; count charges per customer.
  4. Write the reconciliation query that finds customers with more than one charge per period.

💻 Code

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
}

⚠ Common mistakes

  • Mistake: Fixing the code before containing the incident. Why it is wrong: the next scheduled run charges customers again while you debug. Instead: disable the job with its feature flag first, then refund, then diagnose.
  • Mistake: Scaling to one instance and calling it contained. Why it is wrong: the job still runs, a deployment or slot swap briefly overlaps instances, and autoscale may scale out again. Instead: switch the job off explicitly until the fix ships.
  • Mistake: Assuming a 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.
  • Mistake: Adding a lease and calling it fixed. Why it is wrong: leases can overlap after pauses or failovers, and manual reruns bypass them. Instead: make each charge idempotent as well.
  • Mistake: Using a random GUID as the payment idempotency key. Why it is wrong: every run produces a new key, so the provider can't detect duplicates. Instead: derive the key from customer and billing period.
  • Mistake: Calling the provider before recording the charge. Why it is wrong: a crash after charging leaves no trace, and a rerun charges again. Instead: insert a pending row first, then charge, then update.
  • Mistake: Treating a provider timeout as a failure and retrying. Why it is wrong: the charge may have succeeded. Instead: mark it unknown and resolve it by key.
  • Mistake: No plan for when the lease can't be acquired or the provider is down. Why it is wrong: the run silently doesn't happen, or loops retrying and hammers the provider. Instead: skip with a log and an alert if no instance billed by a deadline; on provider outage, stop the run with a circuit breaker and resume later, which idempotent keys make safe.
  • Mistake: No reconciliation. Why it is wrong: you find duplicates when customers complain. Instead: compare with the provider's report daily and alert on anomalies.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes a distributed lock or lease. Why: Checks depth on why leases can overlap and how fencing helps.
    How to answer

    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.

  2. When: Candidate proposes idempotent charges. Why: Checks how the idempotency key and dedup storage are implemented correctly.
    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.

  3. When: Candidate mentions provider timeouts. Why: Checks handling of a payment call whose outcome is unknown.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Autoscale triples the nightly billing run
Situation
A subscription platform's ASP.NET Core API on [Azure App Service, Australia East] hosted the nightly billing BackgroundService; autoscale was enabled to handle [daytime load], taking the plan from one to [three] instances; about [n] customers billed per night.
Signals
Morning spike in support tickets about double charges; the provider dashboard showed [about 3x] the normal charge count for the night; Application Insights showed three 'billing run started' traces at 02:00 with different cloud_RoleInstance values.
Investigation
Queried charges grouped by customer and period to size the impact; correlated run-start logs by instance id; checked the autoscale history and confirmed three instances were up at 02:00; reviewed the code and found no lease and a random GUID used as the provider idempotency key.
Resolution
Immediate: disabled the job with its feature flag, issued refunds through the provider's API from the duplicate list, and briefed support. Real fix: blob-lease leader election plus a unique (CustomerId, Period) charge key written before calling the provider and reused as its idempotency key; later moved the job to an Azure Container Apps scheduled job.
Prevention
A chaos-style integration test running five schedulers concurrently; a daily reconciliation against the provider's settlement file; an alert when any customer has more than one charge per period; an autoscale change checklist item for timer-based work.

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

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me