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

📚 Interview question

Why is idempotency called the core tool of distributed systems? Explain naturally idempotent operations versus deduplication, how idempotency keys and dedup storage work in a .NET service, and what goes wrong when two copies of the same request arrive at the same time.

Idempotency as the answer to retries, duplicates and at-least-once delivery: naturally idempotent operations, idempotency keys, dedup tables with unique constraints in the same transaction as the effect, concurrent duplicates, retention and side effects outside the database.

Mid-Level Theory Intermediate deduplication distributed-systems ef-core idempotency idempotency-keys messaging

🎯 Key points

  • Idempotent: performing the operation once or many times leaves the same state, so duplicates can't corrupt it
  • Needed because retries, timeouts and at-least-once delivery all produce duplicates
  • Naturally idempotent: set-state updates, PUT of full state, upsert or create-if-not-exists by natural key, delete by id, conditional updates (only if version = n)
  • Deduplication: a unique operation id (idempotency key or message id) recorded with a unique constraint
  • Record the key and apply the effect in ONE transaction, or a crash between them breaks it
  • Concurrent duplicates: the unique index (or a Cosmos DB create with id = key returning 409) rejects the second; return the stored result
  • Retention covers the longest duplicate window: 24 hours for HTTP retries, queue TTL plus dead-letter replays for messages, months for payments with chargebacks and reconciliation
  • Side effects outside the database (emails, third-party calls) need their own key passed downstream

⏱ 30-second answer

An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

🗣 Full answer (senior)

How I would answer this in an interview

"Idempotency means the effect of doing something twice is the same as doing it once. It's the core tool of distributed systems because duplicates are normal, not exceptional. A client times out and retries without knowing whether the first call worked. Service Bus and Kafka deliver at least once, so a handler can get the same message again after a lock expires or a rebalance. Users double-click Pay. You can't stop duplicates arriving; you can only make them harmless.

There are two ways to get there. The cheap way is to design operations that are naturally idempotent: 'set the order status to Shipped' instead of 'advance the status', a PUT that replaces the whole resource, an upsert keyed by a natural id, balance = 120 rather than balance += 20 where that's acceptable. When that isn't possible, like charging a card or creating an order, I use deduplication. The caller supplies a unique key, the Idempotency-Key header or the message id, and the service inserts that key into a table with a unique index, in the same EF Core transaction as the business change. If two copies arrive at the same moment, one insert wins and the other hits the unique constraint, which I catch and turn into 'return the stored result'. If the process crashes halfway, the transaction rolls back both the key and the change, so a retry starts clean.

The mistake I see is checking 'have I seen this key?' with a SELECT and then inserting, which races under concurrency, or writing the key in a separate transaction from the change. The unique constraint and the single transaction are what make it correct."


Two routes to idempotency

Route Examples Cost Limits
Naturally idempotent Set state, PUT full resource, upsert by natural key, delete by id None Doesn't work for 'add', 'charge', 'send'
Deduplication by key Idempotency-Key on POST, message id in a consumer, client-generated order id Key table, retention job Key must be stable across retries

Where duplicates come from

Source Why it duplicates
HTTP client retry after a timeout First attempt may have succeeded (partial failure)
Broker redelivery (Service Bus, RabbitMQ, SQS) Lock or visibility timeout expired before completion
Kafka consumer rebalance Offsets not yet committed get reprocessed
Outbox relay Publishes, crashes before marking sent, publishes again
Users Double-click, refresh, back button

Production example

A payments consumer on Azure Service Bus took up to 70 seconds per message during a provider slowdown, longer than the 60-second lock duration. Messages were redelivered while the first attempt was still running, and about 1 in 800 payments was charged twice. Adding an inbox table with a unique index on (MessageId, Consumer), written in the same transaction as the payment record, and passing the order id as the provider's idempotency key, removed duplicates entirely; the extra insert added under 2 ms per message.

🔍 What the interviewer is checking

Checks whether the candidate treats duplicates as normal and can implement idempotency correctly under concurrency and crashes.

Green flags

  • Names the sources of duplicates: retries, at-least-once delivery, rebalances, users.
  • Distinguishes naturally idempotent designs from deduplication.
  • Insists on a unique constraint in the same transaction as the effect.
  • Thinks about retention and downstream side effects.

Red flags

  • Check-then-insert or an in-memory 'seen' set on one instance.
  • Believes broker features give exactly-once processing.
  • No answer for external side effects.

📚 Learn in depth

1. Idempotency, precisely

An operation f is idempotent if f(f(x)) = f(x): applying it again changes nothing. In services we care about the observable effect: rows written, money moved, emails sent. A response may differ (201 first time, 200 with the same body afterwards) as long as the effect doesn't repeat.

2. Why duplicates are unavoidable

Client            API                 DB
  | -- POST (key K) -->|                 |
  |                    | -- INSERT ----->| commit
  |      X <-- 201 ----|                 |   (response lost)
  | -- POST (key K) -->|                 |   retry after timeout
  |                    | -- INSERT K --->| unique violation -> return stored 201

With messaging, at-least-once delivery means a message is redelivered whenever the consumer fails to settle it in time: a lock expiry in Service Bus, a visibility timeout in SQS, an uncommitted offset in Kafka.

3. The dedup table pattern

ProcessedOperations
  OperationKey   nvarchar(100)  -- idempotency key or message id
  Consumer       nvarchar(100)  -- different handlers may process the same message
  ResultJson     nvarchar(max)  -- what to return to a repeated caller
  CreatedUtc     datetime2
  PRIMARY KEY (OperationKey, Consumer)

The algorithm:

  1. Begin a transaction.
  2. Insert the key row.
  3. Apply the business change.
  4. Commit.

If two requests with the same key race, the database's unique index serialises them: one commits, the other gets error 2627 or 2601 (in EF Core, a DbUpdateException wrapping a SqlException). The loser then reads the stored result. If the process crashes before commit, nothing is recorded and a retry works normally.

4. Why check-then-insert is wrong

Request A: SELECT key K -> not found
Request B: SELECT key K -> not found
Request A: INSERT order ... commit
Request B: INSERT order ... commit   <- duplicate

Only a constraint (or a lock) makes the check and the write atomic. Under read committed snapshot, two readers both see 'not found'.

5. Keys: who generates them and how long to keep them

  • The caller generates the key from the business intent (order id, payment attempt id), not per HTTP attempt.
  • A reused key with a different payload should be rejected (store a hash of the request and return 422 or 409).
  • Retention must cover the longest duplicate window: HTTP retry policy, queue TTL, dead-letter replays. Delete old keys in batches with a scheduled job.

6. Effects outside your transaction

Your database transaction can't include an HTTP call to a payment provider or an email send. Options: pass your key downstream as the provider's idempotency key; or write the intent to an outbox in the same transaction and have one worker perform the external call with its own dedup.

Try it yourself

  1. Build the dedup table with EF Core and a composite primary key; fire 20 parallel requests with the same key using Task.WhenAll and count the orders created.
  2. Replace the unique index with a check-then-insert and repeat; count duplicates.
  3. Kill the process (Environment.FailFast) between inserting the key and the order, in both the one-transaction and two-transaction versions, and compare what a retry does.
  4. Write the clean-up job that deletes keys older than 7 days in batches of 5,000.

💻 Code

Idempotent order creation with a dedup table: the key row and the order are saved in one EF Core transaction, and a concurrent duplicate is caught by the primary key.

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Orders;

public sealed class ProcessedOperation
{
    public required string OperationKey { get; init; }
    public required string Consumer { get; init; }
    public required string ResultJson { get; init; }
    public DateTime CreatedUtc { get; init; } = DateTime.UtcNow;
}

public sealed class Order
{
    public Guid Id { get; init; }
    public required string CustomerId { get; init; }
    public decimal Total { get; init; }
}

public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<ProcessedOperation> ProcessedOperations => Set<ProcessedOperation>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<ProcessedOperation>().HasKey(p => new { p.OperationKey, p.Consumer });
}

public sealed record CreateOrder(string CustomerId, decimal Total);
public sealed record OrderCreated(Guid OrderId);

public sealed class CreateOrderHandler(OrdersDb db)
{
    private const string Consumer = "create-order";

    public async Task<OrderCreated> HandleAsync(string idempotencyKey, CreateOrder cmd, CancellationToken ct)
    {
        var order = new Order { Id = Guid.NewGuid(), CustomerId = cmd.CustomerId, Total = cmd.Total };
        var result = new OrderCreated(order.Id);

        db.Orders.Add(order);
        db.ProcessedOperations.Add(new ProcessedOperation
        {
            OperationKey = idempotencyKey,
            Consumer = Consumer,
            ResultJson = System.Text.Json.JsonSerializer.Serialize(result)
        });

        try
        {
            await db.SaveChangesAsync(ct); // one implicit transaction: key + order, or neither
            return result;
        }
        catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
        {
            // A duplicate (possibly concurrent) already committed: return ITS result
            db.ChangeTracker.Clear();
            var existing = await db.ProcessedOperations.AsNoTracking()
                .SingleAsync(p => p.OperationKey == idempotencyKey && p.Consumer == Consumer, ct);
            return System.Text.Json.JsonSerializer.Deserialize<OrderCreated>(existing.ResultJson)!;
        }
    }
}

⚠ Common mistakes

  • Mistake: Check-then-insert (SELECT the key, then insert). Why it is wrong: two concurrent duplicates both see 'not found' and both proceed. Instead: rely on a unique constraint and catch the violation.
  • Mistake: Saving the dedup key and the business change in separate transactions. Why it is wrong: a crash between them either loses the change forever or repeats it. Instead: one transaction for both.
  • Mistake: Generating a new idempotency key per attempt. Why it is wrong: every retry looks new. Instead: derive the key from the business operation and reuse it.
  • Mistake: Thinking Service Bus duplicate detection makes consumers idempotent. Why it is wrong: it only drops duplicate sends within its window; redeliveries to consumers still happen. Instead: make every consumer idempotent.
  • Mistake: Keeping keys for a few minutes. Why it is wrong: redeliveries and dead-letter replays can arrive days later. Instead: retain keys for the longest duplicate window.
  • Mistake: Deduplicating in the database but calling an external API before commit. Why it is wrong: the external effect repeats on every retry. Instead: pass the key downstream or move the call behind an outbox.
  • Mistake: Accepting a reused key with a different body. Why it is wrong: the client gets a result for a request it didn't send. Instead: store a request hash and reject mismatches.

🏛 Senior insight: trade-offs

Idempotency has to go all the way down. Deduplicating in my database doesn't stop my handler calling the payment provider twice if the provider call happens before my transaction commits. So the key flows downstream: my idempotency key becomes the provider's idempotency key, and the email service gets a dedup id too. Where a downstream system has no idempotency support, I record intent first (an outbox row) and make the external call from a single, deduplicated worker.

Beyond SQL. The same idea works without relational constraints, as long as the store gives you an atomic 'insert if absent':

  • Cosmos DB: create the dedup document with id = the key in the same logical partition as the business document, and write both in a transactional batch; a duplicate create returns 409 Conflict.
  • Redis: SET key value NX EX 86400 claims a key atomically. Good for short windows and cheap pre-checks, but it is not in the same transaction as your database write, so treat it as an optimisation, not the source of truth.
  • Kafka: the idempotent producer (enable.idempotence, the default in current clients) removes duplicate writes caused by producer retries; consumers still need their own dedup or idempotent writes, because rebalances replay uncommitted offsets.
  • Service Bus: duplicate detection drops repeated sends with the same MessageId within a configured window; consumers still see redeliveries after lock expiry.

Retention by context. Keys are only useful while a duplicate can still arrive. HTTP retries: 24 hours is typical. Messages: the queue's time-to-live plus however long you might replay dead letters, often 7–14 days. Payments: keep the operation record (not necessarily the hot dedup row) for as long as chargebacks and reconciliation can reference it, which for card payments is months, and archive rather than delete.

Option When it fits Cost When not to
Design it naturally idempotent Updates expressible as 'set state' or conditional writes None Counters, charges, sends
Dedup table in the same transaction Writes to your own database One insert, retention job Effects outside your database
Downstream idempotency key Payments, third-party APIs Provider support needed Provider has no key support (use outbox + single worker)
Broker duplicate detection Duplicate sends within a window Only covers the send side Never a replacement for consumer idempotency

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency keys on an API. Why: Checks the HTTP side: Idempotency-Key header, concurrency and payload mismatch.
    How to 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.

  2. When: Candidate mentions message redelivery or at-least-once delivery. Why: Checks the messaging side: an inbox for Service Bus 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.

  3. When: Candidate mentions retries after timeouts. Why: Checks the root cause: why a caller can't know whether its request worked.
    How to answer

    Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.

🛠 Real-world problems: how you handle them

Service Bus lock expiry charges customers twice
Situation
A payments consumer processed [n] messages an hour from an Azure Service Bus queue with a 60-second lock duration, calling a card provider and writing to Azure SQL.
Signals
Finance reconciliation showed about [1 in 800] payments charged twice; Service Bus metrics showed rising delivery counts; Application Insights traces showed two handler executions for the same MessageId seconds apart.
Investigation
Compared handler durations with the lock duration and saw provider calls taking up to 70 seconds during a slowdown, so locks expired and messages were redelivered while the first attempt was still running; confirmed the handler had no dedup and generated a fresh provider key per attempt.
Resolution
Immediate: raised MaxAutoLockRenewalDuration and refunded duplicates. Real fix: an inbox table keyed on (MessageId, Consumer) written in the same transaction as the payment record, and the order id passed as the provider's idempotency key.
Prevention
A test that delivers the same message twice concurrently and asserts one charge; an alert on delivery count above 3; idempotency added to the handler review checklist.

How to tell it (STAR)

**S:** Our [payments consumer] was charging roughly [1 in 800] customers twice during a provider slowdown. **T:** I owned the fix. **A:** I matched duplicate MessageIds in Application Insights to lock expiries, then added an inbox table in the same transaction as the payment and passed the order id downstream as the provider's idempotency key. **R:** Duplicate charges went to zero, the extra insert cost under [2 ms] per message, and we refunded [n] affected customers within a day.

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me