Skip to content

Optimize beat scheduler tick loop by rebuilding heap only on schedule invalidation - #10167

Open
AsymptotaX wants to merge 10 commits into
celery:mainfrom
AsymptotaX:optimize-beat-tick-heap-rebuild
Open

AsymptotaX wants to merge 10 commits into
celery:mainfrom
AsymptotaX:optimize-beat-tick-heap-rebuild

Conversation

@AsymptotaX

@AsymptotaX AsymptotaX commented Mar 3, 2026 •

Copy link
Copy Markdown

Description

I’d like to propose a small change in beat that gives a pretty big performance win on the scheduler hot path.
Right now Scheduler.tick() can end up doing expensive schedule comparison/rebuild work over and over, even when the schedule hasn’t changed.

This PR switches that logic to explicit heap invalidation: we rebuild only when needed (initial build or actual schedule mutation), and keep using the existing heap otherwise.

In practice this means less CPU spent on bookkeeping inside beat, especially for installations with large periodic schedules and frequent ticks.

My Environment

Mac mini (M4)
macOS-26.3-arm64
Python 3.13.5
Celery 5.6.2
Redis: Docker container running locally on the same host

benchmark

Version Entries Ticks Elapsed (s) Tick rate (ticks/sec) populate_heap calls
OLD 1000 20000 7.5215 2,659.0 1
NEW 1000 20000 0.1354 147,709.5 1
Δ — — −98.2% ×55.6 (+5,456%) 💥
Metric Result
Tick throughput improvement ~55× faster
Hot-path complexity O(n) → O(log n)
Heap rebuilds Only on schedule mutation
Idle CPU usage Near-zero
Functional behavior Unchanged

So the intent is straightforward: keep behavior the same, but stop paying O(n)-style scheduler overhead on every tick when nothing changed.

Important note about schedule mutations

This optimization relies on explicit heap invalidation.
So the expected contract is that schedule changes go through scheduler APIs:

  • add(...)
  • update_from_dict(...)
  • merge_inplace(...)
  • set_schedule(...)

Direct in-place mutation of scheduler.schedule (bypassing these methods) may result in a stale heap until the next explicit invalidation.

This is not a regression for normal or documented usage, but an explicit assumption introduced by this optimization.

Copilot AI 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.

Pull request overview

This PR optimizes the celery beat scheduler's hot path by replacing the per-tick O(n) schedule comparison (via schedules_equal + copy.copy) with an explicit heap invalidation flag (_heap_invalidated). The heap is now rebuilt only when the schedule is actually mutated (via add, update_from_dict, merge_inplace, or set_schedule), rather than on every tick. The benchmark cited in the description claims ~55× throughput improvement.

Changes:

  • celery/beat.py: Removes old_schedulers tracking and copy import; introduces _heap_invalidated flag set at construction and cleared after populate_heap(); each schedule-mutating method now sets the flag.
  • celery/beat.py: Adds _heap_invalidated = True to PersistentScheduler.set_schedule() to keep the subclass consistent.
  • t/unit/app/test_beat.py: Adds a regression test verifying that repeated ticks on an unchanged schedule do not trigger additional populate_heap calls.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
celery/beat.py Core optimization: replaces per-tick schedule diffing with explicit _heap_invalidated flag; removes now-unused copy import and old_schedulers; adds flag-setting to all schedule-mutating methods in both Scheduler and PersistentScheduler
t/unit/app/test_beat.py New test validating that populate_heap is called exactly once for consecutive due ticks without a schedule change

Comment thread celery/beat.py Resolved
Comment thread celery/beat.py Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread celery/beat.py Resolved
Comment thread t/unit/app/test_beat.py Resolved
@codecov

codecov Bot commented Mar 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.59259% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.24%. Comparing base (b8f8521) to head (15c9441).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
celery/beat.py 92.59% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10167   +/-   ##
=======================================
  Coverage   88.23%   88.24%           
=======================================
  Files         153      153           
  Lines       19569    19593   +24     
  Branches     2249     2252    +3     
=======================================
+ Hits        17267    17289   +22     
- Misses       2004     2006    +2     
  Partials      298      298           
Flag Coverage Δ
unittests 88.21% <92.59%> (+<0.01%) ⬆️

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

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

@auvipy auvipy added this to the 5.7.0 milestone Mar 8, 2026
@auvipy

auvipy commented Mar 11, 2026

Copy link
Copy Markdown
Member

@ChickenBenny whenever you have some time, feel free to have a look into it

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


You can also share your feedback on Copilot code review. Take the survey.

Comment thread celery/beat.py Resolved
Comment thread celery/beat.py Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.


You can also share your feedback on Copilot code review. Take the survey.

Comment thread celery/beat.py Resolved
Comment thread celery/beat.py Resolved
Comment thread celery/beat.py Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


You can also share your feedback on Copilot code review. Take the survey.

Comment thread t/unit/app/test_beat.py Resolved
Comment thread celery/beat.py Resolved
Comment thread celery/beat.py Resolved
@AsymptotaX
AsymptotaX force-pushed the optimize-beat-tick-heap-rebuild branch from 6d4a20e to a213605 Compare March 17, 2026 22:50

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread celery/beat.py
Comment on lines +361 to +366
# Backward compatibility: custom scheduler implementations may override
# schedules_equal() and expect tick() to call it to detect updates.
if self._has_custom_schedules_equal():
if (self._last_schedule is None or
not self.schedules_equal(self._last_schedule, self.schedule)):
self._heap_invalidated = True

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

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

In the custom-override path, tick() won’t call schedules_equal() when _last_schedule is None because the or expression short-circuits. Previously schedules_equal(None, self.schedule) was invoked, so subclasses overriding schedules_equal() could rely on being called on the first tick too. Consider calling schedules_equal() unconditionally (even with old_schedules=None) to preserve the historical override contract while still using heap invalidation for performance.

Copilot uses AI. Check for mistakes.
Comment thread t/unit/app/test_beat.py
Comment on lines +455 to +483
def test_tick_calls_custom_schedules_equal_override(self):
class CustomScheduler(mScheduler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.schedules_equal_called = 0
self.force_not_equal = False

def schedules_equal(self, old_schedules, new_schedules):
self.schedules_equal_called += 1
if self.force_not_equal:
return False
return super().schedules_equal(old_schedules, new_schedules)

scheduler = CustomScheduler(app=self.app)
scheduler.add(name='test_tick_calls_custom_schedules_equal_override',
schedule=always_due)

with patch.object(
scheduler, 'populate_heap', wraps=scheduler.populate_heap,
) as populate_heap:
scheduler.tick()
initial_populate_calls = populate_heap.call_count

scheduler.force_not_equal = True
scheduler.tick()
scheduler.tick()

assert scheduler.schedules_equal_called == 2
assert populate_heap.call_count > initial_populate_calls

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

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

This test bakes in the new short-circuit behavior where schedules_equal() isn’t called on the first tick when _last_schedule is None. If the goal of the PR is backward compatibility for custom schedules_equal() overrides, the test should instead expect schedules_equal(None, schedule) to be invoked on the initial tick as it was previously.

Copilot uses AI. Check for mistakes.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants