0
0
Flaskframework~8 mins

Polling as fallback in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Polling as fallback
MEDIUM IMPACT
Polling as fallback affects how quickly the page updates with new data and impacts server load and client rendering frequency.
Updating client UI with server data when real-time push is unavailable
Flask
import time
from flask import Flask, jsonify
app = Flask(__name__)

last_value = None

@app.route('/data')
def data():
    global last_value
    current = time.time()
    if last_value is None or current - last_value > 5:
        last_value = current
        return jsonify({'value': current})
    else:
        return jsonify({'value': None})  # No update
Polling less frequently or only sending updates when data changes reduces unnecessary reflows and server load.
📈 Performance GainReduces reflows and server requests by up to 80%, improving interaction responsiveness.
Updating client UI with server data when real-time push is unavailable
Flask
import time
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/data')
def data():
    # Client polls every 1 second
    return jsonify({'value': time.time()})
Client requests data every second regardless of changes, causing many unnecessary server hits and browser reflows.
📉 Performance CostTriggers frequent reflows and increases server CPU usage; can block rendering if responses are slow.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Frequent polling every 1sHigh (many updates)High (many reflows)High (many paints)[X] Bad
Conditional polling every 5s or on changeLow (few updates)Low (few reflows)Low (few paints)[OK] Good
Rendering Pipeline
Polling triggers network requests that cause the browser to recalculate styles and layout if new data changes the DOM. Frequent polling increases Layout and Paint stages.
Network
Style Calculation
Layout
Paint
⚠️ BottleneckLayout and Paint due to frequent DOM updates from polling responses
Core Web Vital Affected
INP
Polling as fallback affects how quickly the page updates with new data and impacts server load and client rendering frequency.
Optimization Tips
1Avoid polling more often than necessary to reduce reflows and server load.
2Send updates only when data changes to minimize DOM updates.
3Use polling as a fallback only when real-time push is unavailable.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance downside of frequent polling as a fallback?
AIt reduces the size of the JavaScript bundle.
BIt causes many unnecessary reflows and server load.
CIt improves Largest Contentful Paint (LCP).
DIt eliminates the need for CSS.
DevTools: Performance
How to check: Record a performance profile while the page is polling. Look for frequent Layout and Paint events triggered by network responses.
What to look for: High frequency of Layout and Paint events indicates costly polling; fewer events mean better performance.