.NET Development
Idempotency in ASP.NET Core (.NET 10): stop duplicate orders when the client retries
A client sends POST /orders. The server saves the order, but the response takes longer than the client is willing to wait. The client gives up, has no idea whether the order exists, and sends it again. Now there are two orders. You don't need an exotic network to get there: a short timeout or a retry handler left on its defaults is enough.
ASP.NET Core 10 ships nothing documented for this. The IETF has a draft for that header, currently at revision 08 from October 22, 2026, and it isn't an RFC yet. This guide implements that contract with EF Core 10 and SQL Server: a keys table with a unique index, the key saved in the same transaction as the order, and the response replayed from what was stored, including the hard cases and what the design doesn't cover. The code compiles as is, and every output comes from a real run.
The duplicate, reproduced
The test does what an impatient client does. It calls an endpoint with no idempotency using a 1 second timeout; the server saves the order and takes 2 seconds to respond. The client gets the exception, retries, and the server saves another one:
### P1 without Idempotency-Key: client timeout and retry
first attempt: TaskCanceledException
retry: 201 /orders/2 {"id":2,"customer":"P1","product":"Lamp","quantity":1}
in the database: {"customer":"P1","orders":2}
The 1 second timeout only exists in the test: HttpClient waits 100 seconds by default. Any value leads to the same problem, the very case the IETF draft describes.
RFC 9110 already flags the risk. POST isn't idempotent, and a client SHOULD NOT automatically retry a non-idempotent method unless it knows the operation actually is idempotent, or that the original request was never applied. Yet the standard .NET resilience handler retries every HTTP method by default, POST included. Its documentation warns that this can duplicate data and offers DisableForUnsafeHttpMethods to turn it off for POST, PATCH, PUT, DELETE and CONNECT.
Turning retries off prevents the duplicate, but it leaves the client with no safe way to recover. An idempotency key solves both: the client can retry, and the server recognizes the same operation.
The contract: the Idempotency-Key header
Revision 08 of the IETF draft, draft-ietf-httpapi-idempotency-key-header-08, defines a request header that makes non-idempotent methods such as POST or PATCH fault tolerant. Four points matter when you implement it:
- The client generates a unique key per operation, not per session or on the server, and repeats it on every retry. A UUID is recommended.
- The value is a Structured Fields String (RFC 9651), so it goes in double quotes:
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324". - The API has to publish its idempotency specification: the key format and, if keys expire, how long they live.
- On the server, the draft recommends a composite lookup key: the client's key plus attributes only the server knows.
The draft recommends a response for each situation. Here's the table the example implements, with the test that backs each row:
| Case | Response | Test |
|---|---|---|
| First time | 201 with Location and body, stored together with the order | P2 |
| Retry after the original finished | The same stored response | P2, P7 |
| Retry while the original is still running | Wait and replay the response (option A) or 409 (option B) | P3, P4 |
| Same key, different body | 422 | P5 |
| Missing or malformed key | 400 with problem+json | P6 |
| Expired and purged key | Treated as new: another order | P7 |
| Failure before the commit | 500; neither the order nor the key remains | P8 |
The keys table and its unique index
Keys live in the same database as the orders. Each row stores the scope, the key, a fingerprint of the body and the response that was returned (Data/OrdersDb.cs):
using Microsoft.EntityFrameworkCore;
namespace Orders.Api.Data;
public sealed class Order
{
public int Id { get; set; }
public required string Customer { get; set; }
public required string Product { get; set; }
public int Quantity { get; set; }
public DateTime CreatedAt { get; set; }
}
public sealed class IdempotencyRecord
{
public long Id { get; set; }
public required string Scope { get; set; } // operation + client
public required string Key { get; set; } // Idempotency-Key value
public required byte[] Fingerprint { get; set; } // SHA-256 of the body
public int StatusCode { get; set; } // stored HTTP status code
public string? Location { get; set; } // stored Location header
public string? Body { get; set; } // JSON of the stored response
public DateTime CreatedAt { get; set; }
public DateTime ExpiresAt { get; set; }
}
public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<Order>(p =>
{
p.Property(x => x.Customer).HasMaxLength(100);
p.Property(x => x.Product).HasMaxLength(100);
});
model.Entity<IdempotencyRecord>(c =>
{
c.Property(x => x.Scope).HasMaxLength(200);
c.Property(x => x.Key).HasMaxLength(100);
c.Property(x => x.Fingerprint).HasMaxLength(32);
c.HasIndex(x => new { x.Scope, x.Key }).IsUnique(); // the key piece
c.HasIndex(x => x.ExpiresAt); // for purging
});
}
}
The line that does the work is HasIndex(...).IsUnique(). In EF Core indexes aren't unique by default, and without that index two requests with the same key could insert two rows. With it, SQL Server rejects the second one with error 2601, a duplicate key in a unique index, and that error is the signal that this is a retry.
Scope is the context in which the key is unique: the tenant, the operation and a stable client identifier, such as the sub claim. It's the composite key the draft recommends: the same key sent by two clients, or against two operations, doesn't collide. Identity.Name won't do, because a user name can change. The example has no authentication, so the scope ends up as -|POST /orders|anonymous. How the schema gets created is out of scope here: in the test bench, EF Core created it at startup.
The core piece: the key in the same transaction as the order
What makes the design correct is the order of operations, all inside one transaction:
BEGIN TRAN.INSERTthe key.INSERTthe order.UPDATEthe key with the status code, theLocationand the response body.COMMIT.
That way a key "in progress" without a response is never committed. If anything fails before the commit, neither the order nor the key remains, and the retry is processed as if it were the first attempt. The diagram follows an attempt that loses its response and the retry that gets it back:
The executor takes the DbContext and the business operation, and returns an IResult (Idempotency/IdempotentExecutor.cs):
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Orders.Api.Data;
namespace Orders.Api.Idempotency;
// What gets stored so the same response can be replayed.
public sealed record StoredResponse(int StatusCode, string? Location, string Body);
public static class IdempotentExecutor
{
// Replace with the URL of your API's idempotency documentation.
private const string DocsUrl = "https://example.com/docs/idempotency";
public static async Task<IResult> ExecuteAsync(
OrdersDb db,
string scope,
string key,
byte[] fingerprint,
IdempotencyOptions options,
TimeProvider clock,
Func<CancellationToken, Task<StoredResponse>> operation,
CancellationToken ct)
{
// With EnableRetryOnFailure, your own transaction has to run inside the execution strategy.
// Without retries configured, the default strategy runs it once.
var strategy = db.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(() => AttemptAsync(db, scope, key, fingerprint, options, clock, operation, ct));
}
private static async Task<IResult> AttemptAsync(
OrdersDb db,
string scope,
string key,
byte[] fingerprint,
IdempotencyOptions options,
TimeProvider clock,
Func<CancellationToken, Task<StoredResponse>> operation,
CancellationToken ct)
{
db.ChangeTracker.Clear(); // if the strategy repeats the attempt, start from scratch
var now = clock.GetUtcNow().UtcDateTime;
var entry = new IdempotencyRecord
{
Scope = scope,
Key = key,
Fingerprint = fingerprint,
CreatedAt = now,
ExpiresAt = now + options.Lifetime,
};
await using var transaction = await db.Database.BeginTransactionAsync(ct);
var reserved = false; // the catch blocks below only apply to reserving the key
try
{
if (options.MaxWait is { } wait)
{
// SET LOCK_TIMEOUT doesn't accept parameters; ms is an int from configuration, not client text.
var ms = (int)wait.TotalMilliseconds;
#pragma warning disable EF1002
await db.Database.ExecuteSqlRawAsync($"SET LOCK_TIMEOUT {ms}", ct);
#pragma warning restore EF1002
}
// 1. Reserve the key inside the same transaction as the order.
// If another request with the same key hasn't finished, this INSERT waits on its lock.
db.IdempotencyRecords.Add(entry);
await db.SaveChangesAsync(ct);
reserved = true;
if (options.MaxWait is not null)
{
// The maximum wait only applies to the key: the business operation waits as usual.
await db.Database.ExecuteSqlRawAsync("SET LOCK_TIMEOUT -1", ct);
}
// 2. The business work.
var response = await operation(ct);
// 3. Store the response with the order and commit everything at once.
entry.StatusCode = response.StatusCode;
entry.Location = response.Location;
entry.Body = response.Body;
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return new ReplayedResponse(response);
}
catch (DbUpdateException ex) when (!reserved && SqlNumber(ex) is 2601 or 2627)
{
// The key already exists and is committed: this is a retry.
await transaction.RollbackAsync(ct);
db.ChangeTracker.Clear();
var previous = await db.IdempotencyRecords.AsNoTracking()
.SingleAsync(c => c.Scope == scope && c.Key == key, ct);
if (!previous.Fingerprint.AsSpan().SequenceEqual(fingerprint))
{
return Results.Problem(statusCode: 422, type: DocsUrl,
title: "Idempotency-Key already used",
detail: "The same key can't be used with a different body.");
}
return new ReplayedResponse(new StoredResponse(previous.StatusCode, previous.Location, previous.Body!));
}
catch (Exception ex) when (!reserved && SqlNumber(ex) is 1222)
{
// Another request with the same key is still in progress and the wait ran out.
// EF Core treats it as a transient error and wraps it in InvalidOperationException.
await transaction.RollbackAsync(ct);
return Results.Problem(statusCode: 409, type: DocsUrl,
title: "A request with this Idempotency-Key is in progress",
detail: "Retry later with the same key.");
}
finally
{
if (options.MaxWait is not null && !reserved)
{
// If the reservation failed, SET LOCK_TIMEOUT is still set on the session: reset it to the default.
await db.Database.ExecuteSqlRawAsync("SET LOCK_TIMEOUT -1", CancellationToken.None);
}
}
}
private static int? SqlNumber(Exception? ex)
{
for (; ex is not null; ex = ex.InnerException)
{
if (ex is SqlException sql) return sql.Number;
}
return null;
}
// Replays what was stored: the same status code, the same Location and the same body. Content-Type is fixed.
// Other headers (ETag, Cache-Control…) aren't stored: if your contract uses them, store them too.
private sealed class ReplayedResponse(StoredResponse response) : IResult
{
public Task ExecuteAsync(HttpContext http)
{
http.Response.StatusCode = response.StatusCode;
if (response.Location is not null)
{
http.Response.Headers.Location = response.Location;
}
http.Response.ContentType = "application/json; charset=utf-8";
return http.Response.WriteAsync(response.Body);
}
}
}
The code makes two decisions. First, the response is always written from what was stored, even the first time, so the original attempt and every retry return the same status, the same Location, the same Content-Type and the same body, byte for byte. The example doesn't store other headers, such as ETag or Cache-Control: if your contract uses them, store them with the response; transport or security headers, never. The body is serialized with ASP.NET Core's JSON options rather than JsonSerializerOptions.Web: with the latter, Lámpara comes out as L\u00E1mpara, which differs from what Results.Created returns.
Second, for a later retry the draft asks for a response consistent with the completed operation, and replaying the stored one satisfies that.
The endpoint and key validation
The header is validated before the database is touched (Idempotency/IdempotencyKeyHeader.cs):
using Microsoft.Extensions.Primitives;
namespace Orders.Api.Idempotency;
public static class IdempotencyKeyHeader
{
public const string HeaderName = "Idempotency-Key";
// Replace with the URL of your API's idempotency documentation.
private const string DocsUrl = "https://example.com/docs/idempotency";
// The key is a Structured Fields String (RFC 9651): it goes in double quotes.
// This service publishes its format: a UUID in double quotes.
public static bool TryRead(IHeaderDictionary headers, out string key, out IResult? problem)
{
key = "";
problem = null;
StringValues values = headers[HeaderName];
if (StringValues.IsNullOrEmpty(values))
{
problem = Results.Problem(statusCode: 400, type: DocsUrl,
title: "Missing Idempotency-Key header",
detail: "This operation requires an idempotency key.");
return false;
}
var text = values.Count == 1 ? values[0]!.Trim() : "";
if (text.Length < 2 || text[0] != '"' || text[^1] != '"' ||
!Guid.TryParseExact(text[1..^1], "D", out var uuid))
{
problem = Results.Problem(statusCode: 400, type: DocsUrl,
title: "Invalid Idempotency-Key",
detail: "The key must be a UUID in double quotes.");
return false;
}
key = uuid.ToString("D");
return true;
}
}
If the header is missing or isn't a quoted UUID, the response is 400 with problem+json and a link to the documentation, as the draft asks. The endpoint computes the fingerprint and the scope, and hands the order creation to the executor (Program.cs):
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Orders.Api.Data;
using Orders.Api.Idempotency;
var builder = WebApplication.CreateBuilder(args);
// The connection string comes from configuration, never from code.
builder.Services.AddDbContext<OrdersDb>(o => o.UseSqlServer(
builder.Configuration.GetConnectionString("Orders"),
sql => sql.EnableRetryOnFailure())); // forces CreateExecutionStrategy around your own transaction
builder.Services.AddProblemDetails();
builder.Services.AddOptions<IdempotencyOptions>()
.Bind(builder.Configuration.GetSection("Idempotency"))
.Validate(o => o.Lifetime > TimeSpan.Zero, "Lifetime must be greater than zero.")
.Validate(o => o.PurgeInterval > TimeSpan.Zero, "PurgeInterval must be greater than zero.")
.Validate(o => o.MaxWait is null || (o.MaxWait > TimeSpan.Zero && o.MaxWait.Value.TotalMilliseconds <= int.MaxValue),
"MaxWait must be greater than zero and fit in an int of milliseconds.")
.ValidateOnStart(); // invalid configuration stops startup instead of failing in the middle of a request
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHostedService<KeyPurger>();
var app = builder.Build();
app.MapPost("/orders", async (NewOrder newOrder, HttpContext http, OrdersDb db,
IOptions<IdempotencyOptions> options, IOptions<JsonOptions> json, TimeProvider clock, CancellationToken ct) =>
{
if (!IdempotencyKeyHeader.TryRead(http.Request.Headers, out var key, out var problem))
{
return problem!;
}
var fingerprint = SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(newOrder, JsonSerializerOptions.Web));
// The scope is the context in which the key is unique: tenant, operation and a STABLE client identifier
// (the "sub" claim; some authentication schemes deliver it as NameIdentifier). Never Identity.Name: it can change.
const string tenant = "-"; // in a multi-tenant API, the authenticated tenant's id
var subject = http.User.FindFirst("sub")?.Value ?? http.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous";
var scope = $"{tenant}|POST /orders|{subject}";
return await IdempotentExecutor.ExecuteAsync(db, scope, key, fingerprint, options.Value, clock, async ct2 =>
{
var order = new Order { Customer = newOrder.Customer, Product = newOrder.Product, Quantity = newOrder.Quantity, CreatedAt = clock.GetUtcNow().UtcDateTime };
db.Orders.Add(order);
await db.SaveChangesAsync(ct2);
// An email or a queue message sent here is NOT part of the database transaction.
// Same JSON options ASP.NET Core uses for its responses.
var body = JsonSerializer.Serialize(new OrderCreated(order.Id, order.Customer, order.Product, order.Quantity), json.Value.SerializerOptions);
return new StoredResponse(StatusCodes.Status201Created, $"/orders/{order.Id}", body);
}, ct);
});
app.Run();
public sealed record NewOrder(string Customer, string Product, int Quantity);
public sealed record OrderCreated(int Id, string Customer, string Product, int Quantity);
The fingerprint is a SHA-256 of the body once it's bound to the NewOrder model and serialized again, which is the draft's variant that checksums selected elements of the payload.
The project carries one line unrelated to idempotency, because what you declare isn't everything that gets resolved: Microsoft.EntityFrameworkCore.SqlServer 10.0.14 pulls in, through Microsoft.Data.SqlClient 6.1.7, version 9.0.11 of System.Security.Cryptography.Pkcs, which is affected by two Microsoft advisories (CVE-2026-70162 and CVE-2026-84008), fixed in 9.0.21 and 10.0.13. This command also checks transitive dependencies:
dotnet list package --vulnerable --include-transitive
Without that line, the command flags 9.0.11 with both advisories and the build reports NU1902 and NU1903; pinning the package to 10.0.14 clears them (Orders.Api.csproj):
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.14" />
<!-- Bumps the transitive dependency from Microsoft.Data.SqlClient 6.1.7 (9.0.11, affected by CVE-2026-70162 and CVE-2026-84008) -->
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
</ItemGroup>
</Project>
With the API running and the connection string in configuration, this curl creates the order (output trimmed to the status line, Location and body):
curl -i http://localhost:5000/orders \
-H "Content-Type: application/json" \
-H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' \
-d '{"customer":"Ana","product":"Chair","quantity":2}'
HTTP/1.1 201 Created
Location: /orders/1
{"id":1,"customer":"Ana","product":"Chair","quantity":2}
Run it again unchanged and you get the same status, Location and body. And the opening scenario, now with a key: the first attempt times out, both retries get the same 201, and the database holds a single order:
### P2 with Idempotency-Key: client timeout and retry
first attempt: TaskCanceledException
retry 1: 201 /orders/3 {"id":3,"customer":"P2","product":"Lamp","quantity":1}
retry 2: 201 /orders/3 {"id":3,"customer":"P2","product":"Lamp","quantity":1}
identical responses: True
in the database: {"customer":"P2","orders":1}
Two requests at once with the same key
The hard case is the retry that arrives while the original request is still inside its transaction. The unique index already helps here: the second request's INSERT blocks on the first one's uncommitted row. What happens next depends on how long you let it wait.
Option A: the second request waits
This is the default behavior. When the first request commits, the second gets the 2601 and returns the stored response. With 10 simultaneous requests and the first one deliberately spending 1500 ms inside the transaction:
### P3 10 simultaneous requests with the same key (the second one waits)
10 x 201 /orders/4 {"id":4,"customer":"P3","product":"Chair","quantity":2} (finished between 1516 and 1525 ms)
in the database: {"customer":"P3","orders":1}
It works, but it departs from the draft, which says that for a retry arriving before the original request completes the server SHOULD respond with a conflict.
Option B: the second request gets a 409
With MaxWait configured, the executor runs SET LOCK_TIMEOUT before the INSERT. If the lock lasts longer, SQL Server returns error 1222 and the API responds with 409 and problem+json. With a 200 ms max wait:
### P4 10 simultaneous requests with the same key and a 200 ms max wait (409)
1 x 201 /orders/5 {"id":5,"customer":"P4","product":"Chair","quantity":2} (finished between 1512 and 1512 ms)
9 x 409 A request with this Idempotency-Key is in progress (finished between 243 and 243 ms)
retry afterwards: 201 /orders/5 {"id":5,"customer":"P4","product":"Chair","quantity":2}
in the database: {"customer":"P4","orders":1}
Two SQL Server details shape the code. SET LOCK_TIMEOUT stays in effect for the rest of the connection, and we didn't check whether the pool resets it when the connection goes back, so the code sets it back to -1 by hand. And it doesn't accept variables: SET LOCK_TIMEOUT @ms is a syntax error, which is why the value is built from an int in configuration, never from client input.
The maximum wait and both catch blocks apply only to reserving the key: a 2601 or a 1222 means "another request with the same key" only when it comes from that INSERT. That's why the executor sets reserved after the first SaveChangesAsync and resets the timeout to -1 there. Without that flag, in the test, a unique index on the order gave a 500 and an unrelated lock, a false 409.
| Option A: wait | Option B: 409 | |
|---|---|---|
| What the second request gets | The same 201, once the first one commits | 409 after ~240 ms; its retry gets the 201 |
| Draft recommendation | Departs from it (asks for a conflict) | Follows it |
| Work for the client | None | Retry later with the same key |
| Limit | EF Core's command timeout | The configured wait |
The timings come from a single local run. Option A also has a ceiling you don't choose: EF Core's 30 second CommandTimeout, which would make the waiting request fail if the first one takes longer. We didn't test it.
Same key with a different body, or no key at all
If the client reuses a key with a different body, the fingerprint doesn't match and the response is 422 (Unprocessable Content):
### P5 same key with a different body
first: 201 /orders/6 {"id":6,"customer":"P5","product":"Table","quantity":1}
same key, quantity 3: 422 Idempotency-Key already used
in the database: {"customer":"P5","orders":1}
If the key is missing or doesn't match the published format, the response is 400 and the database isn't touched:
### P6 no key and malformed key
no header: 400 Missing Idempotency-Key header
UUID without quotes: 400 Invalid Idempotency-Key
free text: 400 Invalid Idempotency-Key
in the database: {"customer":"P6","orders":0}
Expiration: a policy you publish
The options define how long a key lives, how often expired keys are purged, and whether a concurrent retry waits or gets a 409 (Idempotency/IdempotencyOptions.cs):
namespace Orders.Api.Idempotency;
public sealed class IdempotencyOptions
{
// How long a key lives. This is the policy the API must publish.
public TimeSpan Lifetime { get; set; } = TimeSpan.FromHours(24);
// How often expired keys are deleted.
public TimeSpan PurgeInterval { get; set; } = TimeSpan.FromHours(1);
// null: the concurrent request waits for the first one.
// With a value: if it waits longer than this, it gets a 409.
public TimeSpan? MaxWait { get; set; }
}
Program.cs validates these options at startup with ValidateOnStart: all three times greater than zero and the wait in milliseconds within an int. If a rule fails, the API doesn't start, instead of failing in the middle of a request; we checked it with each value set to zero.
The purge is a BackgroundService with a PeriodicTimer that deletes expired keys with ExecuteDeleteAsync. That method runs the DELETE immediately, without loading the rows into memory (Idempotency/KeyPurger.cs):
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Orders.Api.Data;
namespace Orders.Api.Idempotency;
public sealed class KeyPurger(IServiceScopeFactory scopes, IOptions<IdempotencyOptions> options, TimeProvider clock, ILogger<KeyPurger> log)
: BackgroundService
{
public static Task<int> PurgeAsync(OrdersDb db, DateTime now, CancellationToken ct) =>
db.IdempotencyRecords.Where(c => c.ExpiresAt <= now).ExecuteDeleteAsync(ct);
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(options.Value.PurgeInterval, clock);
while (await timer.WaitForNextTickAsync(ct))
{
try
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDb>();
await PurgeAsync(db, clock.GetUtcNow().UtcDateTime, ct);
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
// An unhandled exception in a BackgroundService stops the whole API (StopHost, since .NET 6).
log.LogError(ex, "Key purge failed; it runs again on the next cycle.");
}
}
}
}
The try/catch inside the loop is needed: since .NET 6, an unhandled exception in a BackgroundService stops the application by default. With the key table dropped on purpose, the process exited without the catch; with it, it logs the error and stays up.
In the expiration test, with a 3 second lifetime:
### P7 expiration: 3 s lifetime in this test
first: 201 /orders/7 {"id":7,"customer":"P7","product":"Table","quantity":1}
retry before expiry: 201 /orders/7 {"id":7,"customer":"P7","product":"Table","quantity":1}
purge: {"deleted":5}
same key after purging: 201 /orders/8 {"id":8,"customer":"P7","product":"Table","quantity":1}
in the database: {"customer":"P7","orders":2}
The purge deleted the 5 expired keys from the whole run, and afterwards the same key created a new order. That's why the lifetime is part of the contract: the draft asks the API to define and publish it. One nuance: the retry path doesn't check ExpiresAt, so an expired key keeps replaying until the purge; after that, the same key creates another order, as in P7. With the defaults it lives 24 to 25 hours, and the API publishes "at least Lifetime".
Two EF Core traps
EnableRetryOnFailure with your own transaction
With EF Core retries turned on, each operation becomes its own retriable unit, and a transaction you open by hand breaks that rule. Without wrapping it, every POST returned 500 with this error:
System.InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.
The fix is the one the message suggests, CreateExecutionStrategy().ExecuteAsync(...), and it's what ExecuteAsync does. It works with and without retries configured: the tests produced the same results in both modes. Keep one consequence in mind: if the strategy repeats the attempt, everything inside it is repeated, including any external effect.
Error 1222 doesn't arrive as a DbUpdateException
The first version of the executor caught only DbUpdateException, and option B returned nine 500s instead of nine 409s: EF Core treated the 1222 as a transient failure and wrapped it in InvalidOperationException. The 2601 did arrive as a DbUpdateException. That's why SqlNumber walks the InnerException chain until it finds the SqlException.
What this design doesn't cover
Idempotency protects what lives inside the database transaction, and nothing else. The test makes it visible: the endpoint saves the order, "sends" a simulated email and fails before the commit. The client retries:
### P8 external effect (email) and failure before the commit
first attempt (fails before the commit): 500
retry: 201 /orders/10 {"id":10,"customer":"P8","product":"Table","quantity":1}
in the database: {"customer":"P8","orders":1}
emails: {"customer":"P8","emails":2}
One order and two emails. The rollback undid the order and the key (order 9 was lost and the retry created order 10), but the email had already gone out. For emails, queues (RabbitMQ, Azure Service Bus) or other APIs you need a transactional outbox: save the event in the same transaction as the order and publish it afterwards. If publishing is repeated, a message can arrive more than once, so consumers have to be idempotent too. The official guidance that describes it uses Azure Cosmos DB; the principle is the same, but we didn't test it with SQL Server.
Also left untested:
- A connection drop during the
COMMIT. EF Core warns that the state of the transaction is then unknown; by design, the retry would hit the key or process again, but we didn't simulate it. - A purge that deletes an expired key just as a retry with that key arrives.
- PostgreSQL, which has its own unique violation code.
- Linux, macOS and .NET 11: everything ran on Windows 11 with LocalDB.
- Whether the .NET resilience handler resends the same header on every retry.
Frequently asked questions
Why does the key go in double quotes?
Because the draft defines it as a Structured Fields String (RFC 9651), and in a header field that type is written in double quotes.
Should a concurrent request wait or get a 409?
The 409 follows the draft's recommendation and doesn't leave requests stuck behind a slow operation. Waiting saves the client some work. If the operation can be slow, go with the 409.
How long should a key live?
Whatever the API publishes. The 24 hours in this example are its default, not a figure from the draft; what matters is documenting it, because once it's purged, the same key creates another order.
Conclusion
Stopping duplicate orders doesn't take a library: a table with a unique index, the key in the same transaction as the order, and the response replayed from storage. The rest are decisions you publish: the key format, whether a concurrent retry waits or gets a 409, and how long each key lives.
If you separate commands from queries, the CQRS in .NET 10 post shows that structure; this POST is a command. Before that, run the curl above against your own API twice: if the second call creates another order, you know where to start.
References
- The Idempotency-Key HTTP Header Field, draft-ietf-httpapi-idempotency-key-header-08 — IETF: ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-08.txt
- RFC 9110, HTTP Semantics (idempotent methods, 409 and 422) — RFC Editor: rfc-editor.org/rfc/rfc9110
- RFC 9651, Structured Field Values for HTTP — RFC Editor: rfc-editor.org/rfc/rfc9651
- Build resilient HTTP apps — Microsoft Learn: learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience
- Connection resiliency in EF Core — Microsoft Learn: learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
- Indexes in EF Core — Microsoft Learn: learn.microsoft.com/en-us/ef/core/modeling/indexes
- SET LOCK_TIMEOUT — Microsoft Learn: learn.microsoft.com/en-us/sql/t-sql/statements/set-lock-timeout-transact-sql
- CVE-2026-70162 — NVD: nvd.nist.gov/vuln/detail/CVE-2026-70162
- CVE-2026-84008 — NVD: nvd.nist.gov/vuln/detail/CVE-2026-84008
- Options pattern in .NET: options validation — Microsoft Learn: learn.microsoft.com/en-us/dotnet/core/extensions/options
- .NET 6 breaking change: Exception handling in hosting — Microsoft Learn: learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/hosting-exception-handling
- Transactional outbox pattern with Azure Cosmos DB — Microsoft Learn: learn.microsoft.com/en-us/azure/architecture/databases/guide/transactional-out-box-cosmos
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment