Implementing the Idempotency-Key pattern in ASP.NET Core 10 with SQL Server: key scope, request fingerprint, stored responses, concurrent duplicates, mismatched payloads, partial failures, expiry and the IETF draft's status codes.
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.
"An idempotency key turns a non-idempotent POST into something a client can retry safely. The client creates a key per logical operation, say a UUID when the user presses Pay, and sends it in the
Idempotency-Keyheader on the first attempt and every retry. On the server, the first request with that key does the work and saves the response; every later request with the same key gets that saved response back without doing the work again. The header comes from an IETF httpapi draft, which still isn't an RFC, but Stripe, Adyen and others have used the pattern for years.The interesting parts are the edge cases. Two copies can arrive at the same moment, so the claim must be atomic: I insert a row with status InProgress and a unique index on client id plus key, and whoever loses the insert gets 409 Conflict and retries later. I store a hash of the method, path and body; if the same key comes back with a different body, that's a client bug and I return 422 rather than silently replaying an unrelated response. For example, at [company] we [added this to the payments API after a mobile client double-charged [N] customers on flaky networks]; duplicates dropped to [zero] in the following months.
The mistake I see is storing the key in a cache after the work is done. If the process crashes between charging and saving the record, the retry charges again. Where I can, I write the business change and the idempotency record in the same database transaction. When the work calls an external provider, I pass my own idempotency key on to the provider too, so the whole chain is idempotent, not just my front door."
| Column | Purpose |
|---|---|
| ClientId + Key | Unique index: keys are scoped per client, never global |
| RequestHash | SHA-256 of method, path and canonical body: detects key reuse with a different payload |
| Status | InProgress / Completed |
| ResponseStatus, ResponseBody, ResponseHeaders (Location) | Replayed verbatim on retries |
| CreatedAt, ExpiresAt | Retention window and clean-up |
| Situation | Response |
|---|---|
| New key | Execute, store, return result |
| Same key, same fingerprint, completed | Replay stored status and body |
| Same key, request still in progress | 409 Conflict (the draft's suggestion) with Retry-After |
| Same key, different fingerprint | 422 Unprocessable Content |
| Key missing on an endpoint that requires it | 400 Bad Request with ProblemDetails |
| Operation failed with 4xx | Store and replay it (the request is bad); for 5xx, release the key so the client can retry |
On a [payments API] handling about [40,000] payments a day, mobile clients on poor connections retried after timeouts and roughly [0.1%] of payments were duplicated. Requiring Idempotency-Key, recording it in the same transaction as the payment, and forwarding it to the payment provider removed duplicates entirely; the extra insert added about 2 ms to p95.
Checks whether the candidate can implement idempotency correctly under concurrency and failure, not just describe the header.
Green flags
Red flags
client --POST /payments--> API --charge--> provider (succeeds)
client <----- timeout ----- (response lost)
client --POST /payments--> API --charge--> provider (charged twice)
The client can't tell "never arrived" from "done but response lost". Only the server can de-duplicate, and it needs a client-supplied identity for the operation to do it.
The server can't recognise a duplicate from the body alone (a customer may legitimately pay $20 twice). The key carries intent: "this is the same attempt". It must be created before the first attempt and persisted by the client across retries (and, for mobile, across app restarts if possible).
claim (INSERT, unique index)
none -------------------------------> InProgress
| execute
+--------------------+-------------------+
| success / 4xx | 5xx / crash
v v
Completed (response stored) released (row deleted)
| or left to lease expiry
| retries replay stored response
A crash while InProgress leaves a stuck row. Give the row a lease (LockedUntil); a retry after the lease expires may take it over. This is safe only if the business operation itself is protected, which is why the same transaction (or a downstream idempotency key) matters.
Hash a canonical form: method + route template values + body bytes. JSON whitespace or property order differences may produce different hashes for the "same" request; most implementations hash the raw body and document that clients must resend identical bytes.
Keys need a retention window long enough to cover realistic retries (minutes to hours) and short enough to bound storage. 24 hours is common (Stripe documents 24 h). A background job deletes expired rows in batches.
draft-ietf-httpapi-idempotency-key-header (httpapi working group, Standards Track) has had several revisions, with -07 expiring in April 2026 and a -08 in 2026; it is not an RFC as of November 2026. It suggests 400 for a missing key, 409 for a request still being processed and 422 for a key reused with a different payload.
Location header, and only one payment row exists.xargs -P 20 curl ...); expect one 201 and 409s or replays.SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IdempotencyRecords').An endpoint filter plus a SQL-backed record, with the claim, business write and stored response in one transaction:
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace Payments;
public sealed class IdempotencyRecord
{
public required string ClientId { get; init; }
public required string Key { get; init; }
public required string RequestHash { get; init; }
public int? ResponseStatus { get; set; }
public string? ResponseBody { get; set; }
public string? Location { get; set; }
public DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset ExpiresAt { get; init; }
}
public sealed record CreatePayment(string AccountId, decimal Amount, string Currency);
public sealed record Payment(Guid Id, string AccountId, decimal Amount, string Currency);
public sealed class PaymentsDb(DbContextOptions<PaymentsDb> options) : DbContext(options)
{
public DbSet<Payment> Payments => Set<Payment>();
public DbSet<IdempotencyRecord> Idempotency => Set<IdempotencyRecord>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Payment>().Property(p => p.Amount).HasPrecision(19, 4);
b.Entity<IdempotencyRecord>().HasKey(r => new { r.ClientId, r.Key }); // the atomic claim
}
}
public static class PaymentEndpoints
{
public static void MapPayments(this WebApplication app) =>
app.MapPost("/payments", CreateAsync).RequireAuthorization();
private static async Task<IResult> CreateAsync(
CreatePayment request, HttpContext http, PaymentsDb db, TimeProvider clock, CancellationToken ct)
{
if (!http.Request.Headers.TryGetValue("Idempotency-Key", out var keyValues)
|| string.IsNullOrWhiteSpace(keyValues) || keyValues.ToString().Length > 64)
return Results.Problem("An Idempotency-Key header (max 64 chars) is required.", statusCode: 400);
string clientId = http.User.FindFirst("client_id")?.Value ?? throw new InvalidOperationException();
string key = keyValues.ToString();
string hash = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request)));
var existing = await db.Idempotency.AsNoTracking()
.SingleOrDefaultAsync(r => r.ClientId == clientId && r.Key == key, ct);
if (existing is not null) return Replay(existing, hash, http);
await using var tx = await db.Database.BeginTransactionAsync(ct);
var now = clock.GetUtcNow();
var record = new IdempotencyRecord
{
ClientId = clientId, Key = key, RequestHash = hash,
CreatedAt = now, ExpiresAt = now.AddHours(24)
};
db.Idempotency.Add(record);
try
{
await db.SaveChangesAsync(ct); // claim: the PK insert blocks a concurrent twin until we commit
}
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
{
return Results.Problem("A request with this Idempotency-Key is already being processed.", statusCode: 409);
}
var payment = new Payment(Guid.CreateVersion7(), request.AccountId, request.Amount, request.Currency);
db.Payments.Add(payment);
// A real provider call goes here, forwarding $"{clientId}:{key}" as the provider's idempotency key.
record.ResponseStatus = StatusCodes.Status201Created;
record.ResponseBody = JsonSerializer.Serialize(payment);
record.Location = $"/payments/{payment.Id}";
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct); // payment and stored response commit together
return Results.Created(record.Location, payment);
}
private static IResult Replay(IdempotencyRecord r, string hash, HttpContext http)
{
if (r.RequestHash != hash)
return Results.Problem("This Idempotency-Key was used with a different request body.", statusCode: 422);
http.Response.Headers["Idempotent-Replayed"] = "true"; // helps clients and support see what happened
if (r.Location is not null) http.Response.Headers.Location = r.Location;
return Results.Content(r.ResponseBody ?? "", "application/json", statusCode: r.ResponseStatus ?? 200);
}
}
Clean-up job, run hourly:
DELETE TOP (5000) FROM dbo.IdempotencyRecords WHERE ExpiresAt < SYSUTCDATETIME();
Idempotency keys are only as strong as the weakest link in the chain. Making my endpoint idempotent is pointless if the payment provider call behind it isn't, so I check that every side effect is either in my transaction, behind the outbox, or protected by a key the downstream system honours. I also prefer a natural idempotency key when the domain has one (an invoice number paid once, an order id) because it doesn't depend on client discipline.
The cost is one indexed insert and a stored response per request, roughly 1-3 ms and a few hundred bytes. For payments that is obviously worth it; for a 'like' button it isn't.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Idempotency-Key header + SQL record in the same transaction | Payments, orders, anything with money | Extra insert, storage, clean-up job | Naturally idempotent PUT/DELETE |
| Natural business key (unique constraint on invoice id) | The domain already identifies the operation | Schema constraint only | Operations that may legitimately repeat |
| Redis-backed key store | High-volume, low-stakes operations | Small window for duplicates on crash | Money movement |
| Client-side de-duplication only | Never on its own | - | Always insufficient |
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.
Have the client send a unique Idempotency-Key header per logical operation (one checkout attempt, not one HTTP attempt), and scope keys per client or API key so one caller can't replay another's. The server stores the key with a hash of the request and the response, atomically with the side effect (same transaction, or a unique constraint on the key). A repeat with the same key and body returns the stored response; the same key with a different body returns 422; a concurrent duplicate gets 409 until the first completes. Keys expire after a documented window such as 24 hours, enforced with a TTL (Redis) or a cleanup job (SQL). Log key reuse and mismatches so replay attempts and buggy clients show up in monitoring.
If the connection drops during COMMIT, the client can't know whether the transaction committed, and a blind retry may apply the work twice. Make the unit idempotent (a unique request id checked at the start and enforced by a unique index), or use ExecuteInTransactionAsync with a verifySucceeded delegate that queries the database to see if the work landed before retrying. Clear the change tracker between attempts so stale Added entities aren't re-sent. Only transient errors should be retried: let permanent failures (constraint violations, login failures) surface immediately. Log each retry and its outcome so an in-doubt commit can be traced and reconciled later.
How to tell it (STAR)
**S:** At [company], customers on poor mobile connections were occasionally charged twice, about [N] a week. **T:** I was asked to stop duplicates without breaking the mobile app's retry behaviour. **A:** I traced duplicates to retries after client timeouts where the first request had actually succeeded. I designed Idempotency-Key support: an atomic claim with a unique index per client and key, a request hash to catch misuse, the stored response committed in the same transaction as the payment, and the key forwarded to our provider. I worked with the mobile team so the key was created once per payment attempt. **R:** Duplicates went to [zero] over the following [six months], p95 rose by only about [2 ms], and support tickets on double charges stopped.
Last updated 23 Nov 2026.