Skip to content

Requeue an acks_late task when storing STARTED fails with a retryable backend error - #11014

Merged
auvipy merged 17 commits into
celery:mainfrom
hasanmahira:fix/requeue-on-backend-unavailable
Nov 28, 2026
Merged

auvipy merged 17 commits into
celery:mainfrom
hasanmahira:fix/requeue-on-backend-unavailable

Conversation

@hasanmahira

@hasanmahira hasanmahira commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Refs #8588. This fixes the case where tasks are lost without running. It deliberately leaves one case open, explained below.

Problem. With task_track_started and acks_late, the worker writes STARTED before running the task body. If the result backend is unreachable, that write raises, and the tracer treats it as a task failure. With the default task_acks_on_failure_or_timeout, the message is then acked. Storing the FAILURE also fails, so nothing records what happened. Every queued task is consumed without running.

Change. In build_tracer, when the STARTED write fails, the task's acks_late is set, and backend.exception_safe_to_retry(exc) is true, raise Reject(exc, requeue=True). Request.on_failure already turns that into reject(requeue=True) without storing a result, so the message waits in the broker until the backend is back. Anything else keeps the current behavior: no acks_late, a backend that doesn't override exception_safe_to_retry (the base class returns False), or a non-retryable error.

This is safe because the task body has not run yet, so redelivery cannot repeat any side effects.

Repro. Redis broker on 6379, separate Redis result backend on 6380. Settings: task_acks_late=True, task_reject_on_worker_lost=True, task_track_started=True. Enqueue 10 tasks, stop the backend, and run celery worker -P prefork -c 1. Each task appends a line to a file.

ran left in queue Pool callback raised exception
main 0 0 (all 10 acked) 10
this PR, backend still down 0 10 0
this PR, backend restarted after 8s 10, each exactly once 0 0

In the last row, all 10 results are stored as SUCCESS.

Left open: a write failing after the task body ran. This is the task_track_started=False case from the issue, and FAILURE stores. I first tried the same requeue for mark_as_done and mark_as_failure. With the backend down for 15 seconds, the 10 tasks ran 1509 times: each run's store failed, the message was requeued, and the task ran again immediately. For tasks with side effects, that is worse than losing the result, so I kept it out of this PR.

Options I can see for that case:

  1. Keep acking (current behavior) and document result_backend_always_retry=True for this setup. In @ChristianMurphy's tests, that setting avoided both problems.
  2. Requeue with a bounded number of redeliveries, similar to task_retry_on_worker_lost (feat(worker): add task_retry_on_worker_lost to limit requeues after worker loss #10843).
  3. Requeue anyway, relying on broker dead-lettering and delivery limits to break the loop.

@auvipy, which would you prefer? I'm happy to do it as a follow-up.

Tests. Three new tests in t/unit/tasks/test_trace.py:

  • requeues with acks_late and a retryable error, without running the body or storing a failure
  • unchanged behavior without acks_late
  • unchanged behavior when the error isn't safe to retry

The first test fails on main.

Checks. t/unit/tasks, t/unit/worker and the base and Redis backend tests pass: 2486 passed. flake8 and isort are clean.

… backend error

With task_track_started and acks_late, a STARTED write that fails because the result backend is unreachable was treated as a task failure, so the message was acked and the task was lost without running. Raise Reject(requeue=True) instead, so the message is redelivered once the backend is back.

Refs celery#8588
@hasanmahira hasanmahira changed the title Requeue an acks_late task when storing STARTED fails with a retryable… Requeue an acks_late task when storing STARTED fails with a retryable backend error Nov 4, 2026
@auvipy auvipy added this to the 5.7.0 milestone Nov 4, 2026
@auvipy auvipy modified the milestones: 5.7.0, 5.7.x Nov 4, 2026
@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.80%. Comparing base (93b5ba0) to head (48ff4b4).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11014      +/-   ##
==========================================
+ Coverage   91.79%   91.80%   +0.01%     
==========================================
  Files         153      153              
  Lines       22243    22288      +45     
  Branches     2784     2792       +8     
==========================================
+ Hits        20417    20462      +45     
  Misses       1530     1530              
  Partials      296      296              
Flag Coverage Δ
unittests 91.78% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@ChristianMurphy ChristianMurphy left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a couple changes before merge. I tested dc38d30, the same change as 613e2ff, with a prefork worker and a Redis result backend that I stopped for 15 s or 60 s. The brokers were Redis, a RabbitMQ classic queue and a RabbitMQ quorum queue.

On a Redis broker and a classic queue, the requeue fixes #8588: all 10 tasks ran once after the backend came back. On a quorum queue it doesn't, because the requeue loops until RabbitMQ drops each task, as the inline comment on line 565 shows.

Most of the waiting could happen in the Redis backend, which already retries writes. set() goes through ensure() with retry_policy, 20 tries about a second apart. But _store_result() reads the stored result first, and that read isn't retried. Each write fails at once on it.

With that read retried the same way on top of this PR, every task ran once on all three brokers, chords included. That was also true with early ack, and through a 60 s outage on a quorum queue. The worker used about 0.1% CPU, and clients reading results still fail at once. This requeue then only runs when an outage outlasts the retries, about once every 20 s per task.

The second change is a warning when the task goes back to the queue. For an error that waiting won't fix, such as a wrong password, the requeue loops forever and nothing in the log says why. The inline comment on line 564 has the numbers.

Documenting result_backend_always_retry=True, option 1 in the description, keeps the tasks but isn't enough on its own. The setting also covers backend writes in the worker's main process, and its retries are unlimited by default. When a pool process exited during the outage, the main process kept retrying mark_as_failure(). The worker then ran 0 of 5 unrelated tasks in 35 s and didn't answer ping.

For the open case, a write that fails after the body ran, the read retry also covers outages up to about 20 s, and the body runs once. Options 2 and 3 requeue there, which runs the body again, as your 1509 runs show.

Waiting in place has costs of its own:

  • While a write waits, its pool process can't take other work. With one process, 0 of 10 ignore_result tasks ran during the outage, against 3 with this PR alone.
  • After a lost pool process, the main process waits about 20 s before it records the failure.

Could the PR add tests for both changes? The new unit tests caught 5 of 5 mutations of the new code. They mock exception_safe_to_retry(), though, so none of them uses a backend's own errors, and none can show the loop. I ran these against main, this PR, and this PR with the read retry:

  • A smoke test that stops the Redis backend container for 15 s while five tasks wait, on a classic and a quorum queue. Main loses all five on both. With this PR, the classic queue run received the tasks 416 times, and the quorum queue run lost all five. Both pass with the read retry.
  • A test_trace.py test with a RedisBackend and a mock client, so that ConnectionError, TimeoutError and ResponseError go through the backend's own exception_safe_to_retry().
  • A sweep over the number of failed reads, from 0 to past max_retries. With the read retry, the body runs once while the failures stay within the limit, and the message goes back once they pass it.
  • A check that the requeue logs a warning.
Suggested tests, with results on main, this PR and the read retry
Test main This PR This PR with the read retry
Smoke, classic queue fails, 0 of 5 ran fails, 416 receipts passes, 3 runs
Smoke, quorum queue fails, 0 of 5 ran fails, 0 of 5 ran passes, 3 runs
Which errors requeue, with RedisBackend and 3 errors 2 fail pass pass
Sweep, 0, 1, 3, 4 and 10 failed reads 4 fail 1 and 3 fail pass
The requeue logs a warning fails fails fails
Read retry in RedisBackend, 4 tests 3 fail 3 fail pass

Stopping the container gives the fast connection errors of an outage. A paused Redis instead makes each try wait for the socket timeout, which slows the loop enough to stay under the quorum queue's delivery limit. A smoke test fits better than an integration test here, because the integration suite shares one worker and one result backend, and stopping the backend would fail the tests that run after it.

The log check passes with a warning like this one:

                         if (task.acks_late
                                 and task.backend.exception_safe_to_retry(exc)):
+                            logger.warning(
+                                'Task %s[%s] requeued: storing STARTED '
+                                'failed: %r',
+                                get_task_name(task_request, name), uuid, exc)
                             raise Reject(exc, requeue=True) from exc

t/smoke/tests/test_backend_outage.py:

"""A short result backend outage doesn't lose tasks or spin the worker (#8588)."""
from __future__ import annotations

from time import monotonic, sleep

import pytest
from pytest_celery import (CeleryBackendCluster, CeleryBrokerCluster, CeleryTestSetup, RabbitMQTestBroker,
                           RedisTestBackend)

from celery import Celery, states, uuid
from t.integration.tasks import get_redis_connection, redis_echo

TASKS = 5
# Shorter than the Redis backend's retry_policy, about 20 s.
OUTAGE = 15


@pytest.fixture
def celery_broker_cluster(celery_rabbitmq_broker: RabbitMQTestBroker) -> CeleryBrokerCluster:
    cluster = CeleryBrokerCluster(celery_rabbitmq_broker)
    yield cluster
    cluster.teardown()


@pytest.fixture
def celery_backend_cluster(celery_redis_backend: RedisTestBackend) -> CeleryBackendCluster:
    cluster = CeleryBackendCluster(celery_redis_backend)
    yield cluster
    cluster.teardown()


@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
    app = default_worker_app
    app.conf.task_acks_late = True
    app.conf.task_track_started = True
    app.conf.worker_prefetch_multiplier = 1
    app.conf.worker_concurrency = 1
    return app


def run_tasks_through_backend_outage(celery_setup: CeleryTestSetup) -> None:
    key = f'backend-outage-{uuid()}'
    # Sending needs no result backend, so this client has none.
    client = Celery('client', broker=celery_setup.app.conf.broker_url, set_as_current=False)
    client.conf.task_default_queue_type = celery_setup.app.conf.task_default_queue_type
    celery_setup.backend.kill()
    try:
        ids = [
            client.send_task(redis_echo.name, (str(i),), {'redis_key': key},
                             queue=celery_setup.worker.worker_queue).id
            for i in range(TASKS)
        ]
        sleep(OUTAGE)
    finally:
        celery_setup.backend.restart()

    redis = get_redis_connection()
    deadline = monotonic() + 30
    while redis.llen(key) < TASKS and monotonic() < deadline:
        sleep(0.5)
    ran = sorted(value.decode() for value in redis.lrange(key, 0, -1))
    assert ran == [str(i) for i in range(TASKS)]

    # The backend's host port changes when it restarts.
    reader = Celery('reader', backend=celery_setup.backend.config()['host_url'], set_as_current=False)
    assert [reader.AsyncResult(i).state for i in ids] == [states.SUCCESS] * TASKS

    logs = celery_setup.worker.logs()
    receipts = sum(logs.count(f'[{task_id}] received') for task_id in ids)
    # Waiting out the outage shouldn't hand each task back hundreds of times.
    assert receipts <= 3 * TASKS


class test_backend_outage:
    def test_tasks_survive_a_short_backend_outage(self, celery_setup: CeleryTestSetup):
        run_tasks_through_backend_outage(celery_setup)

t/smoke/tests/quorum_queues/test_backend_outage.py:

"""A short result backend outage on a quorum queue (#8588).

RabbitMQ drops a message after its delivery limit, 20 by default, so a
requeue loop loses tasks here instead of only spinning.
"""
from __future__ import annotations

import pytest
from pytest_celery import CeleryBackendCluster, CeleryTestSetup, RedisTestBackend

from celery import Celery
from t.smoke.tests.test_backend_outage import run_tasks_through_backend_outage


@pytest.fixture
def celery_backend_cluster(celery_redis_backend: RedisTestBackend) -> CeleryBackendCluster:
    cluster = CeleryBackendCluster(celery_redis_backend)
    yield cluster
    cluster.teardown()


@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
    app = default_worker_app
    app.conf.task_acks_late = True
    app.conf.task_track_started = True
    app.conf.worker_prefetch_multiplier = 1
    app.conf.worker_concurrency = 1
    return app


class test_backend_outage_on_quorum_queue:
    def test_tasks_survive_a_short_backend_outage(self, celery_setup: CeleryTestSetup):
        run_tasks_through_backend_outage(celery_setup)

t/unit/tasks/test_trace_started_store.py, or a class in test_trace.py:

"""STARTED store failures with a Redis backend (#8588)."""
from unittest.mock import MagicMock, Mock, patch

import pytest
from redis import exceptions as redis_errors

from celery.backends.redis import RedisBackend
from celery.exceptions import Reject
from t.unit.tasks.test_trace import TraceCase

MAX_RETRIES = 3


class test_started_store_with_redis_backend(TraceCase):

    def _task(self):
        ran = Mock(name='body')

        @self.app.task(shared=False, track_started=True, acks_late=True)
        def add(x, y):
            ran()
            return x + y

        self.app.conf.result_backend_transport_options = {'retry_policy': {
            'max_retries': MAX_RETRIES, 'interval_start': 0,
            'interval_step': 0, 'interval_max': 0,
        }}
        backend = RedisBackend(app=self.app, url='redis://localhost:1/0')
        backend.client = MagicMock(name='client')
        add.backend = backend
        return add, ran, backend.client

    def _run(self, add):
        with patch('celery.app.trace.report_internal_error'):
            return self.trace(add, (2, 2), {}, eager=False,
                              request={'id': 'id-1', 'delivery_info': {}})

    # Which errors from the backend's own exception_safe_to_retry() send
    # the message back.
    @pytest.mark.parametrize('error, requeued', [
        (redis_errors.ConnectionError('refused'), True),
        (redis_errors.TimeoutError('timed out'), True),
        (redis_errors.ResponseError('WRONGTYPE'), False),
    ])
    def test_requeues_only_for_connection_errors(self, error, requeued):
        add, ran, client = self._task()
        client.get.side_effect = error
        with patch.object(add.backend, 'mark_as_failure') as mark_as_failure:
            if requeued:
                with pytest.raises(Reject) as excinfo:
                    self._run(add)
                assert excinfo.value.requeue is True
                mark_as_failure.assert_not_called()
            else:
                self._run(add)
                mark_as_failure.assert_called()
        ran.assert_not_called()

    # A requeue can repeat without end, so it should say why.
    def test_requeue_is_logged(self):
        add, ran, client = self._task()
        client.get.side_effect = redis_errors.AuthenticationError('invalid password')
        with patch('celery.app.trace.logger') as logger:
            with pytest.raises(Reject):
                self._run(add)
        messages = [str(c) for c in logger.warning.call_args_list + logger.error.call_args_list]
        assert any('id-1' in m for m in messages), messages

    # Sweep the outage length across the retry window. While the backend
    # comes back within retry_policy, the body runs once and nothing is
    # requeued. Past it, the message goes back and the body doesn't run.
    @pytest.mark.parametrize('failed_reads', [0, 1, MAX_RETRIES, MAX_RETRIES + 1, 10])
    def test_outage_length_sweep(self, failed_reads):
        add, ran, client = self._task()
        client.get.side_effect = (
            [redis_errors.ConnectionError('down')] * failed_reads + [None] * 5)
        if failed_reads <= MAX_RETRIES:
            self._run(add)
            ran.assert_called_once()
            assert client.get.call_count == failed_reads + 2  # STARTED, SUCCESS
        else:
            with pytest.raises(Reject) as excinfo:
                self._run(add)
            assert excinfo.value.requeue is True
            ran.assert_not_called()

With the read retry, in t/unit/backends/test_redis.py:

"""Tests that would go with retrying the read in RedisBackend._store_result."""
import json
from unittest.mock import MagicMock

import pytest
from redis import exceptions as redis_errors

from celery import states
from celery.backends.redis import RedisBackend


@pytest.fixture
def backend(app):
    app.conf.result_backend_transport_options = {'retry_policy': {
        'max_retries': 3, 'interval_start': 0, 'interval_step': 0, 'interval_max': 0,
    }}
    backend = RedisBackend(app=app, url='redis://localhost:1/0')
    backend.client = MagicMock(name='client')
    return backend


def test_store_retries_the_read(backend):
    backend.client.get.side_effect = [redis_errors.ConnectionError('down')] * 2 + [None]
    backend.store_result('id-1', None, states.STARTED)
    assert backend.client.get.call_count == 3
    backend.client.pipeline.return_value.__enter__.return_value.execute.assert_called_once()


def test_store_gives_up_after_retry_policy(backend):
    backend.client.get.side_effect = redis_errors.ConnectionError('down')
    with pytest.raises(redis_errors.ConnectionError):
        backend.store_result('id-1', None, states.STARTED)
    assert backend.client.get.call_count == 4


def test_store_after_retry_keeps_success(backend):
    stored = json.dumps({'status': states.SUCCESS, 'result': 4, 'task_id': 'id-1'})
    backend.client.get.side_effect = [redis_errors.ConnectionError('down'), stored]
    backend.store_result('id-1', None, states.STARTED)
    backend.client.pipeline.assert_not_called()


def test_client_reads_fail_fast(backend):
    backend.client.get.side_effect = redis_errors.ConnectionError('down')
    with pytest.raises(redis_errors.ConnectionError):
        backend.get_task_meta('id-1')
    assert backend.client.get.call_count == 1
What I ran: each design under the same outage, CPU, self-heal time, chords, and the read retry

Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0, RabbitMQ 4.1.8, Redis 7.0.15. The worker ran -P prefork -c 1 with task_acks_late, task_reject_on_worker_lost and task_track_started. The result backend was a separate Redis that I stopped before the worker started and restarted after the outage, keeping its data. Ten tasks, or five chords of two tasks each.

15 s outage, ten tasks:

Design Redis broker Classic queue quorum queue Early ack Worker CPU All done after the backend returned
main 10 lost 10 lost 10 lost 10 lost 0.1% never
This PR all ran, 2,436 receipts all ran, 2,971 receipts 10 lost, 210 receipts 10 lost 94 to 106% 0.2 s
result_backend_always_retry=True all ran all ran all ran all ran 0.1% 0.4 to 7.8 s
Read retry in the Redis backend, with this PR all ran all ran all ran all ran 0.1% 0.6 to 0.8 s
Send the task again with a countdown, like task_retry_on_worker_lost all ran, 40 receipts all ran all ran all ran 1.2% 0.6 s with a 5 s countdown
Run the task without storing STARTED ran, no result stored ran, no result stored ran, no result stored ran, no result stored 0.1% ran during the outage
This PR, waiting 1 s before each requeue all ran, 25 receipts all ran all ran not run 0.9% 0.8 s

"All ran" means each task ran once with its result stored. The countdown design keeps unrelated tasks flowing, but it waits default_retry_delay (180 s by default) and gives up after max_retries.

60 s outage on a quorum queue, ten tasks:

Design Result Receipts
This PR 10 lost 210
Read retry alone 9 ran, 1 lost 10
Read retry with this PR all ran 13
result_backend_always_retry=True all ran 10

Five chords, 15 s outage: all five bodies ran with this PR, with result_backend_always_retry=True and with the read retry, on the Redis broker and the classic queue. The read retry with this PR also ran all five on a quorum queue through a 60 s outage. Running the task without storing STARTED didn't run any body, because the header results weren't stored.

Broker CPU during the outage was 4 to 6% with this PR, and 0.2 to 0.9% with the others. With one pool process, ten tasks that store results and ten ignore_result tasks on a classic queue:

Design ignore_result tasks run during the outage
This PR 3
The designs that wait in place 0
Send the task again with a countdown 10

A pool process killed with os._exit() during the outage, then five ignore_result tasks, on a worker with two processes:

Setting Tasks run within 15 s Within 35 s ping reply
main 5 5 yes
result_backend_always_retry=True 0 0 no
Read retry with this PR 0 5 yes

The read retry I ran, on top of 613e2ff. test_redis.py, test_base.py and test_trace.py pass with it (506 tests). Reading a result while the backend is down still fails after 0.1 s, while a store retries for 19 s:

diff --git a/celery/backends/redis.py b/celery/backends/redis.py
index 2a6da4618..99eca125a 100644
--- a/celery/backends/redis.py
+++ b/celery/backends/redis.py
@@ -12,6 +12,7 @@ from urllib.parse import unquote
 from uuid import uuid4
 
 from kombu.utils import symbol_by_name
+from kombu.utils.encoding import bytes_to_str
 from kombu.utils.functional import retry_over_time
 from kombu.utils.objects import cached_property
 from kombu.utils.url import _parse_url, maybe_sanitize_url
@@ -802,6 +803,26 @@ class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin):
             retries, max_retries or 'Inf', humanize_seconds(tts, 'in '))
         return tts
 
+    def _store_result(self, task_id, result, state,
+                      traceback=None, request=None, **kwargs):
+        # The base class reads the stored result before it writes, so it
+        # doesn't replace a SUCCESS. set() retries the write with
+        # retry_policy; retry that read the same way, so that a short outage
+        # doesn't fail the store before the write is tried. Reads by clients
+        # (AsyncResult.state) still fail fast.
+        meta = self._get_result_meta(result=result, state=state,
+                                     traceback=traceback, request=request)
+        meta['task_id'] = bytes_to_str(task_id)
+        current_meta = self.ensure(self._get_task_meta_for, (task_id,))
+        if current_meta['status'] == states.SUCCESS:
+            return result
+        try:
+            self._set_with_state(self.get_key_for_task(task_id),
+                                 self.encode(meta), state)
+        except BackendStoreError as ex:
+            raise BackendStoreError(str(ex), state=state, task_id=task_id) from ex
+        return result
+
     def _set_with_state(self, key, value, state):
         if state == states.FAILURE:
             return self.set(key, value, expires=self.failure_expires)

Comment thread celery/app/trace.py Resolved
Comment thread celery/app/trace.py Resolved
RedisBackend.set() already retries with retry_policy, but the read that _store_result does first didn't, so a short outage failed the store at once and the STARTED requeue looped. Retry that read the same way through a _get_task_meta_for_store() hook. Reads by clients still fail fast. Also log a warning when a task is requeued because STARTED couldn't be stored, since errors like AuthenticationError are retryable for Redis and would otherwise loop silently.
@hasanmahira

Copy link
Copy Markdown
Contributor Author

Thanks @ChristianMurphy, this was really thorough. Pushed 3ec401c with both changes.

Read retry. Same behavior as your diff, but through a small hook instead of copying _store_result into RedisBackend. BaseKeyValueStoreBackend._store_result now reads through _get_task_meta_for_store(), which defaults to _get_task_meta_for(). RedisBackend overrides it to call self.ensure(self._get_task_meta_for, (task_id,)), so it uses the same retry_policy as set(). Client reads (get_task_meta, AsyncResult.state) still fail fast. Happy to switch to your full override if you prefer it.

Warning. Added before the Reject, with your wording: Task %s[%s] requeued: storing STARTED failed: %r.

Measured with the same setup as before: Redis broker, Redis backend on 6380, prefork -c 1, 10 tasks, task_track_started=True.

receipts in a 15 s outage after the backend returns at 8 s
dc38d30 3173 10 ran once
3ec401c 4 10 ran once, 10 receipts, no requeue
Tests.

t/unit/tasks/test_trace_started_store.py: a real RedisBackend with a mock client, using your cases. Requeue for ConnectionError/TimeoutError and not for ResponseError; the requeue is logged (with AuthenticationError); and the outage-length sweep over 0, 1, 3, 4 and 10 failed reads, with max_retries=3.
t/unit/backends/test_redis.py::test_RedisBackend_store_read_retry: the read is retried; the store gives up after the retry policy; a SUCCESS found after a retry is kept; client reads fail fast.
6 of the 13 new tests fail without this commit. t/unit/backends, t/unit/tasks and t/unit/worker pass, apart from test_mongodb.py::test_regression_worker_startup_info, which fails the same way on main here because the container runs as root. flake8 and isort are clean.

I couldn't run the smoke tests: there's no Docker daemon where I'm working. If you'd like t/smoke/tests/test_backend_outage.py and the quorum-queue variant in this PR, I can add them. Or, if you already have them written, would you be OK with me adding them with you as co-author?

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Looks good for Redis, with one question for @auvipy. Re-tested 3ec401c.


@auvipy, this PR requeues an acks_late task when storing STARTED fails during a backend outage, so the task isn't acked without running. Sent back right away, the task comes straight back to the worker and fails again. The worker spins at full CPU until the backend returns. On a RabbitMQ quorum queue each try counts as a delivery, and RabbitMQ drops the task after 20, its default delivery limit.

3ec401c adds a wait before the requeue, in the Redis backend: each store retries its read of the stored result with retry_policy, for about 20 s.

Should the wait stay in each backend's store, or move into the tracer, around the stores a pool process makes?

  • Per backend, as now: every Redis store waits up to about 20 s, including writes from the worker's main process. After 3 pool processes were lost in an outage, the worker didn't run any other task for 58 s. Main ran one at 0.7 s. Each other backend needs its own wait, and the database backend still loses every task.
  • In the tracer: one limit covers every backend, and writes from the main process still fail fast. The tracer can't use retry_policy, which is a Redis transport option. result_backend_max_retries doesn't fit either, since it's unlimited by default. So the tracer needs a new setting with a bounded default, such as about 20 s.

I lean toward the tracer.


On your questions: keep the hook. It's smaller than my override, and _store_result() stays in one place. And yes, please add the smoke tests, with me as co-author. Both pass on 3ec401c, and both fail on main and on dc38d30. Every task ran once on each broker, chords too, and a wrong password now logs a warning about every 19 s.

What I ran: the outage matrix, lost pool processes, the database backend, a wrong password, smoke tests and mutations, and a note on the open question

On the open question in the description: the read retry leaves only outages longer than about 20 s on Redis. There the choice is between running the body again and losing the result.

Celery at 3ec401c, Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0, RabbitMQ 4.1.8, Redis 7.0.15, Postgres 17. The worker ran -P prefork -c 1 with task_acks_late and task_track_started, unless noted.

Redis result backend stopped for 15 s, ten tasks or five chords:

Broker Ten tasks Five chords Receipts Worker CPU
Redis all ran once 5 of 5 bodies 10 0.2%
RabbitMQ classic queue all ran once 5 of 5 bodies 10 0.1%
RabbitMQ quorum queue all ran once 5 of 5 bodies 10 0.1 to 0.2%
RabbitMQ quorum queue, 60 s outage all ran once not run 13 0.2%
Redis, early ack all ran once not run 10 0.2%

With ten more ignore_result tasks on one pool process, none ran during the outage, and all ran after it.

Backend down the whole time, -c 2, 3 tasks that call os._exit(), then 5 ignore_result tasks, with ping every 10 s:

Tree First ignore_result task ran ping replies
main 0.7 s 1 of 1
3ec401c 57.8 s 1 of 5

Database backend (db+postgresql), Postgres stopped for 15 s after the worker started, ten tasks:

Tree On a classic queue On a quorum queue
main 0 of 10 ran, all PENDING 0 of 10 ran, all PENDING
3ec401c 0 of 10 ran, all PENDING, no requeue warning 0 of 10 ran, all PENDING, no requeue warning

The worker log shows BackendStoreError: failed to store result on the backend after Failed operation _store_result. Retrying 0 more times.

Wrong Redis password for 45 s, five tasks: 6 receipts, 3 requeue warnings naming AuthenticationError, and none ran.

The container smoke tests from my last comment: 2 passed on 3ec401c.

The whole unit suite has no new failures. The 11 that fail here also fail on main in my environment.

Mutations of the new code, against test_trace_started_store.py, test_redis.py, test_trace.py, backends/test_base.py and test_request.py. The tests caught each one:

Mutation Caught by
Redis hook without the retry test_outage_length[1]
_store_result() skips the hook test_outage_length[1]
No requeue warning test_requeue_is_logged
Warning logged at debug level test_requeue_is_logged
Client reads retry too test_outage_length[4]
Reject without the acks_late check test_track_started_backend_unavailable__without_acks_late
Reject for any error test_does_not_requeue_other_errors
Reject(requeue=False) test_requeues_for_connection_errors[ConnectionError]

@auvipy
auvipy self-requested a review November 5, 2026 02:54
@auvipy

auvipy commented Nov 5, 2026

Copy link
Copy Markdown
Member

the tracer way seems better to me too

Move the wait before a STARTED requeue from the Redis backend's store into the tracer, as discussed in the review. While a task runs, build_tracer sets store_retry_timeout, and Backend.store_result retries errors that are safe to retry, with the usual exponential backoff, until the new result_backend_store_retry_timeout setting (20 s by default) runs out. This covers the STARTED, result and failure stores of every backend, while stores from the worker's main process and reads by clients still fail fast.

A BackendStoreError raised from an error that is safe to retry counts as safe to retry too, so the database backend, which wraps its errors after its own retries, now waits and requeues like Redis. The Redis-only read retry is removed.
@hasanmahira

Copy link
Copy Markdown
Contributor Author

Thanks both. Pushed 4083a45, which moves the wait into the tracer.

How it works

  • build_tracer sets a store_retry_timeout context variable while the task runs (not for eager tasks).
  • While it is set, Backend.store_result retries an error that is safe to retry. It uses the existing exponential backoff (result_backend_base_sleep_between_retries_ms / result_backend_max_sleep_between_retries_ms) until the timeout runs out, logging a warning per retry.
  • The timeout comes from a new setting, result_backend_store_retry_timeout. Its default is 20 s, and 0/None turns it off. It's documented in the configuration guide.

Doing it in store_result rather than around mark_as_done() means only the store is retried, and on_chord_part_return() and the callbacks still run once. It covers STARTED, the result and the failure, for every backend. Stores from the main process (Request.on_failure() after a lost pool process, the solo pool's callbacks) and client reads don't see the context variable, so they still fail fast.

Database backend. It retries 3 times in under a second, then raises BackendStoreError from the OperationalError. A new Backend.store_error_safe_to_retry() also looks at the __cause__ of a BackendStoreError, so the database backend now waits too, and the STARTED requeue uses the same check. A BackendStoreError with no cause, like Redis's "value too large", is still not retried.

Hook. I removed the Redis read retry and the _get_task_meta_for_store() hook. With the wait in the tracer, nothing uses the hook any more. Happy to put it back if you'd rather keep it.

Measured with prefork -c 1, task_acks_late, task_track_started, 10 tasks:

Redis backend down 15 s Redis down 8 s, then back Postgres stopped 15 s after the worker started
e65eaf0 4 receipts, 0 ran 10 ran once 0 of 10 ran
4083a45 4 receipts, 0 ran, no requeue 10 ran once, no requeue 10 ran once, 10 SUCCESS, no requeue

I didn't re-run the lost-pool-process case. A unit test checks that the context variable is cleared after the task, so a store outside the task fails at once.

Tests

t/unit/tasks/test_trace_started_store.py now uses a fake clock and covers:

  • a short outage, where the task runs once and STARTED and SUCCESS are both stored
  • an outage while storing SUCCESS, where the result is kept
  • a long outage, where the task is requeued after 20 s
  • ResponseError, which is not retried
  • the requeue warning
  • no timeout, which means an immediate requeue
  • the timeout not applying outside the task
  • for a backend that wraps a transient error in BackendStoreError: retried; gives up at the timeout; not retried without a cause

The read-retry tests in test_redis.py are gone with the read retry. t/unit/backends, t/unit/tasks, t/unit/worker and t/unit/app pass, except 3 tests that fail the same way on main here: test_mongodb.py::test_regression_worker_startup_info because I run as root, and two test_app.py timezone tests because of missing tz data. flake8 and isort are clean.

Smoke tests. I'll add yours next, with you as co-author.

Stop the Redis backend container for 15 s while five acks_late tasks with track_started wait, on a classic and on a quorum queue. Each task must run once with a SUCCESS result, and the worker must not receive them more than three times each.

Co-authored-by: Christian Murphy <[email protected]>
@hasanmahira

Copy link
Copy Markdown
Contributor Author

Added your smoke tests in 99c3d79, with you as co-author. The only change is the comment on OUTAGE: it now refers to result_backend_store_retry_timeout instead of the Redis retry_policy. They collect and lint cleanly here, but I can't run them without Docker, so CI will be their first real run.

@auvipy auvipy modified the milestones: 5.7.x, 5.8.0 Nov 5, 2026

@ChristianMurphy ChristianMurphy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a few changes before merge. I tested ae3db1a with a prefork worker against Redis, a RabbitMQ classic queue and a quorum queue, with Redis and Postgres result backends.

Moving the wait into the tracer fixed both problems from my last comment. After 3 lost pool processes, the worker ran the next task at 0.7 s, as on main. The database backend kept every task through a 15 s outage. Every task ran once on each broker, chords too, through 60 s on a quorum queue. The worker used 0.2% CPU or less, the broker 0.5% or less, and throughput without an outage matched main.

The changes, each in an inline comment:

  • Recovery is slower. The wait sleeps up to result_backend_max_sleep_between_retries_ms, 10 s by default, so a store can wake about 10 s after the backend is back.
  • The wait counts against the task's time limits. With a 5 s soft limit, tasks failed without running, or were lost.
  • The wait also applies inside the task body, so update_state() now blocks for 20 s during an outage.
  • The docs leave out that the pool process is blocked, that a task can wait twice, and that the requeue needs task_track_started.

On the database backend the two retry loops nest, which floods the log. The inline comment on _ensure_retryable() suggests one loop.

The tests caught most of the mutations I tried on the new code. They missed these:

  • The backoff never grows. A pool process then reads 3,980 times in 20 s instead of 15.
  • Eager tasks wait too.
  • The default changes to 0.
  • The retry warning goes away.

A test that counts reads through a long outage would catch the first. Could the PR also add a changelog entry? Recent fixes such as #10945 and #10944 add one under "Unreleased".

What I ran: outages on each broker and backend, lost pool processes, time limits, large results, overhead and mutations

Celery at ae3db1a and at main 6b67b23, Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0, RabbitMQ 4.1.8, Redis 7.0.15, Postgres 17. The worker ran -P prefork -c 1 with task_acks_late and task_track_started, unless noted.

Redis result backend stopped for 15 s:

Broker Ten tasks Five chords Receipts Worker CPU Done after the backend returned Same at 3ec401c
Redis all ran once 5 of 5 bodies 10 0.1 to 0.2% 0.6 and 1.8 s 0.6 s
RabbitMQ classic queue all ran once 5 of 5 bodies 10 0.0 to 0.1% 2.6 and 5.6 s 0.6 to 0.8 s
RabbitMQ quorum queue all ran once 5 of 5 bodies 10 0.0 to 0.2% 3.8 and 0.8 s 0.6 s
RabbitMQ quorum queue, 60 s outage all ran once not run 12 0.1% 0.6 s 0.6 s
Redis, early ack all ran once not run 10 0.0% 3.0 s 0.6 s

Broker CPU stayed at 0.5% or less. With ten more ignore_result tasks on one pool process, none ran during the outage and all ran after it, 5.0 s after the backend returned.

Backend down the whole time, -c 2, 3 tasks that call os._exit(), then 5 ignore_result tasks:

Tree First ignore_result task ran ping replies
main 0.7 s 1 of 1
3ec401c 57.8 s 1 of 5
ae3db1a 0.7 s 1 of 1

Database backend, Postgres stopped for 15 s after the worker started, ten tasks:

Tree On a classic queue On a quorum queue
main 0 of 10 ran 0 of 10 ran
ae3db1a 10 of 10 ran once, SUCCESS 10 of 10 ran once, SUCCESS

Tasks with soft_time_limit=5 and time_limit=8, five of them, with the Redis backend down for 15 s:

Tree Ran Stored
main 0 5 PENDING
ae3db1a 3 3 SUCCESS, 1 FAILURE from SoftTimeLimitExceeded before the body ran, 1 PENDING after the hard limit

Tasks that sleep 3 s and return 20 MB, three of them, with task_track_started off and Redis stopped for 12 s during the first one:

Tree Stored Worker CPU while waiting Peak RSS First result stored after Redis was back
main 3 PENDING 0.9% 120 MB never
ae3db1a 3 SUCCESS 0.2% 71 MB 9.3 s

The retries before that store slept 0.02, 0.02, 0.00, 0.08, 0.18, 0.45, 0.81, 0.28, 0.78, 7.76 and 9.61 s.

With a fake clock and the Redis client always failing:

  • One store in a 20 s window: 15 reads. With the backoff not growing: 3,980. With a 1 s cap: 46 on median over 200 runs, 57 at most.
  • update_state() in a task body: waited 20 s, then raised. Main raised at once.
  • task_track_started off and the backend down throughout: the body ran once. The pool process then waited 20 s to store SUCCESS and 20 s more to store FAILURE.

Throughput with no outage, 3,000 tasks with a link each, -c 4, local Redis, two runs each: main 956 and 972 tasks/s, ae3db1a 932 and 988 tasks/s, both with 10 Redis commands per task.

Both smoke tests passed on ae3db1a.

The whole unit suite has no new failures. The 11 that fail here also fail on main in my environment.

Mutations of the new code, against test_trace_started_store.py, test_trace.py, backends/test_base.py, test_redis.py, test_database.py, test_request.py, test_app.py and test_defaults.py:

Mutation Result
Sleep not capped at the deadline caught
remaining <= 0 changed to < 0 caught, by hanging under the fake clock
Retry any error caught
The backoff never grows missed
No deadline, so no wait caught
No BackendStoreError unwrap caught
No retry warning missed
Eager tasks wait too missed
ContextVar not reset caught
Wrapper never applied caught
The requeue check skips the unwrap caught
No requeue warning caught
A requeue without acks_late caught
Reject(requeue=False) caught
Default changed to 0 missed

Comment thread celery/backends/base.py Resolved
Comment thread celery/backends/base.py Resolved
Comment thread celery/app/trace.py Resolved
Comment thread docs/userguide/configuration.rst Resolved
…d use one retry loop

- Cap the sleep between store tries at 1 s, so a state is stored soon after the backend is back.
- Stop waiting a second before the task's soft time limit, or its time limit, so the task is requeued rather than failed or killed.
- Run the task body with the wait off, so update_state() and other stores the task makes fail fast as before.
- Pass the deadline to _ensure_retryable(), so one loop applies both result_backend_max_retries and the timeout. It logs the backend's own error without a traceback and calls on_backend_retryable_error() before each try.
- Rewrite the setting's docs, add a changelog entry, and add tests for the backoff, eager tasks, the default, the retry warning, the time limit and the task body.
Comment thread celery/backends/base.py Resolved
auvipy and others added 2 commits November 8, 2026 20:12
With result_backend_always_retry, max_retries can allow tries after the deadline has passed. Before bac962c they slept for 0 s and hit the backend in a tight loop.

Co-authored-by: Aman <[email protected]>
@ChristianMurphy

Copy link
Copy Markdown
Contributor

Looks better. I reran everything on 34ae4ec and the points from my last review are covered. Two small things are left, and neither needs to block the merge.

10 tasks with task_track_started and acks_late, backend stopped main (9c2f238) this PR
15 s, Redis broker 0 ran 10 ran once, 10 receipts
15 s, classic queue 0 ran 10 ran once, 10 receipts
15 s, quorum queue 0 ran 10 ran once, 10 receipts
60 s, each of the three brokers not run 10 ran once, 14 receipts
15 s, PostgreSQL backend 0 ran, 21,841 log lines 10 ran once, 95 log lines
15 s with a 5 s soft or hard time limit not run 10 ran once, no limit hit
1,500 chains of 3 tasks, Redis killed 3 times for 2 s 424 and 456 stopped 0 stopped, twice

What I checked against the last review:

  • All 10 tasks had run 0.5 to 1.5 s after the backend was back.
  • The wait stopped before the time limit and the task was requeued. The limit did not fire.
  • update_state() from the task body failed at once during the outage, as on main. The result was stored afterwards. On main it was lost.
  • The log had about 3 lines per second during an outage, on Redis and on PostgreSQL.
  • The worker answered inspect ping during every outage.
  • The new tests catch 15 of 16 mistakes I planted in the change. The one they miss is STORE_RETRY_LIMIT_MARGIN = 0.

The two things left:

With the wait turned off, the requeue loops again. The docs say "Set to 0 or None to turn the wait off". With 0 and a 15 s outage, 10 tasks were received 3,554 times on Redis and 4,248 times on a classic queue, with a warning each time. They ran once when the backend was back. On a quorum queue all 10 were dropped at their 21st delivery. That is still no worse than main, which loses them at once. A short sleep before the requeue when the wait is off would keep it from spinning. If you'd rather not add that, a sentence in the docs would do.

A quorum queue's delivery limit still ends it. With the default 20 s and a 450 s outage, two tasks were delivered 21 times and dropped, and the other 8 ran once. RabbitMQ puts a requeued message back at the head. The same messages come around every 20 s and reach the default limit of 20 after about 7 minutes. Main loses every task at once there, so this is an improvement. The docs could say that the delivery limit bounds how long an outage a quorum queue survives.

One question for auvipy: the docs say versionadded:: 5.8 and the milestone is 5.7.x. Which one should it be?

Setup of the runs
  • This PR at 34ae4ec against main at 9c2f238, kombu main (445027e), Python 3.14, Redis 7.4, RabbitMQ 3.13 for the classic queue and 4.1 for the quorum queue, PostgreSQL 16.
  • One prefork worker with 2 processes and worker_prefetch_multiplier=1. The backend container is stopped, 10 tasks are published by a client without a backend, and the backend starts again after the outage. Each task writes its number to a separate Redis. "Receipts" counts received lines in the worker log.
  • Each 60 s run requeued 4 times in total. With result_backend_store_retry_timeout=2 and a 60 s outage, Redis ran all 10 once after 58 requeues, and the quorum queue dropped 2.
  • Without acks_late, a 60 s outage still loses the tasks whose wait runs out, 4 of 10 here. The docs say the requeue needs acks_late, so I only note it.
  • The chains use the settings from Celery chain occasionally loses next task, breaking the chain #9835 on RabbitMQ with a Redis backend. No task ran twice.
  • The two smoke tests didn't run here: the worker image failed to build at its pip install step. I ran their scenario directly instead, 5 tasks, one pool process and a 15 s outage on a classic and a quorum queue. All 5 ran once with 5 receipts on both.
  • Unit tests: t/unit/tasks, t/unit/worker and the base, Redis and database backend tests give the same result as main (the same 2 stamping tests fail on both here), and flake8 is clean on the changed files.

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Also can you look into CI? Several jobs are failing

With result_backend_store_retry_timeout off, a task that can't store STARTED is requeued at once until the backend is back. On a quorum queue each requeue is a delivery, so the delivery limit bounds the outage a task survives. Also check that the store wait stops before the soft time limit, not at it.
Main released 5.7.0 and folded its Unreleased changelog entries into the 5.7.0 notes, so the celery#8588 entry moves to a new Unreleased section at the top.
@hasanmahira

Copy link
Copy Markdown
Contributor Author

Thanks @ChristianMurphy. b2d4419 adds both notes to the docs: with the wait off, a task that can't store STARTED goes straight back to the queue until the backend is back, and on a quorum queue the delivery limit bounds the outage a task survives. The time-limit test now checks that the wait stops before the limit, so it catches STORE_RETRY_LIMIT_MARGIN = 0.

On CI: pre-commit.ci was failing its mergeable check on a merge conflict. Main released 5.7.0 and folded the Unreleased changelog section into the 5.7.0 notes. 7c8315a merges main and moves the #8588 entry to a new Unreleased section at the top. The unit tests and pre-commit pass locally after the merge. The other workflows still need approval to run.

@hasanmahira

Copy link
Copy Markdown
Contributor Author

@auvipy could you approve the workflow runs when you have a moment? They've been waiting since the merge-conflict fix. @ChristianMurphy, if b2d4419 covers your last notes, would you mind updating your review? Thanks both.

@auvipy

auvipy commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

can we adjust the API surface changed so that we can include it in a bug fix release rather then waiting for a feature release? if not, we have to wait until the v5.8.x release cycle starts. will approve the CI later then

hasanmahira and others added 2 commits November 28, 2026 08:17
…lease

Remove result_backend_store_retry_timeout. The 20 s wait is now the private _STORE_RETRY_TIMEOUT in celery.app.trace, and _store_retry, _STORE_RETRY_MAX_SLEEP, _STORE_RETRY_LIMIT_MARGIN and Backend._store_error_safe_to_retry() are private too, so the change adds no public API. The behavior is unchanged.

@auvipy auvipy left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its better

@hasanmahira

Copy link
Copy Markdown
Contributor Author

@auvipy yes, c8fc1bd removes the new public API so this can go in a bug fix release:

  • result_backend_store_retry_timeout is gone. The 20 s wait is the private _STORE_RETRY_TIMEOUT in celery.app.trace.
  • The other new names are private: _store_retry, _STORE_RETRY_MAX_SLEEP, _STORE_RETRY_LIMIT_MARGIN, Backend._store_error_safe_to_retry(). _ensure_retryable() only gained a keyword argument.
  • The setting's docs section is removed, and the changelog entry says "up to 20 seconds".

The behavior is unchanged: with a real Redis backend down for 15 s, all 10 tasks ran once, 0.5 s after it came back.

The open inline threads are all covered; I hadn't replied in them, sorry:

  • Requeue straight back: waits up to 20 s first (4083a45, abaa1d7).
  • Requeue warning: 3ec401c.
  • Sleep cap: 1 s, _STORE_RETRY_MAX_SLEEP (abaa1d7).
  • Nested retry loops on the database backend: one loop in _ensure_retryable(deadline=...), which logs the database error once per try without a traceback (abaa1d7).
  • Time limits and update_state(): the wait stops a second before the limit, and the task body runs with the wait off (abaa1d7).
  • Docs wording: the section is gone with the setting (c8fc1bd).

@auvipy
auvipy merged commit 5aaeb86 into celery:main Nov 28, 2026
546 checks passed
@ChristianMurphy

ChristianMurphy commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

I guess I'm a bit late to the party with this 😅

One case is left after this merge, for whoever follows up. A worker started with --time-limit or --soft-time-limit still loses tasks during a short backend outage. The new wait stops before a limit set on the task or in task_time_limit, but it doesn't see the worker's own option. The limit then fires during the wait.

15 s backend outage, 4 acks_late tasks Before this PR main
No time limit 0 ran 4 ran once
task_time_limit = 8 4 ran once
--time-limit 8 0 ran 2 ran once, 2 never ran and stay PENDING
--soft-time-limit 5 0 ran 2 ran once, 2 stored FAILURE without running
What I ran
  • Celery main at bffee14b2 and at 93b5ba0f8, the commit before this merge, with kombu main (9cd1cef8), redis-py 8.2.0, Python 3.13.
  • Redis 7.4 as the broker and a second Redis 7.4 as the result backend, prefork with 2 processes, task_track_started on.
  • I stopped the backend, sent 4 tasks, and started the backend again 15 s after the stop.
  • Each row with a worker option gave the same result twice on main. The worker log shows 2 "Hard time limit" lines for the first and 2 "Soft time limit" lines for the second.

@auvipy

auvipy commented Nov 29, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy I think you can tackle that on a follow up

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.

4 participants