Deploying Django and FastAPI on a VPS: workers, queues, releases

To host Django, Flask or FastAPI on a VPS you need a virtual environment, an application server under systemd, nginx for static files, and a separate process for background jobs. The decisions that matter are the server type and the number of workers, so this page starts there.

Updated: · Prices in the text are with the public IP (₼10 a month) unless stated otherwise.

Decide: WSGI, ASGI or no web server at all

Your projectApplication serverWhy
Django or Flask with a normal databasegunicorn, gthread workersSimple, predictable, threads cover database waits
FastAPI, Starlettegunicorn with uvicorn workersAsync handlers, process supervision from gunicorn
Django with WebSockets (Channels)An ASGI server plus RedisWSGI cannot hold a socket open
Scrapers, bots, schedulersJust a systemd service or timerNothing listens for visitors

Do not choose async because it sounds faster. One blocking call, such as requests.get() inside an async def handler, freezes every user of that worker.

A clean environment

Ubuntu 24.04 ships Python 3.12 and refuses pip install into the system with externally-managed-environment. That is protection, not a bug: system tools depend on those packages. Use a venv.

sudo apt update
sudo apt install -y python3-venv python3-dev build-essential libpq-dev \
  nginx postgresql redis-server git
sudo adduser --system --group --home /opt/pyweb pyweb
sudo -H -u pyweb git clone https://git.example.az/team/site.git /opt/pyweb/app
sudo -H -u pyweb python3 -m venv /opt/pyweb/venv
sudo -H -u pyweb /opt/pyweb/venv/bin/pip install -r /opt/pyweb/app/requirements.txt gunicorn

Pin exact versions in requirements.txt (pip freeze or pip-tools). Nothing has to be "activated" on a server: calling a program from venv/bin is enough.

Socket first, then the service

Let systemd own the socket. When gunicorn restarts, new connections wait in the queue for a second or two instead of receiving an error. That gives quiet releases with a single instance.

# /etc/systemd/system/pyweb.socket
[Unit]
Description=Socket for the Python site

[Socket]
ListenStream=/run/pyweb.sock
SocketUser=www-data
SocketMode=0660

[Install]
WantedBy=sockets.target
# /etc/systemd/system/pyweb.service
[Unit]
Description=gunicorn for the Python site
Requires=pyweb.socket
After=network.target

[Service]
Type=notify
NotifyAccess=main
User=pyweb
Group=pyweb
WorkingDirectory=/opt/pyweb/app
EnvironmentFile=/etc/pyweb.env
ExecStart=/opt/pyweb/venv/bin/gunicorn mysite.wsgi:application \
    --worker-class gthread --workers 3 --threads 4 \
    --max-requests 1000 --max-requests-jitter 100 --timeout 30
KillMode=mixed
TimeoutStopSec=40
Restart=on-failure
PrivateTmp=true

[Install]
WantedBy=multi-user.target

For FastAPI, install uvicorn[standard] and uvicorn-worker, and replace the class: gunicorn main:app -k uvicorn_worker.UvicornWorker --workers 2. Start with sudo systemctl enable --now pyweb.socket, then test: sudo -u www-data curl -I --unix-socket /run/pyweb.sock -H 'Host: site.example.az' http://localhost/.

The nginx part is short, because Ubuntu already supplies proxy_params:

server {
    listen 80;
    server_name site.example.az;
    client_max_body_size 20m;

    location /static/ { alias /opt/pyweb/static/; expires 7d; }
    location /media/  { alias /opt/pyweb/media/; }
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/pyweb.sock;
    }
}

After HTTPS is on (certificate steps), tell Django it is behind a proxy: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'). Without it, secure redirects can loop.

Counting workers honestly

The formula in the gunicorn documentation, 2 × vCPU + 1, is a starting suggestion based on CPU, and it ignores memory. Check both and take the smaller number:

  • By CPU: 1 vCPU gives 3, 2 vCPU give 5, 4 vCPU give 9.
  • By memory: (RAM − system − database − Celery) ÷ worker size. A Django worker often takes 100–150 MB, and one that imports pandas 250 MB or more.

Example for 4 GB: 0.5 GB for the system, 1 GB for PostgreSQL and Redis, 0.5 GB for Celery. 2 GB remain, at 150 MB per worker that is 13, so the CPU figure of 5 wins. On 1 GB the same sums leave room for two.

Threads are cheap help for requests that wait on a database or an API, and no help at all for calculation, because the global interpreter lock lets one thread run Python code at a time. If top shows workers near 100% CPU, add processes and vCPUs. If workers are idle and users wait, look for slow queries. --max-requests quietly recycles workers and hides small leaks; it does not replace finding a large one.

Celery without surprises

Background jobs need their own limits, otherwise one report takes the website with it.

# /etc/systemd/system/pyweb-celery.service
[Unit]
Description=Celery worker
After=network.target redis-server.service

[Service]
User=pyweb
Group=pyweb
WorkingDirectory=/opt/pyweb/app
EnvironmentFile=/etc/pyweb.env
ExecStart=/opt/pyweb/venv/bin/celery -A mysite worker --loglevel=INFO \
    --concurrency=2 --max-tasks-per-child=200 --max-memory-per-child=250000
KillMode=mixed
TimeoutStopSec=300
Restart=always

[Install]
WantedBy=multi-user.target

Four things people learn late:

  1. celery beat must run exactly once. Two copies send every reminder twice.
  2. With Redis as the broker, a task not acknowledged within the visibility timeout (one hour by default) is delivered again. Raise it if you use long countdowns, and make tasks safe to repeat.
  3. Set Redis maxmemory-policy noeviction for the broker; an eviction policy made for caching can delete queued jobs.
  4. Pass IDs to tasks, not objects, and use transaction.on_commit(), or the worker may look for a row that is not saved yet.

The release routine

manage.py needs the same environment as the service, so let systemd supply it. Save this as a script and run it with sudo:

#!/usr/bin/env bash
set -euo pipefail
cd /opt/pyweb/app
run() { sudo -H -u pyweb "$@"; }
manage() {
  systemd-run --quiet --wait --pipe --collect --uid=pyweb --gid=pyweb \
    --working-directory=/opt/pyweb/app -p EnvironmentFile=/etc/pyweb.env \
    /opt/pyweb/venv/bin/python manage.py "$@"
}
run git fetch --tags
run git checkout --quiet "$1"
run /opt/pyweb/venv/bin/pip install --quiet -r requirements.txt
manage check --deploy
manage migrate --noinput
manage collectstatic --noinput
systemctl restart pyweb pyweb-celery
curl -fsS -o /dev/null --unix-socket /run/pyweb.sock -H 'Host: site.example.az' http://localhost/ && echo released

Going back is the same script with the previous tag, provided the migration did not remove anything the old code reads. Take a dump before every migration and keep it elsewhere; backup to S3 shows how to automate it.

What to order

  • Nano₼14.90/mo

    1 vCPU · 1 GB RAM · 30 GB NVMe

    Public IP +₼10/mo, With public IP: ₼24.90/mo

  • Standard₼39.90/mo

    2 vCPU · 4 GB RAM · 60 GB NVMe

    Public IP +₼10/mo, With public IP: ₼49.90/mo

  • Business₼95.90/mo

    6 vCPU · 12 GB RAM · 120 GB NVMe

    Public IP +₼10/mo, With public IP: ₼105.90/mo

Prices in manat (AZN), billed monthly. The public IP is +₼10 a month and is assigned automatically.

Nano holds a bot or a small Flask service with SQLite. Standard (2 vCPU, 4 GB RAM, 60 GB NVMe) carries Django, PostgreSQL, Redis and two Celery processes. With a public IP (₼10 a month) Nano is ₼24.90 and Standard is ₼49.90. Business (6 vCPU, 12 GB RAM, 120 GB NVMe) is for pandas-style reports and many workers. A heavy queue may deserve its own machine on the private subnet, as may the database. There are no GPUs here, so train models elsewhere. If you only need a chat bot, the Telegram bot page is shorter.

Python hosting questions

How many gunicorn workers should I use on 2 vCPU?

Start with 3 to 5 and check memory first. Add threads if requests wait on a database, and stop adding workers when the CPU is full or free memory falls under about 15%.

Can I use a newer Python than 3.12 on Ubuntu 24.04?

Yes, with uv or pyenv in the service user's home directory, or in a container. Leave the system interpreter alone, because Ubuntu tools depend on it.

Is Django or FastAPI lighter on a small server?

A bare FastAPI worker uses less memory than a full Django one. Once an ORM, templates and libraries are loaded, the gap shrinks, and the database usually decides the speed.

Do I need Docker to deploy Python?

No. A venv with systemd is enough for one or two projects. Containers help when projects need different system libraries or when the same image must run in several places.

Why does my site return 502 after a deploy?

gunicorn failed to start. Read journalctl -u pyweb -n 50: the usual reasons are a missing package, a wrong module path or a variable absent from the environment file.

Read next

All VPS pages

This page in other languages: Azərbaycanca · Русский

Servers in Baku, prices in manat

Create an account, top up your balance and order the plan you need.