0
0
Flaskframework~8 mins

Custom middleware creation in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom middleware creation
MEDIUM IMPACT
This affects the request-response cycle speed and server processing time, impacting how fast the server can respond to user requests.
Adding custom middleware to process requests in Flask
Flask
from flask import Flask, request
app = Flask(__name__)

@app.before_request
def fast_middleware():
    # Quick check without blocking
    if 'X-Special-Header' not in request.headers:
        pass  # Minimal processing

@app.route('/')
def index():
    return 'Hello World!'
Middleware runs quickly without blocking, allowing fast request handling and better throughput.
📈 Performance GainReduces request blocking time from 2 seconds to near zero, improving server responsiveness.
Adding custom middleware to process requests in Flask
Flask
from flask import Flask, request
app = Flask(__name__)

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

@app.route('/')
def index():
    return 'Hello World!'
This middleware blocks every request for 2 seconds, delaying response and increasing server load.
📉 Performance CostBlocks request processing for 2 seconds per request, increasing server response time significantly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking middleware with sleep000[X] Bad
Lightweight middleware with quick checks000[OK] Good
Rendering Pipeline
Middleware runs on the server before the response is sent. It affects server processing time but does not directly impact browser rendering stages.
Server Request Processing
⚠️ BottleneckMiddleware that blocks or performs heavy computation delays the entire request-response cycle.
Optimization Tips
1Avoid blocking operations like sleep or heavy computation in middleware.
2Keep middleware logic simple and fast to reduce server response delays.
3Use DevTools Network tab to monitor server response times and detect middleware bottlenecks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of a custom middleware that uses time.sleep() in Flask?
AIt increases CSS selector complexity.
BIt causes browser layout shifts.
CIt blocks the request processing, increasing server response time.
DIt reduces bundle size.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and check the Time column for server response delays.
What to look for: Look for high 'Waiting (TTFB)' times indicating slow server response caused by middleware.