Queues and duplicate delivery
Queues and duplicate delivery
A message queue decouples a producer from a consumer. Acknowledgment records successful handling according to a broker contract, while idempotency ensures repeated delivery does not repeat the business effect.
A bounded in-process channel is good for local backpressure but loses queued data on process failure. Durable brokers store messages according to configured persistence and replication guarantees. At-most-once can lose work; at-least-once can deliver duplicates; exactly-once has a specific boundary, not a universal promise. RabbitMQ publisher confirms and consumer acknowledgments concern different transfers. Azure Service Bus supports queues, topics, lock-based receive and dead-letter handling; locks can expire. Kafka is an ordered log within partitions, with offsets and scoped transactional processing; global ordering or an external database transaction is not implied. Select a broker by retention, routing, replay, ordering, throughput and operational needs, not library fashion. A message should carry a stable ID, tenant, schema version and meaningful payload. Validate before executing; reject mismatched duplicate IDs rather than assuming every reuse is valid. In a durable consumer, atomically store the inbox marker with the business effect and acknowledge after commit. A unique constraint protects against concurrent duplicates. Limit attempts and quarantine poison messages, with reason and approved replay. Avoid retrying permanent validation errors or emitting duplicate notifications.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models and isolated local integration fixtures are explicitly distinguished.
Observe backpressure on a bounded queue
Use capacity two and a single producer and consumer in one finite sequence. TryWrite reports rejection rather than waiting.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;using System.Threading.Channels;var queue = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.Wait });Console.WriteLine(queue.Writer.TryWrite(10));Console.WriteLine(queue.Writer.TryWrite(20));Console.WriteLine(queue.Writer.TryWrite(30));queue.Writer.Complete();await foreach (int value in queue.Reader.ReadAllAsync()) Console.WriteLine(value);Expected result (not executed):
TrueTrueFalse1020The third item was not accepted. A real producer can await WriteAsync with cancellation, return overload to its caller, or durably spool; never silently drop a required message.
Deduplicate an inventory adjustment in a transaction
SQLite memory database; simulate delivery of the same stable ID twice. This is a local inbox transaction, not a real broker.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires Microsoft.Data.Sqlite 10.0.15; uses only an isolated in-memory database.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:"); db.Open();using (var init = db.CreateCommand()) { init.CommandText = "CREATE TABLE Inbox(Id TEXT PRIMARY KEY NOT NULL); CREATE TABLE Stock(Qty INTEGER NOT NULL); INSERT INTO Stock VALUES(10);"; init.ExecuteNonQuery(); }foreach (string id in new[] { "msg-1", "msg-1" }) { using var tx = db.BeginTransaction(); using var insert = db.CreateCommand(); insert.Transaction = tx; insert.CommandText = "INSERT INTO Inbox(Id) VALUES($id) ON CONFLICT(Id) DO NOTHING"; insert.Parameters.AddWithValue("$id", id); bool first = insert.ExecuteNonQuery() == 1; if (first) { using var update = db.CreateCommand(); update.Transaction = tx; update.CommandText = "UPDATE Stock SET Qty = Qty - 2 WHERE Qty >= 2"; if (update.ExecuteNonQuery() != 1) throw new InvalidOperationException("Insufficient stock"); } tx.Commit(); Console.WriteLine(first ? "applied; acknowledge" : "duplicate; acknowledge");}using var read = db.CreateCommand(); read.CommandText = "SELECT Qty FROM Stock"; Console.WriteLine($"stock={read.ExecuteScalar()}");Expected result (not executed):
applied; acknowledgeduplicate; acknowledgestock=8The unique marker and stock update share a transaction; rollback on failure permits later processing. This fixture uses one tenant and identical payloads; a real multi-tenant inbox includes tenant, consumer identity and payload fingerprint, with a retention policy longer than replay risk.
Classify poison and transient messages
Use a bounded synthetic delivery schedule. No broker or delays are involved.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;foreach (var message in new[] { (Id:"a", Valid:true, Failures:1), (Id:"b", Valid:false, Failures:0), (Id:"c", Valid:true, Failures:5) }) { if (!message.Valid) { Console.WriteLine($"{message.Id}: dead-letter invalid"); continue; } bool done = false; for (int attempt = 1; attempt <= 3; attempt++) { if (attempt <= message.Failures) continue; Console.WriteLine($"{message.Id}: ack attempt {attempt}"); done = true; break; } if (!done) Console.WriteLine($"{message.Id}: dead-letter exhausted");}Expected result (not executed):
a: ack attempt 2b: dead-letter invalidc: dead-letter exhaustedThe three-attempt cap includes the initial attempt. A real broker may count redelivery separately; persist retry information and backoff rather than immediately requeueing forever.
Apply the concept
Design an inbox for warehouse A and B, both receiving message 12. Then simulate a crash after the database commit but before broker acknowledgment.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queues and duplicate delivery — knowledge check
Apply the lesson concepts to the following scenarios.
Which queue is durable by default in this lesson?
When should a durable consumer acknowledge a database update?
What scope does Kafka partition ordering describe?
What is a publisher confirm distinct from?
What should happen to a permanently invalid message?