0
0
Flaskframework~8 mins

Flask-Caching for response caching - Performance & Optimization

Choose your learning style9 modes available
Performance: Flask-Caching for response caching
MEDIUM IMPACT
Improves page load speed by serving cached responses quickly without recomputing them on each request.
Serving frequently requested data in a Flask web app
Flask
from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})

@app.route('/data')
@cache.cached(timeout=60)
def data():
    result = sum(i * i for i in range(1000000))
    return str(result)
Caches the response for 60 seconds, so repeated requests return instantly without recomputation.
📈 Performance GainReduces server processing time to near zero for cached requests, improving LCP significantly
Serving frequently requested data in a Flask web app
Flask
from flask import Flask
app = Flask(__name__)

@app.route('/data')
def data():
    # Simulate expensive computation
    result = sum(i * i for i in range(1000000))
    return str(result)
Every request recomputes the expensive operation, causing slow response times and high server load.
📉 Performance CostBlocks rendering for 100+ ms per request, increasing LCP and server CPU usage
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No caching, recompute on each requestN/A (server-side)N/AHigher due to delayed response[X] Bad
Flask-Caching with simple cacheN/A (server-side)N/ALower due to fast response[OK] Good
Rendering Pipeline
When caching is enabled, the server can skip expensive processing and directly send cached content, reducing time before the browser receives data.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing (expensive computations or database queries)
Core Web Vital Affected
LCP
Improves page load speed by serving cached responses quickly without recomputing them on each request.
Optimization Tips
1Cache expensive route responses to reduce server CPU load.
2Set appropriate cache timeout to balance freshness and speed.
3Use caching to improve Largest Contentful Paint (LCP) by speeding up server responses.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using Flask-Caching for response caching?
AImproves client-side JavaScript execution speed
BDecreases CSS rendering time in the browser
CReduces server processing time by serving cached responses
DReduces image file sizes sent to the client
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page twice; observe response times for repeated requests.
What to look for: Faster response times on repeated requests indicate caching is working; slower times mean recomputation.