Skip to content

fix(sqs): reuse the FIFO deduplication id when a publish is retried - #2864

Open
alirezaazadi wants to merge 2 commits into
celery:mainfrom
alirezaazadi:fix/sqs-fifo-dedup-stable-id
Open

alirezaazadi wants to merge 2 commits into
celery:mainfrom
alirezaazadi:fix/sqs-fifo-dedup-stable-id

Conversation

@alirezaazadi

Copy link
Copy Markdown

Problem

On a FIFO queue, SQS drops a message whose MessageDeduplicationId it has already seen in the last 5 minutes. That is what makes it safe for a producer to retry a send.

Channel._put generated a new MessageDeduplicationId with uuid4() on every call. When SendMessage reaches SQS but the response is lost (a ReadTimeoutError, which the SQS transport treats as a connection error), Connection.ensure retries the publish by calling _put again with the same message. The retry goes out with a different id, so SQS stores the message twice.

botocore's own retries are not affected, because they resend the identical request. Only kombu's retry creates a new id. _put_fanout had the same problem for FIFO SNS topics.

Reproduction on main (4cadf8b), with a fake FIFO queue that stores the message on the first SendMessage and then raises ReadTimeoutError:

SendMessage attempt 1: MessageDeduplicationId=948b1b7d-daea-4e96-87de-5caaa93acd0e
SendMessage attempt 2: MessageDeduplicationId=963fceb9-4e97-487f-bdb0-09cb48ddf02d
messages stored in the FIFO queue: 2
Reproduction script (no AWS account needed)
from unittest.mock import patch

from botocore.exceptions import ReadTimeoutError
from kombu import Connection, Producer
from kombu.transport.SQS import Channel

url = "https://sqs.us-east-1.amazonaws.com/123456789012/tasks.fifo"
conn = Connection("sqs://", transport_options={
    "region": "us-east-1",
    "predefined_queues": {
        "tasks.fifo": {"url": url, "access_key_id": "x", "secret_access_key": "y"},
    },
})
attempts, stored = [], {}


class FakeFifoQueue:
    def send_message(self, **kwargs):
        attempts.append(kwargs["MessageDeduplicationId"])
        stored.setdefault(kwargs["MessageDeduplicationId"], kwargs["MessageBody"])
        if len(attempts) == 1:
            raise ReadTimeoutError(endpoint_url=url)
        return {"MessageId": "1"}


with patch.object(Channel, "sqs", lambda self, queue=None: FakeFifoQueue()):
    Producer(conn).publish(
        {"hello": "world"},
        routing_key="tasks.fifo",
        retry=True,
        retry_policy={"max_retries": 1, "interval_start": 0,
                      "interval_step": 0, "interval_max": 0},
    )

for n, dedup_id in enumerate(attempts, 1):
    print(f"SendMessage attempt {n}: MessageDeduplicationId={dedup_id}")
print(f"messages stored in the FIFO queue: {len(stored)}")

With this PR applied, both attempts send the same id and the queue stores 1 message.

Fix

The generated id is now stored in the message properties with setdefault, so the first attempt records it and every retry of the same publish reuses it. As with a caller-supplied id, the generated one now also appears in the message's properties in the body.

What does not change:

  • A caller-supplied MessageDeduplicationId is still used as is.
  • Every new publish still gets a new id. Producer.publish builds a new properties dict for each call, and Celery's Task.retry() republishes with a new one too (signature_from_request does not copy the received message's properties).
  • A message that a direct exchange routes to several queues shares one id, which is harmless because SQS deduplicates per queue.
  • In _put_fanout, a message without a properties dict has nothing to store the id in, so it behaves as before.

This touches the same function as #2863. I will rebase whichever of the two merges second.

Tests

  • test_fifo_put_reuses_deduplication_id_when_the_message_is_sent_again: _put called twice with the same message sends the same id and stores it in the properties.
  • test_fifo_deduplication_id_survives_a_retried_publish: Producer.publish(retry=True) with send_message raising ReadTimeoutError once; both attempts carry the same id.
  • test_fifo_each_publish_gets_its_own_deduplication_id: two separate publishes still get different ids.
  • test_put_fanout_fifo_reuses_deduplication_id_when_sent_again: the same for _put_fanout.

The first, second and fourth fail on main and pass with the fix; the third passes on both and guards against making the id global. t/unit/transport/SQS and t/unit/asynchronous pass (549 tests), and flake8, isort and codespell are clean on the changed files.

Channel._put generated a new MessageDeduplicationId on every call for a
FIFO queue. Connection.ensure retries a failed publish by calling _put
again with the same message, so a SendMessage whose response was lost
(SQS stored the message, the client saw a read timeout) went out again
with a different id, and SQS stored the message twice. Record the
generated id in the message properties so every retry of one publish
sends the same id. _put_fanout had the same problem for FIFO SNS topics.

A new publish still gets a new id: Producer.publish builds a new
properties dict for each call, and so does Celery's Task.retry().
@codecov

codecov Bot commented Nov 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.46%. Comparing base (c738c54) to head (69c0b23).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2864   +/-   ##
=======================================
  Coverage   86.45%   86.46%           
=======================================
  Files          80       80           
  Lines       11853    11851    -2     
  Branches     1443     1442    -1     
=======================================
- Hits        10248    10247    -1     
+ Misses       1390     1389    -1     
  Partials      215      215           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants