Async Celery by Example: Why and How
Celery is a powerful async task queue that allows you to run tasks asynchronously and out-of-process from the main web application. This brings numerous benefits such as freeing up request workers to handle more user traffic, moving long-running jobs to background processes to prevent blocking the UI, and scaling task execution across multiple machines.
In this comprehensive guide, we‘ll cover:
- What is Celery and why is it useful
- Celery architecture and components
- Basic Celery example – migrating a synchronous task to be async with Celery
- Key Celery concepts – messages, tasks, workers, canvas
- Choosing a broker and result backend
- Handling task results and chains
- Periodic tasks
- Best practices for structure, retries, errors, monitoring
- Celery in production – optimization, scaling, and gotchas
So whether you‘re new to Celery or looking to leverage it in more advanced ways, read on for a complete overview.
What is Celery?
Celery is an open source Python library that enables you to execute tasks asynchronously outside of the main process. This is useful for multiple reasons:
1. Prevent blocking the web server
Often web applications need to execute intensive processing that takes too long to run during a typical web request. This could be generating a large PDF report, resizing hundreds of images, or contacting external APIs.
If you run these requests synchronously, the web worker will be tied up waiting instead of serving other users. Celery allows spinning up background workers to handle these long running tasks, freeing up the web workers.
2. Scale task execution
Celery workers can run on separate machines entirely. So you can handle sudden spikes in traffic or load by easily spinning up more workers.
3. Schedule and rate limit tasks
Built in Celery functionality makes it easy to run periodic tasks on schedules. There‘s also rate limiting options to smooth out task spikes.
4. Simplify code
Celery abstracts away a lot of complexity with a simple API. You avoid having to directly manage threads, processes, queues and signaling.
So in summary, Celery makes asynchronous task execution, scaling, and management much simpler.
Celery Architecture
There are several components in a typical Celery architecture:
Client – The python application that produces "sends" task messages and consumes task results. This is often Django or Flask based web apps.
Message Broker – An intermediate message queue that handles sending task messages between the client and workers. Examples are Redis and RabbitMQ. This buffer means fast clients aren‘t slowed down by busy workers.
Worker – The processes that actually execute the tasks. Usually multiple workers across one or more machines. Executed using celery worker command.
Result Store – Temporary storage typically used to pass results from workers back to clients once tasks finish. Redis or SQLAlchemy are common choices.
Task – The python functions that are executed asynchronously by the workers. Defined in clients using @app.task decorator.
So in practice:
- The web client publishes a task message to the broker, then returns immediately
- A worker pulls the task message off the broker, executes the task function, and stores results in the backend
- The client queries the result backend to retrieve task results to display to users
This allows long running tasks to happen asynchronously without slowing down the client!
Basic Celery Example
Let‘s look at a simple example to demonstrate Celery in action.
Here is a basic Django view that synchronously generates a PDF report from an HTML template:
# views.py
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
import weasyprint
def report_view(request):
# Render HTML template
template = get_template(‘report.html‘)
html = template.render({‘data‘: get_report_data()})
# Generate PDF
pdf = weasyprint.HTML(string=html).write_pdf()
# Return PDF response
response = HttpResponse(pdf, content_type=‘application/pdf‘)
return response
This works, but generating that PDF could take 30+ seconds. So the user gets stuck waiting instead of getting a quick response.
Let‘s migrate this to Celery:
# tasks.py
from celery import shared_task
from io import BytesIO
from django.template.loader import get_template
import weasyprint
@shared_task
def generate_pdf_report(data):
template = get_template(‘report.html‘)
html = template.render(data)
pdf = weasyprint.HTML(string=html).write_pdf()
return pdf
# views.py
from .tasks import generate_pdf_report
def report_view(request):
# Create task
task = generate_pdf_report.delay(get_report_data())
return HttpResponse("PDF being generated")
So what changed?
-
We moved the intensive PDF generation code into a Celery task called
generate_pdf_reportand decorated it with@shared_task. This tells Celery it‘s available to run asynchronously. -
In our view, we call
.delay()on the task instead of running it directly. This asynchronously publishes the task message to the broker rather than running the function body directly. A task ID is immediately returned so we can track results later. -
The view returns a simple confirmation response instead of waiting around for 30+ seconds.
Behind the scenes:
- A Celery worker pulls the task message off of the queue and executes the
generate_pdf_reportfunction - The PDF bytes are stored in the result backend
- Separate code could then query the task ID to show the PDF once it finishes
So we‘ve moved an expensive synchronous process to be a fast asynchronous background job!
The key takeaways are:
- Decorating a function with
@shared_tasktells Celery it‘s available to be run as a task - Calling
.delay()queues up the task message to be consumed by a worker - The clients avoid blocking by not waiting for the result
Celery Concepts
Now that we‘ve seen a simple example flow, let‘s dig deeper into some key Celery concepts.
Messages
The communication between clients and workers is done via messages. When .delay() is called on a task, a message is constructed containing the function name, arguments, routing details, and any options.
This dictates what function the worker should execute. The worker then publishes a result message once processing finishes so the client can access data like return values or errors.
You don‘t directly work with these messages, but they enable the asynchronous magic!
Tasks
As we saw above, tasks are simply Python functions decorated with @shared_task or @app.task. The functions can do anything like query APIs, perform calculations, send emails, run machine learning, etc.
Tasks also include:
- Arguments – Values passed in when calling
.delay() - Kwargs – Keyword args also passed to
.delay() - Options – Specify num_retries, expiration, priority etc.
For example:
@shared_task
def process_video(video_id, quality=‘low‘):
# processing code
pass
# Run task async with args and kwargs
process_video.delay(123, quality=‘high‘)
So tasks provide an easy way to convert existing logic into background jobs.
Workers
Workers are the processes that actually execute task functions. They connect to the broker, pull down messages, run the associated functions, save results, and handle errors/retries.
Workers run independently of the main application so they don‘t tie up critical web processes. You typically run multiple workers across one or more servers.
Common practice is having worker machines separate from the web servers.
Canvas Primitives
Canvas allows chaining tasks together into workflows. The main primitives are:
Groups – Batch together multiple tasks so they execute as a group
Chains – Sequence tasks one after another so each executes asynchronously once the previous finishes
Chords – Run a callback task once a group finishes
We won‘t dive into examples here, but canvases are very powerful for creating robust async logic flows.
Choosing a Broker and Backend
The message broker and result backend power Celery under the hood. Let‘s explore good options for each.
Message Brokers
The broker is responsible for shuttling messages between clients and workers. Common choices include:
Redis – Fast, simple, great for lower volume sites. However, messages are not persistent so tasks could be lost in a failure scenario.
RabbitMQ – Robust and reliable choice built specifically for messaging. Handles persistence, routing of messages, clustering. Best for more demanding workloads.
Amazon SQS – Fully managed AWS queue. Easy scalability and persistence. Could get expensive if high message volume.
The architecture consideration boils down to expected workload and existing infrastructure. Redis provides simplicity while RabbitMQ and SQS handle scalability and reliability better.
Result Backends
The backend stores execution results so the clients can access them. Often this is just task return values or failure exceptions.
Good options are:
Redis – Same pros and cons as using for message broker. Super fast, not persistent.
Memcached – Also in memory, therefore not persistent, but interface differs slightly from Redis.
RPC – Returns results directly from worker to client over RPC calls rather than a intermediary store. Adds client/worker coupling.
Database – Use a SQL database like Postgres to make results persistent and avoid an additional service. But speed will suffer at scale.
If reliability is critical, Postgres is a good option. Otherwise Redis provides a solid combination of speed and ease of use.
Handling Task Results
Since tasks run asynchronously, we need a way to handle updates on their status as they process through the various stages:
- Pending – About to execute
- Started – Running inside worker
- Success – Completed successfully
- Failure – Errored out
- Revoked – Manually canceled
The AsyncResult API provides a standard way to query this info:
from celery.result import AsyncResult
task = generate_pdf_report.delay()
result = AsyncResult(task.id)
# Check if successful
if result.successful():
pdf = result.get()
save_pdf(pdf)
# Handle failure
elif result.failed():
print(result.traceback)
AsyncResult is the gateway to:
- Checking if a task has finished running
- Retrieving return values from successful tasks
- Getting exception tracebacks to handle failures
- Accessing runtime metadata like start time and worker
It enables properly dealing with results whether tasks take a few seconds or a few hours to complete.
Data Expiration
It‘s also important to understand how long task result data is stored before Celery starts automatically deleting it:
- Results are kept for 1 day by default
- This can be extended by configuring
result_expires - Set to None to keep forever
So if you need access to results past a day, make sure you persist them somewhere like a database.
Retries and Errors
Things don‘t always go smoothly when running background tasks, so Celery provides tuning knobs for handling retries and errors gracefully.
Retries
Transient errors can automatically trigger retries. Common configuration options are:
retry_backoff– Introduce delays between retries, like 30 secondsmax_retries– Max number of retries before giving up, default is 3
These provide flexibility for failing tasks worth retrying.
Errors
For serious failures, Celery lets you handle them outside of retries:
- Return values can contain exceptions
AsyncResult.failed()indicates failureresult.tracebackcontains the full stack trace
You could implement notification logic to alert developers of critical job failures.
This gives insight into jobs failing hard and how to address issues.
Periodic Tasks
Celery allows scheduling recurring background jobs using celery beat. This enables running tasks on fixed intervals rather than requiring external cron jobs.
Some examples include:
- Generate sales reports every 12 hours
- Refresh cached model predictions every Monday morning
- Cleanup temporary files nightly
You register the tasks and intervals in the beat schedule:
from celery.schedules import crontab
from .tasks import refresh_model_cache
app.conf.beat_schedule = {
‘refresh_model_predictions‘: {
‘task‘: ‘refresh_model_cache‘,
‘schedule‘: crontab(hour=7, day_of_week=1), # 7am every Monday
},
}
Now that task gets triggered automatically without any external scheduler!
Best Practices
Let‘s move on from API specifics to some recommended best practices when leveraging Celery in production.
Project Structure
A clean project structure keeps Celery logic maintainable as complexity increases. Core ideas are:
Apps – Create a dedicated Celery app for your domain with its own tasks.py module to house its tasks. Avoid cramming unrelated tasks together.
Configuration – Configure Celery settings related to your app in a module like celeryconfig.py. Sets broker URL, result backend, etc.
Factories – Use a factory module to handle initializing Celery, apps, tasks, beat schedules. Avoid code duplication.
Packages – If the project grows very large with diverse task types, break up apps further into domains/subsystems using Python packages.
Sticking to conventions like these make development much smoother.
Idempotency
Idempotency ensures that task operations can rerun without unintended side effects. This is critical for retries working properly.
For example:
@task
def create_user(name, email):
if User.exists(email):
return
User.create(name=name, email=email)
This avoids duplicate users if retries occur. Compare to:
@task
def create_user(name, email):
User.create(name=name, email=email) # Could duplicate
So idempotent tasks:
- Add side effect protection logic
- Leverage transactions if interacting with databases
- Design operations to be rerun safely
This takes forethought but prevents serious consequences.
Monitoring
Celery provides monitoring tools to gain visibility into the background workers:
Flower – Real-time webapp to monitor task execution. Visibility into active jobs, errors, runtimes, and more. Invaluable for debugging.
Events – Capture detailed trace events as tasks execute and route the data to tools like Datadog or log aggregation services.
Notifications – Push notifications on the most severe task failures so developers can respond quickly.
Monitoring provides awareness into distributed tasks that can otherwise be opaque. This helps identify and be proactive about production issues before they cascade.
Scaling Workers
One of the main advantages of Celery is simplifying scaled out task execution across multiple workers. Here are tips for scaling efficiently:
Autoscaling – Leverage cluster autoscaling tools like Kubernetes to automatically launch worker instances matching demand. This handles spikes seamlessly.
Queues – Configure multiple queues with differing priorities instead of one large default queue. Route urgent tasks appropriately.
Rate Limiting – Set a cap on task frequency to smooth out uneven loads coming in from clients.
Latency Alerts – Get notifications when queue latency crosses thresholds indicating struggling workers.
Benchmarking – Profile typical tasks during development to understand resources needed. Right size workers appropriately.
With smart planning, Celery deployments can readily grow from a couple background workers to managing many hundreds or thousands.
Common Pitfalls
While Celery delivers a lot of power, here are some pitfalls to watch out for:
Version Mismatches – The Celery and Py-AMQP lib versions across clients, workers, and even adjacent services can easily get out of sync during updates. Watch out for puzzling connection issues.
Message Brokers – If relying on Redis or Memcached for messaging, ensure you‘ve configured backup/HA appropriately given they have no message persistence.
Network Restrictions – VPCs, security groups, and firewalls can all block connectivity. Important to double check even basic networking.
Serialization – The serialized messages passed around can end up much larger than anticipated. Hitting size limits can lead to silent failures.
Time Drift – Ensure NTP is running properly across all servers and consider running periodic ntpdate checks. Out of sync times lead to bizarre issues.
Resource Leaks – It‘s common for tasks that manage IO, db handles etc to leak resources over time as workers run indefinitely. Profiling helps here.
So while Celery removes a ton of complexity, the distributed nature introduces other types of challenges. Awareness of the common issues helps troubleshooting greatly.
Wrapping Up
We covered a lot of ground across introductory examples to production practices! The key takeaways are:
- Celery enables async task execution so clients avoid blocking on long operations
- Messages passed via queue brokers allow distributing tasks across workers
- Granular task status handling, retries, error handling, and monitoring helps build resilient systems
- following Celery best practices sets you up for smooth scaling
Celery abstracts away the hard parts of building robust, async task flows. Following the patterns here will save you endless hours compared to managing your own distributed architecture.
The tasks library is concise but extremely capable once you understand the moving pieces working together to enable asynchronous paradigms.
Hopefully this end-to-end guide gives you confidence to unlock the benefits of async workflows or helps take your existing deployment to the next level!