0
0
Flaskframework~8 mins

Application factory pattern in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Application factory pattern
MEDIUM IMPACT
This pattern affects the initial load time and memory usage by controlling when and how the Flask app and its extensions are created.
Creating a Flask app for a web service
Flask
from flask import Flask

def create_app():
    app = Flask(__name__)
    @app.route('/')
    def home():
        return 'Hello World!'
    return app

if __name__ == '__main__':
    app = create_app()
    app.run()
Delays app creation until explicitly called, reducing initial load and memory footprint.
📈 Performance GainFaster initial script load; memory allocated only when app runs.
Creating a Flask app for a web service
Flask
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
The app and all extensions are created at import time, increasing startup time and memory usage even if the app is not immediately run.
📉 Performance CostBlocks initial script execution until app and extensions load; higher memory usage on import.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
App created at importN/AN/AN/A[X] Bad
App created via factory on runN/AN/AN/A[OK] Good
Rendering Pipeline
The application factory pattern delays Flask app creation until runtime, reducing blocking during script import and allowing extensions to initialize only when needed.
Script Execution
Memory Allocation
⚠️ BottleneckScript Execution blocking due to early app and extension creation
Core Web Vital Affected
LCP
This pattern affects the initial load time and memory usage by controlling when and how the Flask app and its extensions are created.
Optimization Tips
1Create the Flask app inside a factory function to delay initialization.
2Avoid creating app and extensions at import time to reduce blocking.
3Use the factory pattern to improve startup speed and memory efficiency.
Performance Quiz - 3 Questions
Test your performance knowledge
How does the application factory pattern improve Flask app startup performance?
ABy creating the app at import time
BBy delaying app creation until runtime
CBy removing routes from the app
DBy using global variables for app state
DevTools: Performance
How to check: Record a profile while starting the Flask app and observe the script execution timeline to see when app creation happens.
What to look for: Look for long blocking tasks during import phase indicating early app creation; shorter blocking means better pattern.