Background Tasks with Celery and Redis
Background Tasks with Celery and Redis
Web requests should be fast—ideally responding in under 200 milliseconds. Performing synchronous, long-running operations inside a Flask request handler (such as generating PDF reports, training ML models, processing video, or sending emails) freezes the worker process and causes client timeouts.
Celery is an asynchronous distributed task queue that offloads time-consuming tasks to background worker processes, using Redis or RabbitMQ as a message broker.
1. System Architecture: Flask + Redis + Celery
+-------------------+ 1. HTTP Request (e.g. POST /enroll) +-----------------------+
| Client Browser | ===============================================> | Flask Web Server |
+-------------------+ +-----------------------+
|
2. delay() Task Message
v
+-----------------------+
| Redis (Broker) |
| Queue: 'celery' |
+-----------------------+
|
3. Pulls message
v
+-------------------+ 5. Reads Result (Optional) +-----------------------+
| Client Polling | <----------------------------------------------- | Celery Background |
| or WebSocket | | Worker Process |
+-------------------+ +-----------------------+
4. Sends email, builds
PDF, logs analytics2. Installation & Prerequisites
Ensure Redis is running locally or via Docker:
3. Configuring Celery with Modern Flask
In app/tasks.py:
4. Defining Asynchronous Tasks
Decorate tasks using @celery_app.task:
5. Triggering Tasks from Flask Views (.delay())
Call the task using .delay() (a shortcut for .apply_async()). The Flask view dispatches the message to Redis and returns an immediate HTTP response in milliseconds:
6. Running the Celery Worker Process
In a separate terminal window, start the Celery worker:
Practice Quiz
FlaskTask wrap task execution inside with app.app_context():?Performance Caching with Flask-Caching
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Stateless JWT Authentication with Flask-JWT-Extended | Performance Caching with Flask-Caching |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.