Flask is lightweight, but that doesn't strictly mean it's fast out of the box. To handle thousands of requests per second, you need to configure your environment correctly. Here are 7 pro tips to optimize your Flask application.
1. Use a Production Server (WSGI)
The built-in Flask server is single-threaded. Never use it in production. Use Gunicorn (Green Unicorn), a pre-fork worker model that spawns multiple processes to handle requests simultaneously.
# Install Gunicorn
pip install gunicorn
# Run your app with 4 workers
gunicorn -w 4 -b 0.0.0.0:8000 app:app
2. Enable Gzip Compression
Text-based assets (HTML, JSON, CSS) can be compressed by 70-80% using Gzip. Flask-Compress handles this automatically.
from flask import Flask
from flask_compress import Compress
app = Flask(__name__)
Compress(app) # Compresses responses automatically
3. Caching Static Assets
Browsers should cache your CSS and JS files so they don't download them on every page load. Set the Cache-Control header.
@app.after_request
def add_header(response):
if request.path.startswith('/static'):
# Cache for 1 year
response.headers['Cache-Control'] = 'public, max-age=31536000'
return response
4. Database Optimization (N+1)
Avoid the "N+1 query" problem. This happens when you loop through a list of items and run a query for each one. Use Joins or eager loading (like SQLAlchemy's joinedload) to fetch everything in one go.
5. Background Tasks
If a user uploads a file or requests a report, don't make them wait. Offload the work to a background queue using Celery or Redis Queue (RQ) and return a response immediately.
6. Profile Your Code
Don't guess where the bottleneck is. Use Python's built-in cProfile to see exactly which function is taking the most time.
7. Async/Await (Flask 2.0+)
Modern Flask supports async/await. If your route waits for I/O (like calling an external API or database), making it async frees up the worker to handle other requests while waiting.
@app.route('/data')
async def get_data():
# This won't block the server while waiting!
data = await external_api_call()
return jsonify(data)
You'll need an async-ready server like Hypercorn or Gunicorn with uvicorn workers to fully utilize this.
Start with a solid foundation
Our Dockerfile Generator creates a production-ready setup with Gunicorn implicitly.
Try Dockerfile Generator