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
Performance Caching with Flask-Caching0%
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
HomeTutorialsFlaskPerformance Caching with Flask-Caching
Testing Flask with Pytest, Gunicorn & Docker Deployment

Performance Caching with Flask-Caching

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

Serving high-traffic web applications requires minimizing redundant database queries and expensive computations. If 10,000 users request your course catalog homepage every minute, running the exact same SQL queries 10,000 times wastes database CPU and degrades response times.

Flask-Caching is the standard extension for caching view responses, database query results, and arbitrary Python functions using in-memory caches or Redis.


1. Installing and Configuring Flask-Caching

1pip install Flask-Caching redis

In app.py:

1from flask import Flask
2from flask_caching import Cache
3 
4app = Flask(__name__)
5 
6# Configure Redis cache backend
7app.config["CACHE_TYPE"] = "RedisCache"
8app.config["CACHE_REDIS_URL"] = "redis://localhost:6379/1"
9app.config["CACHE_DEFAULT_TIMEOUT"] = 300 # Default cache expiry: 5 minutes
10 
11# Initialize extension
12cache = Cache(app)

Cache Backends Comparison:

  • SimpleCache: Local Python dictionary memory cache (single-process development only).
  • RedisCache: Production-grade distributed in-memory cache shared across multiple Gunicorn workers.
  • MemcachedCache: High-throughput key-value memory cache.
  • NullCache: Disables caching entirely (useful for testing).

2. Caching Entire View Responses (@cache.cached)

To cache the full HTML or JSON output of a route:

1@app.route("/api/v1/stats")
2@cache.cached(timeout=60) # Cached for 60 seconds
3def get_global_statistics():
4 # Simulated heavy aggregation query across millions of rows
5 stats = {
6 "total_students": Student.query.count(),
7 "total_courses": Course.query.count(),
8 "active_enrollments": 14250
9 }
10 return jsonify(stats)

The first request executes the database query and stores the output in Redis. All subsequent requests for the next 60 seconds return directly from Redis in under 3 milliseconds!


3. Query Parameter-Aware Caching (query_string=True)

If your endpoint accepts query parameters (like pagination or search filters), you must set query_string=True so different query strings create distinct cache keys:

1@app.route("/courses")
2@cache.cached(timeout=120, query_string=True)
3def list_courses():
4 # /courses?page=1 and /courses?page=2 get cached separately!
5 page = request.args.get("page", 1, type=int)
6 courses = Course.query.paginate(page=page, per_page=12)
7 return render_template("courses.html", courses=courses)

4. Caching Expensive Functions (@cache.memoize)

When you want to cache the output of a specific internal function based on its input arguments:

1@cache.memoize(timeout=3600)
2def calculate_user_analytics(user_id):
3 print(f"Executing complex calculation for User {user_id}...")
4 # Heavy aggregation logic
5 return {"user_id": user_id, "score": 98.4}

5. Cache Invalidation (cache.delete / cache.delete_memoized)

When underlying database records change, stale cache entries must be evicted immediately:

1@app.route("/api/v1/courses/new", methods=["POST"])
2def create_course():
3 # ... persist new course to database ...
4
5 # Invalidate cached view so users see the new course immediately!
6 cache.delete_memoized(list_courses)
7 cache.delete("view//courses")
8 return {"status": "Created"}, 201

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens on the second request to an endpoint decorated with @cache.cached(timeout=60)?
Question 2
Why is query_string=True mandatory when caching endpoints with pagination or search filters?
Question 3
What is the primary difference between @cache.cached and @cache.memoize?
Question 4
Which cache backend should be used for production deployments running multiple Gunicorn workers?
Question 5
What does "cache invalidation" mean in web application architecture?
Next Lesson

Testing Flask with Pytest, Gunicorn & Docker Deployment

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

Related Lessons

Previous LessonNext Lesson
Background Tasks with Celery and RedisTesting Flask with Pytest, Gunicorn & Docker Deployment

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