# Idempotent consumers on Service Bus: why duplicate detection is not enough

> Service Bus duplicate detection drops a resent MessageId inside its window and nothing else. Lost locks, lost completes and dead-letter resends still deliver twice: key on the operation, record it with the side effect, and dead-letter early.

- Canonical: https://www.alpacamango.com/docs/azure-service-bus-idempotent-consumers
- Author: Space Dog Vin
- Published: 2026-11-26 · Updated: 2026-11-22
- Topics: Azure, Event-driven, Architecture

**Service Bus duplicate detection protects the send, not the processing. It drops a copy a producer resends with the same ****`MessageId`**** inside a window (ten minutes by default, seven days at most), but never sees a message the broker redelivers after a lost lock or a lost Complete. So the handler must still be idempotent: key it on the business operation, record the key in the side effect's transaction, and dead-letter a hopeless message early.**

## What duplicate detection checks

On a Standard or Premium queue or topic, Service Bus remembers each `MessageId` it accepted during the window. A later send with a remembered ID appears to succeed, and the copy is discarded. Nothing else is compared, except the partition key on a partitioned entity: the same ID with a different body is dropped too.

It exists for a producer that crashed after sending, unsure whether the message landed, and works only if the retry rebuilds the same ID, which a per-attempt GUID never does. Build it from the operation: order number and step, `8812.payment`.

## Where the second delivery comes from

Each happens after the broker accepted the message, out of duplicate detection's sight:

- **The lock runs out.** Peek-lock hides a message for the lock duration, one minute by default and five at most. The Azure Functions trigger renews it for a single-message function, but only for five minutes unless you raise `maxAutoLockRenewalDuration`; a longer run loses the lock, and another instance starts the message while the first still works.
- **The Complete is lost.** Your handler commits, then the connection drops before the settlement arrives. The work is done; the broker never heard.
- **The handler throws.** Functions abandons the message and it returns, up to the maximum delivery count, ten by default.
- **Someone resends it** from the dead-letter queue, after the window has closed or under a new ID.

## Keep the key with the side effect

Unlike SQS and Pub/Sub, Service Bus lets you set the message ID, so one operation key can serve the broker and the consumer. Copy it into an application property too, and have the consumer read it there: an operator who resends under a new ID changes the `MessageId`, not the operation.

After a lost lock, two instances can hold the same message, so "look the key up, then do the work" is a race: the write that records the key must be the check. In Azure SQL, insert the key into a primary-keyed table in the business change's transaction. In Cosmos DB, create a marker item in the same transactional batch as the order. A batch spans one logical partition, so partition on the order ID, and keep slashes out of the key: Cosmos DB ids forbid them.

```python
batch = [
    ("create", ({"id": f"done.{op_key}", "orderId": order_id},), {}),  # 409 if seen
    ("upsert", (paid_order,), {}),
]
container.execute_item_batch(batch_operations=batch, partition_key=order_id)
```

A 409 on the create, which Python raises as `CosmosBatchOperationError`, means the work is done: complete the message. Keep markers as long as anyone might resend; for payments, keep them for good.

Two cases need no table. When the side effect is someone else's API, pass the key as their idempotency key. When it is only more Service Bus messages, a Service Bus transaction completes the input and sends the outputs atomically (Standard or Premium, two minutes at most, no JavaScript SDK). The producer's half, saving a record and sending its message together, is the [transactional outbox on Azure](/docs/azure-transactional-outbox-cosmos-db).

## What a poison message costs

Hardly any money on Standard: a couple of billable operations per attempt. The real costs:

- **Ten runs of everything before the failing line.** An unkeyed side effect ahead of the exception repeats on every attempt. Validate first, and when retrying cannot help, dead-letter the message yourself with a reason.
- **A stalled session.** On a session-enabled queue an abandoned message is served again before anything behind it, so one bad message holds its session for all ten attempts. Resubmitted later, it lands behind newer messages.
- **A queue nobody empties.** The dead-letter queue ignores time to live and never empties itself. Alert on the `DeadletteredMessages` metric (`DeadLetterMessageCount` in the SDK and CLI).
- **Copies for every subscriber.** Resending from a subscription's dead-letter queue in Service Bus Explorer sends a copy to the topic, so every subscription gets it again, even those that handled it. If the copy keeps its `MessageId` inside the topic's window, the topic quietly drops it: a seven-day window, chosen to make sends safe, swallows a week of repairs.

## The same problem on AWS and Google Cloud

SQS assigns its own message IDs, so the key travels in the body or a message attribute; FIFO queues give the same send-side guard on a deduplication ID, over a fixed five minutes. Pub/Sub's exactly-once delivery covers pull subscriptions in one region and keys on Pub/Sub's own message ID, so a publisher's retry is still a new message. The AWS version is [idempotent consumers on SQS and Lambda](/docs/idempotent-consumers-sqs-lambda); [event-driven architecture on Azure](/docs/event-driven-architecture-on-azure) places Service Bus beside Event Grid and Event Hubs.

## The diagram

One order from producer to Cosmos DB: where duplicate detection stops a resend, where the consumer's key stops a redelivery, and where poison messages wait. [Open it in archhy](https://archhy.com/d/ziALIdRwX0pH?utm_source=alpacamango) and make a copy.
