Skip to content

Celery prefetch and routing: handling slow and memory-heavy tasks

Blueprint drawing of a conveyor that task_routes splits in two: quick celery sprigs on queue='default' and heavy bunches on queue='slow_queue', one bunch at a time with worker_prefetch_multiplier = 1

When slow and quick Celery tasks share a worker, the slow ones delay the quick ones, and a worker that runs too many memory-heavy tasks at once can run out of memory and crash. Fix the first by routing slow tasks to a queue with workers of its own (task_routes and celery worker -Q). Fix the second on that worker: fewer processes (-c), worker_max_memory_per_child to replace a process that grows too large, and worker_prefetch_multiplier = 1 so long tasks don’t sit reserved in one worker while another could start them.

If you’re new to Celery, start with what Celery is and how it works. For tasks that disappear rather than wait, read how to stop losing Celery tasks, and for retries and idempotency, the more advanced tips and tricks.

For more on running Celery, see our Celery engineering insights.

Key takeaways

Give slow tasks their own queue

Route them with task_routes and start a worker with -Q slow_queue, so quick tasks never wait behind them.

Add workers where the work is

Routing keeps the queues apart; only more workers raise how many slow tasks finish each second.

Limit prefetch for long tasks

worker_prefetch_multiplier (4 by default) sets how many tasks each worker process reserves. Set it to 1 for long tasks, so they don’t wait in one worker while another is free.

Cap memory per worker

Run heavy tasks with fewer processes (-c) and set worker_max_memory_per_child: memory grows with how many heavy tasks run at once.

Watch the queues

Monitor backlogs and slow tasks with Flower, so you see a clogged queue before your users do.

When we are new to Celery, we tend to use its basic configuration after following the Celery first steps. This is fine if we have just a few tasks running on our cluster and they usually take the same time to be executed. However, as the number of tasks starts to grow and they get more and more complex, there are a few configuration options that we need to take care of if we want to avoid problems.

In this post, we are gonna go through two of the problems that may happen if we don’t take care of our routes. One of them is that if we have a task that takes too long to execute sharing the worker of quick tasks, it may cause a delay on the quick tasks execution and even resource starvation depending on the number of slow tasks. Another problem is that if we have too many tasks waiting in the queue to be executed, we may have problems with the worker’s memory, even making it crash.

Before starting with the goal of this post itself, let’s take a quick look on how to use multiple queues with Celery, how to select which workers will consume each queue and how to route the tasks between those queues. However, if you are pretty comfortable with routing tasks, feel free to jump to the next sections: Dealing with time-consuming tasks or Dealing with memory-consuming tasks.

Introduction to routing

When developing Celery tasks, we should always keep in mind that we are able to create multiple queues and distribute our tasks between them. To do that we need to follow three steps:

The first thing we need to do is to create the queue itself. There are two ways to do that, we can either do it automatically by using the task_create_missing_queues, which will look for the predefined queues and create them for us, or we can do it manually by defining the queues on the project settings. Here is an example of how we can create our queues:

1 - Creating queues automatically

Python
app.conf.task_create_missing_queues = True

task_create_missing_queues is enabled by default in current Celery versions, so a queue you route a task to is created for you; the setting above only matters if your project turned it off.

2 - Creating queues manually

Python
from kombu import Queue

app.conf.task_default_queue = 'default'
app.conf.task_queues = (
    Queue('default', exchange='default', routing_key='default'),
    Queue('queue2', exchange='queue2', routing_key='queue2')
)

The second step is to make the worker consume the newly defined queue. To do that, we can use the celery worker -Q option:

Shell
celery -A proj worker -Q queue2

Finally, we should route our tasks to the created queues. We have three options to do that: do it on the settings, do it on the task or do it on the apply_async call. Here is an example of how to do that:

1 - Routing tasks in the configuration

Python
app.conf.task_routes = {
    'path.to.the.new_task': {
        'queue': 'queue2',
        'routing_key': 'queue2'
    }
}

If you wanna read more about how to set your task_routes, you can check this section of the Celery docs.

2 - Routing tasks on the task definition

Python
@app.task(queue='queue2')
def new_task():
    ...

3 - Routing tasks on the apply_async call

Python
from path.to.the import slow_task

slow_task.apply_async(queue='slow_queue')

That’s it. However, if you still wanna read more about Routing, you should check the Celery documentation.

Now that you are familiarized with Celery and routing, we can start to look at the problems and how we can optimize our usage of Celery to manage them. Here are two tips on how to optimize the use of queues and avoid some issues.

Dealing with time-consuming tasks

Consider that we have two tasks being executed by the same worker, a slow_task and a quick_task. The slow_task takes 10 seconds to execute and you receive a new one every second. In addition, the quick_task executes in 10 milliseconds and you receive 10 new ones per second. In this situation, just during the time it takes to execute one slow_task we would have 10 new slow_tasks and 100 new quick_tasks waiting. If you stop to think about these numbers, in a short period of time, we would have an immense number of tasks waiting to be executed, and some of them may “never” be executed due to the creation/execution rate.

To be able to monitor your Celery usage and check for problems like the one on the example, we recommend you to use Flower, which is a web-based tool for monitoring Celery clusters. You can also check the monitoring section of the more advanced tips and tricks post for more details on how to monitor your tasks.

The situation above will delay a lot the execution of some tasks. For instance, think of your customer waiting for that ‘recovery email’, and it is taking hours to arrive. Also, we may not be able to execute all the needed tasks since the demand is way greater than the supply (check the numbers). Besides these problems, we also want some tasks to be executed more quickly than others. The password recovery email should be sent before the monthly PDF report is generated, for example.

The idea to solve this problem has two parts. First, we need to add more workers so we can solve the supply VS demand problem. Then, we need to create different queues and routes, so the quicker tasks won’t need to wait for the slower tasks.

To apply this solution we need to follow three steps. The first thing we have to do is to create a specific queue for the slow_task to be executed. As we saw in the previous section, we can create the queue on the project’s settings as follows:

Python
from kombu import Queue

app.conf.task_queues = (
    Queue('default', exchange='default', routing_key='default'),
    Queue('slow_queue', exchange='slow_queue', routing_key='slow_queue')
)

The next step, after creating the new queue, is to create a new worker that will consume the new queue and set the default worker to consume only the default queue. We can do that by running the following commands:

Shell
celery -A [PROJECT_APP] worker -n [WORKER_NAME] -Q default
Shell
celery -A [PROJECT_APP] worker -n [WORKER_NAME] -Q slow_queue

Finally, we just need to route the slow_task to the correct worker. We can do this by setting up the task_routes on the project’s settings:

Python
app.conf.task_routes = {
    'path.to.the.slow_task': {
        'queue': 'slow_queue',
        'routing_key': 'slow_queue'
    }
}

Using this approach we would have the slow_tasks taking its time to execute in a separate worker and the quick_tasks being executed as soon as they arrive to the default worker.

Dealing with memory-consuming tasks

Now that we’ve handled the first problem, we can talk about the second one. Let’s keep the same scenario from the first problem’s solution. We have the default_worker taking care of the quick_task and the slow_worker taking care of the slow_task. Previously, we said the slow_task would take 10 seconds to execute and that we received a new one every second. However, this time let’s take things a little bit further.

Let’s say that our slow_task makes a lot of database queries and processes the retrieved data in memory. Also, our database is becoming larger and larger and queries take some time to be executed. Now, our slow_task is taking 30 seconds to execute and we still receive a new one every second. In this new situation, in just one minute, we would have received 60 new slow_tasks and executed only 2.

The problem here is that our worker has a limited amount of memory, and each worker process runs one slow_task at a time. Memory use grows with how many processes run slow_task together: with the default concurrency, one process per CPU core, a few of them loading large query results at once can exhaust the machine’s memory and crash the worker, which would be pretty bad for us.

To keep that in check, start the slow worker with fewer processes (-c 2, for example), so only that many heavy tasks run at once, and set worker_max_memory_per_child so Celery replaces a process once its memory passes the limit. Keep task arguments small as well: pass IDs, not large payloads, since reserved tasks wait in the worker’s memory as messages.

Prefetching is the other half. By default, each worker process reserves four tasks ahead of time (worker_prefetch_multiplier, 4 by default). Those reserved messages cost little memory when their payloads are small, but with long tasks they wait in one worker while another worker could already be running them. Setting worker_prefetch_multiplier to 1 tells Celery to reserve one task per worker process at a time. If you wanna read a little bit more about Celery prefetch limits you can take a look here.

With Django’s CELERY_ settings namespace the setting is CELERY_WORKER_PREFETCH_MULTIPLIER. Its old name, CELERYD_PREFETCH_MULTIPLIER, is still read until Celery 6.0. Two more details are worth knowing:

  • A multiplier of 1 still reserves one extra task per process with Celery’s default early acknowledgment: a worker started with -c 10 can hold 10 tasks running and 10 waiting. To reserve only as many tasks as there are processes, set task_acks_late = True together with worker_prefetch_multiplier = 1, and make the tasks safe to run twice.
  • Tasks that can’t be acknowledged late can use worker_disable_prefetch = True (the worker’s --disable-prefetch flag), added in Celery 5.6: the worker then fetches a task only when a process is free. It currently works only with Redis as the broker.

Prefetch also cuts the other way: for many short tasks, the Celery documentation suggests a much larger multiplier, such as 50 to 150, to save round trips to the broker. That is one more reason to keep quick and slow tasks on separate workers, each with the prefetch that suits it.

Okay, that’s everything for now. Let’s recap:

  • We should use routing to have a more balanced task load between workers;
  • We can use Flower to monitor our Celery cluster and check for problems related to its usage;
  • We should have a separate worker to tasks that takes too long to be executed;
  • When we have tasks that are way too memory-consuming, we should limit how many run at once and be careful with Celery prefetch limits.

If you still wanna read more about how to optimize Celery tasks, there is a section in Celery documentation.

Thanks to Hugo Bessa, Luca Bezerra and Álvaro Justen for reviewing this post.

Frequently asked questions

What does worker_prefetch_multiplier do in Celery?

It sets how many tasks each worker process reserves from the broker ahead of time: a worker reserves the multiplier times its concurrency. The default is 4. Set it to 1 for long tasks, and combine it with task_acks_late=True if each process should reserve only the task it is running. With Django’s CELERY_ settings namespace it is CELERY_WORKER_PREFETCH_MULTIPLIER; CELERYD_PREFETCH_MULTIPLIER is its old name.

Can I turn off prefetching in Celery?

Not with worker_prefetch_multiplier, where 0 means no limit at all. The closest is task_acks_late = True with worker_prefetch_multiplier = 1, which reserves only as many tasks as the worker has processes. On Celery 5.6 or newer with Redis as the broker, worker_disable_prefetch = True makes the worker fetch a task only when a process is free, without late acknowledgment.

How do I route a Celery task to a specific queue?

Name the queue in the task_routes setting, in the task decorator (@app.task(queue="slow_queue")) or when you call it (apply_async(queue="slow_queue")). Then start a worker that consumes that queue with celery -A proj worker -Q slow_queue.

How do I stop slow Celery tasks from blocking quick ones?

Send the slow tasks to a queue of their own and give that queue its own workers. The default workers then only see quick tasks, and you can add workers to the slow queue as its backlog grows.

Why does my Celery worker run out of memory?

Usually because too many memory-heavy tasks run at once, one per worker process, or because a long-running process keeps growing. Run heavy tasks on a worker of their own with fewer processes (-c), set worker_max_memory_per_child so Celery replaces a process once it uses more than the limit, and pass IDs instead of large payloads, since reserved tasks wait in memory as messages.

Article · 16 min read

Reliable Celery tasks in Django: how to stop losing them

Where Celery tasks get lost in a Django app, and the settings and habits that keep them running through broker failures, crashes and deploys.

Flávio Juvenal16 min read

Article · 12 min read

Advanced Celery: mastering idempotency, retries & error handling

Idempotency, atomicity, retries and monitoring for Celery tasks that survive failures.

Filipe Ximenes12 min read

Book a call

Ready for software that finally fits?

Bring us your care model and find the right technical partner to build it with you.