Skip to content

Arm one rate limit timer per bucket, not one per waiting task - #11075

Merged
auvipy merged 6 commits into
celery:mainfrom
jakul:fix-rate-limit-timer-per-request
Nov 26, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
jakul:fix-rate-limit-timer-per-request

Conversation

@jakul

@jakul jakul commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Note: Before submitting this pull request, please review our contributing
guidelines
& [Anti AI spamming Guidelines] (#10932). Before opening an AI based PR make sure you asked
in the discussion forum or in the related open issues first.

Description

Fixes #5927

I reported this bug in discussion #11070, with the cause and this fix.

@ChristianMurphy's analysis in #5927 (comment) is extra evidence for the same cause. With rate_limit="20/s", 200 tasks took 161 s, where the limit allows about 10 s. It also shows a second effect in kombu: Hub.fire_timers() fires at most 10 timers in each loop, then returns a 1 second poll timeout. So the growing number of timers also lowers the task rate.

This PR fixes the Celery part only. It does not change kombu. #10972 changes the same part of consumer.py for #8119, so one of the two PRs will need a rebase.

Consumer._schedule_bucket_request() armed a new timer each time a request found no token in its bucket. Each of these timers re-arms itself while the bucket has requests. So each received task that waited started a chain of timers that lived until the bucket was empty. On a busy queue the bucket is never empty, so the timers, and the CPU used for each task, grew with the number of tasks received. #11070 and #5927 have the details. With the gevent pool each timer is also a greenlet, so the CPU used by the worker grows over time: we saw one worker go from about 0.3 to about 0.85 of a core in about 35 minutes.

Changes in celery/worker/consumer/consumer.py:

  • Consumer._limit_timers records the pending timer of each bucket as (token, entry). _schedule_bucket_request() arms a timer only for a bucket that has none.
  • The timer calls the new _on_bucket_wakeup(bucket, token). It forgets the recorded timer, then calls _schedule_bucket_request(), which arms the next timer if requests still wait.
  • If the token is not the recorded one, _on_bucket_wakeup() does nothing. This stops a second chain if two threads arm a timer at the same moment (the timer2 thread and the consumer, with the solo or threads pool).
  • on_close() empties the buckets with clear_pending(). It now also cancels their timers through self.timer.cancel(entry) and forgets them. Otherwise a bucket whose timer was cancelled would stay marked as armed, and its requests would never move.

The order of the requests and the rate do not change.

Tests in t/unit/worker/test_consumer.py:

  • 10 waiting requests on a real TokenBucket and a real kombu Timer give 1 timer entry.
  • Each bucket gets its own timer.
  • A wakeup moves the requests that have tokens and arms the next timer.
  • A wakeup that empties the bucket arms no timer, and the bucket can get a timer again later.
  • A wakeup from a timer that is no longer recorded does nothing.
  • After on_close(), a bucket gets a timer again.
  • on_close() cancels and forgets the timers, also when timer.cancel() raises.
  • on_close() forgets the timers when the consumer has no timer.

test_schedule_bucket_request now expects the _on_bucket_wakeup callback. The fake consumers in test_consumer.py, test_control.py and test_eta_query_task.py that call Consumer.on_close() now set _limit_timers = {}. Without the fix, 9 tests in test_consumer.py fail.

Before and after, with an in-process script (in-memory broker, solo pool, 5 tasks a second, 10 seconds):

Tasks run Timer entries after 10 s
main 50 53
This branch 50 1

A pytest-celery test (RabbitMQ broker, Redis backend, Celery 5.7.0 in the worker container, 5 tasks a second) counts the pending rate limit timers in the worker each second for 15 seconds:

Pool 5.7.0 5.7.0 with the same change as a patch
prefork 21 to 61 not run
gevent 9 to 92 1 each second

A smoke test, t/smoke/tests/test_rate_limit.py, does the same check. For it, this PR also adds a rate-limited task in t/smoke/tasks.py and an inspect command in t/integration/tasks.py. The inspect command counts the pending rate limit timers. The test runs on the prefork and gevent pools and passes with this fix. Without the fix it fails: in 10 seconds the timers grow from 21 to 55 (prefork) and from 9 to 66 (gevent).

pytest t/unit: 5229 passed, 98 skipped, 2 xfailed. pre-commit run on the changed files passes.

I used Claude Code to write this change. I reviewed and tested it, and I can explain each part.

🤖 Generated with Claude Code

jakul and others added 2 commits November 10, 2026 10:51
Consumer._schedule_bucket_request() armed a new timer each time a
request found no token in its bucket.  Each of these timers re-arms
itself when it fires and the bucket still has requests, so each request
that waited started a chain of timers that lived until the bucket was
empty.  On a busy queue the bucket is never empty, so the number of
timers grew with the number of requests received, and so did the CPU
time used for each task.

Record the pending timer of each bucket, and arm a timer only for a
bucket that has none.  The timer callback forgets the timer before it
moves the requests, so the next timer can be armed.  A token in the
callback arguments makes a timer that is no longer the recorded one
stop, so two chains cannot serve one bucket if two threads arm a timer
at the same time.  on_close() empties the buckets, so it now also
cancels their timers and forgets them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@auvipy auvipy added this to the 5.7.x milestone Nov 11, 2026
@jakul
jakul marked this pull request as ready for review November 11, 2026 12:12
@ChristianMurphy

Copy link
Copy Markdown
Contributor

Looks good. I ran it against the reproduction from #5927 and a few cases around it, and found nothing to change.

4 processes, RabbitMQ unless noted main (9c2f238) this PR (542639b)
200 tasks at 20/s, prefork 145 done after 110 s 200 in 10.1 s
The same on a Redis broker 144 done after 110 s 200 in 10.1 s
2,000 tasks at 100/s, prefork, prefetch multiplier 20 156 done after 150 s 2,000 in 21.5 and 21.4 s
200 tasks at 20/s, solo and threads not run 200 in 10.2 and 10.1 s
The worker's connection cut for 3 s while tasks wait, prefork, solo and threads prefork: 191 of 400 done after 161 s 400 ran once in 26.3 to 26.4 s
control rate_limit to 100/s while tasks wait 235 of 400 done after 159 s 400 ran, the last of them about a second after the change
Every task with countdown=2 110 of 200 done after 108 s 200 in 12.1 s

On main the first seconds give 20 and 16 tasks, then 1 per second. Here every second has 19 or 20.

The reconnect row is the one I looked at hardest, since a bucket still marked as armed after its timer is gone would never move again. on_close() covers it, and the three pools all picked up at the full rate after the reconnect. The rate change swaps the buckets, and the old bucket still drained through its own timer.

The tests cover the change well. The 8 new ones and the changed test_schedule_bucket_request fail on main's consumer.py and pass here. I planted 9 mistakes in the change, such as arming a timer for every request or leaving the timers recorded in on_close(). The tests caught all 9.

One thing that isn't from this PR, in case it matters for your gevent workers: with the gevent pool I got 10 tasks per second for both a 20/s and a 100/s limit, on main and here alike, with the same CPU over 150 s. So gevent seems to have a second limit of its own. I didn't look for the cause.

Setup of the runs
  • This PR at 542639b against main at 9c2f238, kombu main (445027e), py-amqp 5.4.2, Python 3.14, RabbitMQ 3.13, Redis 7.4.
  • One worker with -c 4 (solo with 1), worker_prefetch_multiplier=4 unless noted, --without-gossip --without-mingle. Each task writes the time it ran to a separate Redis. The runs on main were stopped when they were far past the time the limit allows.
  • The cut is Toxiproxy between the worker and RabbitMQ, 8 s into the run, with task_acks_late. No task ran twice.
  • A limit of 30/m gave one task every 2 s over 78 s.
  • The main process used 2.1 to 2.3 s of CPU for the 2,000 tasks.
  • t/unit/worker/test_consumer.py, test_control.py and test_eta_query_task.py: 234 passed here. flake8 is clean on the two changed files.

@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.

Approving. My runs are in my comment above (or below in the new ui), and nothing has changed since 542639b.

@jakul

jakul commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for testing this so thoroughly, @ChristianMurphy. The reconnect and rate-change cases, and the planted mistakes, are a good extra check that the tests cover what matters. Thanks for the gevent note too. That cap is the same on main, so I will keep it out of this PR.

@auvipy
auvipy self-requested a review November 12, 2026 17:13
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.42%. Comparing base (a239c16) to head (7ccbd9f).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11075   +/-   ##
=======================================
  Coverage   91.41%   91.42%           
=======================================
  Files         153      153           
  Lines       22040    22057   +17     
  Branches     2743     2747    +4     
=======================================
+ Hits        20148    20165   +17     
  Misses       1589     1589           
  Partials      303      303           
Flag Coverage Δ
unittests 91.40% <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.

@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Member

seems the unit test coverage needs to be increased

@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.

should we also consider smoke or integration tests for this changes?

jakul and others added 2 commits November 26, 2026 09:55
on_close() cancels the rate limit timers only if the consumer has a
timer. Add a test for a consumer without a timer. The test checks that
on_close() still forgets the timers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test queues more rate-limited tasks than the worker runs in 10
seconds, then reads the number of pending rate limit timers on the
worker each second with a new inspect command.  One bucket waits for
tokens, so the count must stay at 1 or less.  It runs on the prefork and
gevent pools, with a RabbitMQ broker.  Without the fix for celery#5927 the
count grows with the tasks received.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jakul

jakul commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

should we also consider smoke or integration tests for this changes?

I'd already added them to another branch, I'll pull them in here.

@jakul

jakul commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

seems the unit test coverage needs to be increased

❌ Patch coverage is 95.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.21%.

I saw the message but was confused as it said this branch has higher coverage than the base! I've add another tests to test the uncovered code.

@auvipy
auvipy merged commit de28509 into celery:main Nov 26, 2026
536 checks passed
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.

Rate limit not working as expect with redis in celery 4.2.x, 4.3.x and 4.4.x

3 participants