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

📚 Interview question

A customer complains that $2,000 left their account in the Accounts service, but the transfer never arrived in the Payments service and nothing is in progress. Support finds dozens of similar cases from the last week. How do you trace the inconsistency across services, contain it, repair the data safely, and stop it happening again?

A real-world cross-service money inconsistency: tracing a transfer by correlation id through the ledger, outbox, broker, dead-letter queues, inbox and saga state; containing the damage; repairing with idempotent, audited compensating or completing commands driven by a reconciliation report; and preventing recurrence with reconciliation, outbox-age and DLQ alerts.

Senior RealWorldScenario Advanced data-consistency distributed-systems incident-response outbox payments reconciliation

🎯 Key points

  • Contain first: protect customers (pause the failing step or credit provisionally) before root cause
  • Trace one transfer end to end by transfer id / correlation id: ledger, outbox row, broker, DLQ, inbox, saga state
  • Find where the chain broke: unpublished outbox row, dead-lettered message, inbox recorded without the effect, or a saga stuck without a timeout
  • Size the blast radius with a reconciliation query: debits without matching credits, by day and amount
  • Repair by replaying or issuing idempotent commands through the normal code path, never ad hoc UPDATEs to balances
  • Every repair is audited: who, when, why, linked to the incident; financial controls sign off on totals
  • Fix the cause, then prevent: nightly reconciliation with zero-mismatch alert, outbox-age and DLQ alerts, saga timeouts
  • Communicate: customer remediation, finance and, where required, regulators or the board

⏱ 30-second answer

I treat it as an incident with money at stake, so contain first: stop the failing step from creating new cases and make affected customers whole quickly, for example by completing or reversing the transfer through the normal code path.

Then I trace one transfer end to end by its transfer id or correlation id: the ledger debit, the outbox row, the broker, any dead-letter queue, the Payments inbox and the saga state. That shows where the chain broke. A reconciliation query (debits with no matching credit) sizes the blast radius.

The repair is idempotent, audited commands (replay the message or issue a completing or compensating command), never a hand-written UPDATE to balances. Finally I fix the cause and add reconciliation, outbox-age and DLQ alerts so drift is caught in minutes, not by customers. The trade-off: the right repair is slower than a SQL patch, but it keeps the ledger trustworthy.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I say is that this is money, so the priority is customers, then cause. I'd open an incident, get finance involved, and check whether new cases are still being created. If they are, I contain: pause the failing consumer or the feature, or route transfers through a safe path, so the numbers stop growing. Then I trace one case end to end. Every transfer should carry a transfer id that is also the correlation id. I'd look at the Accounts ledger for the debit, the outbox for the TransferDebited row and whether it was published, Service Bus for the message, the dead-letter queue, the Payments inbox for that message id, and the saga state if there is one. Somewhere in that chain is the gap.

For example, at [company] we [found exactly this]. The outbox rows were published, but Payments had dead-lettered [about 60] messages after a release changed the event schema, and the transfer saga had no timeout, so nothing noticed. I wrote a reconciliation query, debits with no matching credit after 15 minutes, which gave us the full list: [63 transfers, $118,000]. We fixed the deserialisation, resubmitted the dead-lettered messages through the normal consumer, which was idempotent on transfer id, and re-ran the reconciliation until it showed zero. Finance signed off the totals, and each affected customer got [an apology and fee refund].

The mistake I see is fixing balances with an UPDATE in production. It skips the domain rules, leaves no audit trail, and if the original message is later replayed you've now paid twice. Repairs go through the same idempotent commands as normal traffic, with an audit record linking each one to the incident. And the lasting fix isn't only the bug: a nightly, or better hourly, reconciliation with an alert on any mismatch, alerts on dead letters and outbox age, and a timeout on every saga step. In a distributed system you don't prevent all inconsistency; you detect it before customers do."


Where the chain can break

Accounts                    Broker                   Payments
BEGIN TRAN
  debit ledger         (1) outbox row never written?  
  INSERT Outbox
COMMIT
relay ---------------> (2) not published? (relay down, outbox age rising)
                       (3) dead-lettered? (poison, schema change, max delivery)
                       ----------------> (4) inbox recorded but effect not applied?
                                         (5) credit failed, saga stuck, no timeout?
Break point Evidence Repair
(1) Debit without outbox row Ledger entry, no outbox row; dual write outside a transaction Issue a completing command from the ledger list; fix to outbox in same transaction
(2) Outbox not published PublishedAt null, rising outbox age Restart or fix relay; it publishes the backlog
(3) Dead-lettered DLQ count, DeadLetterReason Fix the consumer, resubmit from DLQ
(4) Inbox without effect Inbox row exists, no credit; inbox written in a separate transaction Remove the inbox marker and replay, or issue a credit command; fix to same transaction
(5) Saga stuck Saga state old, no timeout fired Add timeout; complete or compensate stuck sagas

Repair options

Option When Risk
Resubmit dead-lettered messages The message is correct and the consumer is fixed Low if the consumer is idempotent
Issue completing command (credit the payee) Transfer should go ahead Must be idempotent on transfer id
Issue compensating command (refund the payer) Transfer can't go ahead (closed account) Customer communication needed
Direct SQL UPDATE Never for balances No audit, bypasses rules, double payment on later replay

Production example

The reconciliation found [63] transfers worth [$118,000] over [six days]. Resubmitting the dead letters after the fix completed 61; two payee accounts had closed, so we refunded the payers with a compensating command. Reconciliation has run hourly since, and the next drift (a relay outage) was caught in [22 minutes] with 14 transfers delayed and none lost.

🔍 What the interviewer is checking

Checks whether the candidate can handle a cross-service data inconsistency calmly and safely: contain, trace with real tools, size the impact, repair through idempotent audited paths, and prevent recurrence.

Green flags

  • Contains the issue and involves finance before deep diving
  • Traces by a single business key through ledger, outbox, broker, DLQ, inbox and saga
  • Uses a reconciliation query to find all affected transfers
  • Repairs with idempotent commands, dry run and audit; adds reconciliation and alerts

Red flags

  • Proposes fixing balances with direct SQL updates
  • Fixes only the reported customer
  • Purges the dead-letter queue or blames "the network" without evidence

📚 Learn in depth

1. Why this happens even with good patterns

Outbox, inbox and sagas give at-least-once delivery and idempotency, but each relies on something running: the relay, the consumer, a timeout. A poison message, a schema change, an inbox written in its own transaction, or a saga without a timeout breaks the chain without throwing anything a user sees. Eventual consistency without monitoring is just eventual inconsistency.

2. Tracing a single transfer

Use one identifier everywhere: the transfer id as the business key, the outbox MessageId, the Service Bus MessageId and CorrelationId, and the W3C trace context in application properties so Application Insights stitches spans together.

Application Insights:  requests | union dependencies | union traces
                       | where customDimensions.TransferId == "t-123"
Accounts DB:           SELECT * FROM LedgerEntries WHERE TransferId = 't-123'
                       SELECT * FROM Outbox WHERE MessageId = 't-123'
Service Bus:           Service Bus Explorer: peek DLQ, filter by MessageId
Payments DB:           SELECT * FROM Inbox WHERE MessageId = 't-123'
                       SELECT * FROM Credits WHERE TransferId = 't-123'

3. Reconciliation as a query

Reconciliation compares the two sides of every money movement by business key after a grace period longer than normal processing time.

Accounts.LedgerEntries (debits)   LEFT JOIN   Payments.Credits
  on TransferId                    where credit is null and debit older than 15 min
=> list of broken transfers, amounts, ages

If the services have separate databases, run it in a reporting store fed by both (CDC, exports or projections) or call each service's API with paging. The output is both a detection signal (count > 0 alerts) and the work list for the repair.

4. Repair principles

  1. Go through the domain. Use the same commands and handlers as normal traffic, so invariants, events and audits happen.
  2. Be idempotent. Key every repair command on the transfer id. If the original message is later replayed, it's a no-op.
  3. Audit. Record operator, reason, incident id and before and after state. Financial controls usually require a second person to approve bulk repairs.
  4. Dry run first. Produce the list and totals, get finance sign-off, then execute in small batches and re-run reconciliation after each.
  5. Communicate. Customers, finance and, depending on the business and the regulator's rules, external reporting. If personal information was exposed (it usually isn't in this kind of incident), assess the Notifiable Data Breaches scheme under the Privacy Act.

5. Prevention

Control Catches
Outbox age alert (oldest unpublished > 60 s) Relay down
DLQ count alert per subscription Poison messages, schema breaks
Saga timeout per step Lost replies, stuck flows
Inbox and effect in one transaction Marked-as-done without the effect
Hourly reconciliation, alert on any mismatch Everything else
Contract tests for events Schema changes breaking consumers

Try it yourself

  1. Build two small services with an outbox and an inbox; inject a schema change that dead-letters the message and confirm no error reaches the user.
  2. Write the reconciliation query and run it on a schedule with an alert when the count is above zero.
  3. Resubmit the dead-lettered messages with Service Bus Explorer or ServiceBusReceiver on the DLQ sub-queue, and confirm the idempotent consumer credits once.
  4. Replay the same message twice more and confirm the balances don't change.
  5. Write the repair command with an audit row and a dry-run mode that prints totals.

💻 Code

The reconciliation query that sizes the problem, and an idempotent, audited repair command that goes through the domain.

-- Debits older than 15 minutes with no matching credit (run in a reporting store fed by both services).
SELECT d.TransferId, d.AccountId, d.Amount, d.CreatedAt,
       DATEDIFF(MINUTE, d.CreatedAt, SYSUTCDATETIME()) AS AgeMinutes
FROM   accounts.LedgerEntries AS d
LEFT JOIN payments.Credits    AS c ON c.TransferId = d.TransferId
WHERE  d.EntryType = 'TransferDebit'
  AND  d.CreatedAt < DATEADD(MINUTE, -15, SYSUTCDATETIME())
  AND  c.TransferId IS NULL
ORDER BY d.CreatedAt;
namespace Payments.Repair;

using Microsoft.EntityFrameworkCore;

public sealed record CompleteTransfer(Guid TransferId, Guid PayeeAccountId, decimal Amount, string IncidentId, string Operator);

public sealed class Credit
{
    public Guid TransferId { get; init; }       // unique: the idempotency key
    public Guid AccountId { get; init; }
    public decimal Amount { get; init; }
    public DateTimeOffset CreatedAt { get; init; }
}

public sealed class RepairAudit
{
    public long Id { get; init; }
    public Guid TransferId { get; init; }
    public required string IncidentId { get; init; }
    public required string Operator { get; init; }
    public required string Outcome { get; init; }
    public DateTimeOffset At { get; init; }
}

public sealed class CompleteTransferHandler(PaymentsDb db, TimeProvider clock)
{
    // Same domain path as live traffic; safe to run twice, and safe if the original message is replayed later.
    public async Task<string> HandleAsync(CompleteTransfer cmd, bool dryRun, CancellationToken ct)
    {
        if (await db.Credits.AnyAsync(c => c.TransferId == cmd.TransferId, ct))
            return "AlreadyCredited";
        if (dryRun)
            return $"WouldCredit {cmd.Amount:C} to {cmd.PayeeAccountId}";

        var now = clock.GetUtcNow();
        db.Credits.Add(new Credit { TransferId = cmd.TransferId, AccountId = cmd.PayeeAccountId, Amount = cmd.Amount, CreatedAt = now });
        db.Audits.Add(new RepairAudit { TransferId = cmd.TransferId, IncidentId = cmd.IncidentId, Operator = cmd.Operator, Outcome = "Credited", At = now });

        try
        {
            await db.SaveChangesAsync(ct);       // credit and audit commit together
            return "Credited";
        }
        catch (DbUpdateException) when (await db.Credits.AsNoTracking().AnyAsync(c => c.TransferId == cmd.TransferId, ct))
        {
            return "AlreadyCredited";             // a concurrent replay won the unique index race
        }
    }
}

public sealed class PaymentsDb(DbContextOptions<PaymentsDb> options) : DbContext(options)
{
    public DbSet<Credit> Credits => Set<Credit>();
    public DbSet<RepairAudit> Audits => Set<RepairAudit>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Credit>().HasKey(c => c.TransferId);
        b.Entity<Credit>().Property(c => c.Amount).HasPrecision(19, 4);
        b.Entity<RepairAudit>().HasKey(a => a.Id);
    }
}

⚠ Common mistakes

  • Mistake: Fixing balances with an UPDATE in production. Why it is wrong: It bypasses domain rules and audit, and a later replay of the original message pays twice. Instead: Issue idempotent completing or compensating commands through the normal handlers.
  • Mistake: Hunting the root cause while new cases keep appearing. Why it is wrong: The blast radius grows during the investigation. Instead: Contain first: pause the failing step or route around it, then investigate.
  • Mistake: Fixing the one complaining customer and closing the ticket. Why it is wrong: There are almost always more silent cases. Instead: Run a reconciliation query to size the full impact.
  • Mistake: Purging the dead-letter queue to clear the alert. Why it is wrong: Those messages are the record of money that didn't move. Instead: Fix the consumer and resubmit, or export them to the repair work list.
  • Mistake: Changing an event's schema (renaming or removing a field) in the producer without checking consumers. Why it is wrong: Consumers fail to deserialise, messages dead-letter silently, and money stops moving. Instead: Make additive changes only, run consumer contract tests in CI, and during recovery deploy a tolerant reader that accepts both the old and new shapes before resubmitting.
  • Mistake: Writing the inbox marker in a separate transaction from the credit. Why it is wrong: A crash between them marks the message as done without the effect. Instead: Commit inbox and effect together.
  • Mistake: Running a bulk repair in one go with no dry run. Why it is wrong: A bug in the repair script multiplies the damage. Instead: Dry run, finance sign-off on totals, small batches, re-run reconciliation after each.
  • Mistake: Treating eventual consistency as self-healing. Why it is wrong: Without timeouts and reconciliation, broken flows stay broken silently. Instead: Detect drift with scheduled reconciliation and alerts.

🏛 Senior insight: trade-offs

The senior framing is that distributed systems don't eliminate inconsistency; they make it detectable and repairable. That means every money movement has a business key carried end to end, every step is idempotent on that key, every flow has a timeout, and a reconciliation job proves the two sides agree. With those in place, an incident like this is a work list, not an investigation across five teams.

The leadership side matters as much as the technical one. I'd run it with clear roles: an incident lead, one engineer per service, a finance contact who owns the totals, and a communications owner for customers and, where the business's licence or regulator requires it, compliance and external reporting. Updates go out on a fixed cadence with the current count, total value and next step. The blameless post-incident review records both the trigger (the schema change) and the reason it lasted six days (no DLQ alert, no saga timeout, no reconciliation), with owners and dates for each action.

I'd also push for the repair tooling to exist before the incident: a dry-run repair command, an audited admin endpoint, and a DLQ resubmission runbook. Under pressure, people write SQL; give them a safer tool and they'll use it.

Option When it fits Cost When not to
Resubmit from DLQ Message is valid, consumer fixed Low Message itself is wrong or stale
Completing command Transfer should go ahead Needs idempotent handler Payee invalid or closed
Compensating command Transfer must be reversed Customer communication When completion is still possible and expected
Direct SQL Non-financial metadata only, with review Audit gaps Balances, ledgers, anything replayable
Metric Target
Reconciliation mismatches older than 15 min 0
Time from first mismatch to alert < 1 hour
Oldest unpublished outbox row < 60 s

🔗 Follow-ups the interviewer may ask

  1. When: Candidate identifies lost or duplicated messages as the cause Why: Checks the outbox and inbox fixes for lost and duplicate messages
    How to answer

    These are two bugs with different causes, so I quantify each with reconciliation queries first.

    • Lost messages: usually a dual write. The order is saved, then the publish fails or is never awaited (a fire-and-forget Task.Run killed on deploy, or a swallowed ServiceBusException).
    • Duplicates: usually publisher retries that create a new MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.

    Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.

    Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.

  2. When: Candidate finds messages in the dead-letter queue Why: Checks handling dead-lettered and poison messages
    How to answer

    First I work out which problem I have:

    • Poison messages: a few messages always fail.
    • A failing dependency: every message fails.
    • Slow consumers: nothing fails, they just can't keep up.

    To tell them apart I use Service Bus metrics (incoming, completed, abandoned, dead-lettered), the DLQ's DeadLetterReason and DeadLetterErrorDescription, DeliveryCount, and traces grouped by exception.

    Poison messages loop when handlers catch and abandon forever, re-publish failures as new messages, or MaxDeliveryCount is huge. The fix: dead-letter permanent failures immediately, fix the handler or data, then resubmit from the DLQ in batches to an idempotent consumer. Scale consumers only up to the downstream's limit. To prevent it: alerts on oldest message age and DLQ count, plus a poison-message test. The trade-off: dead-lettering early keeps the queue flowing, but someone must own the DLQ.

  3. When: Candidate says the transfer saga had no timeout Why: Checks whether the flow should have been a saga with timeouts, or one transaction
    How to answer

    I start with the invariants. If something must be true at every instant (a balance never negative, a seat never double-booked), that data belongs in one aggregate, one service and one local transaction. Often the right answer is to redraw the boundary.

    If other services only need to react and their effects never need undoing (send a receipt, update search), I use the transactional outbox with idempotent consumers: simple, at-least-once and eventually consistent.

    If a later step can fail for business reasons and earlier steps must be undone (payment declined after stock was reserved), I build a saga, usually orchestrated, with compensations, timeouts and persisted state.

    The trade-off: each step up buys flexibility across team and service boundaries, but costs complexity, latency and operating effort, so I pick the lowest one that meets the business rules.

🛠 Real-world problems: how you handle them

Dead-lettered transfer events after a schema change left $118,000 in limbo
Situation
A digital wallet with Accounts and Payments services on [Azure, Australia East] processing [30,000 transfers a day]. Accounts debits and publishes TransferDebited through an outbox to Service Bus; Payments credits the payee. The transfer saga had no step timeout.
Signals
A customer complaint about a $2,000 transfer that never arrived; support found [dozens] of similar cases over [six days]; the Payments subscription's dead-letter count had risen to [63] with no alert; no errors visible to users.
Investigation
Traced one transfer by TransferId in Application Insights and the databases: ledger debit present, outbox row published, message in the Payments DLQ with DeadLetterReason MaxDeliveryCountExceeded and a JsonException in the consumer logs after a release renamed a field. A reconciliation query (debits with no credit after 15 minutes) gave the full list: [63 transfers, $118,000].
Resolution
Immediate: paused the Payments consumer briefly, deployed a fix that read both field names, and resubmitted the dead letters through the idempotent consumer in batches, re-running reconciliation after each. 61 completed; 2 payees had closed accounts, so the payers were refunded with a compensating command. Finance signed off totals; customers received [an apology and fee refund].
Prevention
Hourly reconciliation with an alert on any mismatch older than 15 minutes, DLQ and outbox-age alerts, a 15-minute timeout on each saga step, consumer contract tests for event schemas, and a dry-run repair command with audit as the only approved repair path.

How to tell it (STAR)

**S:** At [company], a customer's $2,000 transfer left their account but never arrived, and support found [dozens] more like it. **T:** I led the incident and the repair. **A:** I traced one transfer by its id through the ledger, outbox, Service Bus and Payments, and found the message in the dead-letter queue after a schema change broke deserialisation. A reconciliation query gave the full list: [63 transfers, $118,000]. We fixed the consumer, resubmitted the dead letters through the idempotent handler in batches, refunded the two that couldn't complete, and finance signed off. Then I added hourly reconciliation, DLQ alerts and saga timeouts. **R:** Every transfer was resolved within [two days], no one was paid twice, and the next drift was caught in [22 minutes] instead of six days.

More in Data Consistency

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me