How would you build idempotent message consumers in .NET for order and payment events?
Razorpay · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Messaging, Microservices
Community answers
Posted by wasAsked editorial collection
Message delivery is commonly at least once, so a consumer must tolerate duplicates. Give each event a stable ID and record processing atomically with the business change, usually in an inbox table with a unique constraint.
Example:
BEGIN TRANSACTION;
INSERT INTO Inbox(RestaurantId,OutletId,MessageId,ReceivedAtUtc)
VALUES(@RestaurantId,@OutletId,@MessageId,@Now);
-- unique violation means already processed
-- apply business update in the same tenant and transaction
COMMIT;
Acknowledge only after commit. Make external side effects idempotent with provider keys or an outbox, because a database transaction cannot atomically include email/payment services. Define ordering assumptions, bounded retries, dead-letter handling, retention, and observability.
Backbencher Developer · · 0 likes
Message brokers usually guarantee at-least-once delivery, so a consumer may receive the same order or payment event more than once (retries, redelivery after a crash, publisher duplicates). Idempotent consumers make duplicates harmless.
1. Give every message a stable ID
- The producer sets a unique MessageId or EventId (for example from the outbox row), which stays the same on redelivery.
2. Inbox / deduplication table
- In the consumer's database, store processed message IDs with a unique constraint.
- Process the message and insert the inbox record in the same transaction:
await using var tx = await db.Database.BeginTransactionAsync(ct);
if (await db.ProcessedMessages.AnyAsync(m => m.Id == msg.Id, ct)) return; // already handled
await ApplyPaymentAsync(msg, ct);
db.ProcessedMessages.Add(new ProcessedMessage(msg.Id, DateTime.UtcNow));
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
If two copies race, the unique constraint makes one fail, and that copy is treated as a duplicate.
3. Make the operations naturally idempotent where possible
- Use state transitions with conditions: UPDATE Orders SET Status = 'Paid' WHERE Id = @id AND Status = 'Pending'.
- Upserts instead of blind inserts; "set balance to X at version N" instead of "add X".
- Pass idempotency keys to external providers (payment gateways) for side effects you cannot roll back.
4. Handle ordering
- Events may arrive out of order (PaymentCaptured before OrderCreated). Use sequence numbers or versions per aggregate, ignore stale events, and retry or park events whose prerequisites are missing.
- Partition by order ID (Kafka key, Service Bus sessions) when strict ordering per order matters.
5. Reliable publishing
- Use the transactional outbox on the producer side so state changes and events are never out of sync.
6. Failure handling
- Retries with backoff for transient errors; dead-letter queues for poison messages, with alerting and a replay tool.
- Libraries such as MassTransit and NServiceBus provide outbox/inbox support out of the box.
Clean up old inbox records after a retention period longer than the maximum redelivery window.