Safety and idempotency as a retry contract: why every layer that retries depends on them, idempotency as effect on state, testing it, and the design options (PUT with client ids, conditional requests, idempotency keys, natural dedup) for retry-safe writes.
A safe method (GET, HEAD, OPTIONS) asks for no state change; an idempotent one has the same effect on server state however many times it's repeated (safe methods plus PUT and DELETE). They matter because a timeout is ambiguous: the server may have done the work. Resilience handlers, gateways, service meshes and browsers retry on that basis, so only idempotent requests can be retried blindly.
When a write must be retryable but isn't naturally idempotent (creating an order, taking a payment), you design idempotency in: PUT to a client-generated id, conditional requests with If-Match, an Idempotency-Key header that replays the stored result, or a unique constraint on a natural key. The trade-off is extra storage and complexity versus duplicate orders and double charges.
"Safety and idempotency are promises the server makes about the effect of a request. Safe means the client isn't asking for any state change, which is GET, HEAD and OPTIONS. Idempotent means sending the same request once or five times leaves the server in the same state, which covers the safe methods plus PUT and DELETE. It's about state, not responses: a second DELETE can return 404 and still be idempotent.
They matter because of timeouts. If a client sends a request and the connection drops, it can't know whether the server processed it. Lots of things retry in that situation: the standard resilience handler on
HttpClient, an Istio or Linkerd sidecar, Azure API Management retry policies, the browser on a connection reset, and a user pressing the button again. If the operation is idempotent, the retry is harmless. If it's a POST that creates an order, the retry creates a second order. So I configure retries to skip unsafe methods, for exampleDisableForUnsafeHttpMethods()inMicrosoft.Extensions.Http.Resilience, and I design writes that need retries to be idempotent. My options are PUT to a client-generated id, conditional updates withIf-Matchso a stale retry fails with 412 instead of applying twice, anIdempotency-Keyheader where the server stores the first result and replays it, or simply a unique constraint, such as one payment per invoice number.The mistake I see is making the database row idempotent but not the side effects: the second request is deduplicated, but it still sends a confirmation email or publishes an event. Idempotency has to cover everything the request triggers, and I prove it with a test that sends the same request three times, including concurrently, and checks the state and the side-effect counts."
| Method | Safe | Idempotent | Retry blindly? |
|---|---|---|---|
| GET, HEAD, OPTIONS | Yes | Yes | Yes |
| PUT | No | Yes | Yes (watch concurrency) |
| DELETE | No | Yes | Yes |
| POST | No | No | Only with an idempotency key |
| PATCH | No | Not guaranteed | Only if designed to be (e.g. merge patch setting values, If-Match) |
| Technique | How | Good for | Cost |
|---|---|---|---|
| PUT with client id | Client generates GUID, PUT /orders/{id} |
Offline/mobile creates | Client owns ids |
| Conditional request | If-Match: "etag" -> 412 on repeat |
Updates, state transitions | ETag plumbing |
| Idempotency-Key | Store key + response, replay on repeat | Payments, order creation | Key store, expiry, concurrency |
| Natural unique constraint | Unique index on (InvoiceId) | Business keys exist | Must map duplicate-key to 200/409 |
| Absolute values not deltas | {"quantity": 5} not {"add": 1} |
PATCH design | May need concurrency control |
A [checkout] service retried timed-out POST /payments calls via its HTTP client policy. During a [payment provider slowdown], [~0.4%] of customers were charged twice. Adding an Idempotency-Key per checkout attempt, forwarding it to the provider, and disabling retries for unsafe methods brought duplicates to zero.
Checks that the candidate connects method semantics to real retry behaviour and can design idempotency into writes that need it.
Green flags
Red flags
Client Gateway Service DB
|--POST /orders-->|---------------->|--INSERT------->|
| | |<--ok-----------|
| | X connection lost before response
|<--504 timeout---|
Did the order get created? Unknown.
The client sees a failure, but the work succeeded. Any retry policy that treats this as "failed, try again" creates a duplicate unless the operation is idempotent.
| Layer | Retries by default? |
|---|---|
| Browser | Some idempotent requests on connection failure |
AddStandardResilienceHandler |
Yes, transient errors (5xx, 408, 429, network); configure DisableForUnsafeHttpMethods() |
| Service mesh (Istio/Linkerd) | Configurable, often on |
| Azure API Management | Only if a retry policy is configured |
| Azure Front Door / load balancers | Some retry on connection failure |
| Humans | Always (double-click, refresh) |
Layers multiply: 3 attempts at 3 layers is up to 27 executions of one click.
DELETE /orders/7 -> 204 state: no order 7
DELETE /orders/7 -> 404 state: no order 7 (same effect: idempotent)
PATCH /cart/items/3 {"quantity": 5} x2 -> quantity 5 (idempotent by design)
PATCH /cart/items/3 {"increment": 1} x2 -> quantity +2 (not idempotent)
Designing payloads as absolute values rather than deltas makes many updates idempotent for free.
A request often does more than write a row: it publishes an event, sends an email, calls a payment provider. Deduplicate them too:
Task.WhenAll; assert one succeeds and the other returns the stored result or 409, never two rows.DelegatingHandler in tests) and let the client retry.WebApplicationFactory test that posts the same order three times and counts rows.(CustomerId, ClientOrderRef) and map the duplicate-key DbUpdateException to a 200 with the existing order.AddStandardResilienceHandler with and without DisableForUnsafeHttpMethods(), inject faults with a test handler, and log attempts.Natural-key deduplication for a POST create, and a client that retries only idempotent methods.
// Program.cs (.NET 10): POST /orders is made retry-safe with a client reference + unique index.
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<OrdersDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
var app = builder.Build();
app.MapPost("/orders", async (CreateOrder cmd, OrdersDb db, CancellationToken ct) =>
{
var order = new Order { Id = Guid.CreateVersion7(), CustomerId = cmd.CustomerId, ClientRef = cmd.ClientRef, Total = cmd.Total };
db.Orders.Add(order);
try
{
await db.SaveChangesAsync(ct);
return Results.Created($"/orders/{order.Id}", order);
}
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2601 or 2627 })
{
// A retry of a request that already succeeded: return the original result, don't create another.
db.ChangeTracker.Clear();
var existing = await db.Orders.AsNoTracking()
.SingleAsync(o => o.CustomerId == cmd.CustomerId && o.ClientRef == cmd.ClientRef, ct);
return Results.Ok(existing);
}
});
app.Run();
public sealed record CreateOrder(int CustomerId, string ClientRef, decimal Total);
public sealed class Order
{
public Guid Id { get; set; }
public int CustomerId { get; set; }
public required string ClientRef { get; set; } // generated once per checkout attempt by the client
public decimal Total { get; set; }
}
public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Order>().HasIndex(o => new { o.CustomerId, o.ClientRef }).IsUnique(); // the dedup guarantee lives in the DB
b.Entity<Order>().Property(o => o.Total).HasPrecision(18, 2);
}
}
// Client side: retries for transient faults, but never for POST/PATCH unless an idempotency key is sent.
builder.Services.AddHttpClient("orders", c => c.BaseAddress = new Uri("https://orders.internal"))
.AddStandardResilienceHandler(o => o.Retry.DisableForUnsafeHttpMethods());
UPDLOCK, HOLDLOCK) in the same transaction, which costs concurrency and can deadlock. Instead: Keep the friendly check if you like, but let a unique constraint or an atomic insert be the real guarantee, and map the duplicate-key error to the original result.increment). Why it is wrong: Every repeat applies again. Instead: Send absolute values, or protect with If-Match.Idempotency is a cross-cutting reliability property, not an endpoint detail. As a default I make one layer responsible for retries (usually the caller's resilience handler) and make every write that layer may retry idempotent. That default gets revisited as the topology changes: adding a service mesh or an APIM retry policy, or moving a call behind a queue, changes who retries, so the retry ownership belongs in the architecture docs and is reviewed when infrastructure changes. For money-moving operations, the idempotency key is part of the contract and is propagated end to end, including to the payment provider.
I measure it: replays and duplicate-key exceptions per endpoint and per client id as custom metrics in Application Insights (a spike means a retry storm or a client bug), retry attempt counts from the resilience handler's telemetry, and a reconciliation job that looks for duplicate business records. Users notice the absence of idempotency as double charges and duplicate orders; they notice over-eager retries as latency, so both sides get dashboards.
| Technique | When it fits | Cost | When not |
|---|---|---|---|
| Client-generated id + PUT | Clients can generate ids; offline sync | Clients own identity | Server-controlled numbering |
| Unique natural key | A business key exists (invoice number, client ref) | Schema constraint, error mapping | No natural key |
| Idempotency-Key store | Payments, public POST APIs | Storage, TTL, in-flight handling | Internal CRUD where duplicates are harmless |
| If-Match conditional | Updates and transitions | ETag support | Creates (nothing to match yet) |
Have the client send a unique Idempotency-Key header per logical operation (one checkout attempt, not one HTTP attempt), and scope keys per client or API key so one caller can't replay another's. The server stores the key with a hash of the request and the response, atomically with the side effect (same transaction, or a unique constraint on the key). A repeat with the same key and body returns the stored response; the same key with a different body returns 422; a concurrent duplicate gets 409 until the first completes. Keys expire after a documented window such as 24 hours, enforced with a TTL (Redis) or a cleanup job (SQL). Log key reuse and mismatches so replay attempts and buggy clients show up in monitoring.
Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.
Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.The danger is amplification: retries at the API, service and client layers multiply, which creates a retry storm against a recovering dependency. Retry at one layer and pair it with a circuit breaker.
In .NET 10 it's Polly v8 (AddRetry) or AddStandardResilienceHandler (3 retries, exponential, jitter, 2 s base). The trade-off is higher success rates against extra load and latency.
With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.
The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:
If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.
Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.
Last updated 23 Nov 2026.