0
0
Flaskframework~8 mins

Why middleware extends functionality in Flask - Performance Evidence

Choose your learning style9 modes available
Performance: Why middleware extends functionality
MEDIUM IMPACT
Middleware affects request processing time and can impact server response speed and resource usage.
Adding functionality to handle requests in a Flask app
Flask
from flask import Flask, g
app = Flask(__name__)

@app.before_request
def fast_middleware():
    g.start_time = 123  # Quick setup without delay

@app.route('/')
def index():
    return 'Hello World!'
Middleware runs quickly without blocking, keeping response fast and user interactions smooth.
📈 Performance GainReduces request blocking time from 1 second to near zero, improving INP.
Adding functionality to handle requests in a Flask app
Flask
from flask import Flask
app = Flask(__name__)

@app.before_request
def slow_middleware():
    import time
    time.sleep(1)  # Simulate slow processing

@app.route('/')
def index():
    return 'Hello World!'
Middleware blocks request processing with unnecessary delay, increasing response time.
📉 Performance CostBlocks response for 1 second per request, increasing INP and slowing user interaction.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Middleware with blocking delayN/A (server-side)N/AN/A[X] Bad
Lightweight, fast middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Middleware runs during the server's request handling before the response is sent, adding processing steps that affect server response time.
Request Handling
Response Generation
⚠️ BottleneckRequest Handling stage is most expensive if middleware is slow or blocking.
Core Web Vital Affected
INP
Middleware affects request processing time and can impact server response speed and resource usage.
Optimization Tips
1Avoid blocking operations inside middleware to keep response fast.
2Use middleware only for necessary processing to minimize overhead.
3Test middleware impact using Network panel to monitor server response times.
Performance Quiz - 3 Questions
Test your performance knowledge
How does slow middleware affect user experience in a Flask app?
AIt increases server response time, causing slower page loads.
BIt reduces the size of the HTML sent to the browser.
CIt improves browser rendering speed.
DIt decreases network latency.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and check the Time column for server response delays.
What to look for: Look for long waiting (TTFB) times indicating slow middleware processing.