Cloud

Azure Service Bus: validate duplicate detection before replaying messages

A production runbook for proving MessageId stability, duplicate-detection scope, replay behavior and consumer idempotency before resending Azure Service Bus messages.

26 Oct 2026 azureservice-busmessagingduplicate-detectionreplaymessage-ididempotencyobservabilityautomationrunbookrollbackproduction

A production replay is ready to resend messages to Azure Service Bus after a consumer outage. The source batch is known, the downstream service has recovered and the queue has duplicate detection enabled. It is tempting to treat that setting as a guarantee that no business action can run twice.

That guarantee stops at the send boundary. Service Bus compares an application-controlled MessageId with the identifiers retained by one queue or topic during its configured history window. A repeated send can succeed while the new copy is discarded. Outside that window, with another identifier, or after a consumer completes the business write but loses its message lock, duplicate processing is still possible.

The running case is an order-command queue receiving a bounded recovery batch. This runbook determines whether the replay should reuse the original identifiers, wait, use a new target, or remain blocked. It ends only when the platform behavior and the business ledger agree.

Freeze the replay contract

Do not start with the replay script. Pin the entity, configuration, source population and intended effect. Record both the original enqueue interval and the planned replay interval; duplicate detection is evaluated when a message is sent, not when it is consumed.

yaml 01-service-bus-replay-contract.yml
incident: INC-SB-1042
namespace: sb-prod-eu
entity_type: queue
entity: order-commands
original_window_utc: 2026-10-26T12:10:00Z/2026-10-26T12:35:00Z
planned_replay_utc: 2026-10-26T18:30:00Z

expected_contract:
duplicate_detection_enabled: true
duplicate_detection_window: PT1H
message_id_source: order-id-plus-command-type
partition_key_source: tenant-id
consumer_idempotency_key: order-id-plus-command-type

containment:
bulk_replay_started: false
producer_deployments_frozen: true
one_canary_only: true
consumer_writes_guarded: true

stop_when:
- message identifier cannot be reconstructed
- duplicate send changes business state
- replayed message cannot be correlated with its original
- queue or dependency pressure exceeds the agreed envelope

Preserve the deployed producer version, replay tool digest, entity resource ID and a redacted manifest of candidate messages. A count is not enough: the decision depends on stable identifiers and the state already written downstream.

Read the effective entity configuration

Duplicate detection is available on Standard and Premium entities, not Basic. It must have been enabled when the queue or topic was created; it cannot be switched on later in place. The history window can be changed when detection is already enabled, but changing it during an incident changes throughput and replay behavior at the same time.

bash 02-read-duplicate-detection.sh
RG="rg-messaging-prod"
NAMESPACE="sb-prod-eu"
QUEUE="order-commands"

az servicebus queue show \
--resource-group "$RG" \
--namespace-name "$NAMESPACE" \
--name "$QUEUE" \
--query '{
  id:id,
  status:status,
  requiresDuplicateDetection:requiresDuplicateDetection,
  duplicateDetectionWindow:duplicateDetectionHistoryTimeWindow,
  partitioning:enablePartitioning,
  sessions:requiresSession,
  active:countDetails.activeMessageCount,
  deadLetter:countDetails.deadLetterMessageCount
}' \
--output json

For a topic, inspect the topic rather than one subscription. Duplicate detection happens when the message enters the topic; subscription filters and consumer settlement happen later. Also capture any forwarding chain, because sending to a different entity creates a different deduplication boundary.

Do not enlarge the window merely to cover the replay. The default is 10 minutes and the supported range is 20 seconds to seven days. A longer window retains and compares more identifiers, which can reduce throughput. Choose it from the maximum legitimate producer retry interval, not from the age of an exceptional recovery batch.

Prove how MessageId is built

Service Bus does not compare payloads, correlation IDs or application properties. It compares the identifier supplied by the sender. If the SDK generated a random identifier, reconstructing the same business command will not reconstruct the same MessageId.

Build an evidence table from the original envelope, producer code and business ledger:

text 03-identifier-evidence.txt
For every replay candidate, record:
original MessageId
business key and command type
original enqueue time
SessionId and PartitionKey when present
payload or envelope fingerprint
downstream ledger status
planned replay MessageId

Accept only when:
the identifier rule is deterministic and versioned
two different business effects cannot share one MessageId
one logical effect cannot receive a new random MessageId on retry
the original and replay identifiers remain linked in audit evidence

A useful key often combines a business identifier and an operation, for example order-8421/confirm. Using only order-8421 could suppress a later cancellation. Using only a generated UUID makes producer retries indistinguishable from new commands.

Include partitioning, sessions and scheduling

The uniqueness key changes when partitioning is enabled: Service Bus evaluates MessageId with PartitionKey. When sessions are used, SessionId and PartitionKey must align. A replay that preserves MessageId but changes the partition or session key may not exercise the same duplicate-detection path and may also break ordering.

Scheduled messages are part of duplicate detection. If a scheduled message reserves an identifier, a non-scheduled send with the same key inside the window is discarded, and the reverse is also true. Inspect scheduled work before assuming a canary disappeared.

For a partitioned entity, avoid using a batched replay as the first proof. First send individually with the exact keys expected in production. Batching, partition routing and deduplication create too many variables for a useful incident canary.

Separate send deduplication from consumer idempotency

Duplicate detection protects ambiguous or repeated sends. It does not prevent redelivery after a consumer lock expires, an AMQP link is detached or the process crashes after committing a downstream write but before complete.

The consumer therefore needs its own durable decision keyed by the business operation. The minimum observable state is:

sql 04-consumer-ledger.sql
-- Illustrative contract; adapt names and transaction semantics.
SELECT business_key,
     operation,
     source_message_id,
     payload_fingerprint,
     status,
     effect_id,
     committed_at_utc
FROM message_effect_ledger
WHERE business_key = @business_key
AND operation = @operation;

The handler should make the ledger decision and the business effect atomic, or use an outbox/inbox pattern that exposes the intermediate state. A trace saying “processed” is not a ledger. The proof must distinguish not_seen, in_progress, committed, compensated and conflict.

If an existing row has the same business key but another payload fingerprint, stop. This is not a harmless duplicate; it is a conflicting command that requires a business decision.

Predict the replay outcome before sending

Classify every candidate into one of four paths:

text 05-replay-outcome-matrix.txt
SAME KEY, STILL IN WINDOW
Send can succeed while Service Bus discards the new copy.
Use only when suppression is the intended result and prove no new delivery occurs.

SAME KEY, WINDOW EXPIRED
The message can be enqueued again.
Require consumer idempotency and verify the downstream ledger before sending.

NEW KEY FOR THE SAME BUSINESS EFFECT
Duplicate detection cannot protect the operation.
Block unless the consumer ledger safely rejects or compensates the repeat.

NEW TARGET ENTITY
The target has a separate identifier history.
Treat this as a migration, with routing, ordering, capacity and rollback checks.

Do not infer suppression from a successful sender response. By design, the service can accept the send operation and silently discard the duplicate copy. The evidence is the absence of a new enqueued message combined with an unchanged business ledger, not the producer status alone.

Run two canaries

Use a synthetic business key that cannot trigger a real fulfillment path. The first canary tests the entity contract; the second tests the consumer contract.

  1. Send the same canary twice with the same MessageId, session and partition properties. Confirm one delivery and one business decision.
  2. Redeliver or resubmit outside the platform protection path in a controlled environment. Confirm that the consumer ledger prevents a second effect.

Record queue counters before and after, the two sender operation IDs, received MessageId, sequence number, consumer trace and ledger result. Counters may be eventually observed and concurrent traffic can obscure a single message, so correlate the canary identifier rather than relying on a dashboard delta alone.

Keep scheduled messages disabled for the canary unless scheduling is the path under test. Keep producer retries at their deployed value: a test client with different retry behavior does not prove production handling.

Execute a bounded replay

The manifest must name the original and planned identifiers explicitly. It should also say why each message is safe to execute now.

yaml 06-replay-manifest.yml
batch: replay-20261026-01
source: order-commands/$DeadLetterQueue
target: order-commands
selection:
original_enqueued_from_utc: 2026-10-26T12:10:00Z
original_enqueued_to_utc: 2026-10-26T12:35:00Z
schema: order-command.v4

identifier_policy:
preserve_message_id: true
preserve_session_id: true
preserve_partition_key: true
add_replay_batch_property: true

gates:
downstream_state_checked: true
consumer_idempotency_proven: true
one_message_canary: passed
max_messages: 100
batch_size: 10
pause_seconds: 60

rollback:
stop_sender: immediate
leave_unprocessed_source_messages: true
quarantine_conflicts: true
compensation_owner: order-platform-oncall

Send one message, wait for settlement and the business result, then compare the ledger. Continue in small batches only while active count, throttling, consumer errors, dependency latency and conflict count remain inside the recorded envelope.

When moving from a DLQ, complete the source message only after the target send and replay ledger are durably recorded. If target send succeeds but source settlement fails, the same source message can be seen again. The replay ledger must turn that ambiguity into a no-op, not another send.

Decide, validate or roll back

Proceed with the replay when identifiers are deterministic, entity settings match the assumption, the platform canary suppresses a repeated send, the consumer canary rejects a repeated effect and the downstream state is known.

Wait when the original send is still inside the detection window but the intended behavior is to enqueue a fresh recovery command. Changing MessageId to bypass the window is not a timing fix; it transfers all protection to the consumer.

Migrate to a new entity only when duplicate detection was absent at creation and the workload requires it durably. Provision the target through infrastructure as code, mirror non-destructive validation traffic, prove routing and capacity, then cut producers over with a return path. Do not delete and recreate the production entity in place during the incident.

Roll back at the first conflicting ledger entry, second business effect, unexplained missing canary or pressure outside the replay envelope. Stop new sends, leave remaining source messages quarantined, preserve the manifest and compensate only effects proven to have occurred.

Conclusion

Azure Service Bus duplicate detection is a precise send-side control, not a global exactly-once guarantee. Its boundary is one entity, one identifier key and one retained time window.

A safe replay proves the effective configuration, reconstructs MessageId and routing keys, predicts whether each send will be discarded or enqueued, then verifies consumer idempotency with a durable ledger. The final decision is explicit: replay, wait, migrate or hold, with a rollback that stops the sender before ambiguity becomes another production incident.