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. 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 analyticsEnsure Redis is running locally or via Docker:
In app/tasks.py:
Decorate tasks using @celery_app.task:
.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:
In a separate terminal window, start the Celery worker:
FlaskTask wrap task execution inside with app.app_context():?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Stateless JWT Authentication with Flask-JWT-Extended | Performance Caching with Flask-Caching |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.