Consumer Idempotency & Deduplication in .NET
Quick Answer: RabbitMQ guarantees at-least-once delivery, which means your .NET consumer will eventually receive the same message twice. Idempotency ensures that processing a duplicate MessageId does nothing extra, preventing double charges or duplicate orders.
Imagine Meena runs a UPI payment app in Hyderabad. Karthik scans a QR code and pays ₹850 for groceries.
The .NET Payment Consumer deducts ₹850 from Karthik's account. One millisecond later, the network drops before BasicAck reaches RabbitMQ.
RabbitMQ assumes the worker died and sends the exact same message again. How do we stop the app from charging Karthik ₹1,700?
1. Why Do We Need Consumer Idempotency?
The problem without deduplication
In a naive consumer, every incoming message runs the business logic blindly without checking if it already ran.
Example 1: Unsafe .NET payment consumer
This code works when the network is perfect, but double-charges Karthik on any retry.
consumer.ReceivedAsync += async (sender, ea) =>
{
var payment = JsonSerializer.Deserialize<UpiPayment>(ea.Body.Span);
await _bankService.DeductAsync(payment.UserId, payment.Amount);
await channel.BasicAckAsync(ea.DeliveryTag, multiple: false);
};
What happens on a network blip
Attempt 1 (msg-991) -> Deducted Rs. 850 from Karthik. Network dropped before Ack! Attempt 2 (msg-991) -> Deducted Rs. 850 AGAIN! Total charged: Rs. 1,700.
This setup works on your local laptop. However, it fails in production.
- Network timeouts after database commits cause RabbitMQ to redeliver messages.
- Worker crashes or pod restarts mid-processing trigger automatic retries.
- Producers retrying a failed publish can push the same event twice.
We cannot stop duplicate deliveries in a distributed system. Instead, we make our .NET consumer safe when duplicates arrive.
The solution: Track Unique MessageId Keys
Idempotency = running the same operation once or five times produces the exact same result.
Deduplication = checking a fast store (MS SQL Server or Redis) for a unique MessageId before doing any work.
Every message from Meena's UPI API carries a unique MessageId (like msg-991). The consumer checks its ledger first. If msg-991 is already there, it skips the charge and sends BasicAck right away.
Live Flow: Idempotency Gate Stopping a Double UPI Charge
Watch Attempt #1 succeed and save msg-991, then watch Attempt #2 get blocked safely.
Even when RabbitMQ redelivers msg-991, the SQL/Redis ledger catches it immediately so Karthik is only charged once.
2. How to Implement Deduplication in .NET
You have two strong choices for storing MessageId keys: MS SQL Server (for strict atomic transactions) or Redis (for ultra-fast lookups).
Example 2: Atomic deduplication with MS SQL Server in C#
Insert the MessageId and deduct the balance inside the exact same SQL transaction.
public async Task HandlePaymentAsync(string messageId, UpiPayment payment)
{
await using var tx = await _db.Database.BeginTransactionAsync();
// Primary Key on MessageId blocks duplicates atomically
var inserted = await _db.Database.ExecuteSqlRawAsync(
"IF NOT EXISTS (SELECT 1 FROM ProcessedMessages WHERE MessageId = {0}) " +
"INSERT INTO ProcessedMessages (MessageId, ProcessedAt) VALUES ({0}, GETUTCDATE())",
messageId);
if (inserted == 0)
{
return; // Duplicate! Skip charge and Ack the message
}
await _bankService.DeductInTxAsync(payment.UserId, payment.Amount);
await tx.CommitAsync();
}
If your app handles thousands of events per second and does not need a SQL transaction, Redis SET NX is even faster.
Example 3: Fast deduplication with Redis SET NX in C#
When.NotExists sets the key only if it is new, with a 24-hour expiry.
var isNew = await _redis.StringSetAsync(
key: $"idem:{messageId}",
value: "1",
expiry: TimeSpan.FromHours(24),
when: When.NotExists);
if (!isNew)
{
return; // Already processed. Safe to Ack and exit.
}
Expected output
[PaymentWorker] msg-991 -> New key saved. Deducted Rs. 850 for Karthik. [PaymentWorker] msg-991 -> Duplicate detected! Skipped charge. Sent BasicAck.
3. MS SQL Server vs. Redis for Deduplication
| Feature | MS SQL Server | Redis (SET NX) |
|---|---|---|
| Atomicity | Shares one transaction with your business data. | Separate from your SQL database. |
| Speed | Fast (2–5 ms) with a Primary Key index. | Ultra-fast (under 1 ms) in memory. |
| Best for | Payments, orders, and financial ledgers. | Emails, SMS alerts, and high-volume webhooks. |
Design tip: Always set BasicProperties.MessageId on the producer side using a deterministic ID (like order-5042-charge) or a GUID generated before the first publish attempt.
4. Common Mistakes to Avoid
1. Using BasicNack when a duplicate is found
If you reject a duplicate message with requeue: true, RabbitMQ will send it back in an endless loop.
Better approach: Always call BasicAckAsync on duplicates so RabbitMQ removes them from the queue.
2. Checking and inserting in two separate queries
If two worker pods check SELECT at the exact same millisecond, both see "not found" and both charge Karthik.
Better approach: Rely on a database PRIMARY KEY constraint or Redis SET NX for atomic locking.
5. Interview Questions & Practice
Question 1: Why does RabbitMQ not guarantee exactly-once delivery?
What the interviewer expects: Understanding of network failures between consumer work and broker acknowledgments.
Strong answer: "In a network, a consumer can finish charging Karthik ₹850 and crash right before its BasicAck reaches RabbitMQ. Because RabbitMQ never saw the Ack, it must redeliver the message. That is why we combine at-least-once delivery with an idempotent consumer."
Practice: E-commerce order confirmation
Design a ProcessedMessages SQL table for an inventory worker that deducts stock when an order arrives. Include a cleanup plan so the table does not grow forever.
Expected result: A table with MessageId VARCHAR(64) PRIMARY KEY and ProcessedAt DATETIME2, plus a nightly job that deletes rows older than 7 days.
6. Next Steps
- Previous Article: Implementing Delayed Retries with Exponential Backoff
- Next Article: Quorum Queues & RabbitMQ Streams for High Availability
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.