Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Flask Performance Tuning on a Linux VPS: Measure First

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to improve Flask application performance on a Linux VPS by measuring first, then optimizing. You'll learn to identify bottlenecks with profiling and load testing, then apply targeted fixes like caching, database query optimization, and using a production WSGI server. The key principle: never guess what's slow—measure it.

What You'll Need

  • A Linux VPS (Ubuntu 20.04/22.04 or similar) with SSH access
  • A Flask application already deployed and running (even in development mode)
  • Python 3.8+ installed on the server
  • Basic command-line familiarity (cd, nano/vim, pip)
  • Optional but helpful: a domain name pointed to the VPS for realistic testing

Step-by-Step

  1. Set up a baseline measurement environment. Install a load testing tool like ab (ApacheBench) or wrk. On Ubuntu: sudo apt install apache2-utils. Also install a Python profiler: pip install flask-profiler or use built-in cProfile. You'll need these to measure before and after changes.
  2. Profile your application in development. Run your Flask app with profiling enabled. For example, wrap your app with flask-profiler to see which endpoints take the most time. Alternatively, use cProfile on a test script that calls your routes. Identify the top 3 slowest functions or routes.
  3. Run a load test against the current setup. Start your Flask app (even with the dev server) and run: ab -n 1000 -c 10 http://your-server-ip/. Record the requests per second (RPS) and average response time. This is your baseline.
  4. Switch to a production WSGI server. Flask's built-in server is single-threaded and not for production. Install Gunicorn: pip install gunicorn. Run your app with gunicorn -w 4 -b 0.0.0.0:8000 app:app. Test again with ab—you should see a significant RPS improvement. Adjust worker count to roughly 2-4 per CPU core.
  5. Add caching for expensive operations. If your profile shows database queries or template rendering as bottlenecks, cache results. Use Flask-Caching with a simple in-memory cache for start, then move to Redis if needed. Example: @cache.cached(timeout=300) on view functions that return static or semi-static content.
  6. Optimize database queries. If you use SQLAlchemy, enable query logging and look for N+1 queries. Use joinedload or subqueryload to eager-load relationships. Add indexes to columns used in WHERE and JOIN clauses. Run EXPLAIN on slow queries and fix missing indexes.
  7. Enable gzip compression. Compress responses to reduce bandwidth. Use Flask-Compress: pip install flask-compress, then Compress(app). Test with ab and also check the Content-Encoding header.
  8. Set up a reverse proxy with Nginx. Nginx serves static files directly and handles buffering, SSL, and keep-alive. Install Nginx, configure it to proxy requests to Gunicorn on a local port (e.g., 8000). Serve static files from Nginx directly. This offloads work from Flask.
  9. Re-measure after each change. After each optimization, run the same ab command and compare RPS and response times. If a change doesn't improve things, revert it. Keep a log of changes and results.
  10. Monitor in production. Use a tool like htop to watch CPU/memory, and check Gunicorn logs for errors. Set up basic alerting if possible. Regularly re-profile to catch new bottlenecks as your app grows.

Common Mistakes

  • Skipping the baseline. Without measuring first, you might optimize the wrong thing and waste hours.
  • Using the Flask dev server in production. It's not designed for concurrent traffic and will crash or be extremely slow.
  • Over-caching. Caching dynamic content (like user-specific data) can serve stale data. Only cache what's safe.
  • Ignoring database indexes. A missing index can make queries exponentially slower as data grows.
  • Too many or too few Gunicorn workers. Too many workers can exhaust memory; too few underutilize CPU. Test different numbers.
  • Not testing after every change. You might combine a good change with a bad one and not know which helped.

Tips

  • Use time on your endpoints in development to get a quick sense of response times.
  • For load testing, use a separate machine if possible to avoid skewing results with the VPS's own load.
  • Consider using a CDN for static assets if your audience is global.
  • Use connection pooling for databases (SQLAlchemy does this by default, but tune pool_size and max_overflow).
  • Keep your Python environment clean—remove unused packages to reduce memory footprint.
  • Regularly update Flask and Gunicorn to get performance improvements and security patches.

Troubleshooting

  • Gunicorn won't start. Check the error log (gunicorn --error-logfile -). Common issues: wrong app module path, missing dependencies, or port already in use.
  • Load test shows no improvement after adding workers. Your bottleneck might be CPU-bound, not I/O. Check if your app is single-threaded due to a global lock (e.g., CPU-heavy Python code). Try increasing workers or switching to an async worker like gevent.
  • Nginx returns 502 Bad Gateway. Gunicorn is not running or is on a different port. Check systemctl status gunicorn and ensure the proxy_pass matches.
  • Caching causes stale data. Set a shorter timeout, or use cache keys that include user ID for personalized content.
  • Memory usage spikes. Reduce the number of workers, or increase max_requests in Gunicorn to recycle workers and free memory.
  • Database queries still slow. Use EXPLAIN ANALYZE to see actual execution. Sometimes adding an index isn't enough—consider denormalizing or using a cache like Redis.

Frequently Asked Questions

How do I know if my Flask app is slow?

Use a profiler to see which functions take the most time, and run a load test to measure requests per second. If response times are high under load, you have a bottleneck.

What's the best production server for Flask?

Gunicorn is the most common and works well with Nginx as a reverse proxy. For async workloads, consider Gunicorn with gevent workers or an ASGI server like Uvicorn if you use async Flask extensions.

Should I use Redis or Memcached for caching?

Redis is more feature-rich and supports data types, while Memcached is simpler and faster for pure key-value caching. Start with in-memory caching, then move to Redis if you need shared cache across multiple servers.

How many Gunicorn workers should I use?

A common formula is 2-4 workers per CPU core. Start with that and adjust based on memory and load test results. Too many workers can cause memory exhaustion.

Is it worth using a CDN for a small Flask app?

If you serve static assets like images, CSS, and JS, a CDN can reduce latency for users far from your server. For a small app with few static files, it may not be necessary.

How often should I re-profile my app?

After significant code changes, or when you notice performance degradation. Also re-profile after adding new features that might introduce N+1 queries or heavy computations.