r/django • • 9h ago

The systemd settings I ended up with for Django + Celery + beat on one VPS (no Docker)

8 Upvotes

I run a Django + Channels app with two Celery workers and beat on one VPS, each as its own systemd service. It took me a while to get the unit files right, so here's what's in them in case it saves someone the trial and error.

For every process:

  • Restart=always with RestartSec=2s, plus RestartSteps=5 and RestartMaxDelaySec=60s. A crashed process comes back in 2 seconds, but if it keeps crashing the wait grows up to a minute, so it doesn't spin in a loop.
  • Its own Linux user per app, not root and not www-data shared with everything else.
  • EnvironmentFile pointing at a root-owned 0600 env file, so secrets aren't in the unit or the repo.
  • PYTHONUNBUFFERED=1, or your logs show up late in journalctl.
  • NoNewPrivileges=true and PrivateTmp=true. On the web process also ProtectSystem=strict and ProtectHome=true, with ReadWritePaths for the app folder.

For the web process:

  • uvicorn bound to 127.0.0.1, never 0.0.0.0. Caddy is the only thing that listens on 80 and 443.
  • --proxy-headers --forwarded-allow-ips=127.0.0.1, so Django sees the real client IP and scheme from the proxy.

For Celery:

  • TimeoutStopSec=90s on the workers (the web process gets 30s). systemd sends TERM, Celery finishes the task it's on, and it only gets killed if it's still going after 90 seconds. If your tasks run longer than that, raise it, or a deploy will cut them off.
  • A separate worker for slow jobs. Mine has one worker on the normal queues and one that only takes the AI queue, both with concurrency 2, so a slow AI call never blocks a quick task.
  • beat as its own service, with django_celery_beat's DatabaseScheduler. Only ever one beat, or every scheduled task runs twice.

For scale: web is around 320 MB, each worker around 280 MB and beat around 140 MB.

Full disclosure, these units come out of a deploy tool I'm building, so I've stared at them more than is healthy. Happy to paste a full unit file in the comments if anyone wants one.

What's in your unit files that you'd never run without?