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.
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.
"Two symptoms, two likely causes. A status going Shipped then back to Paid is an ordering problem: the
OrderPaidevent was processed afterOrderShipped. 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 raisedMaxConcurrentCalls, 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 | 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 | 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 |
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.
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
Red flags
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.
MessageLockLost).MaxConcurrentCalls, PrefetchCount, replica count, MaxAutoLockRenewalDuration, retry policy.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
LastAppliedVersion per aggregate; apply if event.Version > stored. Works when each event carries enough state to supersede older ones (state-carrying events).event.Version must equal stored + 1; otherwise abandon or defer the message and retry later (or park it).SessionId = orderId; the session processor processes one message at a time per session, preserving order. Parallelism across sessions via MaxConcurrentSessions.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.
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.
MaxConcurrentCalls = 8 against the Service Bus emulator and reproduce a status regression.MessageLockLost.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();
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.CustomerId + OrderId + Reason on the ledger) alongside the inbox.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.MaxDeliveryCount. Why it is wrong: wastes capacity and delays other messages. Instead: dead-letter immediately with a reason.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.
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:
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.
These are two bugs with different causes, so I quantify each with reconciliation queries first.
Task.Run killed on deploy, or a swallowed ServiceBusException).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.
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.
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.
Last updated 23 Nov 2026.