This article was drafted with AI help and reviewed by the author.
A warehouse management system (WMS) tells the rest of the business how much stock it has. It does that with a stream of events and, usually, a periodic full snapshot. Both arrive at a consumer that has to turn them into one trusted number per SKU and location.
The hard part is not reading the messages. It is making sure an old or repeated message can never overwrite a newer number. This post shows a .NET 8 consumer on Azure Service Bus that is built around that rule. It uses broker features where they help, and it puts the real guarantees in the database, where they survive retries, replays and restarts.
The C# was compiled against net8.0 with Azure.Messaging.ServiceBus 7.20.1, Azure.Identity 1.13.2 and Microsoft.EntityFrameworkCore.SqlServer 8.0.11. It was not run against a live namespace or database, and it has not been production-tested. It is a generic pattern, not a description of a particular system.
The problem
Here are four ways a stock number goes wrong even when every component reports success.
- A duplicate delta. The WMS sends "minus 2" twice after a timeout. The consumer applies both.
- Two absolute values, reordered. "On hand is 8" is sent before "on hand is 5". Two consumers pick them up in parallel and the 8 lands last.
- A replay from the dead-letter queue. Someone fixes a bug and resubmits yesterday's failed messages. They overwrite today's numbers.
- A snapshot that rolls back an event. The nightly snapshot was taken at 02:00. It is applied at 02:20. An adjustment from 02:10 is quietly undone.
None of these throw an exception. All of them leave channels showing the wrong stock.
Prefer absolute values with a version
If you can influence the WMS contract, ask for absolute on-hand per SKU and location, plus a version that increases for that key. With that shape, the consumer only needs one rule. Apply the event if its version is higher than the stored one. Otherwise ignore it.
Deltas make every duplicate dangerous and every gap permanent. If the WMS only sends deltas, the inbox table below becomes mandatory, ordering matters much more, and the snapshot is your only way back to the truth.
The event used in this post looks like this. The same record appears again in the full model below.
``csharp public sealed record OnHandChanged( string EventId, string Sku, string LocationCode, int OnHand, long Version, DateTime OccurredAtUtc); ``
What Service Bus gives you, and what it does not
Duplicate detection. Official docs say that when it is enabled, Service Bus tracks the application-set MessageId during a time window and drops a later message with the same id. The send still reports success. The window defaults to 10 minutes, with a minimum of 20 seconds and a maximum of 7 days. It needs the Standard or Premium tier.
That helps with a sender that retries after a timeout. It does not help with a resend after the window, a duplicate sent with a new id, or a replay from the dead-letter queue. So it is a first filter, not a guarantee.
Sessions. Official docs say sessions are how you get first-in, first-out processing. A sequence number alone guarantees the order in the queue, not the order of processing across several consumers. With sessions, one receiver holds the lock for a session id, and messages for that session are processed in order.
Use Sku|LocationCode as the session id. Updates for one key are processed one at a time, while different keys still run in parallel.
There are two limits to keep in mind. Sessions only preserve the order the WMS sent. If the WMS emits events out of order, sessions keep them out of order. And official docs warn that a dead-lettered message moved back to the queue loses its original order, because it gets a new enqueue time and sequence number.
Dead-lettering. Official docs say a message that keeps failing is moved to the dead-letter queue once it passes MaxDeliveryCount, which defaults to 10. That is where poison messages should end up, with a reason.
Here is how a producer, or a small adapter in front of the WMS, would build the message:
```csharp using Azure.Messaging.ServiceBus;
public static class WmsEventPublisher { public static ServiceBusMessage ToMessage(OnHandChanged e) => new(BinaryData.FromObjectAsJson(e)) { MessageId = e.EventId, SessionId = $"{e.Sku}|{e.LocationCode}", Subject = "stock.onhand.changed", ContentType = "application/json" }; } ```
Setting MessageId to the WMS event id ties broker deduplication to the business event, which is what official guidance recommends.
The data model
Three tables carry the guarantees.
-
StockLevelholds one row per SKU and location, with the last applied version and timestamps. -
ProcessedMessageis an inbox. Its primary key is the event id. -
StockDriftrecords every difference a snapshot found, and what was done about it.
```csharp using Microsoft.EntityFrameworkCore;
public sealed class StockLevel { public string Sku { get; set; } = ""; public string LocationCode { get; set; } = ""; public int OnHand { get; set; } public long Version { get; set; } public DateTime LastEventAtUtc { get; set; } public DateTime? LastSnapshotAtUtc { get; set; } }
public sealed class ProcessedMessage { public string MessageId { get; set; } = ""; public DateTime ProcessedAtUtc { get; set; } }
public sealed class StockDrift { public long Id { get; set; } public string Sku { get; set; } = ""; public string LocationCode { get; set; } = ""; public int OursBefore { get; set; } public int SnapshotOnHand { get; set; } public DateTime SnapshotAsOfUtc { get; set; } public string Action { get; set; } = ""; }
public sealed class WmsDbContext(DbContextOptions<WmsDbContext> options) : DbContext(options) { public DbSet<StockLevel> StockLevels => Set<StockLevel>(); public DbSet<ProcessedMessage> ProcessedMessages => Set<ProcessedMessage>(); public DbSet<StockDrift> StockDrifts => Set<StockDrift>();
protected override void OnModelCreating(ModelBuilder b) { b.Entity<StockLevel>().HasKey(s => new { s.Sku, s.LocationCode }); b.Entity<StockLevel>().Property(s => s.LastEventAtUtc).IsConcurrencyToken(); b.Entity<ProcessedMessage>().HasKey(m => m.MessageId); b.Entity<ProcessedMessage>().Property(m => m.MessageId).HasMaxLength(128); } }
public sealed record OnHandChanged( string EventId, string Sku, string LocationCode, int OnHand, long Version, DateTime OccurredAtUtc);
public sealed record SnapshotLine(string Sku, string LocationCode, int OnHand);
public enum ApplyOutcome { Applied, Created, Duplicate, Stale } ```
LastEventAtUtc is a concurrency token. The snapshot job reads rows, then writes. If an event lands in between, EF Core raises a concurrency exception instead of silently overwriting the event.
Applying an event
The writer does three things in one transaction.
- Insert the event id into the inbox. A unique key violation means the event was already processed. Stop there.
- Run a conditional update. It only matches if the stored version is lower and the event is newer than the last snapshot.
- If nothing matched, decide if the row is missing or the event is stale.
```csharp using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore;
public sealed class StockWriter(IDbContextFactory<WmsDbContext> dbFactory) { public async Task<ApplyOutcome> ApplyAsync(OnHandChanged e, CancellationToken ct) { await using var db = await dbFactory.CreateDbContextAsync(ct); await using var tx = await db.Database.BeginTransactionAsync(ct);
db.ProcessedMessages.Add(new ProcessedMessage { MessageId = e.EventId, ProcessedAtUtc = DateTime.UtcNow });
try { await db.SaveChangesAsync(ct); } catch (DbUpdateException ex) when (IsUniqueViolation(ex)) { return ApplyOutcome.Duplicate; }
var updated = await db.StockLevels .Where(s => s.Sku == e.Sku && s.LocationCode == e.LocationCode && s.Version < e.Version && (s.LastSnapshotAtUtc == null || s.LastSnapshotAtUtc < e.OccurredAtUtc)) .ExecuteUpdateAsync(set => set .SetProperty(s => s.OnHand, e.OnHand) .SetProperty(s => s.Version, e.Version) .SetProperty(s => s.LastEventAtUtc, e.OccurredAtUtc), ct);
var outcome = ApplyOutcome.Applied;
if (updated == 0) { var exists = await db.StockLevels.AnyAsync( s => s.Sku == e.Sku && s.LocationCode == e.LocationCode, ct);
if (exists) { outcome = ApplyOutcome.Stale; } else { db.StockLevels.Add(new StockLevel { Sku = e.Sku, LocationCode = e.LocationCode, OnHand = e.OnHand, Version = e.Version, LastEventAtUtc = e.OccurredAtUtc }); await db.SaveChangesAsync(ct); outcome = ApplyOutcome.Created; } }
await tx.CommitAsync(ct); return outcome; }
private static bool IsUniqueViolation(DbUpdateException ex) => ex.InnerException is SqlException { Number: 2601 or 2627 }; } ```
ExecuteUpdateAsync sends a single UPDATE ... WHERE to the database. Official EF Core docs say it runs immediately and does not go through the change tracker. The version check happens inside the database, so two consumers cannot both pass it for the same row.
The snapshot condition in the Where clause handles failure 4 from the other side. After a snapshot corrects a row, a delayed event that happened before the snapshot cannot undo the correction, even if its version is higher than the stored one.
A stale event is not an error. It is completed and logged. Retrying it would never succeed, and dead-lettering it would only create noise.
The consumer
The processor is created with a managed identity through DefaultAzureCredential. The identity needs a data-plane receive role on the subscription. No connection string lives in configuration.
```csharp using System.Text.Json; using Azure.Identity; using Azure.Messaging.ServiceBus;
public sealed class WmsEventConsumer : IAsyncDisposable { private readonly ServiceBusClient client; private readonly ServiceBusSessionProcessor processor; private readonly StockWriter _writer;
public WmsEventConsumer(string fullyQualifiedNamespace, StockWriter writer) { writer = writer; client = new ServiceBusClient(fullyQualifiedNamespace, new DefaultAzureCredential()); processor = client.CreateSessionProcessor("wms-stock", "channel-sync", new ServiceBusSessionProcessorOptions { AutoCompleteMessages = false, MaxConcurrentSessions = 16, MaxConcurrentCallsPerSession = 1 });
processor.ProcessMessageAsync += HandleAsync; processor.ProcessErrorAsync += args => { Console.Error.WriteLine($"{args.ErrorSource} {args.EntityPath}: {args.Exception.Message}"); return Task.CompletedTask; }; }
public Task StartAsync(CancellationToken ct) => _processor.StartProcessingAsync(ct);
private async Task HandleAsync(ProcessSessionMessageEventArgs args) { OnHandChanged? e; try { e = args.Message.Body.ToObjectFromJson<OnHandChanged>(); } catch (JsonException ex) { await args.DeadLetterMessageAsync(args.Message, "InvalidPayload", ex.Message); return; }
if (e is null || e.EventId != args.Message.MessageId) { await args.DeadLetterMessageAsync(args.Message, "IdMismatch", "Body EventId must equal MessageId"); return; }
try { var outcome = await _writer.ApplyAsync(e, args.CancellationToken); if (outcome == ApplyOutcome.Stale) { Console.WriteLine($"Stale {e.Sku}@{e.LocationCode} v{e.Version} ignored"); } await args.CompleteMessageAsync(args.Message); } catch (Exception) when (!args.CancellationToken.IsCancellationRequested) { await args.AbandonMessageAsync(args.Message); } }
public async ValueTask DisposeAsync() { await processor.DisposeAsync(); await client.DisposeAsync(); } } ```
AutoCompleteMessages is off, so every message is settled on purpose.
- Bad JSON and id mismatches go to the dead-letter queue with a reason. They will never succeed on retry.
- Applied, created, duplicate and stale events are completed.
- Anything else is abandoned. In a session, the same message is offered again, and after
MaxDeliveryCountattempts it moves to the dead-letter queue.
ToObjectFromJson uses default System.Text.Json options. Those match the publisher above. If the WMS sends snake_case JSON, pass explicit serializer options.
MaxConcurrentCallsPerSession = 1 keeps one key strictly sequential. MaxConcurrentSessions controls overall throughput. Tune it with real load, not with the example value.
Correcting drift with the snapshot
Events are fast. Snapshots are self-correcting. You need both, because a missed or rejected event is otherwise invisible forever.
The reconciler compares each snapshot line with the stored row and takes one of four actions.
- created: the snapshot has a key we have never seen.
- corrected: the numbers differ and no event newer than the snapshot has landed. Take the snapshot value.
- deferred: the numbers differ, but an event newer than the snapshot is already applied. Keep the event and let the next snapshot decide.
- missingfromsnapshot: we have a row the snapshot did not mention. Record it. Do not zero it automatically.
```csharp using Microsoft.EntityFrameworkCore;
public sealed class SnapshotReconciler(IDbContextFactory<WmsDbContext> dbFactory) { public async Task<int> ApplyAsync( IReadOnlyCollection<SnapshotLine> lines, DateTime asOfUtc, CancellationToken ct) { await using var db = await dbFactory.CreateDbContextAsync(ct);
var ours = await db.StockLevels.ToDictionaryAsync( s => (s.Sku, s.LocationCode), ct); var seen = new HashSet<(string, string)>(); var drifts = 0;
foreach (var line in lines) { var key = (line.Sku, line.LocationCode); seen.Add(key);
if (!ours.TryGetValue(key, out var row)) { db.StockLevels.Add(new StockLevel { Sku = line.Sku, LocationCode = line.LocationCode, OnHand = line.OnHand, LastEventAtUtc = asOfUtc, LastSnapshotAtUtc = asOfUtc }); Record(db, line.Sku, line.LocationCode, 0, line.OnHand, asOfUtc, "created"); drifts++; continue; }
if (row.OnHand == line.OnHand) { row.LastSnapshotAtUtc = asOfUtc; continue; }
if (row.LastEventAtUtc > asOfUtc) { // An event newer than the snapshot already landed. Do not roll it back. Record(db, row.Sku, row.LocationCode, row.OnHand, line.OnHand, asOfUtc, "deferred"); continue; }
Record(db, row.Sku, row.LocationCode, row.OnHand, line.OnHand, asOfUtc, "corrected"); row.OnHand = line.OnHand; row.LastSnapshotAtUtc = asOfUtc; drifts++; }
foreach (var row in ours.Values.Where(r => !seen.Contains((r.Sku, r.LocationCode)))) { Record(db, row.Sku, row.LocationCode, row.OnHand, 0, asOfUtc, "missingfromsnapshot"); }
await db.SaveChangesAsync(ct); return drifts; }
private static void Record(WmsDbContext db, string sku, string location, int before, int snapshot, DateTime asOfUtc, string action) => db.StockDrifts.Add(new StockDrift { Sku = sku, LocationCode = location, OursBefore = before, SnapshotOnHand = snapshot, SnapshotAsOfUtc = asOfUtc, Action = action }); } ```
The last case is deliberately conservative. A missing SKU can mean zero stock, a location that was renamed, or a snapshot that was cut short. Zeroing it would hide the difference between those. A person should look at the drift table.
That drift table is also your best health signal. A few corrections a day is normal noise. A steady rise for one location usually means an event type you are not consuming.
Limitations
The snapshot guard compares WMS timestamps on events and snapshots. That assumes one clock. If the WMS can stamp the snapshot with the highest event version it includes, compare versions instead. That is more reliable.
The reconciler loads all stock rows into memory. For a large catalog, process it in pages by SKU range or location.
A DbUpdateConcurrencyException from the reconciler is not handled in the sample. Catch it, reload the affected rows, and run the comparison again.
The inbox table grows forever in this sample. Delete rows older than the longest realistic replay window, and keep that window longer than the broker's duplicate detection window.
The code was compiled, not run. Entity names, the topic and the subscription are placeholders. Shipment confirmations and returns can reuse the same inbox, but they need their own handlers.
Takeaways
- Broker deduplication and sessions are useful filters. They are not your consistency model.
- Ask the WMS for absolute values with a version per key. Deltas make every duplicate dangerous.
- Put an inbox insert and a conditional versioned update in one transaction.
- Treat stale events as complete, not as failures.
- Dead-letter only what can never succeed.
- Apply snapshots so they cannot roll back newer events, and so older events cannot roll back a snapshot.
- Record drift. Do not auto-zero what the snapshot did not mention.
This consumer depends on an earlier decision about which system owns on-hand and which owns available-to-sell. This WMS integration playbook walks through that decision and the shipment and return flows around it.
Top comments (0)