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

📚 Interview question

Implement idempotency keys for a payments POST endpoint in ASP.NET Core. How does the Idempotency-Key header work, what do you store and for how long, how do you handle two requests with the same key arriving at the same time, a reused key with a different body, and a failure halfway through?

Implementing the Idempotency-Key pattern in ASP.NET Core 10 with SQL Server: key scope, request fingerprint, stored responses, concurrent duplicates, mismatched payloads, partial failures, expiry and the IETF draft's status codes.

Senior Coding Advanced aspnet-core ef-core idempotency idempotency-keys payments web-api

🎯 Key points

  • Client generates a unique key (UUID) per logical operation and resends it on every retry
  • Scope keys per client: unique index on (ClientId, Key)
  • Store a request fingerprint (hash of method, path, body); same key + different body = 422
  • Atomic claim: insert an in-progress row; a concurrent duplicate gets 409 Conflict (or waits)
  • Store the final status and body; replays return the stored response, not a re-execution
  • Commit the business change and the idempotency record in one transaction where possible
  • Expire keys after a published window (often 24 h) and clean up in a background job
  • Idempotency-Key is an IETF httpapi Internet-Draft, not yet an RFC (late 2026)

⏱ 30-second answer

The client sends a unique Idempotency-Key (usually a UUID) with a non-idempotent request and reuses it on every retry. The server atomically claims the key with a unique constraint on (client, key), stores a fingerprint of the request, executes the operation and saves the response. A retry with the same key and body gets the stored response replayed; a request still in progress gets 409 Conflict; the same key with a different body gets 422. Ideally the business write and the idempotency record commit in one transaction, so a crash can't leave a charge without a record. Keys expire after a published window, often 24 hours. The trade-off is an extra write per request and storage, in exchange for making POST safe to retry.

🗣 Full answer (senior)

How I would answer this in an interview

"An idempotency key turns a non-idempotent POST into something a client can retry safely. The client creates a key per logical operation, say a UUID when the user presses Pay, and sends it in the Idempotency-Key header on the first attempt and every retry. On the server, the first request with that key does the work and saves the response; every later request with the same key gets that saved response back without doing the work again. The header comes from an IETF httpapi draft, which still isn't an RFC, but Stripe, Adyen and others have used the pattern for years.

The interesting parts are the edge cases. Two copies can arrive at the same moment, so the claim must be atomic: I insert a row with status InProgress and a unique index on client id plus key, and whoever loses the insert gets 409 Conflict and retries later. I store a hash of the method, path and body; if the same key comes back with a different body, that's a client bug and I return 422 rather than silently replaying an unrelated response. For example, at [company] we [added this to the payments API after a mobile client double-charged [N] customers on flaky networks]; duplicates dropped to [zero] in the following months.

The mistake I see is storing the key in a cache after the work is done. If the process crashes between charging and saving the record, the retry charges again. Where I can, I write the business change and the idempotency record in the same database transaction. When the work calls an external provider, I pass my own idempotency key on to the provider too, so the whole chain is idempotent, not just my front door."


The record

Column Purpose
ClientId + Key Unique index: keys are scoped per client, never global
RequestHash SHA-256 of method, path and canonical body: detects key reuse with a different payload
Status InProgress / Completed
ResponseStatus, ResponseBody, ResponseHeaders (Location) Replayed verbatim on retries
CreatedAt, ExpiresAt Retention window and clean-up

Outcomes

Situation Response
New key Execute, store, return result
Same key, same fingerprint, completed Replay stored status and body
Same key, request still in progress 409 Conflict (the draft's suggestion) with Retry-After
Same key, different fingerprint 422 Unprocessable Content
Key missing on an endpoint that requires it 400 Bad Request with ProblemDetails
Operation failed with 4xx Store and replay it (the request is bad); for 5xx, release the key so the client can retry

Production example

On a [payments API] handling about [40,000] payments a day, mobile clients on poor connections retried after timeouts and roughly [0.1%] of payments were duplicated. Requiring Idempotency-Key, recording it in the same transaction as the payment, and forwarding it to the payment provider removed duplicates entirely; the extra insert added about 2 ms to p95.

🔍 What the interviewer is checking

Checks whether the candidate can implement idempotency correctly under concurrency and failure, not just describe the header.

Green flags

  • Atomic claim with a unique constraint, not check-then-insert
  • Fingerprint and 422 on mismatched reuse; 409 while in progress
  • Same-transaction storage or downstream key forwarding
  • Scopes keys per client and defines expiry
  • Knows the header is a draft standard and widely used

Red flags

  • "Store the key in memory" or check-then-insert
  • Caches the key after the side effect in a separate store
  • Treats idempotency as a client concern only

📚 Learn in depth

1. The problem

client --POST /payments--> API --charge--> provider   (succeeds)
client <----- timeout ----- (response lost)
client --POST /payments--> API --charge--> provider   (charged twice)

The client can't tell "never arrived" from "done but response lost". Only the server can de-duplicate, and it needs a client-supplied identity for the operation to do it.

2. Why a client-generated key

The server can't recognise a duplicate from the body alone (a customer may legitimately pay $20 twice). The key carries intent: "this is the same attempt". It must be created before the first attempt and persisted by the client across retries (and, for mobile, across app restarts if possible).

3. The state machine

        claim (INSERT, unique index)
  none -------------------------------> InProgress
                                          |  execute
                     +--------------------+-------------------+
                     | success / 4xx                          | 5xx / crash
                     v                                        v
                 Completed (response stored)             released (row deleted)
                     |                                   or left to lease expiry
                     | retries replay stored response

A crash while InProgress leaves a stuck row. Give the row a lease (LockedUntil); a retry after the lease expires may take it over. This is safe only if the business operation itself is protected, which is why the same transaction (or a downstream idempotency key) matters.

4. Same transaction vs separate store

  • Same SQL transaction (claim, business write, response all commit together): strongest. A crash rolls back everything and the retry starts clean.
  • Separate store (Redis): faster, but there is always a window between the business commit and the record write. Acceptable for low-stakes operations.
  • External side effects (payment providers, emails) can't join your transaction: forward an idempotency key (most providers accept one), or use the outbox pattern so the side effect is sent exactly once from a committed record.

5. Fingerprinting

Hash a canonical form: method + route template values + body bytes. JSON whitespace or property order differences may produce different hashes for the "same" request; most implementations hash the raw body and document that clients must resend identical bytes.

6. Expiry

Keys need a retention window long enough to cover realistic retries (minutes to hours) and short enough to bound storage. 24 hours is common (Stripe documents 24 h). A background job deletes expired rows in batches.

7. Standards status

draft-ietf-httpapi-idempotency-key-header (httpapi working group, Standards Track) has had several revisions, with -07 expiring in April 2026 and a -08 in 2026; it is not an RFC as of November 2026. It suggests 400 for a missing key, 409 for a request still being processed and 422 for a key reused with a different payload.

Try it yourself

  1. Run the code example, POST twice with the same key and body, and confirm the second response is identical, including the Location header, and only one payment row exists.
  2. Fire 20 concurrent requests with the same key (xargs -P 20 curl ...); expect one 201 and 409s or replays.
  3. Send the same key with a different amount and expect 422.
  4. Throw an exception after the payment insert but before commit and confirm a retry succeeds without a duplicate.
  5. Check the unique index with SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('IdempotencyRecords').

💻 Code

An endpoint filter plus a SQL-backed record, with the claim, business write and stored response in one transaction:

using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Payments;

public sealed class IdempotencyRecord
{
    public required string ClientId { get; init; }
    public required string Key { get; init; }
    public required string RequestHash { get; init; }
    public int? ResponseStatus { get; set; }
    public string? ResponseBody { get; set; }
    public string? Location { get; set; }
    public DateTimeOffset CreatedAt { get; init; }
    public DateTimeOffset ExpiresAt { get; init; }
}

public sealed record CreatePayment(string AccountId, decimal Amount, string Currency);
public sealed record Payment(Guid Id, string AccountId, decimal Amount, string Currency);

public sealed class PaymentsDb(DbContextOptions<PaymentsDb> options) : DbContext(options)
{
    public DbSet<Payment> Payments => Set<Payment>();
    public DbSet<IdempotencyRecord> Idempotency => Set<IdempotencyRecord>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Payment>().Property(p => p.Amount).HasPrecision(19, 4);
        b.Entity<IdempotencyRecord>().HasKey(r => new { r.ClientId, r.Key }); // the atomic claim
    }
}

public static class PaymentEndpoints
{
    public static void MapPayments(this WebApplication app) =>
        app.MapPost("/payments", CreateAsync).RequireAuthorization();

    private static async Task<IResult> CreateAsync(
        CreatePayment request, HttpContext http, PaymentsDb db, TimeProvider clock, CancellationToken ct)
    {
        if (!http.Request.Headers.TryGetValue("Idempotency-Key", out var keyValues)
            || string.IsNullOrWhiteSpace(keyValues) || keyValues.ToString().Length > 64)
            return Results.Problem("An Idempotency-Key header (max 64 chars) is required.", statusCode: 400);

        string clientId = http.User.FindFirst("client_id")?.Value ?? throw new InvalidOperationException();
        string key = keyValues.ToString();
        string hash = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request)));

        var existing = await db.Idempotency.AsNoTracking()
            .SingleOrDefaultAsync(r => r.ClientId == clientId && r.Key == key, ct);
        if (existing is not null) return Replay(existing, hash, http);

        await using var tx = await db.Database.BeginTransactionAsync(ct);
        var now = clock.GetUtcNow();
        var record = new IdempotencyRecord
        {
            ClientId = clientId, Key = key, RequestHash = hash,
            CreatedAt = now, ExpiresAt = now.AddHours(24)
        };
        db.Idempotency.Add(record);
        try
        {
            await db.SaveChangesAsync(ct); // claim: the PK insert blocks a concurrent twin until we commit
        }
        catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
        {
            return Results.Problem("A request with this Idempotency-Key is already being processed.", statusCode: 409);
        }

        var payment = new Payment(Guid.CreateVersion7(), request.AccountId, request.Amount, request.Currency);
        db.Payments.Add(payment);
        // A real provider call goes here, forwarding $"{clientId}:{key}" as the provider's idempotency key.

        record.ResponseStatus = StatusCodes.Status201Created;
        record.ResponseBody = JsonSerializer.Serialize(payment);
        record.Location = $"/payments/{payment.Id}";
        await db.SaveChangesAsync(ct);
        await tx.CommitAsync(ct); // payment and stored response commit together

        return Results.Created(record.Location, payment);
    }

    private static IResult Replay(IdempotencyRecord r, string hash, HttpContext http)
    {
        if (r.RequestHash != hash)
            return Results.Problem("This Idempotency-Key was used with a different request body.", statusCode: 422);

        http.Response.Headers["Idempotent-Replayed"] = "true"; // helps clients and support see what happened
        if (r.Location is not null) http.Response.Headers.Location = r.Location;
        return Results.Content(r.ResponseBody ?? "", "application/json", statusCode: r.ResponseStatus ?? 200);
    }
}

Clean-up job, run hourly:

DELETE TOP (5000) FROM dbo.IdempotencyRecords WHERE ExpiresAt < SYSUTCDATETIME();

⚠ Common mistakes

  • Mistake: Checking for the key, then inserting it, as two separate steps. Why it is wrong: two concurrent duplicates both pass the check and both execute. Instead: claim atomically with a unique index and handle the violation.
  • Mistake: Writing the idempotency record after the business commit, in a different store. Why it is wrong: a crash in between leaves a payment with no record, and the retry pays again. Instead: commit both in one transaction, or forward the key to the downstream system.
  • Mistake: Global keys. Why it is wrong: two clients that happen to choose the same key see each other's responses, which is a data leak. Instead: scope by authenticated client id.
  • Mistake: Replaying a stored response when the body differs. Why it is wrong: the client gets a response for a different operation and believes their new request succeeded. Instead: compare a fingerprint and return 422.
  • Mistake: Storing 5xx results permanently. Why it is wrong: a transient failure becomes permanent for that key. Instead: release the key (or don't store) on server errors; store and replay 2xx and 4xx.
  • Mistake: The client generating a new key per retry. Why it is wrong: every retry looks like a new operation. Instead: one key per user intent, persisted across retries.
  • Mistake: No expiry. Why it is wrong: the table grows without bound. Instead: publish a retention window and delete expired rows in batches.

🏛 Senior insight: trade-offs

Idempotency keys are only as strong as the weakest link in the chain. Making my endpoint idempotent is pointless if the payment provider call behind it isn't, so I check that every side effect is either in my transaction, behind the outbox, or protected by a key the downstream system honours. I also prefer a natural idempotency key when the domain has one (an invoice number paid once, an order id) because it doesn't depend on client discipline.

The cost is one indexed insert and a stored response per request, roughly 1-3 ms and a few hundred bytes. For payments that is obviously worth it; for a 'like' button it isn't.

Option When it fits Cost When not to
Idempotency-Key header + SQL record in the same transaction Payments, orders, anything with money Extra insert, storage, clean-up job Naturally idempotent PUT/DELETE
Natural business key (unique constraint on invoice id) The domain already identifies the operation Schema constraint only Operations that may legitimately repeat
Redis-backed key store High-volume, low-stakes operations Small window for duplicates on crash Money movement
Client-side de-duplication only Never on its own - Always insufficient

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions de-duplicating messages or the outbox Why: Checks the related inbox pattern for idempotent message consumers
    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.

  2. When: Candidate explains why POST isn't naturally idempotent Why: Checks the simpler framing of making POST safe to retry
    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.

  3. When: Candidate mentions crashes during commit Why: Checks the commit-in-doubt case with retrying execution strategies
    How to answer

    If the connection drops during COMMIT, the client can't know whether the transaction committed, and a blind retry may apply the work twice. Make the unit idempotent (a unique request id checked at the start and enforced by a unique index), or use ExecuteInTransactionAsync with a verifySucceeded delegate that queries the database to see if the work landed before retrying. Clear the change tracker between attempts so stale Added entities aren't re-sent. Only transient errors should be retried: let permanent failures (constraint violations, login failures) surface immediately. Log each retry and its outcome so an in-doubt commit can be traced and reconciled later.

🛠 Real-world problems: how you handle them

Mobile retries double-charge customers
Situation
A [payments API] behind [API Management] serving a [mobile banking app], about [40,000] payments a day. Mobile clients retry a POST when a request times out.
Signals
Customer complaints about duplicate charges, support tickets [N per week], reconciliation finding pairs of identical payments [1-3 seconds] apart, Application Insights showing client timeouts on slow mobile networks.
Investigation
Matched duplicate payment pairs in SQL by account, amount and timestamp; traced both requests in Application Insights and found the first request succeeded after the client's timeout; confirmed the API had no de-duplication and the provider call had no idempotency key.
Resolution
Immediately refunded duplicates and added a temporary unique constraint on (account, amount, minute) as a blunt guard. Then required Idempotency-Key on POST /payments, stored the record and the payment in one transaction, forwarded the key to the provider and coordinated a mobile release that persists the key per payment attempt.
Prevention
Integration tests firing concurrent duplicates, a nightly reconciliation alert for duplicate pairs, API docs and SDK updated to generate keys, and a checklist item that every money-moving endpoint requires a key.

How to tell it (STAR)

**S:** At [company], customers on poor mobile connections were occasionally charged twice, about [N] a week. **T:** I was asked to stop duplicates without breaking the mobile app's retry behaviour. **A:** I traced duplicates to retries after client timeouts where the first request had actually succeeded. I designed Idempotency-Key support: an atomic claim with a unique index per client and key, a request hash to catch misuse, the stored response committed in the same transaction as the payment, and the key forwarded to our provider. I worked with the mobile team so the key was created once per payment attempt. **R:** Duplicates went to [zero] over the following [six months], p95 rose by only about [2 ms], and support tickets on double charges stopped.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me