Why Exactly-Once Processing Is Hard: RabbitMQ, Retries, and Idempotency
Where RabbitMQ duplicates come from and how an outbox, deduplication keys and idempotent consumers protect database effects and external calls.
THE SHORT VERSION
- With RabbitMQ, acknowledgment and durability choices determine whether a message can be lost or delivered more than once.
- Duplicates come from two crash windows: a consumer that dies before it acks, and a publisher that dies after it publishes but before it records that fact.
- What you can get is exactly-once effects: a stable event id plus an idempotent consumer, under stated assumptions.
- The outbox gives at-least-once publishing. It does not remove duplicates, so the consumer must.
A worker processes a payment, then crashes before it can acknowledge the message. The broker sends the message again. From the broker's point of view, that's recovery working as intended; from the customer's point of view, it could be a second charge.
That gap is why reliable processing takes more than a durable queue. I'll use RabbitMQ to show where duplicates come from and how an outbox, deduplication, and idempotent consumers help. The same reasoning applies to many other brokers.
The Challenge
"Exactly-once" is easy to say and hard to get, because of four facts:
- Networks fail
- Processes crash at inconvenient times
- A message can be delivered and processed but never acknowledged
- Retries can cause duplicate processing
The goal isn't to eliminate these problems. It's to make sure they don't change the outcome.
At-Least-Once vs Exactly-Once
With RabbitMQ, your acknowledgment strategy determines which failure tradeoff you make:
- At-most-once: the broker hands the message over and forgets it (auto-ack). If the consumer crashes mid-work, the message is lost.
- At-least-once: the broker keeps the message until the consumer acknowledges it. If the ack never arrives, the message is delivered again.
A common choice is manual acknowledgment and at-least-once delivery, assuming the queue, messages, and publisher are configured for durability as needed. That moves a problem to the consumer: it may see the same message twice. The consumer must make processing idempotent, so repeating an operation has the same intended effect as doing it once.
Some systems offer exactly-once guarantees under specific conditions. Those guarantees don't automatically extend to every external side effect: a broker cannot make a payment API or an email provider participate in your database transaction. What you can build, within a defined boundary, is an exactly-once effect: work may run more than once, but its durable result is recorded once. The example below uses a stable event ID and records it atomically with a database change.
Where Duplicates Come From
There are two crash windows. Everything else in this article is a way of closing one of them, or of surviving it.
Window 1, consumer side. The consumer receives a message, does the work, and crashes before it sends the ack. The broker never saw the ack, so it redelivers. The work has now been done once and will be done again.
Window 2, producer side. The producer publishes the message, then crashes before it records that it did. After restart it sees "not published" and publishes again. The consumer receives two copies. Publisher confirms narrow this window, but a crash between the confirm and your own record keeps it open.
Retries alone don't close either window. The rest of the design keeps the event available for retry and makes a duplicate safe to handle.
The Outbox Pattern
Writing business data and publishing an event are two separate systems, so they can disagree. The transactional outbox fixes one half of that: the event is written in the same database transaction as the data.
async def process_order(order_data):
async with database.transaction():
# Save order
order = await orders.create(order_data)
# Write to outbox in same transaction
await outbox.create({
'event_id': uuid4(), # stable id, created once
'aggregate_id': order.id,
'event_type': 'order_created',
'payload': serialize(order),
'created_at': datetime.now()
})
# Outbox processor publishes to queue separately
The database transaction guarantees that the order and the outbox row either both exist or neither exists. A separate process reads unpublished rows and publishes them:
async def relay_outbox():
for row in await outbox.fetch_unpublished(limit=100):
await broker.publish(
body=row.payload,
message_id=str(row.event_id), # same id on every attempt
confirm=True, # wait for the publisher confirm
mandatory=True, # surface an unroutable message
)
# Crash here, and the row is still "unpublished".
await outbox.mark_published(row.id)
Look at the comment in the middle. Publishing and marking the row are not atomic. If the relay crashes after the broker accepted the message but before mark_published runs, the row still looks unpublished, and the next run publishes it again. The published flag does not prevent that duplicate. It only stops the relay from re-sending rows it knows it finished.
These are schematic database and broker wrappers, not a particular client's API. The publishing wrapper must wait for confirmation and treat returned, unroutable messages as failures before marking an outbox row published. RabbitMQ can confirm a message even when no queue matched its routing key; mandatory returns let the publisher detect that case. See RabbitMQ's publisher-confirm documentation.
The outbox preserves the event alongside the business write and lets the relay retry publication. With a durable database, a working relay, and appropriate broker durability and publisher confirms, this supports at-least-once publishing. Some events may still be published twice. That's why each event carries a stable event_id, created when the row is written and reused on every attempt; the consumer uses it to recognize duplicates.
Idempotent Consumers
Because a message can be delivered more than once, the consumer needs to cope with duplicates. Here's the shape of a database-backed handler:
async def handle_message(message):
event_id = message.properties.message_id
if not event_id:
# The caller should route invalid messages to its dead-letter policy.
raise ValueError("A stable message_id is required")
async with database.transaction():
# The unique constraint on event_id is the guard.
inserted = await processed_messages.insert_if_absent({
'event_id': event_id,
'processed_at': datetime.now()
})
if not inserted:
logger.info(f"Skipping duplicate: {event_id}")
else:
await do_business_logic(message.body)
# Commit succeeded. Only now acknowledge.
await message.ack()
Three details make this work for a database effect:
- The dedup record and the business effect are written in one transaction. If they were separate, a crash between them would either lose the effect or repeat it.
- The dedup check is an insert against a unique key, not a read followed by a write. A "check if it exists, then process" version has a race: two copies of the same message, handled by two workers at the same moment, can both pass the check.
- Ack after commit. If the process dies before the ack, the message comes back, the insert finds the existing row, and the consumer skips the work and acks. That is window 1 closed.
Store the ids in your database, not in memory, because processes restart. And decide how long to keep them: a dedup table you purge after a week only protects against duplicates that arrive within a week.
What this does and does not cover
This gives exactly-once effects for work that lives in the same database as the dedup table. It holds under these assumptions: the event id is stable, the unique constraint is enforced, and the business write and the dedup insert share a transaction.
It breaks down when the effect is outside that database. If the consumer calls a payment provider and then crashes before committing, the retry calls the provider again. For that case, pass an idempotency key (the event id works) to the provider, if it supports one. If it doesn't, you are back to at-least-once for that side effect, and you need a way to reconcile.
Dead Letter Queues
Messages that repeatedly fail need special handling. We use a tiered retry approach:
- Immediate retry: For transient failures (network blips)
- Delayed retry: Exponential backoff for recoverable failures
- Dead letter queue: For messages that fail after max retries
class MessageHandler:
max_retries = 5
async def handle(self, message):
retry_count = message.headers.get('x-retry-count', 0)
try:
await self.process(message)
except TransientError:
if retry_count < self.max_retries:
await self.retry_with_delay(message, retry_count + 1)
else:
await self.send_to_dlq(message)
except PermanentError:
await self.send_to_dlq(message)
A delayed retry implemented as a new publish creates another opportunity for duplicates. Keep the original event ID, and ensure the handoff between the old delivery and the retry is reliable. We monitor the DLQ and alert when messages land there, so someone can investigate failures that need attention.
Atomic Job Claiming
For long-running jobs, we use atomic claiming to stop two workers from starting the same job:
UPDATE jobs
SET status = 'processing',
worker_id = $1,
started_at = NOW()
WHERE id = $2
AND status = 'pending'
RETURNING *;
If the update returns a row, you own it. If not, another worker already claimed it. The database decides in one statement, so two workers can't both win.
A claim is not a completion guarantee. If the worker dies after claiming, the row stays processing unless something recovers it. Add a lease (for example a claimed_until timestamp that the worker extends while it runs) and let a reaper return expired claims to pending. When it does, the job can run a second time, so the work itself still has to be idempotent. Claiming prevents concurrent duplicates. It does not remove the need for an idempotent consumer.
Circuit Breaker Integration
Message consumers can also trip circuit breakers:
class ConsumerWithCircuitBreaker:
def __init__(self):
self.circuit = CircuitBreaker(
failure_threshold=5,
recovery_timeout=timedelta(seconds=30)
)
async def handle(self, message):
if not self.circuit.can_execute():
# Requeue for later processing
await self.requeue_with_delay(message)
return
try:
await self.process(message)
self.circuit.record_success()
except Exception as e:
self.circuit.record_failure()
raise
This keeps consumers from repeatedly calling a failing downstream service. The breaker here lives inside one consumer process, so each process learns about an outage on its own. The circuit breakers article explains timeouts, probe coordination, and the limitations of the simplified implementation.
Monitoring and Observability
We track several metrics:
- Queue depth: How many messages are waiting
- Processing time: P50, P95, P99 latencies
- Failure rate: Percentage of messages that fail
- DLQ size: Messages that exhausted retries
- Consumer lag: How far behind are we
- Duplicate rate: How often the dedup check skips a message. A sudden rise points at a crashing consumer or an ack problem.
Alerts trigger when:
- Queue depth exceeds threshold for > 5 minutes
- DLQ receives any messages
- Processing time degrades significantly
Ordering Guarantees
Sometimes message order matters. Options:
- Single consumer: Process all messages for a category sequentially
- Partition by key: Route related messages to the same queue
- Sequence numbers: Consumer reorders if needed
Redelivery can also reorder messages, so a retried message may arrive after a later one. We mostly avoid strict ordering requirements. They limit scalability and add complexity.
Lessons Learned
Design for failure: Over a long enough time, messages will fail. Have a plan.
Idempotency is the foundation: With at-least-once delivery, a consumer that can't handle duplicates will eventually write them.
Name the guarantee honestly: Say "at-least-once delivery, exactly-once effects for this table, under these assumptions", not just "exactly-once".
Monitor the DLQ: Alert on arrivals and periodically check that the dead-letter path itself works.
Test the sad path: Simulate network failures, slow consumers, poison messages. Kill a consumer between the work and the ack and check the result. Production will throw these at you.
Keep messages small: Put large payloads in object storage and pass references.
Failures and retries are part of the design. Define which effects must happen once, identify the crash windows around them, and test the behavior when a worker stops in each window.
Sources and further reading
Where the guarantees above are actually specified, and where to go deeper.
- RabbitMQ: Reliability guide. Publisher confirms, consumer acknowledgements and what the broker does and does not promise. The section on why acknowledgements must come after the work is the one people skip.
- RabbitMQ: Dead letter exchanges. How messages end up in a dead letter queue, and the TTL trick that turns one into a delayed retry.
- Pub/Sub: Exactly-once delivery. A precise statement of what a broker can guarantee, and the narrow conditions under which it holds. Useful for calibrating how much you should trust the phrase.
- SQS: Visibility timeout. The mechanism behind redelivery, and the one setting that decides how long a crashed consumer blocks a message.
- Transactional outbox on microservices.io. The pattern that makes a database write and its announcement atomic.
- Timeouts, retries, and idempotency by Marc Brooker. Short and precise on why a retry is only safe when the operation is idempotent.
- Addressing cascading failures from the Google SRE book, for what happens when every consumer retries into a struggling dependency at once.
Continue learning
For a closer look at keeping jobs recoverable when a downstream API fails, continue with When RabbitMQ Isn't Enough. For the underlying pattern, see idempotency keys: the same logical operation needs the same key across retries, including retries sent to an external provider.
FAQ
Does any broker really give exactly-once delivery? Some services offer exactly-once delivery within a documented scope and under specific conditions. That does not automatically make your database writes or external API calls exactly once. Check the service's guarantee and make the side effects safe under the failures it doesn't cover.
Do I need an outbox if I already have retries? Yes, if a database write and its message must not diverge. Retries fix a failed send; they do not fix a message sent for a transaction that later rolled back. The outbox gives at-least-once publishing, so the consumer still needs to drop duplicates.
When should a message go to a dead letter queue? When redelivery will not help, meaning malformed payloads and permanent failures. A rate limit is not that, and sending it to the dead letter queue turns a delay into lost work.
CONCEPTS IN THIS ARTICLE
KEEP GOING
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.