Interview question
Test an idempotent POST retry
Proves repeated requests with one idempotency key create one resource and return a consistent result.
TL;DR
Proves repeated requests with one idempotency key create one resource and return a consistent result.
Idempotency keys, duplicate suppression, response replay, concurrency, and isolated relational constraints.
Practice the problem like a real interview: restate, reason, implement, and test.
Send the same checkout command twice with one idempotency key. Then issue two concurrent requests using a fresh key. Assert one order per key and a consistent response. Use an isolated relational database or test container because uniqueness and races are part of the behavior.
A client times out after the first commit and retries. It receives the original order id rather than creating a second order.
I test both sequential replay and concurrency. The sequential case proves response replay; the concurrent case proves the database boundary, not just an application cache. Reusing a key with a different payload should produce a deliberate conflict.
[Fact]
public async Task Checkout_replays_one_result_for_one_idempotency_key()
{
await using var factory = await ApiTestFactory.WithIsolatedDatabaseAsync();
var client = factory.CreateAuthenticatedClient("buyer-1", "orders.create");
client.DefaultRequestHeaders.Add("Idempotency-Key", "checkout-test-42");
var command = new { ProductId = "p-1", Quantity = 2 };
var first = await client.PostAsJsonAsync("/api/orders", command);
var second = await client.PostAsJsonAsync("/api/orders", command);
first.EnsureSuccessStatusCode();
second.EnsureSuccessStatusCode();
var a = await first.Content.ReadFromJsonAsync<CreateOrderResponse>();
var b = await second.Content.ReadFromJsonAsync<CreateOrderResponse>();
Assert.Equal(a!.OrderId, b!.OrderId);
Assert.Equal(1, await factory.CountOrdersForKeyAsync("checkout-test-42"));
}
The relational unique constraint is the authoritative race guard. The test database is disposable and isolated. A second test should use two clients and Task.WhenAll to force concurrent first attempts.
Next in Contracts & Reliability: Pagination Regression