0
0
Flaskframework~8 mins

Defining Celery tasks in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Defining Celery tasks
MEDIUM IMPACT
This affects the responsiveness of the Flask web app by offloading long-running tasks to background workers, improving user interaction speed.
Running a long task in a Flask web request
Flask
from flask import Flask
from celery import Celery

app = Flask(__name__)
celery = Celery('tasks', broker='redis://localhost:6379/0')

@celery.task
def long_running_task():
    # Long task code here
    return 'done'

@app.route('/process')
def process():
    task = long_running_task.delay()
    return f"Task started: {task.id}"
The long task runs asynchronously in a Celery worker, freeing the web server to respond immediately.
📈 Performance GainNon-blocking request; user sees immediate response; INP improved.
Running a long task in a Flask web request
Flask
from flask import Flask
app = Flask(__name__)

@app.route('/process')
def process():
    # Long task runs here
    result = long_running_task()
    return f"Result: {result}"
The long task runs inside the web request, blocking the server and delaying response to the user.
📉 Performance CostBlocks rendering and user interaction until task completes; increases INP significantly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous task in Flask routeMinimal00[X] Bad
Asynchronous Celery task with immediate responseMinimal00[OK] Good
Rendering Pipeline
Defining Celery tasks moves heavy computation out of the Flask request cycle, so the browser receives a quick response without waiting for task completion.
Network
JavaScript Execution
Interaction Responsiveness
⚠️ BottleneckBlocking synchronous task execution in the Flask request delays response and increases INP.
Core Web Vital Affected
INP
This affects the responsiveness of the Flask web app by offloading long-running tasks to background workers, improving user interaction speed.
Optimization Tips
1Never run long tasks directly in Flask routes; use Celery to run them asynchronously.
2Return immediate responses from Flask routes to keep the UI responsive.
3Monitor INP to ensure user interactions are not blocked by backend processing.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of defining Celery tasks for long-running work in Flask?
AIt prevents blocking the web request, improving interaction responsiveness.
BIt reduces the size of the Flask app bundle sent to the browser.
CIt decreases the number of DOM nodes created on the page.
DIt improves the CSS paint speed in the browser.
DevTools: Performance
How to check: Record a performance profile while triggering the Flask route; observe the time until first response and interaction readiness.
What to look for: Look for long blocking tasks in the main thread delaying response; shorter blocking time indicates better performance.