How to Implement Idempotency Keys in ASP.NET Core 10 Web API Using C# and SQL Server – Prevent Duplicate API Requests (2026)

How to Implement Idempotency Keys in ASP.NET Core 10 Web API Using C# and SQL Server – Prevent Duplicate API Requests (2026)

A customer clicks Place order, your API saves the order, and the response disappears before the browser receives it. The browser retries. Without a shared record of that operation, the second POST can create a second order even though both requests came from one checkout attempt.

This guide implements idempotency keys in ASP.NET Core 10 Web API using C# and SQL Server. The goal is specific: repeated requests with the same authenticated owner, operation and key should replay one committed order response during a documented retention window. Concurrent requests must not both pass a check-then-insert race.

How do you prevent duplicate POST requests in ASP.NET Core?

Require a client-generated Idempotency-Key, scope it to the authenticated caller and operation, fingerprint the validated request, and coordinate processing in shared durable storage. Commit the business change and replay response in one database transaction. A matching retry reuses that response; a live-key payload mismatch is rejected. A dictionary lookup or cache check followed by an independent insert is insufficient under concurrency.

A lost response can trigger a second POST even though the first order was committed. A fresh key on every retry does not fix this.
A lost response can trigger a second POST even though the first order was committed. A fresh key on every retry does not fix this. Original SVG diagram.

1. API idempotency, HTTP methods and ordinary caching

An operation is idempotent when repeating it has the same intended server-side effect as performing it once. It does not require every response to have identical text or status. Deleting an already-deleted resource may return a different status while still leaving the resource deleted. Logging or metering each attempt does not by itself change the intended resource effect.

Method or operationHTTP semanticsApplication consequence
GET, HEAD, OPTIONS, TRACESafe methods are idempotentDo not implement order creation in a GET endpoint
PUT and DELETEIdempotent by defined semanticsImplement the intended replacement/deletion consistently
POSTNot inherently idempotentCreation needs an explicit retry contract when duplicates matter
PATCHNot inherently idempotentA particular patch can be designed to be idempotent; do not assume it

See RFC 9110, section 9.2.2 for the definition. A method’s name alone does not repair an implementation that performs an unintended additional business action on each retry.

Duplicate requests arise from double-clicks, mobile network changes, client timeouts, proxy retries, job restarts and uncertain acknowledgements. Disabling a button reduces accidental clicks but cannot coordinate two servers or recover a response lost after commit. The client must generate one key per logical action and persist it until that action is resolved.

Idempotency is also different from an HTTP response cache. A cache usually avoids repeated reads and tolerates eviction according to its policy. An idempotency record associates a write attempt with its outcome and must remain available for the promised retry horizon. If it disappears too early, the business operation may run again.

Ordinary cachingIdempotency for this order API
Usually keyed by resource/queryKeyed by owner + operation + client key
Often acceptable to recompute after evictionRecomputation can create another order
Focuses on retrieval efficiencyFocuses on write correctness and response recovery
May share public representationsRequires authorization before every lookup or replay

A natural business uniqueness rule remains useful. For example, a merchant checkout reference can have a permanent unique constraint. Two different idempotency keys intentionally represent two different operations in this sample; they can create two identical-looking orders. Do not confuse duplicate-request prevention with detecting every possible duplicate business purchase.

2. Idempotency-Key: current specification status and explicit API policy

As of 4 November 2026, draft-ietf-httpapi-idempotency-key-header-08 is an active Internet-Draft, published 22 October 2026. It is work in progress, not a published RFC. The draft uses a Structured Field string, and recommends documenting key and expiry policies. It describes 400 for a required missing key, 422 for a different payload under a reused key, and 409 for an outstanding concurrent request. Check its status again when implementing.

Our API accepts a deliberately narrow subset: exactly one quoted, non-empty UUID in D format, without parameters. It is not a general-purpose Structured Fields parser. The quote characters are part of the header value:

HTTP request header
Idempotency-Key: "2196fb09-fd35-4ee7-86b3-774ad8237e48"

The implementation normalizes UUID text and SKU case, so equivalent inputs map consistently. It rejects multiple header values and unsupported fields. The server hashes the normalized key for storage; a hash is an identifier, not proof of identity or permission.

SituationThis API’s documented behavior
Missing/invalid key or invalid order400; no idempotency record is written
First valid requestCreate order and completed replay record; return 201
Same owner, operation and key; same fingerprintReplay stored 201 body and Location
Same live key; different normalized request422; no new order
Another transaction holds that scoped key409 with Retry-After: 1; retry unchanged
Database failure or uncertain outcomeSafe failure; resolve by retrying the original key
Key reaches its 24-hour expiryTreated as a new operation; duplicate prevention no longer applies

The 24-hour period is a teaching policy, not an IETF-mandated duration. A client must not keep retrying an old checkout indefinitely. Choose a production retention period from the real retry and reconciliation horizon, and consider a permanent business reference when duplicates remain unacceptable after that window.

Payment providers illustrate why contracts matter. Stripe’s official documentation distinguishes API v1 response replay from API v2 retry behavior. Our sample does not implement either provider’s full contract, process a payment, or copy a provider’s error-retention policy. It records only a successfully committed local order result.

3. Database-backed idempotency architecture and limits

The filter validates the request; a shared SQL lock coordinates instances and the order and replay record commit together.
The filter validates the request; a shared SQL lock coordinates instances and the order and replay record commit together. Original SVG diagram.

The request filter performs input checks and creates a fingerprint. The order service begins a SQL transaction and acquires a transaction-owned application lock scoped to the owner, operation and key. It reads the retained record only after acquiring that lock. A live matching record is replayed. Otherwise, the service writes an order and its response record before committing.

Missing or invalid input returns 400, lock contention returns 409, and a retained record leads to fingerprint comparison and replay. Expiry ends the guarantee.
Missing or invalid input returns 400, lock contention returns 409, and a retained record leads to fingerprint comparison and replay. Expiry ends the guarantee. Original SVG diagram.

A unique composite index on OwnerId, Operation, KeyHash provides an additional invariant: the table cannot contain two records for the same protected scope. The lock coordinates compliant writers before they do business work; the unique index protects the stored identity. Neither is a reason to allow unrelated code paths to bypass the service.

This design suits short operations whose durable side effects are in the same SQL Server database. It intentionally avoids a separately committed Processing row that could be abandoned by a crashed worker. Processing exists as an open transaction and lock; only Completed rows are durably visible.

The service writes the order first and the response record next within one SQL transaction. The branches show the two durable outcomes, not parallel C# operations.
The service writes the order first and the response record next within one SQL transaction. The branches show the two durable outcomes, not parallel C# operations. Original SVG diagram.
ApproachUseful propertyCritical limitation
SQL record plus local SQL business transactionBoth outcomes can commit togetherDatabase load and transaction duration must be controlled
Redis or distributed-cache coordinationFast shared admission and TTL supportA cache write and separate SQL commit are not one atomic transaction
In-memory dictionary or SemaphoreSlimSimple within one processDoes not coordinate separate instances or survive restarts
Durable workflow / queueUseful for long-running asynchronous workNeeds leases, recovery states and an explicit 202/status contract

A Redis SET-if-absent can help coordinate work, but it does not close the crash gap between an SQL order commit and a Redis replay record. Redis persistence, eviction, lease expiry and ownership-safe lock release all need separate consideration. A distributed lock alone is not a complete idempotency implementation.

The guarantee is bounded: one local committed creation per retained scope through this service. It is not an exactly-once guarantee for payment gateways, emails, brokers, all future retries or other database writers.

4. Prerequisites, .NET 10 project setup and secure secrets

Install a current serviced .NET 10 SDK, SQL Server Developer/Express or Windows LocalDB for local practice, an editor supporting .NET 10, and Postman or curl. Use a dedicated development database. The test fixture later creates and removes a randomly named test database on an isolated SQL Server instance.

The researched SQL Server provider listing shows EF Core 10.0.14 targeting .NET 10. This example aligns the provider, Design package and EF tool to 10.0.14. Pin compatible stable versions; do not select EF Core 11 preview merely because a package page offers it.

Create the project — terminal
mkdir IdempotencyDemo
cd IdempotencyDemo
dotnet new web -n IdempotencyDemo.Api -f net10.0
cd IdempotencyDemo.Api
IdempotencyDemo.Api.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>IdempotencyDemo.Api.LocalDevelopment</UserSecretsId>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.14">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>

Replace the generated project file with the one above, create the C# files shown below, and keep all application types in IdempotencyDemo.Api. The UserSecretsId deliberately remains in the project file; removing it would disconnect your local configuration. No third-party idempotency library is required.

Place the shown application files in the API project and the test file in a sibling xUnit project. Migration files are generated from the model.
Place the shown application files in the API project and the test file in a sibling xUnit project. Migration files are generated from the model. Original SVG diagram.
appsettings.json
{
  "ConnectionStrings": { "Orders": "" },
  "DemoAuth": { "AliceKey": "", "BobKey": "" },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
    }
  },
  "AllowedHosts": "localhost"
}
Local development configuration — PowerShell
dotnet user-secrets set "ConnectionStrings:Orders" 'Server=(localdb)\MSSQLLocalDB;Database=IdempotencyDemo;Integrated Security=true;Encrypt=true;TrustServerCertificate=true;ConnectRetryCount=0'
dotnet user-secrets set "DemoAuth:AliceKey" "YOUR_RANDOM_ALICE_KEY_AT_LEAST_32_CHARACTERS"
dotnet user-secrets set "DemoAuth:BobKey" "YOUR_DIFFERENT_RANDOM_BOB_KEY_AT_LEAST_32_CHARACTERS"

TrustServerCertificate=true is for this local development example. In production, use a trusted SQL certificate, encryption with certificate validation, a restricted database identity and your controlled secret mechanism. Environment variable ConnectionStrings__Orders can supply the connection string; credentials must not be committed to source control or logged.

The demo keys must be distinct, random and 32–256 characters. They are not an idempotency key and must not appear in browser-distributed JavaScript. Microsoft’s Secret Manager guidance explains that user secrets are a development convenience, not an encrypted production vault. Set AllowedHosts to your real hostname when deploying.

If you need the EF and SQL basics first, the related ASP.NET Core 10 CRUD and SQL Server tutorial covers that foundation. This article adds a distinct transactional retry contract.

5. DTOs, entity models and the EF Core DbContext

The request contains a SKU and quantity. The server determines the authenticated owner and the unit price. The client cannot supply a customer ID or payment amount that silently changes the protected operation. The response contains the created order fields; its serialized JSON is saved for replay.

Contracts.cs
namespace IdempotencyDemo.Api;

public sealed record CreateOrderRequest(string? Sku, int Quantity);
public sealed record OrderResponse(Guid Id, string Sku, int Quantity,
    decimal UnitPrice, decimal Total, DateTimeOffset CreatedAt);
public sealed record ValidatedOrder(string Sku, int Quantity, string KeyHash,
    string Fingerprint);
public sealed class ApiFailure(int status, string safeMessage) : Exception(safeMessage)
{
    public int Status { get; } = status;
}
public sealed record StoredResponse(int Status, string Body, string ContentType,
    string Location, bool Replayed) : IResult
{
    public async Task ExecuteAsync(HttpContext http)
    {
        http.Response.StatusCode = Status;
        http.Response.ContentType = ContentType;
        http.Response.Headers.Location = Location;
        http.Response.Headers.CacheControl = "no-store";
        // Application-specific diagnostic header, not an IETF standard field.
        http.Response.Headers["Idempotency-Replayed"] = Replayed ? "true" : "false";
        await http.Response.WriteAsync(Body, http.RequestAborted);
    }
}
Entities.cs
namespace IdempotencyDemo.Api;

public sealed class Order
{
    public Guid Id { get; set; }
    public Guid OwnerId { get; set; }
    public string Sku { get; set; } = "";
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Total { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
}
public sealed class IdempotencyRecord
{
    public Guid Id { get; set; }
    public Guid OwnerId { get; set; }
    public string Operation { get; set; } = "";
    public string KeyHash { get; set; } = "";
    public string Fingerprint { get; set; } = "";
    // Only committed Completed records are visible to other requests.
    public string State { get; set; } = "Completed";
    public int StatusCode { get; set; }
    public string ResponseBody { get; set; } = "";
    public string ContentType { get; set; } = "";
    public string Location { get; set; } = "";
    public DateTimeOffset CreatedAt { get; set; }
    public DateTimeOffset ExpiresAt { get; set; }
}

The record stores the request fingerprint, original status, body, content type and relative Location. It does not save arbitrary response headers, cookies or bearer tokens. This example only commits a Completed record with status 201. It is not a generic cache for every possible endpoint result.

OrdersDbContext.cs
using Microsoft.EntityFrameworkCore;

namespace IdempotencyDemo.Api;

public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options)
    : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();

    protected override void OnModelCreating(ModelBuilder model)
    {
        var order = model.Entity<Order>();
        order.ToTable("Orders");
        order.HasKey(x => x.Id);
        order.Property(x => x.Id).ValueGeneratedNever();
        order.Property(x => x.Sku).HasMaxLength(40).IsUnicode(false);
        order.Property(x => x.UnitPrice).HasPrecision(18, 2);
        order.Property(x => x.Total).HasPrecision(18, 2);
        order.HasIndex(x => new { x.OwnerId, x.Id });

        var record = model.Entity<IdempotencyRecord>();
        record.ToTable("IdempotencyRecords", table =>
            table.HasCheckConstraint("CK_Idempotency_Completed",
                "[State] = 'Completed' AND [StatusCode] = 201"));
        record.HasKey(x => x.Id);
        record.Property(x => x.Id).ValueGeneratedNever();
        record.Property(x => x.Operation).HasMaxLength(64).IsUnicode(false);
        record.Property(x => x.KeyHash).HasMaxLength(64).IsUnicode(false);
        record.Property(x => x.Fingerprint).HasMaxLength(64).IsUnicode(false);
        record.Property(x => x.State).HasMaxLength(16).IsUnicode(false);
        record.Property(x => x.ResponseBody).HasColumnType("nvarchar(max)");
        record.Property(x => x.ContentType).HasMaxLength(100).IsUnicode(false);
        record.Property(x => x.Location).HasMaxLength(200).IsUnicode(false);
        record.HasIndex(x => new { x.OwnerId, x.Operation, x.KeyHash })
            .IsUnique().HasDatabaseName("UX_Idempotency_Scope_Key");
        record.HasIndex(x => x.ExpiresAt);
    }
}

EF creates the unique index from IsUnique(). Microsoft’s index documentation covers composite unique indexes; SQL Server unique constraints also enforce uniqueness and create a corresponding unique index. Here we deliberately use a named unique index rather than a separate alternate-key constraint.

Equivalent unique index — explanatory SQL, not a second migration
CREATE UNIQUE INDEX UX_Idempotency_Scope_Key
ON dbo.IdempotencyRecords (OwnerId, Operation, KeyHash);

Do not run that statement after migrations have already created the index. An ordinary non-unique index is insufficient. Including only the raw client key would also be incorrect for this contract because two authenticated customers are allowed to use the same UUID independently.

An optimistic row-version token solves a different problem: detecting competing updates to an existing row. It does not reserve a nonexistent idempotency record. EF’s concurrency guide notes that duplicate inserts generally raise a provider-specific unique-constraint failure rather than DbUpdateConcurrencyException.

6. Endpoint filter: key validation and request fingerprinting

An endpoint filter can inspect bound arguments before the handler runs. This is a better fit here than generic middleware that copies response streams: it can validate the typed order and prepare a domain-specific fingerprint. The service still owns the database transaction, so the filter cannot accidentally save the replay record in an unrelated transaction.

See Microsoft’s Minimal API filter documentation. The filter below is attached only to the POST handler whose first argument is CreateOrderRequest. Reusing it on a different argument order requires changing that binding.

OrderRequestPolicy.cs
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

namespace IdempotencyDemo.Api;

public static class OrderRequestPolicy
{
    public const string Operation = "POST:/api/orders:v1";
    public static readonly object ItemKey = new();
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
    public static string Hash(string value) =>
        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));

    public static ValidatedOrder Validate(string? header, CreateOrderRequest request)
    {
        // Documented API subset: one quoted UUID in D format, no parameters.
        var value = header?.Trim();
        if (value is null || value.Length != 38 || value[0] != '"'
            || value[^1] != '"' || !Guid.TryParseExact(value[1..^1], "D", out var key)
            || key == Guid.Empty)
            throw new ApiFailure(400, "Supply one Idempotency-Key containing a quoted non-empty UUID.");
        var sku = request.Sku?.Trim().ToUpperInvariant();
        if (sku != "KB-01" || request.Quantity is < 1 or > 10)
            throw new ApiFailure(400, "Use SKU KB-01 and a quantity from 1 to 10.");
        // Fixed schema and property order; semantic normalization is explicit.
        var canonical = JsonSerializer.Serialize(new
        {
            schema = 1, operation = Operation, sku, quantity = request.Quantity
        }, Json);
        return new(sku, request.Quantity, Hash(key.ToString("D")), Hash(canonical));
    }
    public static string LockResource(Guid owner, string keyHash) =>
        "order-idem:" + Hash($"{owner:D}|{Operation}|{keyHash}");
}
public sealed class IdempotencyFilter : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context,
        EndpointFilterDelegate next)
    {
        var headers = context.HttpContext.Request.Headers;
        if (!headers.TryGetValue("Idempotency-Key", out var values) || values.Count != 1)
            throw new ApiFailure(400, "Exactly one Idempotency-Key header is required.");
        var request = context.GetArgument<CreateOrderRequest>(0);
        context.HttpContext.Items[OrderRequestPolicy.ItemKey] =
            OrderRequestPolicy.Validate(values[0], request);
        return await next(context);
    }
}
An equivalent normalized order replays; a changed quantity with the same live key returns 422. Whitespace and JSON property order are not significant.
An equivalent normalized order replays; a changed quantity with the same live key returns 422. Whitespace and JSON property order are not significant. Original SVG diagram.

The fingerprint hashes a fixed JSON shape after explicit normalization. SKU values such as kb-01 and KB-01 are equivalent. JSON whitespace and property order do not affect the hash because the server serializes the validated representation itself. Quantity 2 and quantity 3 are different operations under a live key.

This is a documented semantic policy, not a general JSON canonicalization library. If you add an address, currency, discount code or other operation-affecting field, include its normalized value in the fingerprint. Version the fingerprint/operation contract when semantics change, and plan old-key behavior across deployments. Do not silently change the operation scope during a retry window.

SHA-256 does not encrypt payloads. A fingerprint can still reveal equality or permit guessing of low-entropy inputs. The sample does not persist request bodies, but the response record is still sensitive application data. Bound key length and request size before doing database work.

7. Coordinate concurrent requests with a SQL transaction-owned lock

Two API instances share SQL Server but do not share a process-local semaphore. They must agree on one lock resource for the same owner, operation and key. The resource below uses a hash of that scope, and the SQL command passes it as a parameter rather than concatenating it into executable SQL.

SqlRequestLock.cs
using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace IdempotencyDemo.Api;

public static class SqlRequestLock
{
    public static async Task AcquireAsync(OrdersDbContext db, Guid owner,
        string keyHash, CancellationToken ct)
    {
        var transaction = db.Database.CurrentTransaction
            ?? throw new InvalidOperationException("Begin a SQL transaction first.");
        await using var command = db.Database.GetDbConnection().CreateCommand();
        command.Transaction = transaction.GetDbTransaction();
        command.CommandTimeout = 10;
        command.CommandText = """
            DECLARE @result int;
            EXEC @result = sys.sp_getapplock
                @Resource = @resource,
                @LockMode = 'Exclusive',
                @LockOwner = 'Transaction',
                @LockTimeout = 0,
                @DbPrincipal = 'public';
            SELECT @result;
            """;
        var parameter = command.CreateParameter();
        parameter.ParameterName = "@resource";
        parameter.DbType = DbType.String;
        parameter.Size = 100;
        parameter.Value = OrderRequestPolicy.LockResource(owner, keyHash);
        command.Parameters.Add(parameter);
        var code = Convert.ToInt32(await command.ExecuteScalarAsync(ct));
        if (code >= 0) return;
        if (code == -1)
            throw new ApiFailure(409, "A request with this key is in progress. Retry the same request later.");
        ct.ThrowIfCancellationRequested();
        if (code is -2 or -3)
            throw new ApiFailure(503, "Database coordination interrupted. Retry with the same key.");
        throw new InvalidOperationException("SQL application lock could not be acquired.");
    }
}
The SQL lock is shared coordination across API instances. A contender returns 409 immediately; after the winner commits, retry returns the recorded result.
The SQL lock is shared coordination across API instances. A contender returns 409 immediately; after the winner commits, retry returns the recorded result. Original SVG diagram.

sys.sp_getapplock supports transaction ownership and a zero lock timeout. In this implementation, a nonnegative return code means success; -1 means the resource was not immediately available and maps to 409. Cancellation and deadlock return codes need separate handling. Locks owned by a transaction release when it commits or rolls back.

All cooperating instances must use the same database, database principal and resource format. This sample uses public as the application-lock principal; review permissions with the DBA rather than granting the application db_owner. A lock in one database does not coordinate an independent database shard.

The contender returns before reading the other transaction’s record. Consequently, a changed payload may first receive 409 while the original is active, then 422 after a completed record becomes visible. The service does not use NOLOCK to read uncommitted responses.

An alternative is inserting a unique reservation row and handling the duplicate-key race. That can work, but a durable Processing reservation also needs a recovery/lease design. This short local transaction avoids that separate state while still enforcing uniqueness at the database level.

8. Implement atomic order creation and response replay

OrderService.cs
using System.Data;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;

namespace IdempotencyDemo.Api;

public sealed class OrderService(OrdersDbContext db, TimeProvider clock,
    ILogger<OrderService> logger)
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
    public async Task<StoredResponse> CreateAsync(Guid owner, ValidatedOrder request,
        CancellationToken ct)
    {
        await using var transaction = await db.Database.BeginTransactionAsync(
            IsolationLevel.ReadCommitted, ct);
        await SqlRequestLock.AcquireAsync(db, owner, request.KeyHash, ct);
        var now = clock.GetUtcNow();
        var existing = await db.IdempotencyRecords.AsNoTracking().SingleOrDefaultAsync(
            x => x.OwnerId == owner && x.Operation == OrderRequestPolicy.Operation
                && x.KeyHash == request.KeyHash, ct);
        if (existing is not null && existing.ExpiresAt > now)
        {
            if (!string.Equals(existing.Fingerprint, request.Fingerprint,
                    StringComparison.Ordinal))
                throw new ApiFailure(422, "This key was used with a different order request.");
            logger.LogInformation("Replaying order response for operation {Operation}",
                OrderRequestPolicy.Operation);
            // No write to commit. Disposal rolls back this read-only transaction.
            return new(existing.StatusCode, existing.ResponseBody,
                existing.ContentType, existing.Location, true);
        }
        if (existing is not null)
        {
            // Expired keys are treated as new operations under this API's policy.
            await db.IdempotencyRecords.Where(x => x.Id == existing.Id).ExecuteDeleteAsync(ct);
        }
        var order = new Order
        {
            Id = Guid.NewGuid(), OwnerId = owner, Sku = request.Sku,
            Quantity = request.Quantity, UnitPrice = 49.00m,
            Total = 49.00m * request.Quantity, CreatedAt = now
        };
        db.Orders.Add(order);
        await db.SaveChangesAsync(ct);
        var dto = new OrderResponse(order.Id, order.Sku, order.Quantity,
            order.UnitPrice, order.Total, order.CreatedAt);
        var body = JsonSerializer.Serialize(dto, Json);
        var location = $"/api/orders/{order.Id:D}";
        var record = new IdempotencyRecord
        {
            Id = Guid.NewGuid(), OwnerId = owner,
            Operation = OrderRequestPolicy.Operation, KeyHash = request.KeyHash,
            Fingerprint = request.Fingerprint, State = "Completed",
            StatusCode = 201, ResponseBody = body,
            ContentType = "application/json; charset=utf-8", Location = location,
            CreatedAt = now, ExpiresAt = now.AddHours(24)
        };
        db.IdempotencyRecords.Add(record);
        await db.SaveChangesAsync(ct);
        await transaction.CommitAsync(ct);
        // The HTTP response is written only after SQL commit succeeds.
        return new(201, body, record.ContentType, location, false);
    }
}

The two SaveChangesAsync calls are inside the same explicit transaction. Saving the order does not commit that transaction by itself. If writing the response record fails, disposing the uncommitted transaction rolls the order back. The response is not sent until CommitAsync succeeds. Microsoft’s EF Core transaction guidance explains the atomic boundary.

A committed order survives a lost HTTP response. A matching same-key retry retrieves its stored result instead of creating another order.
A committed order survives a lost HTTP response. A matching same-key retry retrieves its stored result instead of creating another order. Original SVG diagram.

On replay, the service reads the saved JSON string and returns the original status, content type and Location. It does not regenerate a new ID, timestamp or body from the current order. A later GET may show a changed resource; replay answers what the original creation request produced.

Idempotency-Replayed is a diagnostic header defined by this sample, not a standard field. First creation returns false and replay returns true. Date, tracing and other transport headers can differ; the code does not promise a byte-for-byte copy of the entire HTTP message.

Validation failures, lock contention and transient failures do not create replay records here. After rollback, the same key can be attempted again. If your business needs to persist deterministic declines or failed outcomes, design and test those states explicitly instead of caching every 500 response or treating all failures as safely retryable.

9. Authentication, safe error handling and Program.cs

The local handler maps two private demo keys to fixed owner IDs. It does not trust an OwnerId supplied in JSON or a caller-controlled customer header. Every replay is behind authentication, just like a new order request.

DemoKeyHandler.cs
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

namespace IdempotencyDemo.Api;

// Local teaching authentication. Replace with a trusted identity provider.
public sealed class DemoKeyHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
    ILoggerFactory logs, UrlEncoder encoder, IConfiguration configuration)
    : AuthenticationHandler<AuthenticationSchemeOptions>(options, logs, encoder)
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-Demo-Key", out var values)
            || values.Count != 1 || values.ToString().Length > 256)
            return Task.FromResult(AuthenticateResult.NoResult());
        var supplied = SHA256.HashData(Encoding.UTF8.GetBytes(values.ToString()));
        var users = new[]
        {
            ("00000000-0000-0000-0000-000000000001", "DemoAuth:AliceKey"),
            ("00000000-0000-0000-0000-000000000002", "DemoAuth:BobKey")
        };
        foreach (var (id, setting) in users)
        {
            var configured = configuration[setting]!;
            var expected = SHA256.HashData(Encoding.UTF8.GetBytes(configured));
            if (!CryptographicOperations.FixedTimeEquals(supplied, expected)) continue;
            var identity = new ClaimsIdentity(
                [new Claim(ClaimTypes.NameIdentifier, id)], Scheme.Name);
            return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(
                new ClaimsPrincipal(identity), Scheme.Name)));
        }
        return Task.FromResult(AuthenticateResult.Fail("Invalid demo key."));
    }
}

Replace this demo authentication with a trusted identity provider for production. Validate token issuer, audience, expiry and permissions, and include tenant scope when identities are not globally unique. See the related JWT authentication in ASP.NET Core 10 guide. An idempotency key is never an authentication credential.

ApiErrorHandler.cs
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace IdempotencyDemo.Api;

public sealed class ApiErrorHandler(ILogger<ApiErrorHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception error,
        CancellationToken ct)
    {
        if (http.RequestAborted.IsCancellationRequested) return true;
        var status = error switch
        {
            ApiFailure e => e.Status,
            BadHttpRequestException => 400,
            SqlException or DbUpdateException => 503,
            OperationCanceledException => 503,
            _ => 500
        };
        logger.LogWarning("Order request failed: {Type}, status {Status}, trace {TraceId}",
            error.GetType().Name, status, http.TraceIdentifier);
        if (status is 409 or 503) http.Response.Headers.RetryAfter = "1";
        http.Response.Headers.CacheControl = "no-store";
        var result = Results.Problem(statusCode: status,
            title: status >= 500 ? "Request outcome unavailable." : "Request rejected.",
            detail: error is ApiFailure safe ? safe.Message
                : status >= 500 ? "Retry the same operation with the same key within the retention window." : null,
            extensions: new Dictionary<string, object?> { ["traceId"] = http.TraceIdentifier });
        await result.ExecuteAsync(http);
        return true;
    }
}

The handler returns safe ProblemDetails and logs a type, status and trace ID. It does not expose SQL messages, connection strings, raw request headers or response bodies. The Retry-After value is a small backoff hint, not a promise that the operation will be complete after one second. Rate-limit, authentication and body-binding errors may use their own framework response shapes.

The ASP.NET Core error-handling documentation describes IExceptionHandler. The explicit logging also avoids assuming that .NET 10 middleware diagnostics will log every handled exception. For more detail, see the related global exception-handling tutorial.

Program.cs
using System.Security.Claims;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using IdempotencyDemo.Api;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 16 * 1024);
string Required(string key) => !string.IsNullOrWhiteSpace(builder.Configuration[key])
    ? builder.Configuration[key]! : throw new InvalidOperationException($"Configure {key}.");
var connection = Required("ConnectionStrings:Orders");
var alice = Required("DemoAuth:AliceKey");
var bob = Required("DemoAuth:BobKey");
if (alice.Length is < 32 or > 256 || bob.Length is < 32 or > 256 || alice == bob)
    throw new InvalidOperationException("Configure distinct random demo keys of 32–256 characters.");

// No EnableRetryOnFailure: transaction retries need an explicit, verified strategy.
builder.Services.AddDbContext<OrdersDbContext>(o => o.UseSqlServer(connection));
builder.Services.AddScoped<OrderService>();
builder.Services.AddSingleton<TimeProvider>(TimeProvider.System);
builder.Services.AddAuthentication("DemoKey")
    .AddScheme<AuthenticationSchemeOptions, DemoKeyHandler>("DemoKey", _ => { });
builder.Services.AddAuthorization();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<ApiErrorHandler>();
builder.Services.ConfigureHttpJsonOptions(o =>
    o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);

var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (http, next) =>
{
    http.Response.Headers.CacheControl = "no-store";
    await next(http);
});
var api = app.MapGroup("/api").RequireAuthorization();
api.MapPost("/orders", async (CreateOrderRequest request, HttpContext http,
    OrderService service, CancellationToken ct) =>
{
    var owner = Guid.Parse(http.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
    var validated = (ValidatedOrder)http.Items[OrderRequestPolicy.ItemKey]!;
    return await service.CreateAsync(owner, validated, ct);
}).AddEndpointFilter<IdempotencyFilter>();
api.MapGet("/orders/{id:guid}", async (Guid id, HttpContext http,
    OrdersDbContext db, CancellationToken ct) =>
{
    var owner = Guid.Parse(http.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
    var order = await db.Orders.AsNoTracking().Where(x => x.Id == id && x.OwnerId == owner)
        .Select(x => new OrderResponse(x.Id, x.Sku, x.Quantity,
            x.UnitPrice, x.Total, x.CreatedAt)).SingleOrDefaultAsync(ct);
    return order is null ? Results.NotFound() : Results.Ok(order);
});
app.Run();

The app rejects unknown JSON fields, limits request bodies to 16 KB, requires authentication and disables response caching with no-store. The GET endpoint filters by owner and returns 404 for a missing or inaccessible order. There is no public order enumeration endpoint.

No OpenAPI UI package is needed for this example; the instructions use Postman and curl. If you add OpenAPI documentation, explicitly describe the quoted key and authentication header. Do not expose a production testing UI with embedded credentials.

10. Create the SQL Server schema with EF Core migrations

With the files saved and development secrets configured, restore, generate the initial migration and apply it to your local development database:

Migration commands — from IdempotencyDemo.Api
dotnet restore --use-lock-file
dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.14
dotnet tool run dotnet-ef migrations add InitialCreate
dotnet tool run dotnet-ef database update
dotnet build --no-restore

Review the generated migration for the Orders and IdempotencyRecords tables, the composite unique index, the expiry index and the completed-result check constraint. Commit the migration, model snapshot, local tool manifest and resolved dependency lock file. The official migration guide explains generated migrations and deployment options.

Check the database schema — SQL Server query
SELECT name, is_unique
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.IdempotencyRecords');

SELECT name, definition
FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID(N'dbo.IdempotencyRecords');

The generated migration source is not reproduced as fabricated output here. Generate it from this model, inspect the actual SQL and apply a reviewed script or migration bundle during deployment. Do not run EnsureCreated against a production database managed by migrations, and do not grant the runtime application schema-management permissions just to simplify deployment.

11. Test the idempotent POST endpoint with Postman or curl

For a repeatable check, run the ASP.NET Core idempotency smoke test on GitHub against the local demo. It checks missing keys, order creation, exact response replay, and reuse of a key with a different quantity.

These steps were not executed while writing the article. Start the API locally, trust its development certificate, and use the actual listening URL:

Run locally — terminal
dotnet dev-certs https --trust
dotnet run --urls "https://localhost:7045;http://localhost:5045"

In Postman, create private local variables baseUrl=https://localhost:7045, demoKey with Alice’s configured key, and requestKey with one generated UUID. Keep the same requestKey for every retry of this logical operation. Keep secrets out of shared environment exports.

First order request

Send POST {{baseUrl}}/api/orders with these headers:

Postman headers
Content-Type: application/json
X-Demo-Key: {{demoKey}}
Idempotency-Key: "{{requestKey}}"
JSON request body
{
  "sku": "KB-01",
  "quantity": 2
}

Expected status: 201 Created. The response contains Location, Cache-Control: no-store and Idempotency-Replayed: false. The following shape is illustrative; the ID, date and formatting come from your actual run:

Illustrative successful response
{
  "id": "a615dc97-d1bf-4473-9ef1-74797d74bf2f",
  "sku": "KB-01",
  "quantity": 2,
  "unitPrice": 49.00,
  "total": 98.00,
  "createdAt": "2026-11-04T12:00:00+00:00"
}

Replay, payload mismatch and owner isolation

  1. Repeat the identical request with the same key and identity. Expect 201, the same saved body and Location, and Idempotency-Replayed: true.
  2. Change quantity to 3 while retaining the live key. Expect 422 and no additional order.
  3. Remove the key, omit its quotes or send an empty UUID. Expect 400.
  4. Use a new UUID. Expect a new order: a different key is a different operation.
  5. Use Bob’s key with Alice’s UUID. Expect an independent order for Bob, not Alice’s replay.
  6. Request Alice’s returned Location using Bob’s credentials. Expect 404.
  7. Send concurrent same-key requests. Depending on timing, a contender sees 409 or replays after the first transaction completes.

A fingerprint mismatch response should have status 422 and a safe detail similar to the following, with an actual trace ID assigned by the server:

Illustrative mismatch ProblemDetails
{
  "title": "Request rejected.",
  "status": 422,
  "detail": "This key was used with a different order request.",
  "traceId": "example-trace-id"
}

curl example

This Bash example expects DEMO_KEY to be set privately. The single-quoted header preserves the double quotes in the HTTP key value. Reuse the exact same key string for retries; do not regenerate it in a retry loop.

curl — Bash
curl -i "https://localhost:7045/api/orders" \
  -H "Content-Type: application/json" \
  -H "X-Demo-Key: $DEMO_KEY" \
  -H 'Idempotency-Key: "2196fb09-fd35-4ee7-86b3-774ad8237e48"' \
  --data '{"sku":"KB-01","quantity":2}'

The single-quoted Bash header above preserves the double quotes directly. Trust the local certificate in your client rather than turning off certificate validation globally. Do not use this synthetic order endpoint to test real payment credentials.

Inspect actual rows — restricted development SQL query
SELECT OwnerId, COUNT(*) AS OrderCount
FROM dbo.Orders
GROUP BY OwnerId;

SELECT OwnerId, Operation, State, StatusCode, CreatedAt, ExpiresAt
FROM dbo.IdempotencyRecords;

Use a clean development scenario when interpreting counts: creating a fresh key or testing Bob intentionally adds orders. Do not copy response data from a real customer database into a public debugging report.

Seven real-SQL integration tests

The tests exercise the order service against SQL Server, not EF’s in-memory provider. They cover response replay, changed payloads, owner separation, deterministic lock contention, eight concurrent callers, expiry and failure after the order write. A fake or SQLite substitute cannot validate sp_getapplock behavior; see Microsoft’s database testing guidance.

Create the test directory — from IdempotencyDemo
mkdir IdempotencyDemo.Tests
IdempotencyDemo.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="xunit.v3" Version="4.0.2" />
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <ProjectReference Include="../IdempotencyDemo.Api/IdempotencyDemo.Api.csproj" />
  </ItemGroup>
</Project>

Use the current xunit.v3 package shown in the test project below. Its fixture lifecycle methods return ValueTask. The package supports a stand-alone test executable, so the command uses dotnet run rather than assuming a particular dotnet test runner configuration. See the official xUnit v3 guide. Use a dedicated test instance and an account permitted to create/drop only disposable test databases. The fixture overrides Initial Catalog with a random IdemIntegration_ name, creates it, then removes that test database on teardown.

IdempotencyIntegrationTests.cs
using IdempotencyDemo.Api;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

// Run only against a disposable, isolated SQL Server test instance.
public sealed class SqlFixture : IAsyncLifetime
{
    public string Connection { get; private set; } = "";
    public OrdersDbContext Open() => new(new DbContextOptionsBuilder<OrdersDbContext>()
        .UseSqlServer(Connection).Options);
    public async ValueTask InitializeAsync()
    {
        var server = Environment.GetEnvironmentVariable("IDEMPOTENCY_TEST_SERVER_CONNECTION")
            ?? throw new InvalidOperationException("Set the isolated SQL test server connection.");
        var value = new SqlConnectionStringBuilder(server)
        {
            InitialCatalog = "IdemIntegration_" + Guid.NewGuid().ToString("N"),
            ConnectRetryCount = 0
        };
        Connection = value.ConnectionString;
        await using var db = Open();
        await db.Database.EnsureCreatedAsync();
    }
    public async ValueTask DisposeAsync()
    {
        if (string.IsNullOrEmpty(Connection)) return;
        var name = new SqlConnectionStringBuilder(Connection).InitialCatalog;
        if (!name.StartsWith("IdemIntegration_", StringComparison.Ordinal))
            throw new InvalidOperationException("Refusing to delete a non-test database.");
        await using var db = Open();
        await db.Database.EnsureDeletedAsync();
    }
}
public sealed class IdempotencyIntegrationTests(SqlFixture fixture)
    : IClassFixture<SqlFixture>
{
    private static ValidatedOrder Request(string key, int quantity = 2) =>
        OrderRequestPolicy.Validate(
IdempotencyIntegrationTests.cs
using IdempotencyDemo.Api;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

// Run only against a disposable, isolated SQL Server test instance.
public sealed class SqlFixture : IAsyncLifetime
{
    public string Connection { get; private set; } = "";
    public OrdersDbContext Open() => new(new DbContextOptionsBuilder<OrdersDbContext>()
        .UseSqlServer(Connection).Options);
    public async Task InitializeAsync()
    {
        var server = Environment.GetEnvironmentVariable("IDEMPOTENCY_TEST_SERVER_CONNECTION")
            ?? throw new InvalidOperationException("Set the isolated SQL test server connection.");
        var value = new SqlConnectionStringBuilder(server)
        {
            InitialCatalog = "IdemIntegration_" + Guid.NewGuid().ToString("N"),
            ConnectRetryCount = 0
        };
        Connection = value.ConnectionString;
        await using var db = Open();
        await db.Database.EnsureCreatedAsync();
    }
    public async Task DisposeAsync()
    {
        if (string.IsNullOrEmpty(Connection)) return;
        var name = new SqlConnectionStringBuilder(Connection).InitialCatalog;
        if (!name.StartsWith("IdemIntegration_", StringComparison.Ordinal))
            throw new InvalidOperationException("Refusing to delete a non-test database.");
        await using var db = Open();
        await db.Database.EnsureDeletedAsync();
    }
}
public sealed class IdempotencyIntegrationTests(SqlFixture fixture)
    : IClassFixture<SqlFixture>
{
    private static ValidatedOrder Request(string key, int quantity = 2) =>
        OrderRequestPolicy.Validate($"\"{key}\"", new("KB-01", quantity));
    private async Task<StoredResponse> Run(Guid owner, ValidatedOrder request,
        TimeProvider? clock = null)
    {
        await using var db = fixture.Open();
        return await new OrderService(db, clock ?? TimeProvider.System,
            NullLogger<OrderService>.Instance).CreateAsync(owner, request, default);
    }
    [Fact]
    public async Task RepeatedRequestReplaysSameBodyAndCreatesOneOrder()
    {
        var owner = Guid.NewGuid();
        var request = Request(Guid.NewGuid().ToString("D"));
        var first = await Run(owner, request);
        var again = await Run(owner, request);
        Assert.False(first.Replayed);
        Assert.True(again.Replayed);
        Assert.Equal(first.Body, again.Body);
        Assert.Equal(first.Location, again.Location);
        await using var db = fixture.Open();
        Assert.Equal(1, await db.Orders.CountAsync(x => x.OwnerId == owner));
    }
    [Fact]
    public async Task DifferentPayloadWithSameKeyIsRejected()
    {
        var owner = Guid.NewGuid(); var key = Guid.NewGuid().ToString("D");
        await Run(owner, Request(key, 2));
        var error = await Assert.ThrowsAsync<ApiFailure>(() => Run(owner, Request(key, 3)));
        Assert.Equal(422, error.Status);
    }
    [Fact]
    public async Task SameKeyForDifferentOwnersIsIsolated()
    {
        var key = Guid.NewGuid().ToString("D");
        var first = await Run(Guid.NewGuid(), Request(key));
        var other = await Run(Guid.NewGuid(), Request(key));
        Assert.False(other.Replayed);
        Assert.NotEqual(first.Location, other.Location);
    }
    [Fact]
    public async Task HeldDatabaseLockDeterministicallyReturnsInProgress()
    {
        var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D"));
        await using var holding = fixture.Open();
        await using var transaction = await holding.Database.BeginTransactionAsync();
        await SqlRequestLock.AcquireAsync(holding, owner, request.KeyHash, default);
        var error = await Assert.ThrowsAsync<ApiFailure>(() => Run(owner, request));
        Assert.Equal(409, error.Status);
        await transaction.RollbackAsync();
        var successful = await Run(owner, request);
        Assert.Equal(201, successful.Status);
    }
    [Fact]
    public async Task ConcurrentCallsCreateOnlyOneOrder()
    {
        var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D"));
        var start = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
        async Task<StoredResponse> Attempt()
        {
            await start.Task;
            for (var attempt = 0; attempt < 40; attempt++)
            {
                try { return await Run(owner, request); }
                catch (ApiFailure e) when (e.Status == 409)
                { await Task.Delay(50); }
            }
            throw new TimeoutException("Concurrent test did not finish within its retry budget.");
        }
        var calls = Enumerable.Range(0, 8).Select(_ => Attempt()).ToArray();
        start.SetResult(true);
        var results = await Task.WhenAll(calls);
        Assert.Single(results.Where(x => !x.Replayed));
        Assert.Single(results.Select(x => x.Body).Distinct());
        await using var db = fixture.Open();
        Assert.Equal(1, await db.Orders.CountAsync(x => x.OwnerId == owner));
        Assert.Equal(1, await db.IdempotencyRecords.CountAsync(x => x.OwnerId == owner));
    }
    [Fact]
    public async Task ExpiredRecordAllowsANewOperationUnderDocumentedPolicy()
    {
        var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D"));
        var now = DateTimeOffset.UtcNow;
        var first = await Run(owner, request, new FixedClock(now));
        var next = await Run(owner, request, new FixedClock(now.AddHours(25)));
        Assert.False(next.Replayed);
        Assert.NotEqual(first.Location, next.Location);
        await using var db = fixture.Open();
        Assert.Equal(2, await db.Orders.CountAsync(x => x.OwnerId == owner));
    }
    [Fact]
    public async Task FailureAfterOrderSaveRollsBackOrderAndReleasesTheKey()
    {
        var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D"));
        var options = new DbContextOptionsBuilder<OrdersDbContext>()
            .UseSqlServer(fixture.Connection).AddInterceptors(new FailAfterSave()).Options;
        await using (var failing = new OrdersDbContext(options))
        {
            var service = new OrderService(failing, TimeProvider.System,
                NullLogger<OrderService>.Instance);
            await Assert.ThrowsAsync<InvalidOperationException>(() =>
                service.CreateAsync(owner, request, default));
        }
        await using (var check = fixture.Open())
            Assert.Equal(0, await check.Orders.CountAsync(x => x.OwnerId == owner));
        Assert.False((await Run(owner, request)).Replayed);
    }
    private sealed class FailAfterSave : Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor
    {
        public override ValueTask<int> SavedChangesAsync(
            Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesCompletedEventData data,
            int result, CancellationToken ct = default)
            => throw new InvalidOperationException("Injected test failure after SQL write.");
    }
    private sealed class FixedClock(DateTimeOffset now) : TimeProvider
    {
        public override DateTimeOffset GetUtcNow() => now;
    }
}
quot;\"{key}\"", new("KB-01", quantity)); private async Task<StoredResponse> Run(Guid owner, ValidatedOrder request, TimeProvider? clock = null) { await using var db = fixture.Open(); return await new OrderService(db, clock ?? TimeProvider.System, NullLogger<OrderService>.Instance).CreateAsync(owner, request, default); } [Fact] public async Task RepeatedRequestReplaysSameBodyAndCreatesOneOrder() { var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D")); var first = await Run(owner, request); var again = await Run(owner, request); Assert.False(first.Replayed); Assert.True(again.Replayed); Assert.Equal(first.Body, again.Body); Assert.Equal(first.Location, again.Location); await using var db = fixture.Open(); Assert.Equal(1, await db.Orders.CountAsync(x => x.OwnerId == owner)); } [Fact] public async Task DifferentPayloadWithSameKeyIsRejected() { var owner = Guid.NewGuid(); var key = Guid.NewGuid().ToString("D"); await Run(owner, Request(key, 2)); var error = await Assert.ThrowsAsync<ApiFailure>(() => Run(owner, Request(key, 3))); Assert.Equal(422, error.Status); } [Fact] public async Task SameKeyForDifferentOwnersIsIsolated() { var key = Guid.NewGuid().ToString("D"); var first = await Run(Guid.NewGuid(), Request(key)); var other = await Run(Guid.NewGuid(), Request(key)); Assert.False(other.Replayed); Assert.NotEqual(first.Location, other.Location); } [Fact] public async Task HeldDatabaseLockDeterministicallyReturnsInProgress() { var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D")); await using var holding = fixture.Open(); await using var transaction = await holding.Database.BeginTransactionAsync(); await SqlRequestLock.AcquireAsync(holding, owner, request.KeyHash, default); var error = await Assert.ThrowsAsync<ApiFailure>(() => Run(owner, request)); Assert.Equal(409, error.Status); await transaction.RollbackAsync(); var successful = await Run(owner, request); Assert.Equal(201, successful.Status); } [Fact] public async Task ConcurrentCallsCreateOnlyOneOrder() { var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D")); var start = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); async Task<StoredResponse> Attempt() { await start.Task; for (var attempt = 0; attempt < 40; attempt++) { try { return await Run(owner, request); } catch (ApiFailure e) when (e.Status == 409) { await Task.Delay(50); } } throw new TimeoutException("Concurrent test did not finish within its retry budget."); } var calls = Enumerable.Range(0, 8).Select(_ => Attempt()).ToArray(); start.SetResult(true); var results = await Task.WhenAll(calls); Assert.Single(results.Where(x => !x.Replayed)); Assert.Single(results.Select(x => x.Body).Distinct()); await using var db = fixture.Open(); Assert.Equal(1, await db.Orders.CountAsync(x => x.OwnerId == owner)); Assert.Equal(1, await db.IdempotencyRecords.CountAsync(x => x.OwnerId == owner)); } [Fact] public async Task ExpiredRecordAllowsANewOperationUnderDocumentedPolicy() { var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D")); var now = DateTimeOffset.UtcNow; var first = await Run(owner, request, new FixedClock(now)); var next = await Run(owner, request, new FixedClock(now.AddHours(25))); Assert.False(next.Replayed); Assert.NotEqual(first.Location, next.Location); await using var db = fixture.Open(); Assert.Equal(2, await db.Orders.CountAsync(x => x.OwnerId == owner)); } [Fact] public async Task FailureAfterOrderSaveRollsBackOrderAndReleasesTheKey() { var owner = Guid.NewGuid(); var request = Request(Guid.NewGuid().ToString("D")); var options = new DbContextOptionsBuilder<OrdersDbContext>() .UseSqlServer(fixture.Connection).AddInterceptors(new FailAfterSave()).Options; await using (var failing = new OrdersDbContext(options)) { var service = new OrderService(failing, TimeProvider.System, NullLogger<OrderService>.Instance); await Assert.ThrowsAsync<InvalidOperationException>(() => service.CreateAsync(owner, request, default)); } await using (var check = fixture.Open()) Assert.Equal(0, await check.Orders.CountAsync(x => x.OwnerId == owner)); Assert.False((await Run(owner, request)).Replayed); } private sealed class FailAfterSave : Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor { public override ValueTask<int> SavedChangesAsync( Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesCompletedEventData data, int result, CancellationToken ct = default) => throw new InvalidOperationException("Injected test failure after SQL write."); } private sealed class FixedClock(DateTimeOffset now) : TimeProvider { public override DateTimeOffset GetUtcNow() => now; } }
Set the isolated test server and run — PowerShell
$env:IDEMPOTENCY_TEST_SERVER_CONNECTION = 'Server=(localdb)\MSSQLLocalDB;Integrated Security=true;Encrypt=true;TrustServerCertificate=true;ConnectRetryCount=0'
dotnet run --project IdempotencyDemo.Tests/IdempotencyDemo.Tests.csproj

The test-only interceptor throws after SaveChanges has written the order but before the service commits. The test checks that rollback leaves no order and that the same key can execute afterward. EF’s interceptor documentation explains registration. This is a controlled injected failure, not proof of every possible network or database outage.

The tests are supplied, not reported as passing. Also add HTTP integration tests for authentication, duplicate header rejection, unknown JSON fields, status and replay headers. Exercise real connection loss around commit in an isolated fault-injection environment; the supplied interceptor test does not simulate an ambiguous COMMIT acknowledgment.

12. Server failures, commit uncertainty and retries

Only Completed rows are committed. Failed uncommitted work rolls back; commit uncertainty is resolved by retrying with the same key, not by assuming failure.
Only Completed rows are committed. Failed uncommitted work rolls back; commit uncertainty is resolved by retrying with the same key, not by assuming failure. Original SVG diagram.
Failure pointDatabase outcomeClient recovery
Before SQL transaction / validation failureNo new order or replay recordCorrect input; reuse policy depends on whether this is still the same logical operation
After order SaveChanges but before commitUncommitted work rolls backRetry same key after rollback resolves
Commit succeeded but HTTP response was lostOrder and replay record both existSame-key retry returns stored result
Connection lost during CommitAsyncClient cannot safely assume success or rollbackRetry same key; SQL outcome determines replay versus execution
Client disconnects during processingCancellation may race with database completionDo not assume cancellation means no order; resolve using same key

Microsoft’s connection-resiliency guidance discusses commit uncertainty and execution strategies. This sample does not enable EF automatic transaction retries. If you add them, replay the entire transaction with fresh state and an explicit success-verification strategy; do not merely add EnableRetryOnFailure around manually managed transactions.

The client should use bounded exponential backoff with jitter for retryable failures, honor the API’s hints, and retain the original key and normalized parameters. A new key after a timeout defeats deduplication. A 422 requires fixing key/payload usage, not a blind retry. A 409 may resolve once the active transaction finishes. A 503 can also indicate a persistent configuration fault, so retries must be bounded and observable.

Expiry and cleanup

A completed record is retained for 24 hours in this example. On a request after expiry, the service deletes that expired record inside its scoped transaction and processes a new operation. The old order remains. The expiry test deliberately expects two orders after 25 hours, making the boundary visible.

Unused expired keys also need scheduled cleanup. Run a small-batch job under a dedicated maintenance identity, monitor its progress, and choose a schedule compatible with your retention policy:

Expiry cleanup batch — schedule outside request processing
DELETE TOP (500)
FROM dbo.IdempotencyRecords
WHERE ExpiresAt <= SYSUTCDATETIME();

Do not delete Orders as part of this cleanup. Do not shorten retention merely to reduce table size. The sample uses the application TimeProvider for expiry; synchronize instance clocks or adopt a consistent database-time policy before a distributed deployment. SQL cleanup and requests can contend, so keep batches small and handle transient deadlocks without weakening correctness.

EF’s ExecuteDelete documentation explains that it executes immediately rather than waiting for SaveChanges. The service’s per-key expired-row deletion is safe within its already-open transaction. A bare ExecuteDelete elsewhere does not automatically join an unrelated business transaction.

13. Security, production performance and external side effects

Protect the scope and replay data

  • Authenticate and authorize before lookup and replay; never let a key authorize access.
  • Include tenant and caller/client identity in the scope where applicable. Do not accept owner scope directly from the request body.
  • Use high-entropy keys without personal data. Keep keys, payloads and stored response bodies out of routine logs.
  • Encrypt and restrict database access according to your data classification. Hashing a key does not encrypt the saved response.
  • Bound request size, response size, active key creation and per-caller rates. Otherwise, a caller can create unbounded records using fresh UUIDs.
  • Preserve authorization behavior after account suspension or permission changes; replay is not an authentication bypass.
  • Store only permitted headers. Never replay Set-Cookie, bearer tokens or a user-specific cross-request security header indiscriminately.

The example validates one small order shape and produces a bounded response. It does not include a production distributed rate limiter, quotas, authorization roles or a full identity provider. Those are required deployment decisions, not guarantees supplied by an idempotency key.

Keep the transaction short and observable

Use indexed scope lookups, async I/O and cancellation tokens. Do not share a DbContext across parallel requests. Monitor transaction duration, application-lock contention, replay rate, payload mismatches, SQL failures and expiry cleanup backlog. Alert on unique-index violations: a recurring violation can indicate a writer bypassing the lock protocol or a scope mismatch, not merely harmless load.

A zero lock timeout avoids waiting on the application lock, but SQL queries, commits and cleanup can still wait on other database resources. Configure database/HTTP timeouts coherently and load-test representative traffic. No throughput or latency benchmark is claimed here.

For IIS deployment, install the appropriate Hosting Bundle, use HTTPS, configure a restricted identity and secure connection configuration, and test retries across application-pool restarts. See the related ASP.NET Core 10 IIS deployment guide. Durable SQL state survives an API process restart; a process-local dictionary would not.

Payments, emails and brokers are outside this transaction

Do not hold this SQL transaction open while charging a card or sending email and assume the two systems committed together. The remote service may succeed while the local transaction rolls back, or vice versa. Pass a stable provider-supported idempotency reference, reconcile uncertain outcomes and use an appropriate durable workflow or transactional outbox boundary.

For payment processing, also validate webhook signatures, deduplicate incoming events and enforce valid state transitions. Request idempotency, webhook deduplication and business uniqueness are separate protections. This tutorial creates an order only; it deliberately makes no exactly-once claim about an external payment provider.

14. Common mistakes and troubleshooting

Symptom or mistakeWhy it mattersCorrective check
Two orders despite checking the record firstBoth requests can observe no rowAcquire shared coordination before checking; preserve the unique index
Works on one server but duplicates after scalingAn in-memory lock is per processUse the same database lock scope across instances
Key reused with changed quantityThe client changed the logical operationExpect 422 while the record is live; use a new key for a deliberate new order
Unquoted UUID returns 400This endpoint documents a quoted-string subsetInclude literal double quotes in the header
Missing migrations or duplicate index nameSchema is absent or manual SQL was run twiceInspect generated migrations and sys.indexes
Application lock reports an errorMissing transaction, permissions or inconsistent scopeCheck return codes and transaction ownership; do not grant broad roles blindly
Unique violation is caught as concurrency-token failureInsert uniqueness is not optimistic row-version handlingInspect provider-specific errors in restricted diagnostics
Transaction error after enabling retriesAutomatic execution strategy conflicts with ad hoc transaction managementUse an explicit verified transaction retry design
Same body but fingerprint differs after deploymentNormalization or operation schema changedPreserve retry compatibility and version the contract deliberately
Order committed but client saw 503 or disconnectCommit acknowledgment or HTTP response was lostRetry same key; do not assume no order exists
Old key creates another orderThe retention window has endedUse a longer documented horizon or permanent business uniqueness
Cleanup causes blocking or deadlocksLarge deletes contend with live trafficUse expiry index, short batches, monitoring and bounded recovery
Tests pass with EF InMemory but production duplicatesThe substitute does not reproduce SQL lockingRun the supplied real-SQL tests and fault scenarios
LocalDB connection failsWrong instance, unsupported platform or missing installationUse Windows LocalDB or configure a reachable SQL Server instance

Useful developer questions are often about the race, not about generating a UUID. The Stack Overflow race-condition discussion illustrates that concern. EF’s historical commit-failure discussion reinforces the need to distinguish retry policy from outcome verification. These are research context, not normative API contracts or proof of a current EF defect.

When diagnosing a failure, establish whether the request reached SQL, whether its transaction committed, whether a live scoped record exists, and whether the retry used the original key and parameters. Avoid deleting records to “unstick” a request before understanding the committed business outcome.

15. Frequently asked questions

Is POST idempotent in ASP.NET Core 10 by default?

No. ASP.NET Core does not infer an order-creation retry contract from POST. The application must define the key scope, payload consistency, concurrency and replay behavior.

Should the client or server generate the idempotency key?

The client initiating the logical operation should generate and retain it before the first attempt. If the key is delivered only in the server’s response, a lost first response leaves the client unable to reuse it.

Can two users use the same key?

Yes under this sample’s policy, because owner identity is part of the protected scope. Their records and orders remain separate. A production multi-tenant system may need tenant, client and user components rather than one owner ID.

Why return 201 again on a replay?

The stored result represents the original creation response. This sample reuses its status, body and Location while marking the replay with an application-specific header. An alternative contract can differ, but clients must know what to expect.

Why does the same key with a different body return 422?

A live key identifies one operation. Reusing it with a different normalized request is rejected instead of silently returning an unrelated order. If the first request is still active, the contender may see 409 before the service can inspect the completed record.

Do JSON whitespace and property order change the fingerprint?

No in this implementation. It fingerprints the validated server-generated representation. Adding or changing a meaningful field requires updating that representation and planning compatibility.

Should I store failed responses too?

That is a contract decision. This implementation saves only completed order creation. Validation, contention and uncommitted failures leave no record. A payment API may need durable declines or in-doubt states with different retry semantics.

Is a Redis lock enough?

It can coordinate admission, but it does not atomically commit a separate SQL order and replay record. Consider lease loss, eviction, crashes and recovery. Keep the authoritative correctness boundary explicit.

What happens after expiry?

The sample treats an expired key as a new operation and may create another order. The old order is not removed. Clients must not rely on replay beyond the advertised window.

Does this guarantee exactly-once payment processing?

No. It protects one local SQL order operation during retention. External payments, webhooks and messages need their own stable references, deduplication and reconciliation policies.

Can I use this for a ten-minute background job?

Do not keep a SQL transaction and application lock open for that duration. Use a durable asynchronous workflow with an explicit reservation state, lease, recovery policy and status endpoint.

Were these code examples tested?

They were reviewed against documentation but were not compiled or executed here. Run the build and seven supplied SQL integration tests locally, then test the HTTP contract and commit-uncertainty scenarios in staging. No test screenshot or benchmark is fabricated.

16. Conclusion and useful follow-up topics

A dependable idempotent POST endpoint needs more than a key in a header. The key must have an authenticated scope, the payload needs a documented equivalence policy, concurrent requests need shared coordination, and the business change and replay result need one durable commit boundary.

The sample keeps that boundary visible: validate first, acquire a SQL transaction-owned lock, check the retained fingerprint, then either replay or commit an order and its response. Retention and external systems remain explicit limits. Run and extend the tests before production rather than treating a successful manual request as evidence that retries are safe.

Suggested supporting articles — not created here

  • Designing idempotency-key compatibility across rolling API deployments and schema changes.
  • Building a reconciliation workflow for ambiguous SQL COMMIT outcomes.
  • Coordinating checkout references across tenants and database shards.

These are focused future directions. No additional article or published post is created as part of this draft.

17. References and further reading

Primary implementation references checked on 4 November 2026:

  1. HTTP semantics and idempotent methods
  2. Current Idempotency-Key document status
  3. Idempotency-Key draft-08 text (work in progress)
  4. Stripe idempotency contracts
  5. EF Core SQL Server provider
  6. SQL Server provider package
  7. EF Core Design 10.0.14
  8. EF Core transactions
  9. Composite and unique indexes
  10. SQL Server unique constraints
  11. SQL Server application locks
  12. EF Core connection resiliency and commit uncertainty
  13. EF Core concurrency conflicts
  14. EF Core migrations
  15. Minimal API endpoint filters
  16. Development secret storage
  17. ASP.NET Core error handling
  18. ExecuteDelete behavior
  19. Choosing a database testing strategy
  20. EF Core interceptors
  21. xUnit v3 project and execution guide
  22. xunit.v3 package

Research scope and search intent

The research reviewed HTTP specifications, Microsoft documentation, package pages, provider documentation and developer discussions. Competing tutorials covered payment state machines and generic middleware/storage providers. This guide focuses on a visible local SQL transaction boundary, explicit fingerprint semantics, a documented retention limit and executable real-SQL test examples. It does not claim that every competing article omits those subjects.

The primary query is idempotency keys in ASP.NET Core. Related intent includes preventing duplicate POST requests, SQL Server idempotency, EF Core transactions, concurrent request handling, request fingerprints, response replay and the Idempotency-Key header. No reliable keyword-volume or competition dataset was available, so no volume, CPC, ranking or earnings figures are invented. The direct answers, comparison tables and original diagrams serve developer comprehension rather than promise search outcomes.

Comments