Exactly-Once Delivery: The Elusive Guarantee

Explore exactly-once semantics in distributed messaging - why it's hard, how Kafka and SQS approach it, and practical patterns for deduplication.

published: reading time: 27 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

Delivery guarantees depend on broker configuration, failure assumptions, and the side effects a consumer commits. This guide explains Kafka transactions, SQS FIFO's five-minute send deduplication window, and idempotent processing. It also shows where external databases and APIs need their own transaction or duplicate-handling strategy.

Introduction

Distributed systems fail in ways that are hard to predict. A producer sends a message. The broker receives it and acknowledges. The acknowledgment gets lost in transit. The producer sends again. Now the broker has two copies. Or the consumer processes the message, crashes before committing its offset, and on restart receives the same message again.

sequenceDiagram
    Producer->Broker: Send(msg)
    Broker->Producer: ACK
    Note over Producer,Broker: ACK lost in transit
    Producer->Broker: Send(msg)
    Broker->Producer: ACK
    Note over Broker,Consumer: Two copies in broker

Retries can create duplicates at the producer, broker, or consumer boundary. At-least-once delivery depends on a broker’s configured durability, acknowledgments, retention, and failure model. Exactly-once needs a defined boundary and coordination for the output side effects inside that boundary.

Delivery semantics

Message systems typically offer one of three guarantees.

At-least-once means a broker retries delivery until its acknowledgment or retention rules say otherwise. A consumer may see a message more than once if processing succeeds but the acknowledgment is lost. The guarantee depends on broker durability, acknowledgment settings, retention, and the failures in scope; it does not mean messages can never be lost.

At-most-once means messages may be lost but never duplicated. The consumer acknowledges before processing. If the consumer crashes after ack but before processing, the message is gone. This is rare and usually a poor trade-off.

Exactly-once describes one externally visible result for an input within a stated boundary. The message may be read or processed again after a failure. A transaction must cover the output and the consumed position, or the sink must make repeated attempts idempotent. A broker transaction alone does not include unrelated databases or APIs.

stateDiagram-v2
    [*] --> AtMostOnce: Ack before processing
    AtMostOnce --> AtLeastOnce: Ack after processing
    AtLeastOnce --> ExactlyOnce: Define boundary and make effects repeat-safe

    note right of AtMostOnce
        Risk: Message loss
        Use case: Log aggregation
    end note

    note right of AtLeastOnce
        Risk: Duplicates
        Use case: Most applications
    end note

    note right of ExactlyOnce
        Risk: Higher latency
        Use case: Financial transactions
    end note

The delivery guarantee spectrum:

Guarantee Duplicates Loss Complexity Typical Use
At-most-once No Yes Low Critical logging
At-least-once Possible Depends on configuration and failure model Medium Many applications with idempotent consumers
Exactly-once Hidden within the defined boundary Depends on configuration and failure model High Use when the effect and boundary justify the coordination

Kafka’s exactly-once semantics

Kafka transactions can atomically write output records to Kafka topics and commit the consumed offsets in Kafka. With consumers using read_committed, aborted transactional output is not exposed as committed data. This makes the visible Kafka-to-Kafka result behave as one committed processing result; it does not mean a record is physically read only once.

Kafka achieves this through transactions introduced in version 0.11. When you enable transactions, Kafka writes messages to partitions as part of a transaction. Consumer offsets are committed as part of the same transaction, tying message consumption to offset commit.

flowchart LR
    Input[(Input topic)] --> Processor[Processor]
    Processor -->|transactional output| Output[(Output topic)]
    Processor -->|offset in same Kafka transaction| Offsets[(Consumer offsets)]
    Processor -. separate sink boundary .-> DB[(External database)]

The transaction boundary in this example covers Kafka input offsets and Kafka output records. A database, payment API, or email provider sits outside it and needs its own coordination or idempotency strategy. See Exactly-Once Semantics in Stream Processing for the transaction-boundary discussion.

For Kafka’s delivery model and failure assumptions, see the Kafka design documentation.

For more on Kafka’s partitioning and consumer groups, see Apache Kafka.

AWS SQS FIFO

SQS Standard queues can deliver a message more than once. FIFO queues preserve order within a message group and suppress duplicate sends that use the same deduplication ID during the five-minute deduplication interval. This is a bounded send-side guarantee, not an exactly-once guarantee for a consumer’s database write.

FIFO queues use content-based deduplication or a caller-supplied deduplication ID to discard duplicate sends within a five-minute window. Reusing an ID after that interval can create another message.

sqs.send_message(
    QueueUrl=queue_url,
    MessageBody=json.dumps({'order_id': '12345', 'action': 'ship'}),
    MessageDeduplicationId='order-12345-ship',
    MessageGroupId='orders'
)

SQS applies a hash to the message body to derive the deduplication ID when you enable content-based deduplication. Identical bodies produce identical deduplication IDs.

SQS FIFO does not make external side effects exactly once. If a consumer’s visibility timeout expires before it deletes the message, SQS can deliver it again, so the consumer should make database changes and other effects idempotent.

For more on SQS features, see AWS SQS and SNS.

RabbitMQ and idempotent consumers

RabbitMQ manual acknowledgments can support at-least-once processing when the queue, message, and publisher settings provide the required durability. Redelivery can still produce duplicates, so consumers should be idempotent.

Idempotency means processing the same message multiple times has the same effect as processing it once. Here is how to actually do it.

Deduplication table: Store processed message IDs in the same database as the side effect. Insert the ID and apply the business update in one transaction; commit before acknowledging the broker. An external API call needs its own idempotency key or coordination.

INSERT INTO processed_messages (msg_id, processed_at)
VALUES ('msg-123', NOW())
ON CONFLICT (msg_id) DO NOTHING;

-- Claim the message ID and apply the business effect in the same database transaction.
-- Commit the transaction before acknowledging the broker delivery.
-- If the ID already exists, skip the effect and acknowledge the duplicate.

Natural idempotency: Some operations are naturally idempotent. Setting a field to the same value twice leaves the database in the same state. UPDATE users SET status = 'active' WHERE id = 1 can run twice and nothing changes. Spotting these operations and using them cuts down on overhead.

Coordinate the acknowledgment: Commit the database effect before acknowledging the message. A crash between those steps can cause redelivery, so store a stable message ID in the same database transaction as the effect. Broker acknowledgment and a database commit are not one transaction by default.

For more on RabbitMQ’s acknowledgment model, see RabbitMQ.

Practical patterns

Idempotency keys

Every message carries a unique ID or you derive one from content. The consumer stores processed IDs. When a message arrives, check if its ID was already processed and skip if so. This approach works with any message broker.

The check, side effect, and marker in a separate cache are not atomic. If the consumer crashes after do_work but before setex, a retry can repeat the effect. Use this cache only when the effect is already idempotent; for database effects, store the event ID and update in one database transaction. External APIs need their own idempotency support or coordination.

def process_message(msg):
    msg_id = msg.headers.get('x-idempotency-key') or hash(msg.body)

    if redis.exists(f"processed:{msg_id}"):
        return

    do_work(msg)
    redis.setex(f"processed:{msg_id}", ttl=86400, value='1')

Set the TTL longer than your maximum retry window to prevent unbounded growth.

Outbox pattern

The outbox pattern addresses the dual-write problem. Instead of writing to the database and publishing a message in two separate steps, you write both to the database in a single transaction.

flowchart TD
    Service-->|1 write| DB[(Outbox Table)]
    DB-->|2 read| Relay[Outbox Relay]
    Relay-->|3 publish| Broker[Message Broker]
    Atomic["Atomic write ensures consistency"]
    DB --> Atomic

The outbox table lives in the same database as your business data. You write the business record and outbox event in the same transaction. A separate process polls the outbox and publishes to the broker. The relay must retry after failures, so consumers should handle repeated publication.

With a durable outbox and a live retrying relay, the event can be published after a restart if the business record committed. The relay may publish the same row more than once, so preserve its event ID and make consumers idempotent.

For more on these patterns, see Event-Driven Architecture and Asynchronous Communication.

Transactional outbox with CDC

In high-throughput systems, polling the outbox adds latency. Change Data Capture tools like Debezium tail the database transaction log and publish when records change. This is faster but adds operational complexity.

The pattern stays the same: write to the outbox atomically with business data, let CDC handle propagation.

When exactly-once matters

You do not always need exactly-once. For many use cases, at-least-once with idempotent consumers is sufficient and simpler. A log aggregator can handle duplicates. A notification system can usually tolerate a duplicate email if it is not critical.

Exactly-once matters for financial transactions (duplicate charges are serious), inventory operations (double decrements overstate deductions), unique constraints (double user creation may violate uniqueness), and external API calls (retrying a non-idempotent API creates duplicate side effects).

Measure the cost of duplicates in your system before implementing exactly-once. The complexity is real and the operational burden is higher.

Saga pattern vs outbox pattern

The saga pattern and outbox pattern solve different reliability problems. A saga coordinates a multi-service workflow; an outbox makes a database change and its outgoing event record atomic within one service.

The saga pattern coordinates local transactions across services. If a later step fails, the workflow may run compensating actions for earlier steps. Compensation is business logic, not an atomic rollback.

The outbox pattern handles the database-to-broker dual-write problem within a service. It commits the business record and outgoing event in one database transaction; a retrying relay publishes the event, possibly more than once.

Aspect Saga Pattern Outbox Pattern
Problem solved Multi-service distributed transactions Single-service dual-write consistency
Failure handling Compensating transactions Eventual publication
Idempotency needed Yes (compensating transactions must be idempotent) Yes (outbox relay may retry)
Complexity High (requires careful compensation design) Medium (requires polling outbox)
Consistency model Eventual Stronger eventual (within a single service)
Use when Multiple services must update in coordinated way Service needs to publish events atomically with database changes

Use the saga pattern when you have multiple independent services each making state changes that must be coordinated. Use the outbox pattern when a single service needs to publish events reliably without a distributed transaction coordinator.

For more on saga, see Saga Pattern. For outbox, see Outbox Pattern.

Idempotent consumer with Redis deduplication

Redis works well as a fast deduplication store for idempotent consumers. Store processed message IDs with a TTL longer than your retry window:

import redis
import json
import hashlib

class RedisIdempotentConsumer:
    def __init__(self, redis_client: redis.Redis, ttl_seconds: int = 86400):
        self.redis = redis_client
        self.ttl = ttl_seconds

    def _get_dedup_key(self, message) -> str:
        """Derive a unique key from the message."""
        msg_id = message.get('message_id')
        if msg_id:
            return f"dedup:{msg_id}"

        # Fallback: hash the message content
        content = json.dumps(message, sort_keys=True)
        content_hash = hashlib.sha256(content.encode()).hexdigest()[:16]
        return f"dedup:hash:{content_hash}"

    def is_duplicate(self, message) -> bool:
        """Check if this message was already processed."""
        key = self._get_dedup_key(message)
        return self.redis.exists(key) == 1

    def mark_processed(self, message) -> None:
        """Mark message as processed with TTL."""
        key = self._get_dedup_key(message)
        self.redis.setex(key, self.ttl, '1')

    def process(self, message: dict) -> bool:
        """
        Process message idempotently.
        Returns True if processed, False if duplicate.
        """
        if self.is_duplicate(message):
            return False

        # Process the actual work
        do_work(message)

        # Mark as processed
        self.mark_processed(message)
        return True

# Usage in a consumer loop
consumer = RedisIdempotentConsumer(redis_client, ttl_seconds=86400)

for message in receive_messages():
    if consumer.process(message):
        print(f"Processed message {message['message_id']}")
    else:
        print(f"Skipped duplicate {message['message_id']}")

Set the TTL longer than your maximum retry window. If a message might be retried for up to 1 hour due to broker retry policies, set TTL to 2 hours or more. If you process millions of messages per day, watch Redis memory usage.

Kafka transactions and external sinks

Kafka transactions coordinate Kafka records and consumer offsets. They do not automatically include a database transaction, HTTP request, or object-store write. A connector can extend the boundary only if that connector and destination implement a documented coordination protocol; verify the exact connector version and failure behavior before relying on it.

For an application writing to a database, common choices are to store the processed offset or idempotency key in the same database transaction as the business update, or to use an idempotent upsert keyed by a stable event ID. If the application also publishes an event after a database change, use an outbox so the business update and outgoing record are committed together in the database. The outbox pattern covers that dual-write case.

Deterministic processing can make retries safe when repeated input produces the same output, but it does not make every side effect idempotent. A counter increment, email, or payment call still needs deduplication or a destination-side idempotency key. For the stream-processing definition of these guarantees, see Exactly-Once Semantics in Stream Processing.

Google Cloud Pub/Sub

Pub/Sub’s exactly-once feature applies to pull subscriptions, including StreamingPull, and its delivery guarantee is regional. When enabled, the subscriber can determine whether an acknowledgment succeeded, and Pub/Sub does not redeliver a message after it has accepted that acknowledgment. A message can still be redelivered while it remains unacknowledged or its deadline expires.

This feature governs subscription delivery. It does not atomically commit an external database update with the acknowledgment. If a subscriber updates a database and crashes before Pub/Sub accepts its acknowledgment, the message can be delivered again; use a database transaction that records the message ID with the effect or make the effect idempotent. See the official Pub/Sub exactly-once delivery documentation for supported subscription types and regional limits.

Comparing broker support

Broker Exactly-Once Support Notes
Kafka Yes (transactions) Within Kafka ecosystem
SQS FIFO Yes (deduplication) Within SQS, 5-min window
RabbitMQ No (build it yourself) At-least-once with idempotency
Google Pub/Sub Yes, when enabled Pull subscription delivery, within one region; external side effects need separate handling

Trade-off comparison tables

Idempotency implementation strategies

Picking an idempotency approach means balancing latency, storage, and complexity against your message volume. This table shows each strategy across those dimensions.

Strategy Complexity Latency Overhead Storage Required Best For
Deduplication table Medium 1-2 DB round trips Grows with message volume High-value transactions
Redis TTL keys Low 1-2 Redis ops Keys with TTL High-throughput, short retry windows
Natural idempotency Low None None Operations that set deterministic values
Database transaction with message ID Medium Database transaction Grows with message volume Database effects that must survive redelivery

Message broker exactly-once comparison

Exactly-once support varies across brokers, and the guarantees are not equivalent. This table shows the scope, deduplication window, and whether your consumer still needs idempotency logic.

Broker Exactly-Once Scope Deduplication Window Consumer Idempotency Required?
Kafka Kafka records and offsets in one transaction N/A (transactional) Yes for external systems
SQS FIFO Duplicate-send suppression for a deduplication ID 5 minutes Yes for consumer side effects
RabbitMQ Not supported natively N/A Yes, mandatory
Google Pub/Sub Pull subscription delivery, when enabled and within one region No publisher-side deduplication window in this feature Yes for effects outside the acknowledged subscription delivery

Outbox pattern deployment options

The outbox pattern works in a few different ways, each with different latency and operational costs. This table compares polling, CDC, and hybrid approaches.

Approach Latency Complexity Consistency Guarantee Operational Overhead
Polling outbox Higher (poll interval) Low Eventual (within poll window) Low
CDC (Debezium) Low (log-based) High Near real-time High (additional infrastructure)
Polling + CDC Flexible Medium Tunable Medium

Saga vs outbox decision matrix

Saga and outbox overlap but suit different architectures. Use this matrix to pick the right pattern based on how many services are involved and what consistency guarantees you need.

Condition Use Saga Pattern Use Outbox Pattern
Multi-service distributed transaction Yes No
Single-service dual-write problem No Yes
Cross-service consistency required Yes No
Event publication alongside business data No Yes
Compensating transactions available Yes No
Low operational complexity desired No Yes

Production failure scenarios

Scenario 1: the payment processor crash

A payment service processes an order and publishes a “payment successful” event to an SQS FIFO queue. The consumer receives the message, calls the payment gateway, updates the order status, but crashes before calling DeleteMessage on SQS. The visibility timeout passes. Another consumer instance picks up the same message and processes the payment again.

The failure window is the visibility timeout, defaulting to 30 seconds but configurable up to 12 hours. If processing takes longer than the timeout, SQS redelivers the message before your consumer has deleted it. This is a split-brain scenario that happens more often than people expect when running multiple consumer instances.

Idempotency is not optional here. A longer visibility timeout only delays the problem. The only real fix is making your payment consumer recognize that order X has already been paid and skip the duplicate.

Store order_id + payment_status + processed_at in a payments table with a unique constraint. Before processing, check if a record exists with status completed for this order ID. If it does, acknowledge and move on. If not, process the payment and insert the record atomically.

On the visibility timeout itself: set it to at least 2x your maximum processing time. If your payment gateway calls take up to 10 seconds, go with 30 seconds minimum. More is fine, but remember that messages are invisible to all consumers during this window, which can back up processing under load.

Scenario 2: the Kafka transaction timeout

A processor consumes a Kafka record, writes to a database, and commits its Kafka offset. These are separate commits unless the sink implements its own coordination. If the database commit succeeds and the offset commit fails, Kafka can replay the record and the database write may repeat. If the offset is committed before the database write, a crash can leave the side effect missing.

Kafka transactions do not close this gap because the database is outside their boundary. Store the consumed position or a stable event ID in the same database transaction as the business update, use an idempotent write, or use a sink with documented offset coordination. Test crashes between each commit. An outbox solves the separate case where an application must atomically save business data and an event for later publication.

Scenario 3: the RabbitMQ network partition

During a network partition, RabbitMQ’s publisher confirms timeout. The producer retries. After the partition heals, the original message and the retry both get delivered, creating duplicates. The consumer processes both and fails to detect the duplicate because a bug in its hash generation makes the same message look different each time.

Network partitions typically last from a few seconds to several minutes. During that window, the producer retries the same message multiple times. When the partition heals, the consumer gets all copies in rapid succession. If your deduplication logic uses message content hashing and your message contains a timestamp or sequence number, identical business payloads produce different hashes. The consumer treats them as distinct messages.

Use an explicit message_id header derived from the business event, not a random UUID generated per publish attempt:

# Bad: UUID generated on every publish attempt
MessageBody=json.dumps({'order_id': '12345', 'created_at': time.time()})

# Good: stable deduplication ID from business key
sqs.send_message(
    QueueUrl=queue_url,
    MessageBody=json.dumps({'order_id': '12345', 'action': 'ship'}),
    MessageDeduplicationId='order-12345-ship',  # stable ID
    MessageGroupId='orders'
)

Your deduplication table must survive consumer restarts. An in-memory cache wipes on restart and lets duplicates through. Store processed IDs in a database table with a unique constraint, or use Redis with persistence enabled (RDB or AOF). The ON CONFLICT DO NOTHING pattern handles concurrent inserts safely.

Scenario 4: the Pub/Sub ack deadline miss

A Pub/Sub subscriber processes a message that requires calling an external API. The API call takes longer than the ack deadline. Pub/Sub redelivers the message to another subscriber instance. Both instances call the external API with the same payload. The external system gets duplicate side effects.

The ack deadline defaults to 10 seconds, configurable from 10 to 600 seconds. When processing exceeds this window, Pub/Sub treats the message as unacknowledged and redelivers it. With multiple subscriber instances running, you can end up with concurrent processing of the same message by different workers.

For long-running operations, increase the ack deadline to at least 2x your expected processing time. If your API call takes 15 seconds, set the deadline to 45 seconds. You can also call modifyAckDeadline dynamically when you know processing is running long.

Increasing the deadline only reduces deadline expirations; it does not cover process crashes. Make external API calls idempotent or pass a destination-supported idempotency key. A payment gateway, for example, should recognize a repeated charge request and return the original result.

If the external API does not support idempotency keys, distributed locking is a last resort. Acquire a lock scoped to the message ID before calling the API, release it after ack. A second subscriber picks up the same message, finds the lock held, and nacks to trigger redelivery. This adds latency and complexity but protects systems that have no built-in idempotency.

Scenario 5: the outbox relay crash

A service writes to the outbox table and business tables in a single transaction. The relay crashes after reading the event but before publishing. The business operation is committed, while publication waits for the relay to recover and retry.

The outbox relay reads unpublished events from the outbox table and publishes them to the broker. If it crashes between reading and publishing, the event is still in the outbox table but has not been published. On restart, the relay picks it up again and publishes it. That only works if the relay implements at-least-once semantics and idempotent publishing.

When the relay reads an outbox event, it publishes to the broker and records progress in the database. These actions are not one transaction. If publish succeeds but recording progress fails, the relay may publish the same event again on its next poll. Preserve a stable outbox event ID and make the consumer idempotent; broker deduplication may help within its supported scope, but does not replace sink-side handling.

On polling versus push-based relay: a polling relay reads the outbox on a schedule, so publish latency equals the poll interval. A push-based relay uses database triggers or change data capture to get notified immediately when an outbox event is created. Polling is simpler. CDC is faster but adds operational complexity.

Quick recap

  • Understand that exactly-once refers to processing semantics, not transport guarantees
  • Identify whether your system needs exactly-once or if at-least-once with idempotent consumers is sufficient
  • Choose the right message broker based on your exactly-once support requirements (Kafka, SQS FIFO, Pub/Sub)
  • Implement idempotency keys for message deduplication across retries
  • Use the outbox pattern to solve the dual-write problem atomically
  • Consider CDC tools like Debezium for high-throughput outbox relay
  • Design consumers to be idempotent regardless of broker guarantees
  • Apply natural idempotency where operations allow (e.g., SET same value)
  • Use saga pattern with compensating transactions for multi-service coordination
  • Monitor Redis memory usage if using it for deduplication at high message volumes
  • Set TTL longer than maximum retry window to prevent premature key expiration
  • Design stream processing outputs to be deterministic when possible

Interview questions

1. What makes exactly-once delivery hard in distributed systems?
  • Partial failures cause message duplication when acks get lost
  • Consumers can crash after processing but before committing offsets
  • Any retry across producer-broker-consumer chain creates duplicates
2. How do at-least-once, at-most-once, and exactly-once differ?
  • At-least-once: retries delivery within the broker's durability and retention rules; duplicates are possible
  • At-most-once: may lose a message if acknowledged before processing
  • Exactly-once: one visible result within a named transaction or idempotency boundary, despite possible retries
3. How does Kafka implement exactly-once within its ecosystem?
  • Transactions (0.11+) write messages and offset commits atomically
  • Ties message consumption to offset commit in a single transaction
  • Only applies within Kafka; external systems need extra handling
4. What is content-based deduplication in SQS FIFO?
  • SQS hashes the message body to generate deduplication IDs
  • Duplicate sends with the same deduplication ID are suppressed during a five-minute interval
  • This does not prevent a consumer redelivery or make an external database update exactly once
  • You can also supply an explicit MessageDeduplicationId
5. Why does RabbitMQ need idempotent consumers?
  • RabbitMQ only guarantees at-least-once with manual acks
  • Use deduplication tables with ON CONFLICT DO NOTHING
  • Use naturally idempotent operations, such as setting a field to the same value
  • Commit the message ID and database effect together, then acknowledge; redelivery is still possible between those steps
6. What is the outbox pattern and what problem does it solve?
  • Writes the business record and outbox event in one database transaction
  • A relay process polls the outbox and publishes to the broker
  • If the business record exists, the event will eventually publish
7. When do you choose saga over outbox?
  • Saga: multi-service distributed transactions with compensating actions
  • Outbox: single-service dual-write consistency (one database, one transaction)
  • Saga coordinates across services; outbox handles reliable event publication
8. How does Redis help with message deduplication?
  • Use message_id or content hash as the dedup key
  • SETEX with TTL longer than your retry window prevents premature expiry
  • Fast in-memory lookups scale well for high-throughput systems
9. What are compensating transactions in sagas?
  • When a step fails, undo previous steps by running counter-transactions
  • Each saga step needs a corresponding compensation
  • Compensations must be idempotent since they can be retried
10. What does Pub/Sub's exactly-once delivery feature cover?
  • It applies to pull subscriptions, including StreamingPull, within one region
  • After Pub/Sub accepts an acknowledgment, it does not redeliver that message
  • Unacknowledged messages can be redelivered; an external database effect is outside this guarantee
11. What happens in Pub/Sub when a consumer crashes after processing but before ack?
  • Message gets redelivered within the ack deadline window
  • Subscriber must be idempotent to survive this safely
  • The message can be redelivered because Pub/Sub has not accepted an acknowledgment
  • Store the message ID with the database effect or make the external effect idempotent
12. What is natural idempotency and why does it matter?
  • Operations that produce the same result regardless of repetitions
  • Example: UPDATE users SET status='active' WHERE id=1 changes nothing if run twice
  • Reduces need for external deduplication stores and overhead
13. How does CDC relate to the outbox pattern?
  • CDC tools like Debezium tail the transaction log instead of polling
  • Faster propagation in high-throughput systems
  • Trade-off: more operational complexity than polling outbox
14. What are the costs of implementing exactly-once?
  • Higher latency from transactional coordination
  • Operational complexity: outbox polling, CDC, saga coordination
  • Consumer idempotency is non-negotiable regardless of broker support
  • At-least-once + idempotent consumers is simpler for most use cases
15. How does SQS visibility timeout interact with idempotency?
  • Consumer has a visibility window to process and delete the message
  • If it times out without deleting, SQS redelivers
  • Your consumer needs to handle this redelivery idempotently
16. What is an idempotency key in message publishing?
  • A unique identifier the publisher attaches to enable broker-side deduplication
  • A stable event ID can help consumers identify repeated deliveries
  • Broker-side deduplication is specific to each broker and may have a limited scope or window
  • A publisher retry can still create multiple messages unless the broker supports deduplicating that publish
17. Why measure duplicate cost before implementing exactly-once?
  • Not every system needs it; at-least-once + idempotent consumers often suffices
  • Log aggregators and non-critical notifications tolerate duplicates fine
  • Financial transactions, inventory, and unique constraints may actually need it
18. What must a Kafka consumer do to make a database side effect safe?
  • Kafka transactions cover Kafka records and offsets, not an arbitrary database write
  • Use a stable idempotency key or store the processed offset in the same database transaction as the business update
  • Rely on connector offset coordination only after verifying that connector's documented behavior and version
19. Why does deterministic processing not guarantee exactly-once side effects?
  • Determinism helps reproduce state when the same input is replayed
  • A repeated counter increment, email, or payment can still create a second visible effect
  • Coordinate the output commit with the input position or make the sink idempotent
20. Compare exactly-once support across Kafka, SQS FIFO, RabbitMQ, and Pub/Sub.
  • Kafka: transactional output records and offsets within Kafka
  • SQS FIFO: suppresses duplicate sends with the same deduplication ID for five minutes
  • RabbitMQ: no native support, build it yourself
  • Pub/Sub: optional exactly-once delivery for regional pull subscriptions; external effects still need handling

Further reading

Conclusion

Delivery behavior depends on the transport, the consumer’s commit boundary, and the failure model. At-least-once with idempotent effects is a practical choice when broker durability and replay assumptions fit the workload. Add transaction coordination when the required visible result spans a boundary that can support it.

The outbox pattern and idempotency keys are the practical tools here. They work across brokers and do not require special broker features.

For related reading, see Message Queue Types, Distributed Transactions, and Pub-Sub Patterns.

Category

Related Posts

Ordering Guarantees in Distributed Messaging

Understand how message brokers provide ordering guarantees, from FIFO queues to causal ordering across partitions, and the trade-offs in distributed systems.

#distributed-systems #messaging #kafka

Dead Letter Queues: Handling Message Failures Gracefully

Design and implement Dead Letter Queues for reliable message processing. Learn DLQ patterns, retry strategies, monitoring, and recovery workflows.

#data-engineering #dead-letter-queue #kafka

Apache Kafka: Distributed Streaming Platform

Learn Kafka topics, partitions, consumer groups, delivery guarantees, Kafka transactions, and the boundary between stream processing and external effects.

#kafka #messaging #streaming