Sub topic 8
Duplicates and out-of-order delivery: writing idempotent consumers
This chapter assumes you can send, receive, and delete SQS messages and that you know what a visibility timeout is. The examples use Python with boto3 and a DynamoDB table as the state store.
Why duplicates happen
A standard SQS queue guarantees at-least-once delivery. Every message is delivered one or more times, never zero. SQS stores each message on several servers for durability. A delete request can occasionally miss a server that still holds a copy, so that copy can be delivered again.
Most duplicates come from the application and its retry layers, not from SQS itself:
| Source | What happens |
|---|---|
| Visibility timeout expires | Processing takes longer than the timeout. The message becomes visible again while the first consumer is still working. |
| Crash before delete | The consumer finishes the work but dies before `delete_message`. |
| Producer retry | A `send_message` call times out and the client retries, although the first call actually succeeded. |
| Lambda or SNS retry | A failed batch is retried, or SNS redelivers after a slow acknowledgement. |
| Redrive from a dead-letter queue | An operator moves old messages back to the source queue. |
Standard queues also give only best-effort ordering. Messages usually arrive in send order, but a retried message can arrive after messages sent later.
You cannot remove these cases, because they follow from running a distributed system. You make the consumer safe instead.
What idempotent means
An operation is idempotent if running it several times has the same effect as running it once. Setting status = "shipped" is idempotent. Adding 1 to a counter is not. Sending an email is not, unless you track that you already sent it.
You can get idempotency in three ways:
- Make the operation naturally idempotent. Prefer "set" and "upsert" over "increment" and "append". Write to a key derived from the event, such as an S3 object named after the order ID.
- Track processed events. Store a unique ID for each handled event and skip any ID you have seen.
- Use versions. Reject any update older than the state you already hold. This also handles out-of-order delivery.
Choose the right idempotency key
Do not use the SQS MessageId as the key. If a producer retries a send, SQS assigns a new MessageId to the second copy. Put a business identifier in the message body instead, such as eventId or a combination of orderId and event type. The producer creates it once, and retries reuse it.
Pattern: record processed events
The consumer below claims the event ID with a conditional write. DynamoDB accepts the write only if no item with that ID exists, so two consumers racing on the same event cannot both win.
import json
import time
import boto3
from botocore.exceptions import ClientError
sqs = boto3.client("sqs")
dynamodb = boto3.client("dynamodb")
TABLE = "processed-events" # partition key: eventId (S), TTL attribute: expiresAt
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
def claim(event_id):
"""Return True if this consumer is the first to claim the event."""
try:
dynamodb.put_item(
TableName=TABLE,
Item={
"eventId": {"S": event_id},
# Keep claims for 14 days, which matches the maximum retention
"expiresAt": {"N": str(int(time.time()) + 14 * 24 * 3600)},
},
ConditionExpression="attribute_not_exists(eventId)",
)
return True
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False
raise
def release(event_id):
dynamodb.delete_item(TableName=TABLE, Key={"eventId": {"S": event_id}})
def process(order):
print("processing", order)
while True:
resp = sqs.receive_message(
QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=20
)
for msg in resp.get("Messages", []):
order = json.loads(msg["Body"])
if claim(order["eventId"]):
try:
process(order)
except Exception:
release(order["eventId"]) # let a later delivery retry the work
continue # do not delete the message
# Either processed now or already processed earlier: remove it
sqs.delete_message(
QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"]
)Set the DynamoDB TTL on expiresAt so old claims expire. Keep claims at least as long as a duplicate could plausibly arrive, which is bounded by the queue's retention period.
Pattern: reject stale updates
Ordering problems are about state, not repeats. If an order_shipped event arrives before order_paid, a blind write leaves the order in the wrong state. Give each event a monotonically increasing version from the producer, and apply an update only if it is newer than the stored one.
import boto3
from botocore.exceptions import ClientError
dynamodb = boto3.client("dynamodb")
def apply_update(order_id, status, version):
"""Apply the update only if it is newer than the stored state."""
try:
dynamodb.update_item(
TableName="orders",
Key={"orderId": {"S": order_id}},
UpdateExpression="SET #s = :s, version = :v",
ConditionExpression="attribute_not_exists(orderId) OR version < :v",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={
":s": {"S": status},
":v": {"N": str(version)},
},
)
return True
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False # stale or duplicate: safe to ignore
raise
apply_update("1001", "shipped", 3)
apply_update("1001", "paid", 2) # arrives late and is ignoredThe same condition also rejects exact duplicates, because a repeated version is not strictly greater than the stored one. Versioning therefore gives you both protections for state-style data.
Common errors
- Deleting before processing. This turns at-least-once into at-most-once, and a crash loses the message.
- Using
MessageIdas the key. Producer retries produce new IDs, so duplicates pass the check. - Checking then writing. A
get_itemfollowed by aput_itemhas a race window. Use one conditional write. - Side effects outside your store. An email or a payment call cannot be rolled back by DynamoDB. Pass the event ID as the provider's own idempotency key where the API supports one.
- Relying on FIFO to cover everything. FIFO deduplication only covers a five-minute window, and a consumer can still process a message twice after a visibility timeout. Keep the consumer idempotent even on FIFO queues. The next chapter covers FIFO groups.
Exercise
A consumer increments a ordersToday counter once for each message. Under load, the count is slightly higher than the number of orders. Explain the likely cause and give two ways to fix it.
Show answer
Some messages were delivered more than once, for example after a visibility timeout expired or a crash happened before the delete, and each delivery incremented the counter. One fix is to record each eventId with a conditional write and increment only when the claim succeeds. The better fix is to write both in a single DynamoDB transaction. Another fix is to stop incrementing and compute the count from stored per-order items, so a repeated event rewrites the same item.
Exercise
Why does apply_update use version < :v and not version <= :v?
Show answer
With <, an update whose version equals the stored version is rejected, so exact duplicates are ignored. With <= a duplicate would be applied again, which is harmless for a plain overwrite but wrong if the update has other side effects.