What is Celery in Python? Brokers, workers and result backends

Celery is a distributed task queue for Python. Your application sends a task, such as sending an email or calling a slow external API, to a message broker like RabbitMQ or Redis, and separate worker processes pick it up and run it in the background, so the web request returns right away. A result backend stores what each task returns, for the code that needs it later.
In this article, I walk through each of those parts: why you’d use a task queue, how producers, the broker and workers fit together, how to call tasks from Django, and where results are stored. Most task queues follow the same pattern, so the ideas apply beyond Celery. If you already run Celery in production, read how to stop losing Celery tasks and how to make tasks safe to rerun.
For more on running Celery, see our Celery engineering insights.
Key takeaways
Use it for slow or unreliable work
Send emails, call external APIs and run heavy jobs outside the request, so users get a fast response.
The broker holds the queue
RabbitMQ or Redis stores each task until a worker takes it. Amazon SQS also works, with fewer features.
Workers run the tasks
Separate processes, usually built from the same codebase as the web app, take tasks from the queue and run them.
Pass IDs, not objects
Send a model’s primary key and fetch a fresh copy inside the task, so it never works on stale data.
Results go to a backend
delay() returns a handle to the task; get() waits for the value the result backend stores.
Schedules work too
Celery Beat queues tasks on a schedule, so the same workers run your cron jobs.
Exploring the Power of Asynchronous Task Queues
In broad terms, the reason for employing async task queues is the need for lightning-fast user responses. The most straightforward use case involves delegating time-consuming CPU-intensive tasks. However, the real star of the show is the ability to execute external API calls. When you rely on external services, the clock is no longer in your hands, and there’s uncertainty about when, or even if, the results will arrive. System downtimes or glitches on the other end can keep you waiting indefinitely.
Another compelling use case for async tasks is in the realm of result value preparation and caching. They’re your secret weapon when it comes to spreading out those massive database insertions over time, guarding against unintentional DDoS attacks on your own database. And let’s not forget about cron jobs, which can be seamlessly managed using async tasks.
When it comes to wrangling async tasks in Python, you’re spoiled for choice. While RQ is gaining some well-deserved attention lately, Celery remains the undisputed heavyweight champion. With its robust features and widespread adoption, Celery has long been the go-to tool for developers looking to harness the power of asynchronous task queues.
Read more: Dealing With Resource-Consuming Tasks on Celery
Understanding the Architecture of Async Task Queues
The challenge of running asynchronous tasks neatly aligns with the classic Producer/Consumer problem. Producers are responsible for depositing tasks into a queue, while consumers eagerly scan the beginning of the queue for pending tasks, select the first one, and execute it.
The producer/consumer pattern
In the context of asynchronous task queues, these roles take on specific names. Producers are commonly represented by ‘web nodes’ or any system responsible for task submission. The queue itself plays the crucial role of the ‘broker,’ and the task executors are referred to as ‘workers.’ Interestingly, workers can not only process tasks but also add new tasks to the queue, effectively donning the hat of ‘producers’ themselves.
Now that we have a high-level overview, let’s delve a bit deeper into the inner workings of this fascinating architecture.
Choosing The Ideal Celery Broker
The concept of a broker is straightforward: it’s essentially a queue. However, the implementation of a queue in a computer system offers various options. One of the simplest methods is using a text file. Text files can hold a sequence of job descriptions to be executed, making them a potential choice for serving as the broker in our system. However, there’s a caveat with text files; they are not designed to handle real application challenges like network communication and concurrent access. Consequently, for a more robust solution, we need to explore other options.
SQL databases, with their network capabilities and concurrent access handling, might seem like an attractive choice. However, they often fall short in terms of speed, making them less ideal for certain use cases. On the other end of the spectrum, NoSQL databases can be incredibly fast but may lack the level of reliability needed for critical tasks.
So, when it comes to building queues for asynchronous tasks, the goal is to strike a balance. You want a solution that is fast, reliable, and capable of handling concurrent operations. This is where tools like RabbitMQ, Redis, and SQS come into play.
Celery, being a versatile asynchronous task queue system, provides comprehensive support for both RabbitMQ and Redis. While SQS and Zookeeper are also available options, they are typically offered with limited capabilities.
In essence, the choice of your broker, the heart of your asynchronous task queue system, can significantly impact the performance and reliability of your application. It’s a critical decision that can shape how your tasks are processed and executed, ensuring a seamless user experience.
Harmonizing Web and Worker Nodes in Celery
Web and worker nodes are essentially plain servers, with a key distinction: Web nodes handle incoming requests from the internet and dispatch jobs for asynchronous processing, while Workers are the machines responsible for picking up these tasks, executing them, and delivering responses. Despite this clear separation in functionality, it’s common practice to house the code for both types of nodes within the same code repository. This practice, in fact, offers several advantages.
By co-locating the code for web and worker nodes, you create a synergy that allows them to reap the benefits of shared components such as models and services. This unified approach not only fosters code reusability but also serves as a bulwark against inconsistencies.
In the realm of asynchronous task queues, this approach ensures a smoother workflow and enhances the overall efficiency of your system. Join us as we explore the merits of this unified approach in optimizing the performance and maintainability of your web application.
Handling Tasks in the Celery Framework
Here is an example showcasing the execution of tasks using Celery:
Worker Node:
from celery import Celery
app = Celery(...)
@app.task
def add(a, b):
return a + bWeb Node:
from tasks import add
result = add.delay(4, 5).get()
print(result) # Output: 9In the first block, the code represents a task that should run asynchronously. It is implemented in the worker node. The second block showcases the code that places a job in the queue to be executed. This code is typically found in the web node. In this specific example, the web node places an “add” job and waits until the result becomes available. Upon receiving the response, the result is printed.
Let’s explore a Django-specific example:
Worker Node:
@app.task
def update_attendees(event, n):
event.attendees_number = n
event.save()Web Node:
event = Event.objects.get(name='DjangoCon')
update_attendees.delay(event, 9001)In this case, the web node places a task to update the number of attendees for an event. It is important to note that passing complex objects, like a Model instance, as task parameters can lead to problems.
When objects are serialized and stored in the broker, security vulnerabilities may arise if complex objects are allowed. Additionally, database objects passed as parameters can become outdated during the time period between the task placement and its execution.
To tackle these issues, it is recommended to pass the ID of the object as a parameter and fetch a fresh copy from the database within the task implementation. Here’s an updated version of the example:
@app.task
def update_attendees(event_id, n):
event = Event.objects.get(id=event_id)
event.attendees_number = n
event.save()
event = Event.objects.get(name='DjangoCon')
update_attendees.delay(event.id, 9001)By following this approach, you ensure that the task works with the most up-to-date version of the object.
Storing and Retrieving Task Results in Celery
In the previous examples, we have treated the delay and get functions as a single action, but in reality, they serve distinct purposes. The delay function places the task in the queue and returns a promise that allows monitoring of the task’s status and retrieval of its result once it’s ready. On the other hand, calling get on this promise blocks the execution until the result becomes available. However, we have missed an essential piece of the architecture by not mentioning the results backend.
Introducing the Results Backend
The results backend plays a crucial role in storing task results. Typically, you can utilize the same instance you are using for the broker to act as the results backend.
How a task and its result travel
While there are other technologies available beyond the supported broker options that can serve as the results backend in Celery, the implementation details may differ based on the chosen technology. For instance, when using Postgres, the get method performs polling to check if the result is ready, while technologies like Redis handle this through a pub/sub protocol.
By comprehending the basics of the components in the Celery architecture, you now have a stronger understanding of how it works, gaining confidence in utilizing this powerful tool.
If you found this post helpful and are eager to expand your knowledge about Celery, I recommend taking a look at my other blog post, on idempotency, retries and error handling in Celery tasks.
Feel free to reach out if you have any further questions or need additional assistance. Let’s explore the exciting possibilities together!
Frequently asked questions
What is Celery in Python?
Celery is an open-source distributed task queue for Python. It runs functions, called tasks, in separate worker processes instead of inside the web request, so slow work such as sending emails, calling external APIs or processing files doesn’t make users wait.
How does Celery work?
Your application, the producer, calls a task with delay(). Celery serializes the call and puts it on a message broker. A worker process takes it from the queue and runs it, and, when you need the return value, stores it in a result backend where your code can read it.
What is a Celery broker?
The broker is the queue that holds tasks between the application and the workers. Celery fully supports RabbitMQ and Redis; Amazon SQS also works, with fewer features. RabbitMQ is the most reliable choice, and Redis is common when a project already runs it.
What is the Celery result backend?
It’s where Celery stores the value each task returns, so the code that queued the task can read it later with get(). It’s often the same Redis instance as the broker, but it can also be a SQL database. You only need it when something reads task results.
Is Celery only for Django?
No. Celery works with any Python application, including Flask and FastAPI projects and plain scripts. Django has first-class support, so it’s the most common pairing.
Related articles
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.
16 min read

Article · 12 min read
Advanced Celery: mastering idempotency, retries & error handling
Idempotency, atomicity, retries and monitoring for Celery tasks that survive failures.
12 min read




