Idempotency as the answer to retries, duplicates and at-least-once delivery: naturally idempotent operations, idempotency keys, dedup tables with unique constraints in the same transaction as the effect, concurrent duplicates, retention and side effects outside the database.
An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.
"Idempotency means the effect of doing something twice is the same as doing it once. It's the core tool of distributed systems because duplicates are normal, not exceptional. A client times out and retries without knowing whether the first call worked. Service Bus and Kafka deliver at least once, so a handler can get the same message again after a lock expires or a rebalance. Users double-click Pay. You can't stop duplicates arriving; you can only make them harmless.
There are two ways to get there. The cheap way is to design operations that are naturally idempotent: 'set the order status to Shipped' instead of 'advance the status', a
PUTthat replaces the whole resource, an upsert keyed by a natural id,balance = 120rather thanbalance += 20where that's acceptable. When that isn't possible, like charging a card or creating an order, I use deduplication. The caller supplies a unique key, theIdempotency-Keyheader or the message id, and the service inserts that key into a table with a unique index, in the same EF Core transaction as the business change. If two copies arrive at the same moment, one insert wins and the other hits the unique constraint, which I catch and turn into 'return the stored result'. If the process crashes halfway, the transaction rolls back both the key and the change, so a retry starts clean.The mistake I see is checking 'have I seen this key?' with a
SELECTand then inserting, which races under concurrency, or writing the key in a separate transaction from the change. The unique constraint and the single transaction are what make it correct."
| Route | Examples | Cost | Limits |
|---|---|---|---|
| Naturally idempotent | Set state, PUT full resource, upsert by natural key, delete by id | None | Doesn't work for 'add', 'charge', 'send' |
| Deduplication by key | Idempotency-Key on POST, message id in a consumer, client-generated order id | Key table, retention job | Key must be stable across retries |
| Source | Why it duplicates |
|---|---|
| HTTP client retry after a timeout | First attempt may have succeeded (partial failure) |
| Broker redelivery (Service Bus, RabbitMQ, SQS) | Lock or visibility timeout expired before completion |
| Kafka consumer rebalance | Offsets not yet committed get reprocessed |
| Outbox relay | Publishes, crashes before marking sent, publishes again |
| Users | Double-click, refresh, back button |
A payments consumer on Azure Service Bus took up to 70 seconds per message during a provider slowdown, longer than the 60-second lock duration. Messages were redelivered while the first attempt was still running, and about 1 in 800 payments was charged twice. Adding an inbox table with a unique index on (MessageId, Consumer), written in the same transaction as the payment record, and passing the order id as the provider's idempotency key, removed duplicates entirely; the extra insert added under 2 ms per message.
Checks whether the candidate treats duplicates as normal and can implement idempotency correctly under concurrency and crashes.
Green flags
Red flags
An operation f is idempotent if f(f(x)) = f(x): applying it again changes nothing. In services we care about the observable effect: rows written, money moved, emails sent. A response may differ (201 first time, 200 with the same body afterwards) as long as the effect doesn't repeat.
Client API DB
| -- POST (key K) -->| |
| | -- INSERT ----->| commit
| X <-- 201 ----| | (response lost)
| -- POST (key K) -->| | retry after timeout
| | -- INSERT K --->| unique violation -> return stored 201
With messaging, at-least-once delivery means a message is redelivered whenever the consumer fails to settle it in time: a lock expiry in Service Bus, a visibility timeout in SQS, an uncommitted offset in Kafka.
ProcessedOperations
OperationKey nvarchar(100) -- idempotency key or message id
Consumer nvarchar(100) -- different handlers may process the same message
ResultJson nvarchar(max) -- what to return to a repeated caller
CreatedUtc datetime2
PRIMARY KEY (OperationKey, Consumer)
The algorithm:
If two requests with the same key race, the database's unique index serialises them: one commits, the other gets error 2627 or 2601 (in EF Core, a DbUpdateException wrapping a SqlException). The loser then reads the stored result. If the process crashes before commit, nothing is recorded and a retry works normally.
Request A: SELECT key K -> not found
Request B: SELECT key K -> not found
Request A: INSERT order ... commit
Request B: INSERT order ... commit <- duplicate
Only a constraint (or a lock) makes the check and the write atomic. Under read committed snapshot, two readers both see 'not found'.
Your database transaction can't include an HTTP call to a payment provider or an email send. Options: pass your key downstream as the provider's idempotency key; or write the intent to an outbox in the same transaction and have one worker perform the external call with its own dedup.
Task.WhenAll and count the orders created.Idempotent order creation with a dedup table: the key row and the order are saved in one EF Core transaction, and a concurrent duplicate is caught by the primary key.
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace Orders;
public sealed class ProcessedOperation
{
public required string OperationKey { get; init; }
public required string Consumer { get; init; }
public required string ResultJson { get; init; }
public DateTime CreatedUtc { get; init; } = DateTime.UtcNow;
}
public sealed class Order
{
public Guid Id { get; init; }
public required string CustomerId { get; init; }
public decimal Total { get; init; }
}
public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<ProcessedOperation> ProcessedOperations => Set<ProcessedOperation>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<ProcessedOperation>().HasKey(p => new { p.OperationKey, p.Consumer });
}
public sealed record CreateOrder(string CustomerId, decimal Total);
public sealed record OrderCreated(Guid OrderId);
public sealed class CreateOrderHandler(OrdersDb db)
{
private const string Consumer = "create-order";
public async Task<OrderCreated> HandleAsync(string idempotencyKey, CreateOrder cmd, CancellationToken ct)
{
var order = new Order { Id = Guid.NewGuid(), CustomerId = cmd.CustomerId, Total = cmd.Total };
var result = new OrderCreated(order.Id);
db.Orders.Add(order);
db.ProcessedOperations.Add(new ProcessedOperation
{
OperationKey = idempotencyKey,
Consumer = Consumer,
ResultJson = System.Text.Json.JsonSerializer.Serialize(result)
});
try
{
await db.SaveChangesAsync(ct); // one implicit transaction: key + order, or neither
return result;
}
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
{
// A duplicate (possibly concurrent) already committed: return ITS result
db.ChangeTracker.Clear();
var existing = await db.ProcessedOperations.AsNoTracking()
.SingleAsync(p => p.OperationKey == idempotencyKey && p.Consumer == Consumer, ct);
return System.Text.Json.JsonSerializer.Deserialize<OrderCreated>(existing.ResultJson)!;
}
}
}
SELECT the key, then insert). Why it is wrong: two concurrent duplicates both see 'not found' and both proceed. Instead: rely on a unique constraint and catch the violation.Idempotency has to go all the way down. Deduplicating in my database doesn't stop my handler calling the payment provider twice if the provider call happens before my transaction commits. So the key flows downstream: my idempotency key becomes the provider's idempotency key, and the email service gets a dedup id too. Where a downstream system has no idempotency support, I record intent first (an outbox row) and make the external call from a single, deduplicated worker.
Beyond SQL. The same idea works without relational constraints, as long as the store gives you an atomic 'insert if absent':
id = the key in the same logical partition as the business document, and write both in a transactional batch; a duplicate create returns 409 Conflict.SET key value NX EX 86400 claims a key atomically. Good for short windows and cheap pre-checks, but it is not in the same transaction as your database write, so treat it as an optimisation, not the source of truth.enable.idempotence, the default in current clients) removes duplicate writes caused by producer retries; consumers still need their own dedup or idempotent writes, because rebalances replay uncommitted offsets.Retention by context. Keys are only useful while a duplicate can still arrive. HTTP retries: 24 hours is typical. Messages: the queue's time-to-live plus however long you might replay dead letters, often 7–14 days. Payments: keep the operation record (not necessarily the hot dedup row) for as long as chargebacks and reconciliation can reference it, which for card payments is months, and archive rather than delete.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Design it naturally idempotent | Updates expressible as 'set state' or conditional writes | None | Counters, charges, sends |
| Dedup table in the same transaction | Writes to your own database | One insert, retention job | Effects outside your database |
| Downstream idempotency key | Payments, third-party APIs | Provider support needed | Provider has no key support (use outbox + single worker) |
| Broker duplicate detection | Duplicate sends within a window | Only covers the send side | Never a replacement for consumer idempotency |
The client sends a unique Idempotency-Key (usually a UUID) with a non-idempotent request and reuses it on every retry. The server atomically claims the key with a unique constraint on (client, key), stores a fingerprint of the request, executes the operation and saves the response. A retry with the same key and body gets the stored response replayed; a request still in progress gets 409 Conflict; the same key with a different body gets 422. Ideally the business write and the idempotency record commit in one transaction, so a crash can't leave a charge without a record. Keys expire after a published window, often 24 hours. The trade-off is an extra write per request and storage, in exchange for making POST safe to retry.
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.
Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.
How to tell it (STAR)
**S:** Our [payments consumer] was charging roughly [1 in 800] customers twice during a provider slowdown. **T:** I owned the fix. **A:** I matched duplicate MessageIds in Application Insights to lock expiries, then added an inbox table in the same transaction as the payment and passed the order id downstream as the provider's idempotency key. **R:** Duplicate charges went to zero, the extra insert cost under [2 ms] per message, and we refunded [n] affected customers within a day.
Last updated 23 Nov 2026.