Skip to content

Memory leak with ETA/countdown tasks in 5.7.0: reference cycle between Request and its timer Entry (from #10535) #11139

Closed

Description

@rbedoyatag

Checklist

  • I have verified that the issue exists against the main branch of Celery.
  • This has already been asked to the discussions forum first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).
  • I have tried to reproduce the issue with pytest-celery and added the reproduction script below.

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None. I searched issues and PRs for _eta_timer_entry, scheduled_requests, task_scheduled and eta/countdown memory or leak on 2026-11-20. No open PR touches celery/worker/strategy.py.

Environment & Settings

Celery version: 5.7.0 (collider). The last good version is 5.6.3. main at a2d470f (2026-11-19) is also affected.

celery report Output:

software -> celery:5.7.0 (collider) kombu:5.7.0 py:3.13.18
            billiard:4.3.2 redis:8.1.0
platform -> system:Linux arch:64bit
            kernel version:6.10.14-linuxkit imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:redis results:disabled

broker_url: 'redis://:********@host.docker.internal:6379/9'
deprecated_settings: None
task_serializer: 'json'
accept_content: ['json']
task_ignore_result: True
worker_prefetch_multiplier: 1

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: 3.13 (also reproduced on 3.14.10 and 3.15.2)
  • Minimal Celery Version: 5.7.0 (5.6.3 is not affected)
  • Minimal Kombu Version: 5.7.0
  • Minimal Broker Version: Redis 7.2.6
  • Minimal Result Backend Version: N/A (results disabled)
  • Minimal OS and/or Kernel Version: Linux 6.10.14 (Docker python:3.13-slim, python:3.14-slim, python:3.15-slim-trixie)
  • Minimal Broker Client Version: redis-py 8.1.0
  • Minimal Result Backend Client Version: N/A

Python Packages

pip freeze Output:

From the main run, Python 3.13. The 5.7.0 and 5.6.3 runs used pip install "celery[redis]==<version>" in fresh containers on the same day.

amqp==5.4.2
billiard==4.3.2
celery @ https://github.com/celery/celery/archive/a2d470f198444db889608537a5792216b447429e.tar.gz
click==8.5.1
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
kombu==5.7.0
packaging==26.3
prompt_toolkit==3.0.53
python-dateutil==4.0.0
redis==8.1.0
typing_extensions==4.16.0
tzdata==2026.6
tzlocal==5.4.5
vine==5.1.0
wcwidth==0.9.4

Other Dependencies

Details

A Redis 7.2.6 server as the broker. Nothing else.

Minimally Reproducible Test Case

Details

app.py:

import gc
import os

from celery import Celery

# Long-lived objects standing in for a real application's imports, config and caches. A larger old generation makes
# CPython's full collections rarer, which is how dead cycles pile up in a real worker (0 disables it).
BALLAST = [{'i': i, 's': str(i)} for i in range(int(os.environ.get('BALLAST', '0')))]

app = Celery('repro', broker=os.environ.get('BROKER_URL', 'redis://localhost:6379/15'))
app.conf.update(task_serializer='json', accept_content=['json'], task_ignore_result=True,
                worker_prefetch_multiplier=1)


def rss_mb():
    with open('/proc/self/status') as f:
        return next(int(line.split()[1]) // 1024 for line in f if line.startswith('VmRSS'))


@app.task
def notify(payload):
    # Trivial work, like a webhook/notification task: the payload is barely used
    return len(payload['rows'])


@app.task
def probe():
    # Runs in the consumer process (solo pool): counts Request objects still alive
    from celery.worker.request import Request

    before = sum(isinstance(o, Request) for o in gc.get_objects())
    rss_before = rss_mb()
    freed = gc.collect()
    after = sum(isinstance(o, Request) for o in gc.get_objects())
    print(f'PROBE live_requests={before} rss_mb={rss_before} | gc.collect()={freed} '
          f'| live_requests={after} rss_mb={rss_mb()}', flush=True)

send.py:

import random
import sys

from app import notify, probe

if sys.argv[1] == 'probe':
    probe.delay()
else:
    # ~30k small dicts per message (a few MB once deserialized), countdown 1-5 s
    payload = {'rows': [{'node': f'n{j}', 'value': 'v' * 150, 'n': j, 'meta': {'a': j}} for j in range(30_000)]}
    for _ in range(int(sys.argv[1])):
        notify.apply_async((payload,), countdown=random.randint(1, 5))

run.sh. Run it in a fresh container, for example
docker run --rm -e BROKER_URL=redis://<redis-host>:6379/2 -v $PWD:/repro python:3.15-slim-trixie sh /repro/run.sh c570 'celery[redis]==5.7.0':

#!/bin/sh
# run.sh LABEL PIP_SPEC : 200 countdown tasks, worker RSS every 40, then a gc probe
set -e
pip install -q "$2" 2>/dev/null
cd /repro
echo "$1: celery $(celery --version), python $(python -V | cut -d' ' -f2), BALLAST=${BALLAST:-0}"
celery -A app worker -P solo --concurrency=1 --prefetch-multiplier=1 -O fair \
  --without-gossip --without-mingle --loglevel=info > /tmp/worker.log 2>&1 &
W=$!
sleep 12
rss() { echo $(( $(awk '/VmRSS/{print $2}' /proc/$W/status) / 1024 )); }
echo "$1 start rss_mb $(rss)"
for b in 1 2 3 4 5; do
  for r in 1 2 3 4 5 6 7 8 9 10; do BALLAST=0 python send.py 4; sleep 6; done
  echo "$1 after $((b*40)) tasks rss_mb $(rss)"
done
sleep 8; echo "$1 idle rss_mb $(rss)"; BALLAST=0 python send.py probe; sleep 5
grep PROBE /tmp/worker.log | sed "s/^/$1 /"
echo "$1 succeeded: $(grep -c 'succeeded in' /tmp/worker.log)"

Expected Behavior

A countdown/ETA task's Request is freed when the task finishes, as in 5.6.3, together with its message body and decoded arguments. Worker memory then stays flat under a steady load of countdown tasks.

With 5.6.3 and the script above, once the worker is idle the only live Request is the probe's own, and gc.collect() finds nothing to free:

py315-c563 PROBE live_requests=1 rss_mb=273 | gc.collect()=0 | live_requests=1 rss_mb=273
py314-c563 PROBE live_requests=1 rss_mb=219 | gc.collect()=0 | live_requests=1 rss_mb=219

Actual Behavior

With 5.7.0 and main, requests for countdown tasks that have finished stay alive with their payloads. They are freed only when the cyclic GC happens to do a full collection. No traceback; all 201 tasks succeed.

Same script, idle worker, then the probe:

py315-c570 PROBE live_requests=4 rss_mb=298 | gc.collect()=300109 | live_requests=1 rss_mb=274
py315-main PROBE live_requests=4 rss_mb=269 | gc.collect()=300109 | live_requests=1 rss_mb=268
py314-c570 PROBE live_requests=4 rss_mb=310 | gc.collect()=300109 | live_requests=1 rss_mb=296
py313-c570 PROBE live_requests=4 rss_mb=307 | gc.collect()=150084 | live_requests=1 rss_mb=291
py313-main PROBE live_requests=4 rss_mb=305 | gc.collect()=150084 | live_requests=1 rss_mb=267

Worker RSS (MB) during the run, BALLAST=0:

start 40 tasks 80 120 160 200 idle
Python 3.15.2, celery 5.6.3 61 265 264 250 269 273 273
Python 3.15.2, celery 5.7.0 62 302 317 319 287 310 310
Python 3.15.2, main 62 295 311 312 312 304 304
Python 3.14.10, celery 5.6.3 56 247 252 255 260 264 264
Python 3.14.10, celery 5.7.0 59 303 307 309 312 310 310

On Python 3.13 with BALLAST=1000000, 5.6.3 finishes at 518 MB idle, against 573 MB for 5.7.0 and 559 MB for main.

The minimal script only keeps a few requests at a time. A real worker keeps far more, because it has a much larger long-lived heap (so full collections are rarer) and bigger arguments. We measured that on a real application worker: Python 3.15, solo pool, the same 200 countdown tasks with a few MB of arguments each.

  • 5.6.3: RSS stayed flat at 277–295 MB, and gc.collect() freed 0 objects.
  • 5.7.0: RSS swung between 550 and 970 MB. Once idle, 18 dead Request objects were alive, and gc.collect() freed 2,040,808 objects (850 MB → 591 MB).

In production, a solo-pool worker (1.2 GB memory limit, about 300 countdown tasks an hour, a few MB of arguments each) had been stable on 5.6.3. On 5.7.0 it was OOM-killed every 10–60 minutes. Prefork wouldn't help: the consumer (main) process holds ETA requests, so --max-memory-per-child doesn't recycle them.

Cause

celery/worker/strategy.py (5.7.0 and main) stores the timer entry on the request:

if eta:
    consumer.qos.increment_eventually()
    req._eta_timer_entry = call_at(
        eta, apply_eta_task, (req,), priority=6)
    task_scheduled(req)
    return task_message_handler

call_at() returns a kombu.asynchronous.timer.Entry whose args is (req,), which makes a cycle:

  • req._eta_timer_entry → Entry
  • Entry.args → (req,) → req

When the entry fires, the timer drops it. Then task_ready() removes the request from state.requests, and state.scheduled_requests is a WeakSet. Nothing outside the cycle refers to the request any more, but reference counting can't free a cycle, so the request and its message wait for the cyclic GC. The rate-limited branch (call_at(eta, limit_post_eta, (req, bucket, 1), ...)) makes the same cycle.

Possible fix

Either of these keeps what #10535 needs, namely query_task and cancelling entries on connection loss:

  1. Store a weak reference to the entry. Entry already has a __weakref__ slot, and the timer queue keeps the entry alive until it fires or is cancelled:

    # strategy.py
    req._eta_timer_entry = weakref.ref(call_at(eta, apply_eta_task, (req,), priority=6))
    
    # Consumer.on_close() / connection loss
    ref = r._eta_timer_entry
    entry = ref() if ref is not None else None

    This doesn't depend on ordering. It also covers the threaded timer firing before call_at() returns, the race the comment in strategy.py describes.

  2. Set request._eta_timer_entry = None in Consumer.apply_eta_task(), in Consumer._limit_post_eta() and in task_ready(). This is simpler, but the threaded timer can fire before the assignment in strategy.py, which leaves the cycle in place.

A regression test can push a countdown task through the strategy, fire the timer and call task_ready(). Then, with gc.disable() in effect, it asserts that a weakref.ref to the request returns None.

Activity

  1. added this to the 5.7.x milestone on Nov 21, 2026
  2. auvipy commented on Nov 21, 2026

    @auvipy
    Member

    @ghirailghiro can you verify this? also contributions are welcome @rbedoyatag

  3. ghirailghiro commented on Nov 21, 2026

    @ghirailghiro
    Contributor

    Thanks for the detailed report and the repro, it made this easy to chase down. I could reproduce it: on main an idle worker still has dead requests lying around and gc.collect() frees ~30k objects, with the fix it frees nothing.

    I went with the weakref approach you suggested, since the timer already keeps the entry alive until it fires. PR is up here: #11148

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions