Delivery and idempotence
Delivery is not completion
A consumer normally receives a message, performs work, and acknowledges successful handling. In a queue, acknowledgment might delete a received message; in a subscription, it updates delivery state. A visibility timeout or lock temporarily reserves work, and an acknowledgment deadline defines when unacknowledged work can be retried. These mechanisms do not ensure a worker is alive or that an external effect has committed.
Consider this synthetic sequence:
0s Worker A receives E1; lease lasts 30s8s Worker A commits the packing record9s Worker A crashes before acknowledgment30s Lease expires; E1 can become eligible again31s Worker B receives E1 and checks the durable record32s Worker B acknowledges without applying the effect againThe second receive is legitimate redelivery. Acknowledging before committing risks losing work; committing before acknowledging can cause repeated delivery. A lease is not a permanent distributed lock. Even before expiration, some at-least-once systems can redeliver. Extend leases only within supported limits and bound handler execution. A message acknowledgment is distinct from a publisher's confirmation that a broker accepted a message.
At-least-once, at-most-once and exactly-once
At-most-once allows zero or one delivery, so failures can lose work. At-least-once allows repeated delivery within the system's supported retention and retry contract. Exactly-once is meaningful only with a precise scope: which message identity, transport, subscription, acknowledgment, time window and region? None of these terms alone guarantees an external payment or database update happens once.
SQS FIFO deduplicates matching sends within its documented five-minute interval. A consumer that misses its visibility timeout can still face redelivery. Azure Service Bus duplicate detection uses a message ID within a configured window; it is not a substitute for application-level protection. Pub/Sub exactly-once delivery applies to pull subscriptions with its documented regional and acknowledgment requirements, not push subscriptions; repeated publishes can still represent distinct messages. Eventarc Standard is at-least-once. Google Pub/Sub dead-letter attempt counts are approximate and depend on correctly configured permissions.
Consult SQS FIFO processing, Azure message loss and duplicates, Pub/Sub exactly-once and Pub/Sub dead-letter topics. Do not treat marketing labels as end-to-end proofs.
Try an idempotent consumer model
Idempotency means that applying the same logical operation again does not add another intended effect. For example, recording the same packing request twice should not pack twice. The following Python 3 example runs locally without a broker, database, network or dependencies. It stores one quantity per event ID and detects conflicting reuse of an ID. The dictionary models a ledger; it is not persistent storage and is not safe for concurrent workers.
def apply_event(ledger, event): # Sequential, in-memory teaching model; no external effects. if not isinstance(event, dict): return "invalid" key = event.get("event_id") quantity = event.get("quantity") if not isinstance(key, str) or not key or type(quantity) is not int or quantity <= 0: return "invalid" if key in ledger: return "duplicate" if ledger[key] == quantity else "conflict" ledger[key] = quantity return "applied"
ledger = {}for event in [ {"event_id": "E1", "quantity": 2}, {"event_id": "E1", "quantity": 2}, {"event_id": "E1", "quantity": 3}, {"event_id": "E2", "quantity": 1},]: print(apply_event(ledger, event))print(sum(ledger.values()))Expected output:
appliedduplicateconflictapplied3E1 adds two units once, the duplicate changes nothing, the conflicting message is rejected and E2 adds one unit. A real handler must validate identity and schema, atomically insert a unique event record together with the business change in the same database transaction when possible, and acknowledge only after commit. If two workers race, a separate check-then-write is insufficient; enforce uniqueness and transactional behavior. For external effects, use a downstream idempotency key and reconciliation or an outbox/inbox design, not an in-memory flag. The outbox records the outgoing event with the business transaction; its relay can publish more than once, so downstream deduplication remains necessary. Store processed IDs long enough for the expected replay horizon and secure the ledger.
Ordering, retries and dead-letter handling
Ordering normally applies within a group, partition, session or key, not across the whole system. Use a stable order ID as a grouping key when the order lifecycle requires sequence. A hot key may limit parallelism; retries can block later messages or cause them to arrive again, depending on the service. When applying state changes, validate sequence or version numbers rather than trusting arrival time. A late OrderAccepted must not revert a newer OrderShipped state.
A transient error, such as a temporary dependency outage, may justify a retry with bounded exponential backoff and jitter (randomized spacing). A permanent validation failure should go to a reviewed failure path rather than consuming every retry. A dead-letter queue or topic holds failed messages for investigation when configured; it does not fix them. Some systems can drop events after a retry horizon without dead-lettering. In a teaching policy with at most three total attempts, failures on attempts one and two retry, and failure on attempt three goes to the failure path. This exact threshold is a model, not a provider setting.
Before replaying dead-letter messages, identify the root cause, fix the consumer or schema, review payloads under least privilege, preserve the original event ID, choose a small bounded batch and monitor successful business effects. If the event conflicts with current state, reconcile manually. Set retention and alerting for the failure path itself. Do not blindly replay a whole backlog.
Count attempts, cost and recovery
A batch contains 1,000 logical messages. Forty need one extra attempt and ten different messages need two extra attempts. Total attempts = 1,000 + 40 + 20 = 1,060. At a hypothetical $2 per million attempts, the modeled charge is $0.00212, before any storage, transfer, API overhead or worker costs. Actual provider pricing units differ; this is arithmetic practice, not a cloud quote.
If a lease lasts 10 seconds but an operation needs 14 seconds, the lease expires before completion unless renewed; another worker may start processing. A longer lease reduces this risk but can delay recovery after a crash. Measure processing duration, configure the lease accordingly, renew when appropriate, and maintain idempotency regardless. For retries with base 2 seconds and maximum 10 seconds, a deterministic no-jitter sequence is 2, 4, 8, 10; production clients should randomize bounded delays where appropriate and respect deadlines.
Practice: trace an event through a crash, duplicate and conflict; calculate retry load and propose a dead-letter review procedure. Use counts of distinct successful effects, retry rate, oldest unprocessed age, dead-letter age and acknowledgment failures to diagnose the system. No real notification or queue is required. Next: workflow orchestration and integration.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Delivery and idempotence — knowledge check
Choose the best answer for each offline scenario.
The worker commits and crashes before acknowledging. What should the next worker do?
What is the effect of SQS FIFO send deduplication?
Which Pub/Sub mode supports the documented exactly-once delivery feature?
1,000 messages, 40 with one additional attempt and 10 others with two. How many attempts?
A permanently invalid message reaches a failure path. What is the best next step?