📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What do safety and idempotency mean for a REST API in practice? Why do clients, gateways and resilience handlers depend on them when retrying, how do you test that an endpoint really is idempotent, and what design options do you have when an operation must be retryable but isn't naturally idempotent?

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.

Intermediate Theory Intermediate aspnet-core idempotency resilience rest retries web-api

🎯 Key points

  • Safe = no requested state change (GET, HEAD, OPTIONS); idempotent = N identical requests have the same effect as one (safe + PUT, DELETE)
  • Idempotency is about server state, not identical responses (second DELETE may be 404)
  • A timeout is ambiguous: the request may have succeeded, so only idempotent operations can be retried blindly
  • Retries happen at many layers: HttpClient resilience handler, service mesh, API gateway, browser, user double-click
  • Make writes retry-safe: PUT to client-generated id, If-Match conditional updates, Idempotency-Key header on POST, unique constraints for natural dedup
  • Side effects (emails, events, payments) must also be deduplicated, not just the database row
  • Test it: send the same request 2-3 times (and concurrently) and assert identical final state and side-effect counts

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 example DisableForUnsafeHttpMethods() in Microsoft.Extensions.Http.Resilience, and I design writes that need retries to be idempotent. My options are PUT to a client-generated id, conditional updates with If-Match so a stale retry fails with 412 instead of applying twice, an Idempotency-Key header 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."


Properties by method (RFC 9110)

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)

Making a write retry-safe

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate connects method semantics to real retry behaviour and can design idempotency into writes that need it.

Green flags

  • Explains why a timeout is ambiguous
  • Lists the layers that retry and the multiplication effect
  • Offers several techniques (client ids, unique constraints, idempotency keys, If-Match)
  • Mentions deduplicating side effects and testing concurrency

Red flags

  • "Just add retries" without regard to method
  • Check-then-insert deduplication
  • Thinks idempotent means identical responses

📚 Learn in depth

1. Why a timeout is ambiguous

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.

2. Who retries

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.

3. Idempotency is about effect

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.

4. Side effects

A request often does more than write a row: it publishes an event, sends an email, calls a payment provider. Deduplicate them too:

  • Write the event to an outbox in the same transaction as the row, so a deduplicated request publishes nothing new.
  • Forward the idempotency key to downstream providers that support it (most payment APIs do).
  • Consumers of events use an inbox table to drop duplicates, because brokers deliver at least once.

5. Testing idempotency

  • Sequential: send the same request three times; assert one row and one outbox message.
  • Concurrent: send two identical requests with Task.WhenAll; assert one succeeds and the other returns the stored result or 409, never two rows.
  • Chaos: drop the response after commit (a DelegatingHandler in tests) and let the client retry.

Try it yourself

  1. Write a WebApplicationFactory test that posts the same order three times and counts rows.
  2. Add a unique index on (CustomerId, ClientOrderRef) and map the duplicate-key DbUpdateException to a 200 with the existing order.
  3. Configure AddStandardResilienceHandler with and without DisableForUnsafeHttpMethods(), inject faults with a test handler, and log attempts.
  4. Change a PATCH from delta to absolute values and repeat it to confirm idempotency.

💻 Code

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());

⚠ Common mistakes

  • Mistake: Defining idempotent as "returns the same response". Why it is wrong: A repeated DELETE may return 404; what matters is the resulting state. Instead: Define and test it as the same effect on state.
  • Mistake: Retrying every failed request at every layer. Why it is wrong: Non-idempotent requests duplicate, and layered retries multiply load during an outage. Instead: Retry at one layer, only idempotent methods (or keyed POSTs), with backoff and jitter.
  • Mistake: Relying on a "check then insert" in application code as the only duplicate guard. Why it is wrong: Under READ COMMITTED two concurrent requests can both pass the check and both insert. A check-then-insert is only safe if the check takes a range lock (SERIALIZABLE or 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.
  • Mistake: Deduplicating the row but not side effects. Why it is wrong: The retry still sends the email or publishes the event twice. Instead: Use an outbox in the same transaction and forward keys downstream.
  • Mistake: Designing PATCH payloads as deltas (increment). Why it is wrong: Every repeat applies again. Instead: Send absolute values, or protect with If-Match.
  • Mistake: Assuming GET is safe because the code "only reads". Why it is wrong: Hidden writes (marking notifications read, generating reports) get triggered by prefetchers and retries. Instead: Move state changes to unsafe methods.
  • Mistake: Shipping idempotency with no telemetry. Why it is wrong: You can't tell a retry storm or a buggy client from normal traffic. Instead: Log and count replays and duplicate-key hits per endpoint and client, and alert on spikes.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency keys Why: Checks the mechanics of idempotency keys for POST
    How to answer

    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.

  2. When: Candidate mentions retries at multiple layers Why: Checks retry policy design: backoff, jitter and retry amplification
    How to answer

    Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.

    • What to retry: 5xx, 408, 429 (honour Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.
    • How: exponential backoff with jitter, so thousands of clients don't retry in lockstep. Cap the attempts, and keep the whole thing inside a total timeout.
    • Safety: retry only idempotent operations. For POST, use an idempotency key or disable retries for unsafe methods.

    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.

  3. When: Candidate mentions events or side effects being duplicated Why: Checks deduplication on the consumer side of messaging
    How to answer

    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:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    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.

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me