0
0
Flaskframework~8 mins

Before_request hooks in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Before_request hooks
MEDIUM IMPACT
This affects server response time and perceived page load speed by running code before each request is processed.
Running code before every HTTP request in a Flask app
Flask
from flask import Flask, g
app = Flask(__name__)

@app.before_request
def lightweight_task():
    g.data = 'ready'

@app.route('/')
def index():
    return g.data
The before_request hook does minimal work, avoiding blocking and allowing fast response.
📈 Performance GainResponse time is near instant, improving LCP and user experience.
Running code before every HTTP request in a Flask app
Flask
from flask import Flask, g
app = Flask(__name__)

@app.before_request
def heavy_task():
    # Simulate heavy computation or blocking IO
    import time
    time.sleep(2)  # blocks request handling
    g.data = 'done'

@app.route('/')
def index():
    return g.data
The before_request hook blocks every request for 2 seconds, delaying response and increasing load time.
📉 Performance CostBlocks server response for 2 seconds per request, increasing LCP significantly.
Performance Comparison
PatternServer DelayBlocking OperationsImpact on LCPVerdict
Heavy blocking code in before_requestHigh (2+ seconds)Yes (sleep or blocking IO)Severe delay[X] Bad
Minimal setup in before_requestLow (milliseconds)NoFast response[OK] Good
Rendering Pipeline
Before_request hooks run on the server before the response is generated and sent to the browser. Heavy or blocking operations here delay the server response, which delays the browser's ability to start rendering the page.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing stage is most expensive if before_request hooks do heavy work.
Core Web Vital Affected
LCP
This affects server response time and perceived page load speed by running code before each request is processed.
Optimization Tips
1Avoid blocking or heavy computations in before_request hooks.
2Use before_request hooks only for quick setup or checks.
3Offload heavy tasks to background jobs or async processes.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of doing heavy work in a Flask before_request hook?
AIt causes the browser to skip rendering the page.
BIt delays the server response, increasing page load time.
CIt increases the size of the HTML sent to the browser.
DIt reduces the number of HTTP requests the browser makes.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and check the Time to First Byte (TTFB) for the request.
What to look for: A high TTFB indicates server-side delay likely caused by heavy before_request hooks.