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

📚 Interview question

Explain message delivery guarantees: at-most-once, at-least-once and exactly-once. Why do people call exactly-once delivery a myth, what do Kafka transactions and Service Bus duplicate detection really give you, and how do you get effectively-once processing in a .NET consumer?

Covers at-most-once and at-least-once delivery, where duplicates come from, why end-to-end exactly-once delivery is impossible over an unreliable network, what broker features (Kafka idempotent producer and transactions, Service Bus duplicate detection, SQS FIFO dedup) actually guarantee, and how idempotent consumers deliver effectively-once processing.

Mid-Level Theory Intermediate delivery-guarantees distributed-systems exactly-once idempotency inbox-pattern messaging

🎯 Key points

  • At-most-once: settle before processing (or receive-and-delete); a crash loses the message
  • At-least-once: settle after processing; a crash, lock expiry, network drop or broker failover redelivers, so duplicates happen
  • Exactly-once delivery is impossible end to end: the ack can be lost after the work is done (Two Generals)
  • Kafka idempotent producer and transactions: exactly-once only for read-process-write inside Kafka, never across an external database
  • Service Bus duplicate detection drops resends with the same MessageId inside the window (default 10 min, max 7 days); SQS FIFO dedups for 5 minutes
  • Effectively-once = at-least-once delivery + idempotent consumer (natural idempotency or inbox table in the same transaction)
  • Transient faults: retry with backoff, then abandon so the broker redelivers; dead-letter after MaxDeliveryCount
  • Side effects outside your database (emails, payments) need idempotency keys at the provider

⏱ 30-second answer

At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.

Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".

  • Kafka transactions give exactly-once only for read-process-write within Kafka.
  • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.

🗣 Full answer (senior)

How I would answer this in an interview

"The guarantee depends on when the consumer acknowledges relative to doing the work. If I acknowledge first and then process, which is receive-and-delete in Service Bus or auto-commit before processing in Kafka, a crash in the middle loses the message: that is at-most-once, fine for metrics, wrong for payments. If I process first and then acknowledge, a crash after the database commit but before the complete means the broker redelivers: that is at-least-once, and it is what I use for anything that matters. Duplicates also come from producers retrying a send after a timeout, from lock expiry when a handler is slow, and from Kafka rebalances.

Exactly-once delivery is a myth in the sense that no broker can promise your handler runs once, because the acknowledgement travels over the same unreliable network; it is the Two Generals problem. Vendors use the phrase for narrower things. Kafka's idempotent producer and transactions give exactly-once for a consume-transform-produce loop where input offsets and output records commit atomically inside Kafka; the moment you write to SQL Server or call Stripe, you are back to at-least-once. Service Bus duplicate detection remembers MessageIds for a window, default ten minutes and up to seven days, and silently drops a resend; that protects against producer retries, not against your handler running twice.

So what I build is effectively-once processing. For example, at [company] our [invoice consumer] used an inbox table with a unique key on (MessageId, Consumer), inserted in the same EF Core transaction as the invoice, and a duplicate simply hit the unique constraint and was completed as a no-op; [duplicate invoices went from a handful a week to zero]. For external side effects I pass an idempotency key, such as Stripe's Idempotency-Key, so the provider dedups too."


The three guarantees

Guarantee How you get it Failure behaviour Use for
At-most-once Ack before processing; receive-and-delete; fire-and-forget send Loss on crash Telemetry, cache invalidation hints
At-least-once Ack after processing; producer retries Duplicates on crash, timeout, lock expiry Everything business-critical
Exactly-once (end to end) Not achievable across independent systems n/a Use effectively-once instead

Where duplicates come from

Producer         Broker              Consumer            DB
   |--send m1---->|                     |                 |
   |  (ack lost)  |                     |                 |
   |--retry m1--->|  (duplicate #1: producer retry)      |
   |              |--m1 (lock 30s)----->|                 |
   |              |                     |--INSERT-------->| commit
   |              |                     X crash before Complete
   |              |--m1 again---------->|  (duplicate #2: redelivery)

What the vendor features really guarantee

Feature Guarantees Does not guarantee
Kafka idempotent producer (EnableIdempotence) No duplicate writes from producer retries to a partition Consumer-side duplicates
Kafka transactions + read_committed Atomic consume-process-produce within Kafka Writes to external databases or APIs
Service Bus duplicate detection Drops a resend with the same MessageId inside the window Handler running twice after lock loss
SQS FIFO dedup Drops a duplicate within 5 minutes by dedup id or content hash Redelivery after visibility timeout

Making the consumer idempotent

Technique How When
Natural idempotency UPDATE ... SET Status = 'Paid' WHERE Id = @id; upsert by business key State-setting operations
Inbox / dedup table Insert (MessageId, Consumer) with a unique key in the same transaction as the change Increments, inserts, anything not naturally idempotent
Version check Apply only if event.Version == current + 1 Ordered entity updates
Provider idempotency key Pass a stable key to Stripe, email provider External side effects

Production example

A loyalty service credited points on OrderPaid. During a Service Bus throttling incident, handlers exceeded the 30-second lock, and about 0.4% of messages were processed twice, over-crediting roughly 3,100 customers. Adding an inbox table checked in the same transaction, plus lock renewal, brought duplicates to zero at a cost of one extra indexed insert (about 2 ms) per message.

🔍 What the interviewer is checking

Checks the candidate understands why duplicates are unavoidable and can design consumers that produce correct results anyway.

Green flags

  • Ties the guarantee to ack-before versus ack-after processing
  • Explains why exactly-once delivery can't be guaranteed end to end
  • Knows the real scope of Kafka EOS and Service Bus duplicate detection
  • Describes an inbox with a unique key in the same transaction

Red flags

  • Claims a broker setting gives exactly-once processing
  • Dedups with a check-then-act race
  • Completes messages before the work is committed

📚 Learn in depth

1. Why it comes down to the ack

A consumer does two things: the work and the acknowledgement. They can't be atomic across two systems (your DB and the broker) without a distributed transaction. So one of them must happen first:

Ack first:   [ack] ---- crash ---- [work]   -> message lost      (at-most-once)
Work first:  [work] ---- crash ---- [ack]   -> message redelivered (at-least-once)

There is no third ordering. That is the root of the "myth".

2. The Two Generals problem

Two parties communicating over a lossy channel can't reach certain agreement that a message was received: every confirmation needs its own confirmation. A broker that hasn't heard "complete" can't know whether you processed the message. It must choose: redeliver (risking duplicates) or not (risking loss).

3. How Service Bus settles messages

  • Peek-lock: the message is locked for LockDuration (default 30 s, max 5 min). CompleteMessageAsync removes it; AbandonMessageAsync releases it and increments DeliveryCount; when DeliveryCount exceeds MaxDeliveryCount (default 10) it goes to the dead-letter queue.
  • ServiceBusProcessor renews locks automatically up to MaxAutoLockRenewalDuration (default 5 min). A handler that runs longer than that loses the lock and the message is redelivered while the first run continues: a guaranteed duplicate.
  • Duplicate detection keeps a history of MessageIds; a send with a seen id inside the window is accepted and dropped. It must be enabled at creation time.

4. Kafka's exactly-once semantics (EOS)

  • Idempotent producer: each producer gets an id and sequence numbers per partition; the broker rejects a duplicate sequence. Default on in recent clients.
  • Transactions: the producer writes output records and the consumer's offsets in one transaction (SendOffsetsToTransaction), then commits. Consumers with IsolationLevel.ReadCommitted see only committed data.
  • The scope is Kafka-to-Kafka. If the step writes to SQL Server, a crash between the SQL commit and the Kafka commit replays the input.

5. The inbox pattern in one transaction

BEGIN TRAN
  INSERT InboxMessages (MessageId, Consumer, ProcessedAt)   -- unique key
  UPDATE Accounts SET Points = Points + 50 WHERE Id = @id
COMMIT
Complete message

If the message is redelivered, the insert violates the unique key (SQL error 2627/2601), you roll back and complete the message. Two concurrent copies: one commits, the other blocks on the key and then fails. Clean up rows older than the maximum redelivery horizon (for example 14 days).

6. Side effects you can't put in your transaction

An email or a card charge can't join your SQL transaction. Options: pass a provider idempotency key derived from the message id; or write the intent to an outbox and let a single sender with its own dedup do the call. Accept that some providers only offer at-least-once and design the user experience around it ("you may receive this email twice").

Try it yourself

  1. Write a Service Bus handler that sleeps 40 s with LockDuration 30 s and MaxAutoLockRenewalDuration 0; watch the message arrive twice.
  2. Switch to ReceiveAndDelete, throw in the handler, and confirm the message is gone.
  3. Enable duplicate detection on a queue, send the same MessageId 5 times, and count deliveries.
  4. Add an inbox table with a unique index; replay the same message 100 times in parallel with Parallel.ForEachAsync and check the balance changed once.
  5. With Confluent.Kafka, build a transactional consume-produce loop and kill it mid-batch; verify a ReadCommitted consumer sees no duplicates in the output topic.

💻 Code

An effectively-once Service Bus handler: the inbox row and the business change commit together, and a duplicate is completed as a no-op.

// LoyaltyHandler.cs
using Azure.Messaging.ServiceBus;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Loyalty;

public sealed record OrderPaid(Guid OrderId, Guid CustomerId, decimal Total);

public sealed class InboxMessage
{
    public required string MessageId { get; init; }
    public required string Consumer { get; init; }
    public DateTimeOffset ProcessedAt { get; init; }
}

public sealed class LoyaltyHandler(LoyaltyDbContext db, ILogger<LoyaltyHandler> logger)
{
    private const string ConsumerName = "loyalty-points";

    public async Task HandleAsync(ProcessMessageEventArgs args)
    {
        var evt = args.Message.Body.ToObjectFromJson<OrderPaid>()!;
        await using var tx = await db.Database.BeginTransactionAsync(args.CancellationToken);
        try
        {
            db.Inbox.Add(new InboxMessage
            {
                MessageId = args.Message.MessageId,
                Consumer = ConsumerName,
                ProcessedAt = DateTimeOffset.UtcNow
            });
            // Not naturally idempotent (an increment), hence the inbox row.
            await db.Customers.Where(c => c.Id == evt.CustomerId)
                .ExecuteUpdateAsync(s => s.SetProperty(c => c.Points, c => c.Points + (int)evt.Total),
                    args.CancellationToken);
            await db.SaveChangesAsync(args.CancellationToken);
            await tx.CommitAsync(args.CancellationToken);
        }
        catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
        {
            // Unique key on (MessageId, Consumer): we already processed this message.
            await tx.RollbackAsync(args.CancellationToken);
            logger.LogInformation("Duplicate {MessageId} ignored", args.Message.MessageId);
        }
        // Complete only after the commit (at-least-once). A crash before this line means redelivery,
        // which the inbox turns into a no-op.
        await args.CompleteMessageAsync(args.Message, args.CancellationToken);
    }
}
// LoyaltyDbContext.cs (relevant mapping)
protected override void OnModelCreating(ModelBuilder b)
{
    b.Entity<InboxMessage>(e =>
    {
        e.ToTable("InboxMessages");
        e.HasKey(x => new { x.MessageId, x.Consumer });   // the dedup guarantee lives in the database
    });
}

⚠ Common mistakes

  • Mistake: Believing "exactly-once" in a vendor's docs covers your whole handler. Why it is wrong: Kafka EOS is Kafka-to-Kafka; Service Bus duplicate detection only drops producer resends. Instead: assume at-least-once at your boundary and deduplicate.
  • Mistake: Checking "have I seen this id?" in one query and doing the work in another. Why it is wrong: two concurrent copies both pass the check. Instead: rely on a unique key inserted in the same transaction as the change.
  • Mistake: Completing the message before committing the database transaction. Why it is wrong: a crash in between loses the work (at-most-once by accident). Instead: commit, then complete.
  • Mistake: Using a random MessageId per send. Why it is wrong: producer retries get new ids, so neither duplicate detection nor an inbox can spot them. Instead: derive the id from the business event (order id plus event type).
  • Mistake: Long handlers without lock renewal. Why it is wrong: the lock expires and another instance processes the same message concurrently. Instead: keep handlers short, set MaxAutoLockRenewalDuration, or move long work elsewhere.
  • Mistake: Treating a send timeout or a broker failover as "not sent" and dropping the message, or as "sent" and moving on. Why it is wrong: a network partition leaves you not knowing, and either guess loses or duplicates data. Instead: retry the send with the same MessageId (the SDK's ServiceBusRetryOptions do this with backoff) and let dedup absorb the duplicate.
  • Mistake: Catching transient errors in the handler and completing the message anyway. Why it is wrong: a brief SQL failover silently loses the work. Instead: let the exception propagate (or abandon) so the broker redelivers, with MaxDeliveryCount as the backstop.
  • Mistake: Keeping inbox rows forever. Why it is wrong: the table grows without bound and slows inserts. Instead: purge rows older than the longest realistic redelivery horizon.
  • Mistake: Calling external APIs without an idempotency key. Why it is wrong: a redelivered message charges the card twice. Instead: pass a stable key derived from the message.

🏛 Senior insight: trade-offs

I treat "exactly-once" as a property of the business outcome, not of delivery. The network will drop acks, brokers will fail over and pods will be killed mid-handler; the question is never "will the broker deliver once?" but "what happens if this handler runs twice?" For each consumer I want a one-line answer: naturally idempotent, inbox table, version check, or provider idempotency key.

Option When it fits Cost When not to
Natural idempotency (set state, upsert) Final-state updates Design effort only Increments, appends
Inbox table Any DB-backed handler One indexed insert per message (~1-3 ms), cleanup job Side effects outside the DB
Broker dedup (Service Bus, SQS FIFO) Cheap guard against producer retries Throughput cost for long windows As the only protection
Kafka transactions Kafka-to-Kafka stream processing Latency, complexity Handler writes to SQL or APIs

How I evaluate a strategy: (1) a test that delivers the same message twice concurrently and asserts one outcome; (2) a chaos run (kill pods, fail over the database with Azure Chaos Studio) followed by a reconciliation query that compares source and target counts; (3) production metrics: dedup hits per consumer, lock-lost errors and DLQ rate. A sudden rise in dedup hits usually points at lock expiry or a struggling dependency, long before anyone sees wrong data.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions an inbox or dedup table Why: Checks they can implement it correctly, including concurrent duplicates and cleanup
    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 talks about producer retries creating duplicates Why: Checks they understand the producer side and the dual-write problem
    How to answer

    The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.

    The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.

    A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.

  3. When: Candidate says the answer is idempotency Why: Checks the breadth of idempotency techniques beyond messaging
    How to 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.

🛠 Real-world problems: how you handle them

Loyalty points credited twice after Service Bus lock expiry
Situation
A loyalty service in [Azure Australia East] consumes `OrderPaid` from a Service Bus subscription and adds points to the customer's balance in Azure SQL. It processes about [200,000] messages a day across [3] pods.
Signals
Customer complaints about doubled points; Application Insights shows the same `MessageId` handled twice, seconds apart, on different pods; Service Bus metrics show rising `DeliveryCount` and some lock-lost exceptions during an Azure SQL DTU saturation event.
Investigation
Queried Application Insights for operations grouped by `MessageId` with count > 1; correlated with SQL `sys.dm_db_resource_stats` showing CPU at 100%; checked `ServiceBusProcessorOptions`: `MaxAutoLockRenewalDuration` was set to zero, so slow handlers lost their 30-second lock and the message was redelivered while the first handler was still running.
Resolution
Immediate: restored lock auto-renewal (5 minutes) and scaled the database. Real fix: added an `InboxMessages` table with a primary key on (MessageId, Consumer), inserted in the same transaction as the points update; ran a one-off script to reverse duplicate credits using the trace data.
Prevention
Integration test that delivers the same message twice concurrently and asserts one credit; dashboard tile for dedup hits per consumer; alert on lock-lost errors; consumer checklist item: "what happens if this runs twice?"

How to tell it (STAR)

**S:** Our loyalty service [at company] was crediting some customers twice after a database slowdown. **T:** I was asked to stop the duplicates and repair the balances. **A:** I grouped Application Insights traces by message id and found handlers running twice on different pods; lock renewal had been disabled, so slow handlers lost their lock. I re-enabled renewal as a stop-gap, then added an inbox table keyed on message id and consumer in the same transaction as the update, and scripted the corrections from the traces. **R:** Duplicate credits dropped to zero, [about 3,100] balances were corrected within a day, and the 'runs twice' test became part of our consumer template.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me