MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Background Tasks with Celery and Redis0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
9.1Background Tasks with Celery and Redis9.2Performance Caching with Flask-Caching
HomeTutorialsFlaskBackground Tasks with Celery and Redis
Performance Caching with Flask-Caching

Background Tasks with Celery and Redis

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

Visual Architecture Blueprint
+-------------------+        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 analytics

2. Installation & Prerequisites

1pip install celery redis

Ensure Redis is running locally or via Docker:

1docker run -d -p 6379:6379 --name redis-server redis:alpine

3. Configuring Celery with Modern Flask

In app/tasks.py:

1import time
2from celery import Celery, Task
3from flask import Flask
4 
5def celery_init_app(app: Flask) -> Celery:
6 # Subclass Task to automatically run within Flask's application context!
7 class FlaskTask(Task):
8 def __call__(self, *args: object, **kwargs: object) -> object:
9 with app.app_context():
10 return self.run(*args, **kwargs)
11 
12 celery_app = Celery(app.name, task_cls=FlaskTask)
13 celery_app.config_from_object({
14 "broker_url": app.config.get("CELERY_BROKER_URL", "redis://localhost:6379/0"),
15 "result_backend": app.config.get("CELERY_RESULT_BACKEND", "redis://localhost:6379/0"),
16 "task_ignore_result": False,
17 "task_serializer": "json",
18 "result_serializer": "json",
19 "accept_content": ["json"]
20 })
21 celery_app.set_default()
22 app.extensions["celery"] = celery_app
23 return celery_app

4. Defining Asynchronous Tasks

Decorate tasks using @celery_app.task:

1from celery import shared_task
2import time
3 
4@shared_task(bind=True, max_retries=3)
5def send_welcome_email(self, user_email, username):
6 try:
7 print(f"Starting email dispatch to {user_email}...")
8 # Simulate SMTP network latency
9 time.sleep(4)
10 print(f"Email successfully delivered to {username}!")
11 return {"status": "Delivered", "recipient": user_email}
12 except Exception as exc:
13 # Automatic retry with exponential backoff on failure
14 raise self.retry(exc=exc, countdown=2 ** self.request.retries)

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:

1from flask import Flask, jsonify, request
2from app.tasks import send_welcome_email
3 
4@app.route("/api/v1/register", methods=["POST"])
5def register():
6 data = request.get_json()
7 email = data.get("email")
8 username = data.get("username")
9 
10 # Offload task to Celery worker asynchronously!
11 # Returns immediately without waiting 4 seconds
12 task = send_welcome_email.delay(email, username)
13 
14 return jsonify({
15 "message": "User registered successfully!",
16 "task_id": task.id
17 }), 202

6. Running the Celery Worker Process

In a separate terminal window, start the Celery worker:

1celery -A wsgi.celery_app worker --loglevel=info

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What role does Redis serve in a Celery + Flask architecture?
Question 2
What method is used to trigger an asynchronous Celery task execution from a Flask route handler?
Question 3
Why is running tasks in the background critical for web application performance?
Question 4
Why must a custom Celery FlaskTask wrap task execution inside with app.app_context():?
Question 5
What HTTP status code is most appropriate when an endpoint accepts a request and queues it for background processing without waiting for completion?
Next Lesson

Performance Caching with Flask-Caching

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Stateless JWT Authentication with Flask-JWT-ExtendedPerformance Caching with Flask-Caching

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext