0
0
Flaskframework~8 mins

Calling tasks asynchronously in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Calling tasks asynchronously
HIGH IMPACT
This concept affects how quickly the main web request responds by offloading long tasks to run separately, improving user experience and server responsiveness.
Handling a long-running task during a web request
Flask
from flask import Flask, request
from threading import Thread
app = Flask(__name__)

def async_task():
    long_task()

@app.route('/process')
def process():
    Thread(target=async_task).start()
    return "Task started asynchronously"
The long task runs in a separate thread, allowing the request to respond immediately.
📈 Performance GainResponse is fast, reducing INP and improving user experience.
Handling a long-running task during a web request
Flask
from flask import Flask, request
app = Flask(__name__)

@app.route('/process')
def process():
    # Long task runs synchronously
    result = long_task()
    return f"Task done: {result}"
The long task blocks the request, delaying response and causing poor user experience.
📉 Performance CostBlocks rendering and response for the entire task duration, increasing INP significantly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous long taskMinimal0Blocks response delaying paint[X] Bad
Asynchronous task with threadMinimal0Immediate response enables fast paint[OK] Good
Rendering Pipeline
When tasks run synchronously, the browser waits for the server response, delaying rendering and interaction. Asynchronous tasks free the server to respond quickly, allowing the browser to paint and become interactive sooner.
Server Processing
Response Time
Interaction Readiness
⚠️ BottleneckServer Processing blocks response when tasks run synchronously.
Core Web Vital Affected
INP
This concept affects how quickly the main web request responds by offloading long tasks to run separately, improving user experience and server responsiveness.
Optimization Tips
1Never run long tasks synchronously during a web request.
2Use threads or background workers to handle long tasks asynchronously.
3Asynchronous tasks improve interaction responsiveness (INP) by freeing the request.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of calling tasks asynchronously in Flask?
AThe browser downloads assets quicker.
BThe server uses more CPU for each request.
CThe web request responds faster, improving user interaction.
DThe database queries run faster.
DevTools: Performance
How to check: Record a performance profile while triggering the endpoint; look for long server processing blocking the main thread.
What to look for: Long gaps before first paint and interaction indicate synchronous blocking; short gaps indicate good async handling.