0
0
Flaskframework~8 mins

After_request hooks in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: After_request hooks
MEDIUM IMPACT
This affects the response time after the main request processing, impacting how quickly the server sends the final response to the client.
Modifying response headers after request processing
Flask
from flask import Flask
app = Flask(__name__)

@app.after_request
def add_header(response):
    response.headers['X-Fast-Header'] = 'fast'
    return response
Adds headers quickly without blocking, allowing the response to be sent immediately.
📈 Performance GainNo blocking delay, improves LCP by avoiding unnecessary wait
Modifying response headers after request processing
Flask
from flask import Flask, request
app = Flask(__name__)

@app.after_request
def add_header(response):
    import time
    time.sleep(1)  # Simulate slow operation
    response.headers['X-Slow-Header'] = 'slow'
    return response
The after_request hook blocks the response by sleeping for 1 second, delaying the entire response to the client.
📉 Performance CostBlocks response for 1000ms, increasing LCP significantly
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy processing in after_request hook0 (server-side)0 (client-side)0 (client-side)[X] Bad - delays response start
Lightweight header modification in after_request hook0 (server-side)0 (client-side)0 (client-side)[OK] Good - fast response
Rendering Pipeline
After_request hooks run after the main request handler but before the response is sent. Heavy operations here delay the server's response, increasing the time before the browser can start rendering.
Server Response Preparation
Network Transfer
Browser Rendering Start
⚠️ BottleneckServer Response Preparation
Core Web Vital Affected
LCP
This affects the response time after the main request processing, impacting how quickly the server sends the final response to the client.
Optimization Tips
1Avoid heavy or blocking operations in after_request hooks.
2Use after_request hooks only for fast, simple response modifications.
3Offload slow tasks to background workers to keep response times low.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of a slow after_request hook in Flask?
AIt increases the size of the HTML sent to the client.
BIt delays the server response, increasing page load time.
CIt causes the browser to reflow the page multiple times.
DIt blocks JavaScript execution on the client.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and check the Time column for the main document request. Look for long 'Waiting (TTFB)' times.
What to look for: High Time To First Byte (TTFB) indicates server-side delays, possibly from slow after_request hooks.