Development Playbook

Your agent's POST endpoint charges twice on retry: six tests that force a real idempotency key

A failing xUnit suite shows an agent-written payment endpoint double-charging under retries and concurrent duplicates, then drives an endpoint filter that fixes it. About 15 minutes to try.

Five identical arrows converging on a single ring drawn as a technical blueprint, with one arrow leaving on the far side

A mobile client sends a payment, the connection drops before the response arrives, and the app does what every retry library does: it sends the same request again. The agent-written POST /payments endpoint does what the prompt asked, so it charges the card a second time. Nothing in the diff looks wrong. The handler is four lines, it passes its tests, and the bug only exists when the network does something the tests never simulate.

The standard fix is an idempotency key: the client generates a unique value per logical operation and sends it in an Idempotency-Key header, and the server promises that repeating a request with the same key doesn’t repeat the work. Agents know the pattern by name, but ask for it vaguely and the usual result is a check-then-insert on a dictionary that two simultaneous retries walk straight through.

This Playbook builds the check first. Six xUnit tests pin down what an idempotent POST has to do, including the two cases agents most often miss (concurrent duplicates and a key reused with a different body). They fail against the naive endpoint, you hand them to the agent as the target, and a small endpoint filter turns them green. Everything here runs offline against .NET 10 and WebApplicationFactory, about 15 minutes end to end. The tests, the prompt and the check that proves it worked need nothing from any one agent: any tool that can read files and run dotnet test can do this.

What an idempotent POST has to promise

The IETF HTTP API working group has an Internet-Draft for the header, draft-ietf-httpapi-idempotency-key-header. At revision 08 (dated 22 October 2026 on its datatracker page ) it is still a draft, not a standard, but its error rules are a sensible spec to give an agent. Section 2.7 says a server should answer 400 when a required key is missing, 422 when a key is reused with a different payload, and 409 when a retry arrives while the original is still being processed.

Stripe’s documentation describes the same contract in production terms. Keys are up to 255 characters, the server saves the response of the first request and replays it on retries, and the idempotency layer compares incoming parameters to the original request and errors if they differ. Stripe also notes that it prunes keys after at least 24 hours, which tells you a real store needs an expiry.

Turn that into behaviour you can assert:

  1. No key: 400, and nothing is charged.
  2. Same key, same body: the second call returns the first response, and the ledger has one entry.
  3. Same key, different body: 422, and nothing new is charged.
  4. Same key arriving eight times at once: one charge, and every caller gets the same response.
  5. A different key is a different operation.
  6. A request that failed must not pin its key, or the client can never retry the thing it most needs to retry.

Cases 4 and 6 are the ones a first draft misses. They’re also the ones with no visible symptom until production traffic produces a retry storm.

The naive endpoint

Create the projects. The pin on Microsoft.AspNetCore.Mvc.Testing matters: at the time of writing an unpinned dotnet add package resolves to the 11.x line, which refuses to install on net10.0.

dotnet new web -n Api
dotnet new xunit -n Api.Tests
cd Api.Tests
dotnet add package Microsoft.AspNetCore.Mvc.Testing --version "10.*"
dotnet add reference ../Api

Here’s the kind of endpoint an agent produces from “add a POST /payments endpoint that charges an account”. The Task.Delay stands in for the call to a card processor. PaymentLedger records what was charged, which is what the tests count.

using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<PaymentLedger>();
builder.Services.AddSingleton<IdempotencyStore>();
var app = builder.Build();

app.MapPost("/payments", async (CreatePayment request, PaymentLedger ledger) =>
{
    var payment = await ledger.ChargeAsync(request.AccountId, request.AmountPence);
    return TypedResults.Created($"/payments/{payment.Id}", payment);
}).AddEndpointFilter<IdempotencyFilter<CreatePayment, Payment>>();

app.Run();

public record CreatePayment(string AccountId, long AmountPence);
public record Payment(Guid Id, string AccountId, long AmountPence);

public class PaymentLedger
{
    private readonly ConcurrentBag<Payment> _payments = new();
    public int Count => _payments.Count;

    public virtual async Task<Payment> ChargeAsync(string accountId, long amountPence)
    {
        await Task.Delay(50); // stands in for the card processor call
        var payment = new Payment(Guid.NewGuid(), accountId, amountPence);
        _payments.Add(payment);
        return payment;
    }
}

The last line, public partial class Program;, exposes the entry point to WebApplicationFactory. Every agent-written minimal API needs it before it can be tested this way.

Write the tests before the fix

Each test gets its own factory, so every one starts with an empty ledger, and asserts on the ledger count as well as the HTTP response. Counting what the system did, not just what it replied, is the point: a replayed 201 with two charges behind it would look fine in the response.

using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;

public class IdempotencyTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;
    public IdempotencyTests(WebApplicationFactory<Program> factory) => _factory = factory;

    private static HttpRequestMessage Post(string? key, long amount = 1999, string account = "acc-1")
    {
        var request = new HttpRequestMessage(HttpMethod.Post, "/payments")
        {
            Content = JsonContent.Create(new CreatePayment(account, amount))
        };
        if (key is not null) request.Headers.Add("Idempotency-Key", key);
        return request;
    }

    // A fresh factory per test so every test starts with an empty ledger.
    private (HttpClient Client, PaymentLedger Ledger) Start()
    {
        var factory = _factory.WithWebHostBuilder(_ => { });
        return (factory.CreateClient(), factory.Services.GetRequiredService<PaymentLedger>());
    }

    [Fact]
    public async Task Missing_key_is_rejected()
    {
        var (client, ledger) = Start();
        var response = await client.SendAsync(Post(key: null));
        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        Assert.Equal(0, ledger.Count);
    }

    [Fact]
    public async Task Retry_with_same_key_and_body_charges_once_and_replays_the_response()
    {
        var (client, ledger) = Start();
        var first = await client.SendAsync(Post("k-1"));
        var second = await client.SendAsync(Post("k-1"));

        Assert.Equal(HttpStatusCode.Created, first.StatusCode);
        Assert.Equal(HttpStatusCode.Created, second.StatusCode);
        Assert.Equal(await first.Content.ReadAsStringAsync(), await second.Content.ReadAsStringAsync());
        Assert.Equal(1, ledger.Count);
    }

    [Fact]
    public async Task Same_key_with_different_body_is_a_422_and_does_not_charge()
    {
        var (client, ledger) = Start();
        await client.SendAsync(Post("k-2", amount: 1999));
        var reused = await client.SendAsync(Post("k-2", amount: 5000));

        Assert.Equal(HttpStatusCode.UnprocessableEntity, reused.StatusCode);
        Assert.Equal(1, ledger.Count);
    }

    [Fact]
    public async Task Concurrent_duplicates_charge_once()
    {
        var (client, ledger) = Start();
        var responses = await Task.WhenAll(
            Enumerable.Range(0, 8).Select(_ => client.SendAsync(Post("k-3"))));

        var bodies = await Task.WhenAll(responses.Select(r => r.Content.ReadAsStringAsync()));
        Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode));
        Assert.Single(bodies.Distinct());
        Assert.Equal(1, ledger.Count);
    }

    [Fact]
    public async Task Different_keys_are_independent_charges()
    {
        var (client, ledger) = Start();
        await client.SendAsync(Post("k-a"));
        await client.SendAsync(Post("k-b"));
        Assert.Equal(2, ledger.Count);
    }

    // ...the failure test below goes here, then the closing brace of the class.
}

The failure case needs a ledger that throws on its first call. Make ChargeAsync virtual and subclass it in the test class:

    private sealed class FailsOnce : PaymentLedger
    {
        private int _calls;
        public override Task<Payment> ChargeAsync(string accountId, long amountPence) =>
            Interlocked.Increment(ref _calls) == 1
                ? throw new InvalidOperationException("processor timeout")
                : base.ChargeAsync(accountId, amountPence);
    }

    [Fact]
    public async Task A_failed_attempt_does_not_pin_the_key()
    {
        var factory = _factory.WithWebHostBuilder(b => b.ConfigureServices(s =>
            s.AddSingleton<PaymentLedger, FailsOnce>()));
        var client = factory.CreateClient();

        var first = await client.SendAsync(Post("k-4"));
        var retry = await client.SendAsync(Post("k-4"));

        Assert.Equal(HttpStatusCode.InternalServerError, first.StatusCode);
        Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
        Assert.Equal(1, factory.Services.GetRequiredService<PaymentLedger>().Count);
    }

See it fail

Run dotnet test in Api.Tests against the naive endpoint. The five tests above (before the failure case was added) give:

[xUnit.net 00:00:00.73]     IdempotencyTests.Concurrent_duplicates_charge_once [FAIL]
[xUnit.net 00:00:01.01]     IdempotencyTests.Same_key_with_different_body_is_a_422_and_does_not_charge [FAIL]
[xUnit.net 00:00:01.14]     IdempotencyTests.Retry_with_same_key_and_body_charges_once_and_replays_the_response [FAIL]
[xUnit.net 00:00:01.21]     IdempotencyTests.Missing_key_is_rejected [FAIL]
  Failed IdempotencyTests.Concurrent_duplicates_charge_once [436 ms]
  Error Message:
   Assert.Single() Failure: The collection contained 8 items
Failed!  - Failed:     4, Passed:     1, Skipped:     0, Total:     5, Duration: 940 ms - Api.Tests.dll (net10.0)

The one that passes is the independent-keys test, which passes trivially because the endpoint ignores keys altogether. Eight concurrent requests produced eight distinct payments. That’s the double charge, reproduced and countable.

Hand the failing suite to the agent

Prompt the agent with the tests as the contract and the constraints that stop the common bad answers:

Make the tests in Api.Tests/IdempotencyTests.cs pass without editing them.
Constraints:
- Implement idempotency as an IEndpointFilter applied to POST /payments, not inside the handler.
- The key must be scoped to the caller, not global.
- Concurrent requests with the same key must run the handler once and share its result.
  Do not use check-then-insert on a dictionary.
- If the handler throws, the key must be released so the client can retry.
- Compare a hash of the request body to detect key reuse with a different payload.
- Run dotnet test and show the output.

Each constraint exists because of a specific habit. Left alone, agents tend to put the logic in the handler (so the next endpoint needs it copied), use a plain Dictionary or a ContainsKey followed by an add (a race), and skip the scoping. The “do not edit the tests” line matters as much: an agent whose goal is a green run will sometimes loosen the assertion that’s in its way.

The fix that turns it green

This is one implementation that satisfies the constraints. The store uses ConcurrentDictionary.GetOrAdd with a Lazy<Task>, so the first caller for a key creates the entry and everyone else awaits the same task. Lazy<T> in its default mode runs the factory once, which is what makes the concurrent case safe. GetOrAdd alone isn’t enough here: it can invoke its value factory more than once under contention, so the work has to live inside the Lazy, not in the factory.

public sealed record StoredCreated<T>(string Location, T Value);

public sealed class IdempotencyStore
{
    private sealed record Entry(string Fingerprint, Lazy<Task<object>> Result);
    private readonly ConcurrentDictionary<string, Entry> _entries = new();

    // The first caller for a key runs the work; later callers with the same fingerprint await that run.
    public async Task<(bool Conflict, object? Result)> RunAsync(
        string key, string fingerprint, Func<Task<object>> work)
    {
        var entry = _entries.GetOrAdd(key, _ => new Entry(fingerprint, new Lazy<Task<object>>(work)));
        if (entry.Fingerprint != fingerprint) return (true, null);
        try
        {
            return (false, await entry.Result.Value);
        }
        catch
        {
            _entries.TryRemove(KeyValuePair.Create(key, entry)); // a failed run must not pin the key
            throw;
        }
    }
}

public sealed class IdempotencyFilter<TRequest, TBody>(IdempotencyStore store) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
    {
        var http = ctx.HttpContext;
        if (!http.Request.Headers.TryGetValue("Idempotency-Key", out var keys) || string.IsNullOrWhiteSpace(keys))
            return Results.Problem("Idempotency-Key header is required.", statusCode: 400);

        var body = ctx.Arguments.OfType<TRequest>().Single();
        var fingerprint = Convert.ToHexString(
            SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(body))));
        // Scope the key to the caller so two clients can't collide. Replace "anon" with the authenticated user id.
        var scopedKey = $"{http.User.Identity?.Name ?? "anon"}:{keys}";

        var (conflict, result) = await store.RunAsync(scopedKey, fingerprint, async () =>
        {
            var created = (Created<TBody>)(await next(ctx))!;
            return new StoredCreated<TBody>(created.Location!, created.Value!);
        });

        if (conflict)
            return Results.Problem("Idempotency-Key was already used with a different request body.", statusCode: 422);
        var stored = (StoredCreated<TBody>)result!;
        return TypedResults.Created(stored.Location, stored.Value);
    }
}

Wire it up with builder.Services.AddSingleton<IdempotencyStore>(); and .AddEndpointFilter<IdempotencyFilter<CreatePayment, Payment>>() on the MapPost, and change the handler to return TypedResults.Created(...) so the filter can pattern-match the result. The Microsoft docs describe IEndpointFilter, AddEndpointFilter<T>() and the Arguments list on the invocation context, and note that filters run before and after the handler, which is what this relies on (Filters in Minimal API apps ).

Run the suite again:

Passed!  - Failed:     0, Passed:     6, Skipped:     0, Total:     6, Duration: 869 ms - Api.Tests.dll (net10.0)

Check that the tests would catch a regression

A green run says the code passes the tests. It doesn’t say the tests would notice if the code got worse. Delete the TryRemove line from the store (the one that releases a failed key) and run again:

[xUnit.net 00:00:01.02]     IdempotencyTests.A_failed_attempt_does_not_pin_the_key [FAIL]
Expected: Created
Actual:   InternalServerError
Failed!  - Failed:     1, Passed:     5, Skipped:     0, Total:     6, Duration: 764 ms - Api.Tests.dll (net10.0)

Exactly the one test aimed at that behaviour fails. That’s a hand-made mutation, a one-line version of what Stryker.NET automates. Run dotnet stryker over the filter and store if you want the same check across every mutation operator. The key-scoping line has no test yet: add one that sends the same key from two different users and expects two charges, once the endpoint has real authentication.

Make it yours

Other stacks and shapes:

  • A database-backed store. For more than one instance, the dictionary has to become a table with a unique index on the scoped key, inserted before the work starts. The unique violation is your “someone else got here first” signal. Keep the same six tests and run them against the new store, which is the reason to write them against HTTP behaviour and not against the class.
  • A 409 instead of waiting. The IETF draft suggests answering 409 for a retry that arrives mid-flight. The store above makes the second caller wait and then replay, which is friendlier to clients that retry aggressively, but it holds a request open for as long as the first one runs. If your processor can take 30 seconds, return 409 and let the client back off.
  • Other result types. The filter casts to Created<TBody>. For an endpoint that returns Ok<T> or Accepted, extend the stored record to hold a status code, or write a middleware that captures the response stream. The tests don’t change.
  • TypeScript clients. The same contract applies on the sending side: generate the key once per user action, not once per attempt, or the retry gets a new key and the guard does nothing. A Vitest test with a fake fetch that fails once and succeeds on retry checks it.

What goes wrong

The fingerprint is over the deserialised object, so {"a":1} and {"a": 1} match, which is usually what you want. It also means field order or defaults that the model binder fills in can change the hash if you ever serialise differently on the two sides. Hash what the server understood, consistently.

Memory grows without bound. Nothing expires. Stripe prunes after at least 24 hours for a reason, so a production store needs a TTL and a size limit, and the tests need a clock they can move (TimeProvider, which the fake clock post covers).

A cancelled first request fails its waiters. If the client that ran the work disconnects, the cancellation propagates through the shared task and the other callers get an error too. Decide whether the work should run under the request’s cancellation token at all for a payment, and test the answer.

The filter reads the first argument of type TRequest. If the handler takes two parameters of that type, Single() throws. That’s a loud failure, which is the right kind.

Don’t bother with any of this for endpoints that are naturally idempotent (PUT with a full replacement, DELETE), or for operations where a duplicate is harmless and cheap. The cost here is a store, an expiry policy and a decision about in-flight duplicates.

First 15 minutes

Pick one POST endpoint in your codebase that moves money, sends an email or creates an order. Copy the Post helper and the concurrent-duplicates test from above and point them at it, with the ledger replaced by whatever counts the side effect. Run it: if it reports eight creations for eight requests, the endpoint has the bug, and the prompt above is what to give your agent.