Forward Deployed EngineeringSoftware EngineeringDistributed Systems

What's the difference between at-least-once and exactly-once delivery, and why should an FDE care?

Question 26 of 73 · Updated

On this page

Interview-ready answer#

At-least-once delivery means that a message is delivered one or more times, assuming the system's durability, retry and retention conditions hold. The consumer must expect duplicate deliveries. Exactly-once processing means that each logical event contributes its intended effect once within a specified transactional or deduplication boundary, even if the system retries or executes some processing steps more than once.

The distinction matters because an acknowledgement can be lost after a consumer commits its work. The broker cannot safely conclude from silence that the work did not happen, so it may redeliver. If the consumer blindly repeats a database update, sends a second notification or creates another refund, the customer's business state becomes incorrect.

As an FDE, I would generally prefer a durable at-least-once transport combined with stable event identifiers, idempotent consumers, atomic state changes and acknowledgement after commit. For workflows that publish events after updating a database, I would use a transactional outbox. When calling external systems, I would use supported idempotency keys and reconcile uncertain outcomes. I would claim exactly-once behavior only for the specific effects and failure model that the design actually guarantees.

1. Delivery guarantees versus business effects#

SemanticsWhat the guarantee means within its scopeMain trade-off
At-most-onceA logical message is delivered at most once; it may be lostSimplicity at the expense of completeness
At-least-onceA logical message is eventually delivered one or more times under the stated assumptionsRetries can produce duplicates
Exactly-onceA logical message or processing effect occurs exactly once within the stated guarantee boundaryRequires coordination, durable state or deduplication

These guarantees depend on the system configuration and failure assumptions. An expired message, exhausted retry policy, permanently unavailable consumer or unrecoverable storage loss can invalidate an unconditional promise of eventual delivery.

Separate three concepts:

  • Delivery: how often the broker presents a message to a consumer.
  • Execution: how often consumer code runs.
  • Effect: how many times the intended business mutation becomes visible.

A system can deliver a message twice and execute a handler twice while producing only one business effect. This is commonly called effectively-once processing. Conversely, a broker that deduplicates producer requests does not necessarily prevent duplicate payments or emails in an external service.

2. Why duplicate deliveries happen#

Consider a warehouse integration that processes an inventory adjustment of +5 units. The consumer receives event E42, commits the adjustment, and crashes before acknowledging the message. The broker later delivers E42 again.

Loading diagram…

A naive increment would add 10 units instead of five. An idempotent transactional consumer recognizes the same logical event and does not repeat the update.

The opposite ordering is also dangerous: acknowledging first and committing afterward creates a message-loss window if the consumer crashes before the commit. Acknowledgement after a durable commit is the safer ordering for at-least-once consumers, provided the handler can safely process duplicates.

Other causes include producer retries after a publish timeout, expired visibility leases, network partitions, consumer rebalances and manual replay. Delivery guarantees do not imply ordering guarantees. Parallel processing and retries can reorder events unless the architecture explicitly preserves the required ordering.

3. Idempotency and the transactional inbox#

An operation is idempotent if repeating it has the same intended effect as applying it once. Setting a record to a specified state can sometimes be intrinsically idempotent, whereas adding an amount to a balance generally is not. Even a state-setting operation can overwrite newer data when old events arrive late; use version checks or sequence numbers when order matters.

Use an immutable event ID generated by the producer and retained across retries. Scope it appropriately, for example by tenant, producer and logical consumer. Store the event identity and enough immutable payload information to distinguish legitimate replay from accidental reuse of an ID for a different operation.

The transactional inbox pattern records the event and applies the business mutation within the same database transaction. A unique constraint enforces deduplication even when workers race. If the mutation fails, the inbox insert rolls back too.

Avoid these common errors:

  • Checking an in-memory set that disappears on process restart.
  • Checking for an event in one transaction and applying its effect in another.
  • Generating a new ID for every retry of the same operation.
  • Deleting deduplication records before the longest supported replay horizon.
  • Treating two messages with different IDs as different legitimate business operations without checking business-level invariants.

For example, two distinct event IDs may both request a refund for the same purchase. Inbox deduplication prevents duplicate processing of one ID, but refund eligibility and remaining refundable amount still need independent atomic validation.

4. Tested Python example: apply an event once#

This local SQLite example processes additive inventory adjustments with a durable inbox. It assumes one trusted event-ID namespace, already authenticated producers, validated event schemas and a dedicated connection with no active transaction and normal SQLite transaction behavior. Negative adjustments are allowed for illustration; a real inventory service would enforce quantity bounds and business rules.

PYTHON
import sqlite3 def apply_event(db, event_id, item, delta, fail=False): # The caller authenticates the producer and validates the event schema. with db: db.execute('BEGIN IMMEDIATE') previous = db.execute( 'SELECT item, delta FROM inbox WHERE event_id=?', (event_id,)).fetchone() if previous is not None: if previous != (item, delta): raise ValueError('Event ID reused with different payload') return False db.execute('INSERT INTO inbox VALUES (?,?,?)', (event_id, item, delta)) db.execute('''INSERT INTO totals VALUES (?,?) ON CONFLICT(item) DO UPDATE SET quantity=quantity+excluded.quantity''', (item, delta)) if fail: raise RuntimeError('Simulated pre-commit failure') return True

Set up the toy database and exercise the lost-acknowledgement case:

PYTHON
db = sqlite3.connect(':memory:') db.executescript(""" CREATE TABLE inbox( event_id TEXT PRIMARY KEY, item TEXT NOT NULL, delta INTEGER NOT NULL ); CREATE TABLE totals( item TEXT PRIMARY KEY, quantity INTEGER NOT NULL ); """) assert apply_event(db, 'E42', 'sku-1', 5) is True assert apply_event(db, 'E42', 'sku-1', 5) is False assert db.execute('SELECT quantity FROM totals').fetchone() == (5,)

The first call commits both the event record and the adjustment. A repeated call returns False without adding another five units. If an exception occurs before the transaction commits, the transaction context manager rolls back both writes. An ID reused with a different item or quantity is rejected instead of being silently treated as a duplicate.

A real consumer acknowledges either a successfully committed event or a verified duplicate. It does not acknowledge transient processing failures as successful. Permanently invalid events require an explicit quarantine or dead-letter policy rather than an endless retry.

Local verification: Python 3.13.5 and SQLite 3.46.1 executed the exact helper. All 9,333 cases passed: 9,331 sequences of zero through five delivery attempts over three logical events with or without simulated pre-commit failures, and two conflicting-payload checks. The test harness independently tracked expected committed event IDs and per-item totals and asserted both after each step. The tests use local in-memory databases, sequential calls and simulated exceptions. They do not establish durability under actual process or power loss, concurrent production behavior, or the guarantees of a distributed broker.

SQLite's BEGIN IMMEDIATE serializes writers in this simplified example. In a production database use an appropriate transactional upsert, unique constraint and isolation strategy, with concurrency tests. This toy example has no broker, external side effect, tenant schema or deduplication cleanup.

5. The transactional outbox: solving the dual-write problem#

Suppose creating an order must also publish an OrderCreated event. If the application commits the order first and then publishes, it may crash between the two operations, leaving a committed order with no event. If it publishes first and then fails to commit the order, downstream services may act on a nonexistent order.

Store the order mutation and an outbox record in the same local transaction. A separate relay reads committed outbox entries and publishes them to the broker. Mark an entry sent only after the broker confirms publication, or track progress through a correctly configured change-data-capture mechanism.

Loading diagram…

The relay can crash after publishing but before recording publication progress. It may publish the same outbox event again. Therefore the outbox prevents the local database and event-intent record from diverging; it does not automatically make broker publication or downstream business effects exactly once.

Typical outbox metadata includes an immutable event ID, aggregate ID, event type, schema version, payload, creation time and relay progress. Preserve stable event IDs across retries. Monitor backlog age, relay lag, stalled leases and publication errors. Ensure cleanup does not destroy the recovery or audit history required by the customer.

6. Broker guarantees and their boundaries#

Technology or patternRelevant guarantee and caveat
Kafka idempotent producerPrevents certain producer-retry duplicates in the log under supported configuration; not a general business deduplicator
Kafka transactionsCan atomically commit produced Kafka records and consumed offsets in a Kafka read-process-write pipeline; downstream consumers need the appropriate isolation mode
SQS StandardAt-least-once delivery and possible reordering; consumers need idempotency
SQS FIFOProvides ordering within message groups and producer deduplication within its supported scope; a message can still be received again if not deleted before visibility timeout
RabbitMQ publisher confirms and consumer acknowledgementsImprove delivery reliability; uncertain confirms and unacknowledged deliveries may lead to retries
WebhooksCommonly retried when an endpoint fails or times out; verify signatures, event identity and provider-specific retry semantics

The table describes established concepts, not a claim about every current product configuration. Check the exact broker, client version, transaction limits, retention, failure assumptions and acknowledgement settings before choosing an implementation.

A Kafka transaction cannot atomically include an arbitrary external HTTP request or independently managed database merely because the code runs inside the Kafka consumer. Exactly-once Kafka processing is valuable for Kafka-scoped effects, but the scope must be stated explicitly.

7. External APIs and uncertain outcomes#

A payment, refund, email or CRM mutation may be outside the consumer's local database transaction. A local inbox alone cannot guarantee exactly-once execution of such a side effect. Marking the event processed before the HTTP call risks losing the external effect; marking it afterward risks repeating it.

For an external service with supported idempotency:

  1. Create a durable operation record with a stable business operation ID and immutable request parameters.
  2. Submit the request using that same provider-supported idempotency key.
  3. Record the authoritative result and provider reference.
  4. If the response is lost, mark the result uncertain and reconcile with the provider using its supported lookup or retry contract.
  5. Retry only within the documented key lifetime and semantics, or escalate when the outcome cannot be established safely.

A successful retry response is meaningful only within the provider's idempotency and status contract. Do not assume every API supports idempotency, that keys are retained indefinitely, or that a timeout means a request failed. If there is no reliable deduplication or reconciliation mechanism, the application cannot promise exactly-once external effects across arbitrary crashes. Use a controlled human workflow, compensating operations where appropriate, or an explicit risk decision.

8. Ordering, retries and production operations#

Failure scenarioExpected design behavior
Consumer dies before commitTransaction rolls back; redelivery may apply the event
Consumer dies after commit, before ackReplay is recognized; no repeated effect
Broker publish acknowledgement lostProducer retries using stable event identity; downstream deduplicates
Two workers receive the same logical eventDatabase uniqueness and atomic transaction protect the effect
Same ID arrives with changed payloadReject and investigate an integrity violation
Distinct IDs represent the same business operationEnforce business uniqueness or domain invariants separately
Older event arrives after newer stateApply aggregate version checks, buffering or reconciliation as required
Permanent schema or policy failureQuarantine with diagnostic information and an accountable recovery process

Use exponential backoff with jitter and bounded retries. A dead-letter queue is not successful processing; it is a record that requires monitoring, triage and potentially controlled replay. Align deduplication retention with both automated and manual replay horizons.

Partition by aggregate when per-aggregate ordering matters. For example, applying an inventory snapshot older than the current version can corrupt state even if each event was processed only once. Idempotency does not replace ordering, version validation or consistency checks.

Track duplicate delivery rates, retry counts, oldest unprocessed event, consumer lag, outbox age, dead-letter volume, uncertain external operations and reconciliation discrepancies. Carry event and correlation IDs through logs and traces without exposing unnecessary customer payloads. Authenticate producers and enforce tenant-scoped processing, especially during replay.

9. What I would test before a customer launch#

Build failure-injection tests around the transaction and acknowledgement boundaries. Kill the consumer before commit and after commit; duplicate and reorder messages; run multiple workers against the same event; force relay failures; simulate provider timeouts after an accepted request; and replay older events. Inspect actual durable state instead of relying only on application logs.

Verify the business invariants: one committed effect per valid logical event, no lost accepted event within the supported failure assumptions, no unauthorized cross-tenant effect, and no repeated payment or refund caused by replay. Measure recovery time and operational cost under realistic throughput and failures.

For a low-risk telemetry stream, occasional loss may be acceptable if explicitly agreed. For inventory, financial operations, customer notifications or enterprise workflow mutations, durability and duplicate-safe business effects are much more important. Choose the weakest guarantee that safely satisfies the customer's requirements rather than adding expensive coordination everywhere.

Likely interviewer follow-ups#

Is exactly-once delivery impossible? Unqualified end-to-end guarantees across arbitrary independent systems are not justified. Exactly-once effects are achievable within specified transactional or deduplication boundaries and failure assumptions. State those boundaries.

Why acknowledge after commit? Acknowledging before commit can permanently lose work. Acknowledging afterward can produce a duplicate on failure, which an idempotent consumer can safely handle.

Does an outbox eliminate duplicates? No. It atomically stores business state and event intent. Relay retries may publish duplicates, so downstream processing still needs suitable deduplication.

What is the difference between an inbox and an outbox? The inbox tracks consumed events and protects local effects; the outbox records events that a local mutation needs to publish.

Does exactly-once mean messages arrive in order? No. Ordering is a separate guarantee; versioned updates and appropriate partitioning may be necessary.

What would you tell a customer? Explain which business effects are protected, the failure and replay assumptions, how uncertain outcomes are reconciled, and the evidence from tests. Avoid promising universal exactly-once delivery across systems you do not control.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models