[Refactor/Chore] Celery worker rebuilds the result backend for every task under gevent (8.5% of worker CPU)
Self Checks
- [x] I have read the Contributing Guide and Language Policy.
- [x] This is only for refactors or chores; if you would like to ask a question, please head to Discussions.
- [x] I have searched for existing issues search for existing issues, including closed ones.
- [x] I confirm that I am using English to submit this report, otherwise it will be closed.
- [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
- [x] Please do not modify this template :) and fill in all the required fields.
Description
The Celery worker rebuilds the result backend object for every task it runs.
Celery keeps the result backend per thread unless the backend is declared thread safe (result_backend_thread_safe, default False). Dify starts workers with the gevent pool, where every task runs in a new greenlet and thread-local state is greenlet-local. celery/app/trace.py reads task.backend for every task, finds nothing for the new greenlet, and calls Celery._get_backend(). That goes through backends.by_url → backends.by_name → load_extension_class_names, which calls importlib.metadata.entry_points() and scans the metadata of every installed package.
Dify sets task_ignore_result=True, so the backend that is rebuilt for each task is not even used to store a result.
I propose setting result_backend_thread_safe=True when the backend is Redis (the default CELERY_BACKEND). The Redis backend works through a connection pool, and Celery then builds it once per process.
Motivation
Measured on 1.19.0 (Celery 5.6.3), worker -P gevent -c 100, one worker process, a 22-node workflow called through POST /v1/workflows/run at concurrency 20.
CPU profile of the worker (py-spy, 100 Hz, 30 s, idle time excluded):
| Share of worker CPU inside the entry-point scan | |
|---|---|
| Current | 8.5% (249 of 3,008 samples), all under trace_task → Task.backend → Celery._get_backend → by_name → load_extension_class_names → entry_points |
With result_backend_thread_safe=True |
0% (0 of 2,995 samples) |
Throughput of the same worker, three rounds of 300 runs each:
| Runs per second | Median latency | |
|---|---|---|
| Current | 9.68, 9.62, 9.65 | 1.93–1.96 s |
With result_backend_thread_safe=True |
10.56, 10.98, 10.79 | 1.68–1.74 s |
That is about 11% more throughput. The cost is per task, so it applies to every queue the worker serves (workflow execution, storage, dataset indexing, mail), not only to workflows.
Additional Context
Both measurements were taken with #46244, #46254 and #46266 applied, so the baseline here is already higher than stock 1.19.0. I will open a pull request with the one-line change and a test.