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

📚 Interview question

After a release, customers' loyalty balances and order statuses in the Customer service are sometimes wrong: an order shows as Shipped then reverts to Paid, and some points are credited twice. The Customer service consumes integration events from Ordering over Azure Service Bus. How do you investigate and fix the ordering, versioning and idempotency problems?

A production incident with out-of-order and duplicate integration events corrupting a consumer's state: diagnosing with traces and Service Bus metrics, then fixing with aggregate versions, Service Bus sessions, inbox deduplication, idempotent operations and contract version handling, plus safe data repair.

Senior RealWorldScenario Advanced architecture azure-service-bus idempotency incident-response integration-events message-ordering

🎯 Key points

  • Service Bus is at-least-once; FIFO only within a session processed by one receiver at a time; competing consumers, prefetch, abandons and lock expiry reorder or duplicate
  • Diagnose: correlate event ids, aggregate versions and delivery counts in traces; diff MaxConcurrentCalls, PrefetchCount, replicas and lock settings
  • Ordering fix A: aggregate version on every event; apply only if version > stored (full parallelism, state-carrying events)
  • Ordering fix B: sessions keyed by order id; strict per-order order, but throughput bounded by MaxConcurrentSessions and hot keys
  • Duplicates: inbox with unique (consumer, message id) in the same transaction as the state change
  • Increments (loyalty credits) also need a business key (customer + order + reason), because republished events get new message ids
  • Unknown event versions dead-letter immediately; repair from the source of truth with compensating entries
  • Monitor and alert on stale/skipped versions, inbox duplicate hits, lock-lost exceptions and DLQ depth; add shuffle-and-duplicate tests

⏱ 30-second answer

I'd first confirm the mechanics: Azure Service Bus delivers at least once and only orders messages within a session, so after a release that raised consumer concurrency or scaled out, events for the same order can be processed out of order and redelivered. Traces with event ids, aggregate versions and delivery counts prove it.

The fixes: every event carries the aggregate version and the consumer applies it only if newer (or I use sessions keyed by order id); an inbox with a unique key dedups by message id in the same transaction; increments like loyalty credits use a natural idempotency key (order id plus reason). Unknown event versions dead-letter. Then I rebuild the corrupted state from the source of truth.

The trade-off: sessions give ordering but limit parallelism per key; version checks keep parallelism but require versioned events.

🗣 Full answer (senior)

How I would answer this in an interview

"Two symptoms, two likely causes. A status going Shipped then back to Paid is an ordering problem: the OrderPaid event was processed after OrderShipped. Points credited twice is a duplicate problem: the same event, or two events meaning the same thing, applied twice. Neither is a Service Bus bug; it never promised exactly-once or global FIFO. So my first question is what changed in the release. Typically someone raised MaxConcurrentCalls, added replicas, or changed retry and lock settings, and the consumer was quietly relying on single-threaded, in-order processing.

To confirm, I pull a few affected orders and line up their events in Application Insights: event id, aggregate version, enqueued time, processed time, delivery count and which instance handled them. I'd expect to see version 4 processed before version 3, and an event with delivery count 2 where the first attempt's lock expired mid-processing and another instance picked it up. For example, at [company] we [found exactly this after scaling consumers from one to four instances], and [the lock duration was shorter than our p99 processing time].

The fixes are layered. For ordering, every event carries the aggregate version, and the consumer stores the last applied version per order and ignores anything older; or, if strict per-order sequencing matters, I enable sessions with the order id as session id. For duplicates, an inbox table with a unique key on consumer and message id, written in the same transaction as the state change. For the loyalty credit, which is an increment, I add a natural key too, order id plus reason, with a unique constraint on the ledger, because a republished event might carry a new message id. Unknown event versions go to the dead-letter queue instead of crash-looping. Finally I repair the data by rebuilding the affected customers' state from Ordering's source of truth, not with hand-written updates.

The mistake I see is fixing only the symptom, say, adding a lock, instead of making the consumer correct under reordering and duplication, which is the normal operating condition for messaging."


Symptom to cause

Symptom Likely cause Evidence
Status regresses (Shipped -> Paid) Out-of-order processing Older version processed after newer, different instances
Points credited twice Redelivery (lock lost) or republish Same event id twice, or delivery count > 1
Errors only since release Concurrency/scale-out/lock changes Config diff, replica count
Some messages crash-loop Unknown event version Deserialisation errors, rising delivery counts

Fix options

Fix Solves Cost
Aggregate version check in consumer Reordering, stale duplicates Version on every event
Service Bus sessions keyed by order id Strict per-order ordering Parallelism limited per order; session-aware consumers
Inbox (unique consumer + message id) Redelivery duplicates Table, cleanup
Natural idempotency key on effects Duplicates with new message ids Unique constraint per effect
Lock renewal / longer lock duration Lock-expiry redeliveries Must match processing time
Dead-letter unknown versions Crash loops DLQ monitoring

Production example

After scaling a consumer from 1 to 4 instances with MaxConcurrentCalls of 16, about 0.8% of orders showed regressed statuses and 0.3% of loyalty credits doubled. Version checks plus an inbox and a unique ledger key brought both to zero, throughput stayed at 600 messages per second, and a rebuild from Ordering's data repaired 4,200 customers in 35 minutes.

🔍 What the interviewer is checking

Checks that the candidate can diagnose messaging ordering and duplication issues from evidence and fix them with layered, correct-by-design consumer techniques, including safe data repair.

Green flags

  • Knows Service Bus delivery guarantees and session semantics precisely
  • Uses traces, delivery counts and release diffs to prove the cause
  • Layers version checks or sessions, inbox and natural idempotency keys
  • Dead-letters unknown versions; repairs from the source of truth with compensating entries
  • Adds shuffle-and-duplicate tests and reconciliation

Red flags

  • Blames the broker or proposes single-threaded consumers as the fix
  • Message-id dedup only, ignoring republished events
  • Hand-editing production data

📚 Learn in depth

1. Why order and uniqueness break

Ordering publishes:   v3 OrderPaid   v4 OrderShipped     (enqueued in order)
Competing consumers:
   instance A: receives v3, slow (GC pause, DB wait)...........commits v3 (Paid)  <- regresses!
   instance B: receives v4, fast -> commits v4 (Shipped)

Lock expiry:
   instance A: receives msg, processing > lock duration (default 30 s, max 5 min)
   lock expires -> message visible again -> instance B processes it too -> duplicate effect

Service Bus provides at-least-once delivery with peek-lock; FIFO only within a session. Competing consumers, prefetch, retries and lock expiry all reorder or duplicate.

2. Investigation toolkit

  • Application Insights: custom dimensions for event id, aggregate id, version, delivery count, instance; query in KQL to find versions applied out of order.
  • Service Bus metrics: incoming vs completed, abandoned messages, dead-lettered, lock lost exceptions (MessageLockLost).
  • Release diff: MaxConcurrentCalls, PrefetchCount, replica count, MaxAutoLockRenewalDuration, retry policy.
  • Data: compare consumer state with publisher state for a sample of orders.
customEvents
| where name == "EventApplied" and timestamp > ago(1d)
| extend orderId = tostring(customDimensions.OrderId), version = toint(customDimensions.Version)
| order by orderId asc, timestamp asc
| extend prevVersion = prev(version), prevOrder = prev(orderId)
| where orderId == prevOrder and version < prevVersion

3. Ordering strategies

  1. Version check (last-writer-wins by version): store LastAppliedVersion per aggregate; apply if event.Version > stored. Works when each event carries enough state to supersede older ones (state-carrying events).
  2. Gap detection: if events are deltas, event.Version must equal stored + 1; otherwise abandon or defer the message and retry later (or park it).
  3. Sessions: SessionId = orderId; the session processor processes one message at a time per session, preserving order. Parallelism across sessions via MaxConcurrentSessions.

4. Idempotency layers

Layer 1: inbox      UNIQUE (Consumer, MessageId)           -> drops redeliveries
Layer 2: semantic   UNIQUE (CustomerId, OrderId, Reason)   -> drops republished duplicates with new ids
Layer 3: version    WHERE LastAppliedVersion < @version    -> drops stale updates

All in the same transaction as the state change, so a crash never records the inbox entry without the effect, or vice versa.

5. Versioning the contract

The release may also have introduced OrderShippedV2. Consumers should handle known versions explicitly, upcast v1 to an internal model, and dead-letter unknown types with a clear reason rather than throwing until MaxDeliveryCount.

6. Repairing data safely

  • Identify affected aggregates (version mismatch with publisher, duplicate ledger entries).
  • Rebuild from the source of truth: request a resync from Ordering's API, or replay its outbox history into the fixed consumer.
  • Reverse duplicate credits as compensating ledger entries (auditable), not deletions.
  • Notify customers if balances were visible and wrong; assess whether it is a privacy incident (it usually isn't, but document the assessment).

Try it yourself

  1. Write a test harness that shuffles and duplicates a stream of events and assert your consumer ends in the right state.
  2. Run a consumer with MaxConcurrentCalls = 8 against the Service Bus emulator and reproduce a status regression.
  3. Add a version check and an inbox, and rerun the harness.
  4. Switch to a session processor keyed by order id and compare throughput.
  5. Set a lock duration shorter than processing time and observe redeliveries and MessageLockLost.

💻 Code

The fixed consumer: inbox, version check and a natural idempotency key, all in one transaction.

namespace Customer.Consumers;

using System.Text.Json;
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

public sealed record OrderStatusChangedV2(Guid OrderId, Guid CustomerId, string Status, long Version, int PointsEarned);

public sealed class OrderStatusConsumer(CustomerDbContext db, ILogger<OrderStatusConsumer> log)
{
    private const string ConsumerName = "customer.order-status";

    public async Task HandleAsync(ProcessMessageEventArgs args, CancellationToken ct)
    {
        var msg = args.Message;
        if (msg.Subject != "orders.order-status-changed.v2")
        {
            await args.DeadLetterMessageAsync(msg, "UnknownEventType", msg.Subject, ct); // no crash loop
            return;
        }
        var evt = JsonSerializer.Deserialize<OrderStatusChangedV2>(msg.Body, JsonSerializerOptions.Web)!;

        await using var tx = await db.Database.BeginTransactionAsync(ct);
        try
        {
            // Layer 1: inbox. Unique index on (Consumer, MessageId) rejects redeliveries.
            db.Inbox.Add(new InboxEntry(ConsumerName, msg.MessageId, DateTimeOffset.UtcNow));

            // Layer 3: only apply newer versions; stale or duplicate versions update 0 rows.
            var updated = await db.CustomerOrders
                .Where(o => o.OrderId == evt.OrderId && o.LastAppliedVersion < evt.Version)
                .ExecuteUpdateAsync(s => s
                    .SetProperty(o => o.Status, evt.Status)
                    .SetProperty(o => o.LastAppliedVersion, evt.Version), ct);
            if (updated == 0)
                log.LogInformation("Skipped stale event {Version} for order {OrderId}", evt.Version, evt.OrderId);

            // Layer 2: natural key. Unique index on (CustomerId, OrderId, Reason) stops double credits
            // even if the event is republished with a new message id.
            if (evt.Status == "Delivered" && evt.PointsEarned > 0)
                db.LoyaltyLedger.Add(new LoyaltyEntry(evt.CustomerId, evt.OrderId, "OrderDelivered", evt.PointsEarned));

            await db.SaveChangesAsync(ct);
            await tx.CommitAsync(ct);
        }
        catch (DbUpdateException ex) when (ex.InnerException is Microsoft.Data.SqlClient.SqlException { Number: 2601 or 2627 })
        {
            // Duplicate key: already processed. Roll back and complete the message.
            await tx.RollbackAsync(ct);
            log.LogInformation("Duplicate message {MessageId} ignored", msg.MessageId);
        }
        await args.CompleteMessageAsync(msg, ct);
    }
}

public sealed record InboxEntry(string Consumer, string MessageId, DateTimeOffset ProcessedAt);
public sealed record LoyaltyEntry(Guid CustomerId, Guid OrderId, string Reason, int Points);
// Program.cs: option B for strict per-order ordering, session processor keyed by order id.
var processor = client.CreateSessionProcessor("orders", "customer", new ServiceBusSessionProcessorOptions
{
    MaxConcurrentSessions = 32,          // parallel across orders
    MaxConcurrentCallsPerSession = 1,    // sequential within an order
    AutoCompleteMessages = false
});
// Publisher side: message.SessionId = orderId.ToString();

⚠ Common mistakes

  • Mistake: Assuming Service Bus delivers exactly once and in order. Why it is wrong: it guarantees at-least-once; FIFO holds only within a session, and even then prefetch, abandons and redelivery after lock loss can change the order you process in if the consumer isn't session-aware. Instead: design consumers for duplicates and reordering.
  • Mistake: Fixing by setting MaxConcurrentCalls = 1 everywhere. Why it is wrong: kills throughput and still breaks on scale-out or redelivery. Instead: version checks or sessions keyed by aggregate id.
  • Mistake: Dedup by message id only. Why it is wrong: the same business action can arrive with a different message id: the publisher republishes from outbox history after a fix, an upgrade replays events, or an operator resubmits copies. A message-id inbox lets each of those through, and an increment like a loyalty credit is applied again. Instead: add a business-level unique constraint on the effect (for example CustomerId + OrderId + Reason on the ledger) alongside the inbox.
  • Mistake: Inbox insert in a separate transaction from the state change. Why it is wrong: a crash between them loses or duplicates the effect. Instead: same transaction.
  • Mistake: Events without aggregate versions. Why it is wrong: consumers can't tell newer from older. Instead: include a monotonically increasing version per aggregate.
  • Mistake: Turning on sessions without checking throughput. Why it is wrong: each session is processed sequentially, so throughput is capped by MaxConcurrentSessions times per-message latency, and one hot key (a big customer) becomes a bottleneck. Instead: load test with realistic key distribution, or use version checks where strict sequencing isn't needed.
  • Mistake: Letting unknown event versions throw until MaxDeliveryCount. Why it is wrong: wastes capacity and delays other messages. Instead: dead-letter immediately with a reason.
  • Mistake: Repairing with ad-hoc SQL updates. Why it is wrong: unauditable and error-prone. Instead: rebuild from the source of truth and post compensating ledger entries.
  • Mistake: Lock duration shorter than processing time. Why it is wrong: locks expire and messages are processed twice. Instead: auto lock renewal and processing time well under the lock.

🏛 Senior insight: trade-offs

This incident is the norm, not an edge case: every messaging consumer eventually sees duplicates and reordering. The senior response is to make correctness a property of the consumer, verified by tests that shuffle and duplicate messages, rather than of the infrastructure configuration. Concurrency settings then become a throughput knob, not a correctness risk.

Choosing between sessions and version checks is a throughput decision. With sessions, messages for one order are processed strictly one at a time, so maximum throughput is roughly MaxConcurrentSessions / per-message latency: 32 sessions at 50 ms is about 640 messages a second, and a single busy key can't go faster than 20 a second. Session locks also add overhead when keys are many and short-lived. Version checks keep full competing-consumer parallelism but require state-carrying events. Delta events (points earned, stock decremented) need strict sequencing or business idempotency keys, which is often an argument for redesigning the event to carry state. I load test both with a realistic key distribution before choosing.

Monitoring makes this proactive: I emit a metric each time a stale version is skipped and each time the inbox or business key rejects a duplicate. A sudden rise in either after a deployment is an early warning that something upstream changed, long before customers notice.

Option When it fits Cost When not to
Version check, state-carrying events Most status-style projections Version on every event Pure delta events
Sessions keyed by aggregate Strict per-aggregate sequencing, deltas Throughput capped per key, hot keys Very high fan-in on one key
Inbox + business keys All consumers with side effects Tables, cleanup jobs Read-only, naturally idempotent upserts
Reconciliation job Financial or customer-visible state Batch compute Never skip for money

I'd alert on version regressions, duplicate-rejection rate, DLQ depth and lock-lost exceptions, and track drift found by reconciliation.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes an inbox table. Why: Checks inbox implementation depth, including concurrent duplicates.
    How to answer

    With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.

    The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.

    Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.

  2. When: Candidate mentions the publisher side or the outbox. Why: Checks the related lost and duplicated message incident with outbox and inbox.
    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.

  3. When: Candidate talks about aggregate versions or replaying history. Why: Checks understanding of versions and streams in event-sourced publishers.
    How to answer

    Event sourcing stores every state change as an immutable event in an append-only stream per aggregate, and derives current state by replaying those events. The event log is the source of truth; tables you query are projections built from it. Appends use the expected stream version for optimistic concurrency. Snapshots speed up replay for long streams, and events are evolved by additive changes and upcasting, never by editing history.

    It's worth it when the history itself is valuable: audit, temporal queries ("what did we know on 1 July?"), complex behaviour. It's a poor fit for CRUD and for teams new to it, because you pay in eventual consistency, schema evolution and harder queries.

🛠 Real-world problems: how you handle them

Scaling a consumer exposes out-of-order and duplicate event processing
Situation
A [retail] Customer service consumed order events from Azure Service Bus to maintain order status and loyalty balances for [~1.2 million] customers. A release scaled the consumer from [1] to [4] instances with `MaxConcurrentCalls` of [16] to clear a backlog.
Signals
Support tickets about statuses reverting and doubled points; [~0.8%] of orders with regressed status; `MessageLockLost` exceptions and abandoned message counts rising in Service Bus metrics; delivery counts of 2+ on [~0.3%] of messages.
Investigation
KQL queries in Application Insights lining up event versions per order across instances; release config diff showing concurrency and replica changes; comparison of consumer state against Ordering's API for a sample of [500] orders; processing time p99 of [45 s] against a [30 s] lock.
Resolution
Immediate: scaled back to one instance to stop further corruption. Fix: added aggregate versions with a consumer version check, an inbox in the same transaction, a unique ledger key per (customer, order, reason), auto lock renewal, and dead-lettering of unknown versions. Repaired [4,200] customers by resyncing from Ordering and posting compensating ledger entries.
Prevention
A consumer test harness that shuffles and duplicates event streams; nightly reconciliation of statuses and balances; alerts on version regressions, DLQ depth and lock-lost exceptions; consumer checklist in the service template.

How to tell it (STAR)

**S:** At [company], after we scaled the Customer service consumer to [4] instances, order statuses started reverting and some loyalty points were credited twice. **T:** As [on-call senior engineer, then incident owner], I had to stop the corruption, fix the cause and repair data. **A:** I scaled back to one instance, proved the reordering and lock-expiry redeliveries with KQL over event versions, then added version checks, an inbox and a unique ledger key, wrote [the post-incident review], and led a resync with compensating entries. **R:** Corruption stopped completely, throughput reached [600 msg/s] on four instances, [4,200] customers were repaired in [35 minutes], and the shuffle-and-duplicate harness became part of our consumer template.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me