DataC# · TypeScript

Idempotency Key

Make a repeated request or message produce the same effect as the first one by deduplicating on a unique key and returning the stored result.

On this page
  1. Problem
  2. Context
  3. Solution
  4. Implementation
  5. Trade-offs
  6. Alternatives
  7. Anti-patterns
  8. Related lessons
  9. Interview questions

Problem

Networks lose responses, not just requests. A client that sends "charge 50 EUR" and gets a timeout cannot know whether the charge happened. If it retries, the customer may pay twice; if it does not, the order may never be paid. The same ambiguity exists for messages: brokers deliver at least once, so a consumer will eventually see the same OrderPlaced event twice.

Retries, redeliveries, double-clicks and replays are therefore normal, and any operation with side effects (creating records, sending emails, moving money) must be safe to perform more than once. HTTP PUT and DELETE are idempotent by definition when implemented correctly, but POST and most message handlers are not.

Context

Use this pattern when:

  • Clients or infrastructure retry requests after timeouts or errors.
  • Message consumers receive at-least-once deliveries from a broker or an outbox relay.
  • The operation has side effects that must not be duplicated: payments, orders, notifications.
  • A durable store is available to remember which keys were processed.

Solution

The client generates a unique idempotency key (a UUID) for each logical operation and sends it with every attempt, for example in an Idempotency-Key header. Messages carry a unique event id for the same purpose. The key identifies the intent, not the attempt, so retries reuse it.

The server records the key atomically before or together with the side effect, using a unique constraint so two concurrent attempts cannot both win. When the operation completes, it stores the response alongside the key. A later request with the same key returns the stored response without executing again; a concurrent request that finds the key still in progress gets a conflict and retries later.

Store a hash of the request body with the key and reject a reused key with a different payload, which catches client bugs. Keys expire after a retention window (Stripe-style APIs keep them for about 24 hours), long enough to cover any realistic retry.

How it works, step by step

  1. 1Client creates one key per logical operation and resends it on every retry.
  2. 2Server tries to insert the key with status "in progress"; the unique constraint rejects duplicates.
  3. 3If the key already exists and is complete, return the stored response.
  4. 4If it exists and is in progress, return 409 Conflict (or wait) so the client retries later.
  5. 5Otherwise perform the operation, store the response with the key, and return it.

Implementation

The C# example is ASP.NET Core minimal API middleware logic backed by EF Core and a unique key. The TypeScript example shows an idempotent message consumer (the inbox pattern) on PostgreSQL, where the dedup record and the side effect share a transaction.

C#Idempotent POST endpoint with EF Core
using Microsoft.EntityFrameworkCore;

public sealed class IdempotencyRecord
{
    public string Key { get; init; } = "";          // primary key => unique
    public string RequestHash { get; init; } = "";
    public int? StatusCode { get; set; }
    public string? ResponseBody { get; set; }
    public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow;
}

app.MapPost("/payments", async (HttpRequest http, PaymentRequest body, AppDbContext db, IPayments payments) =>
{
    var key = http.Headers["Idempotency-Key"].ToString();
    if (string.IsNullOrWhiteSpace(key)) return Results.BadRequest("Idempotency-Key header is required");

    var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(
        System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body)));

    var existing = await db.Idempotency.AsNoTracking().FirstOrDefaultAsync(r => r.Key == key);
    if (existing is not null)
    {
        if (existing.RequestHash != hash) return Results.UnprocessableEntity("Key reused with a different request");
        if (existing.StatusCode is null) return Results.Conflict("Request with this key is still in progress");
        return Results.Content(existing.ResponseBody!, "application/json", statusCode: existing.StatusCode);
    }

    var record = new IdempotencyRecord { Key = key, RequestHash = hash };
    db.Idempotency.Add(record);
    try
    {
        await db.SaveChangesAsync(); // unique key: only one concurrent attempt gets past here
    }
    catch (DbUpdateException)
    {
        return Results.Conflict("Request with this key is already being processed");
    }

    var result = await payments.ChargeAsync(body, key); // pass the key on to the PSP too
    record.StatusCode = StatusCodes.Status201Created;
    record.ResponseBody = System.Text.Json.JsonSerializer.Serialize(result);
    await db.SaveChangesAsync();

    return Results.Content(record.ResponseBody, "application/json", statusCode: record.StatusCode);
});

If the process crashes between charging and storing the response, the record stays "in progress". Passing the same key to the payment provider (most support idempotency keys) makes the eventual retry safe end to end; a cleanup job can expire stuck records.

TypeScriptIdempotent consumer with an inbox table
import pg from 'pg';

type OrderPlaced = { eventId: string; orderId: string; customerEmail: string };

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

/**
 * processed_events(event_id text primary key, processed_at timestamptz).
 * The dedup insert and the side effect commit together, so a redelivered
 * event is skipped and a failed attempt leaves no trace.
 */
export async function handleOrderPlaced(event: OrderPlaced): Promise<'processed' | 'duplicate'> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    const inserted = await client.query(
      'INSERT INTO processed_events (event_id, processed_at) VALUES ($1, now()) ON CONFLICT (event_id) DO NOTHING',
      [event.eventId],
    );
    if (inserted.rowCount === 0) {
      await client.query('ROLLBACK');
      return 'duplicate';
    }

    await client.query(
      'INSERT INTO loyalty_points (customer_email, order_id, points) VALUES ($1, $2, 10)',
      [event.customerEmail, event.orderId],
    );

    await client.query('COMMIT');
    return 'processed';
  } catch (error) {
    await client.query('ROLLBACK');
    throw error; // the broker redelivers; nothing was recorded
  } finally {
    client.release();
  }
}

This works because the side effect lives in the same database as the inbox. For external side effects (sending an email, calling an API), pass the event id on as that system's idempotency key or record the call's outcome before acknowledging.

In production

  • Generate keys on the client, per logical operation; a key generated on the server per attempt deduplicates nothing.
  • Enforce uniqueness in the database (primary key or unique index); check-then-insert in application code races under concurrency.
  • Scope keys per client or tenant so one customer cannot collide with or probe another's keys.
  • Expire keys after a window that comfortably covers client retry policies, and document it.
  • Natural idempotency is cheaper when available: SET status = shipped is idempotent, SET balance = balance - 50 is not.

Trade-offs

Benefits

  • Retries and redeliveries become safe, which is what makes retry and at-least-once messaging usable.
  • Clients get a definitive answer after ambiguous failures by simply retrying.
  • Effectively-once processing without distributed transactions.

Costs

  • Extra storage and a write per operation for the dedup records.
  • Handling the in-progress state, crashes mid-operation and key expiry adds complexity.
  • External side effects outside the local transaction still need their own idempotency.
  • Clients must be changed to generate and reuse keys correctly.

Alternatives

Naturally idempotent operations
Design writes as absolute state changes (set, upsert by business key, PUT) so repeating them has no further effect.
Conditional writes and versioning
Use optimistic concurrency (expected version or ETag) so a duplicate update is rejected because the version has already moved on.
Broker-level deduplication
Some brokers deduplicate within a window (SQS FIFO deduplication id, Kafka idempotent producer); helpful but limited in scope and time.

Anti-patterns

New key per retry
Generating the key inside the retry loop makes every attempt look new and defeats the purpose.
Check then act without a constraint
Two concurrent attempts both see "not processed" and both execute; only an atomic insert or unique index prevents this.
Marking processed before the side effect commits
If the side effect then fails, the record says done and the retry is skipped, losing the operation.
Ignoring payload mismatches
Returning the stored response for a reused key with a different body hides client bugs that send different operations under one key.

Interview questions

What does idempotent mean for an API?

Performing the operation once or many times with the same input leaves the system in the same state and, ideally, returns the same response. GET, PUT and DELETE are defined as idempotent in HTTP; POST is not, which is why APIs add idempotency keys to it.

How do you handle two concurrent requests with the same idempotency key?

Insert the key atomically with a unique constraint before doing the work. The first insert wins and proceeds; the second fails the constraint and receives a 409 Conflict or waits and then reads the stored result.

Is exactly-once delivery possible?

Not over an unreliable network in general: the sender cannot distinguish a lost message from a lost acknowledgement. Systems achieve effectively-once processing by combining at-least-once delivery with idempotent handling and deduplication.

How long should idempotency keys be stored?

Longer than any client will keep retrying the same operation, including offline mobile clients and queued jobs. Around 24 hours is common for APIs, while message inboxes often keep ids for days to cover replays and redrives.