Performance Caching with Flask-Caching
Performance Caching with Flask-Caching
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
In app.py:
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:
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:
4. Caching Expensive Functions (@cache.memoize)
When you want to cache the output of a specific internal function based on its input arguments:
5. Cache Invalidation (cache.delete / cache.delete_memoized)
When underlying database records change, stale cache entries must be evicted immediately:
Practice Quiz
@cache.cached(timeout=60)?query_string=True mandatory when caching endpoints with pagination or search filters?@cache.cached and @cache.memoize?Testing Flask with Pytest, Gunicorn & Docker Deployment
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Background Tasks with Celery and Redis | Testing Flask with Pytest, Gunicorn & Docker Deployment |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.