Sub topic 8
Duplicates and Out-of-Order Delivery: Writing Idempotent Consumers
This chapter assumes you can send, receive, and delete SQS messages with boto3, and that you know what a visibility timeout is. It covers why a standard queue can deliver a message more than once, how to write a consumer that tolerates this, and how FIFO queues reduce the problem.
Why duplicates happen
A standard queue gives at-least-once delivery. Each message is delivered one or more times, and the order is best effort. Two common causes of duplicates:
- The queue stores copies of each message on several servers. In rare cases a copy is not removed in time and is delivered again.
- Your consumer processes a message but crashes, or runs past the visibility timeout, before it calls
delete_message. The message becomes visible again and another consumer receives it.
Messages can also arrive out of order, because a retried message returns to the queue after later messages have already been handled.
Make the consumer idempotent
An operation is idempotent if running it twice has the same result as running it once. You cannot stop duplicates, so you make them harmless.
A reliable approach is to record a unique business key, such as orderId, and skip any message whose key you have already handled. The check and the side effect should be one atomic step. This example uses a SQLite primary key as the guard.
import json
import sqlite3
db = sqlite3.connect("processed.db")
db.execute("CREATE TABLE IF NOT EXISTS processed (order_id TEXT PRIMARY KEY)")
def handle(body):
order = json.loads(body)
try:
with db: # commits on success, rolls back on error
db.execute("INSERT INTO processed VALUES (?)", (order["orderId"],))
print("charging order", order["orderId"]) # the side effect
except sqlite3.IntegrityError:
print("duplicate, skipping", order["orderId"])
handle('{"orderId": "1001"}')
handle('{"orderId": "1001"}') # the second call is skippedIn production, use a conditional write in your own database, such as a unique constraint or a DynamoDB conditional put. Prefer natural idempotency where you can. For example, "set status to shipped" is safe to repeat, while "add 1 to a counter" is not.
Do not rely on arrival order in a standard queue. Put a version number or timestamp in each message and ignore anything older than what you have stored.
FIFO message groups and deduplication IDs
A FIFO queue, whose name must end in .fifo, adds two features.
- Message group ID: messages with the same group ID are delivered in order, and only one message per group is in flight at a time. Different groups are processed in parallel. Use a key such as a customer ID, so one customer's events stay ordered while many customers scale out.
- Deduplication ID: if you send a second message with the same deduplication ID within the 5-minute deduplication window, SQS accepts the call but does not enqueue it again. With content-based deduplication enabled, SQS derives the ID from a hash of the message body.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.create_queue(
QueueName="payments.fifo",
Attributes={"FifoQueue": "true"},
)["QueueUrl"]
for attempt in range(2): # simulates a retried send
sqs.send_message(
QueueUrl=queue_url,
MessageBody='{"paymentId": "p-1", "amount": 25}',
MessageGroupId="customer-42",
MessageDeduplicationId="p-1",
)Only one message reaches the queue. Because a FIFO queue's deduplication covers only the send side and only for 5 minutes, your consumer still needs idempotent logic.
Exercise
A standard queue consumer charges a customer card for each order message. After a deployment, some customers were charged twice. Name one likely cause and one fix.
Show answer
Likely cause: processing took longer than the visibility timeout, or the consumer crashed before deleting the message, so the message was delivered again. Fix: make the consumer idempotent by recording each orderId in a store with a unique constraint and skipping orders already recorded. Also set the visibility timeout above the longest expected processing time.