The symptom and three explanations#
A fictional orders-api publishes an order.placed message for every order, and fulfilment-worker consumes it and creates a shipment. On 2026-11-18 at 14:22 UTC the warehouse reports two shipments for order ord-31877, created 31 seconds apart. Three explanations fit:
- The producer sent it twice. The publish call timed out on the client after 10 seconds, although the broker had stored the message, and the retry published a second message.
- The broker delivered it again. The consumer processed the message and acknowledged it, and the broker delivered it again anyway, as at-least-once delivery allows.
- The consumer processed it twice. The worker created the shipment and then crashed before its acknowledgment, so the message became available again and a second delivery repeated the work.
All three predict two shipments. The time between them predicts little: a client timeout plus a queue wait can come to about the same 30 seconds as a visibility timeout. Choose the observation where explanations disagree
Where the predictions differ#
| Observation | Producer sent twice | Broker redelivered | Consumer crashed before ack |
|---|---|---|---|
| Two shipments for one order | yes | yes | yes |
| Message ids of the two processings | differ | same | same |
| Delivery or receive count on the second processing | 1 | can be above 1 | above 1 |
| Publish attempts for the order in the producer's log | two, the first timed out | one | one |
| The first processing's acknowledgment in the consumer's log | logged | logged | missing, and the process ended |
| Time between the processings | client timeout plus queue wait | about the ack deadline or visibility timeout | about the ack deadline or visibility timeout |
The message id row separates the producer from the other two, and Google's Pub/Sub documentation states the rule: the service assigns distinct ids to a message the publisher sent twice, keeps the same id across redeliveries, and different ids mean the duplication occurred upstream at the publisher. Pub/Sub duplicates · Redelivery and message id
For the same id, the acknowledgment row separates the broker from the consumer. SQS documents both cases for standard queues: a message that is not deleted becomes visible again, and on rare occasions a copy on a server that was unavailable during the delete is delivered again. Kafka has the consumer case under another name: a consumer that crashes after processing and before saving its position makes the next consumer process the same messages again. SQS visibility timeout · SQS at-least-once delivery · Kafka delivery semantics
The lab: 20,000 orders, three causes#
The script simulates 20,000 orders. A few are published twice after a client timeout, a few are delivered again after an acknowledgment, and a few are delivered again after the consumer crashed before acknowledging. Each processing is logged the way a consumer can log it: order, message id, delivery attempt, producer request id, start time and whether the ack went out. It needs Python 3.8 or later.
import collections, random, sys
seed = int(sys.argv[1]) if len(sys.argv) > 1 else 1
BACKLOG = float(sys.argv[2]) if len(sys.argv) > 2 else 40.0 # longest wait in the queue, seconds
rng = random.Random(seed)
CLIENT_TIMEOUT, VISIBILITY = 10.0, 30.0
processed = [] # one line per processing, as the consumer logs it
truth = {}
msg_ids = iter(range(1, 10**9))
def deliver(order, req, sent_at, cause):
msg = f"m-{next(msg_ids):06d}"
start = sent_at + rng.uniform(0, BACKLOG) # time waiting in the queue
acked = cause != "consumer" # the consumer crashes before its ack
processed.append((order, msg, 1, req, start, acked))
if cause in ("broker", "consumer"): # the same message comes back
processed.append((order, msg, 2, req, start + VISIBILITY + rng.uniform(0, 5), True))
for n in range(20000):
order = f"ord-{n:05d}"
cause = rng.choices(["none", "producer", "broker", "consumer"], [0.994, 0.003, 0.001, 0.002])[0]
truth[order] = cause
t = n * 0.5
if cause == "producer": # stored, but the reply came after the client gave up
deliver(order, f"req-{n:05d}-a", t, "none")
deliver(order, f"req-{n:05d}-b", t + CLIENT_TIMEOUT + rng.uniform(0, 2), "none")
else:
deliver(order, f"req-{n:05d}-a", t, cause)
by_order = collections.defaultdict(list)
for row in processed:
by_order[row[0]].append(row)
def classify(a, b): # uses only what the consumer logged
if a[1] != b[1]:
return "producer"
return "broker" if a[5] else "consumer"
stats = collections.defaultdict(lambda: {"n": 0, "gaps": [], "ok": 0, "row": None})
for order, rows in by_order.items():
if len(rows) < 2:
continue
a, b = sorted(rows, key=lambda r: r[4])
s = stats[truth[order]]
s["n"] += 1
s["gaps"].append(b[4] - a[4])
s["ok"] += classify(a, b) == truth[order]
s["row"] = s["row"] or (a, b)
print(f"seed={seed} backlog={BACKLOG:.0f}s")
print("cause dups msg ids attempts req ids 1st acked gap s rule agrees")
for cause in ("producer", "broker", "consumer"):
s = stats[cause]
a, b = s["row"]
print(f"{cause:9} {s['n']:4} {'same' if a[1] == b[1] else 'differ':9} {a[2]},{b[2]} "
f"{'same' if a[3] == b[3] else 'differ':9} {'yes' if a[5] else 'no':9} "
f"{min(s['gaps']):3.0f}..{max(s['gaps']):<3.0f} {s['ok']}/{s['n']}")
Before running python3 dups.py, write down which columns will differ between the three causes and whether the gap ranges will overlap. Python 3.11 printed:
seed=1 backlog=40s
cause dups msg ids attempts req ids 1st acked gap s rule agrees
producer 50 differ 1,1 differ yes 1..45 50/50
broker 19 same 1,2 same yes 30..35 19/19
consumer 40 same 1,2 same no 30..35 40/40
The producer's duplicates arrived between 1 and 45 seconds apart, a range that contains every redelivery's 30 to 35 seconds, so the gap cannot assign a pair to a cause. The message ids split producer from redelivery in every pair, and the first acknowledgment splits the two redeliveries. The "rule agrees" column only checks the bookkeeping, since the simulation builds each cause the way the brokers' documentation describes it. A producer duplicate that shared a message id, or a gap range that did not overlap, would have falsified the prediction.
Run python3 dups.py 1 0 to empty the queue. With no wait, the producer's duplicates fall 10 to 12 seconds apart and timing alone does separate them, which is why timing looks decisive on a quiet queue and fails during a backlog. Other seeds change the counts and not the pattern.
Read it on a real system#
The observation needs the consumer to log, for every processing, the message id, the delivery or receive count, an id the producer set, such as a request id or idempotency key, and the result of its acknowledgment. With those fields in CloudWatch Logs, one query lines up both processings:
fields @timestamp, @logStream, orderId, messageId, receiveCount, requestId, event
| filter orderId = "ord-31877"
| sort @timestamp asc
On SQS, each received message carries its MessageId and, when requested, ApproximateReceiveCount, the number of times it has been received and not deleted. Do not call receive-message to look at a message, since a receive changes its visibility and count. ReceiveMessage For separating the same-id cases on SQS, including a delete that used an old receipt handle, see why an SQS consumer processes a message twice.
On Pub/Sub, each message carries its message id and publish time. A delivery attempt count exists only when the subscription has a dead-letter topic, and the subscription/expired_ack_deadlines_count metric shows how often subscribers missed the ack deadline. Delivery attempts · Pub/Sub duplicates
On Kafka, log each record's topic, partition and offset; a consumer's position in a partition is the offset of the next message it will read, so a reprocessed record shows the same offset twice. A producer that retries a send whose first attempt succeeded writes the message to the log again, unless the idempotent producer deduplicates it with its producer id and sequence number. Kafka delivery semantics
On the producer side, look for publish timeouts and retries for the order around the first processing. A client request id carried into the message lets you match each message to the request that created it. Idempotent APIs and retries
Limits#
Two subscriptions on one Pub/Sub topic each receive their own copy of every message, and the message id is assigned once, when the message is published, so both copies carry it. A second subscription or consumer group that nobody meant to create looks like a redelivery until you log the subscription's name. Pub/Sub basics · PubsubMessage
A relay that republishes from an outbox after a crash creates a second message with a new id. The row says "producer", and the producer is the relay, not the service that wrote the order.
Some brokers hide producer duplicates before you can see them. An SQS FIFO queue accepts a message with a deduplication id it has already seen within five minutes and does not deliver it again. A retry after that window is accepted as a new message. Message deduplication ID
A consumer that logs neither the message id nor its acknowledgment leaves only the timing, which the lab shows cannot decide. Add the fields before the next duplicate. A duplicate created by the user, such as a double click that sent two requests, is upstream of all three explanations. One click, two orders
Questions#
Does exactly-once delivery stop duplicate processing?
It stops redeliveries of a message that was acknowledged successfully, on brokers that offer it, such as Pub/Sub's exactly-once subscriptions. It does not merge two messages that the producer published, and a consumer that crashes before acknowledging still gets the message again.
Why do the duplicates have different message ids?
The producer published twice. Look for a publish call that timed out or failed on the client while the broker stored the message, then a retry that published it again.
Should the consumer deduplicate by message id or by order id?
By an id that the business operation owns, such as the order id or an idempotency key set by the producer. A message id catches redeliveries only; it does not catch a second message carrying the same order.