Skip to content

Running Sanic in production with multi-worker and Nginx

Deploy a Sanic application in production: multi-worker fast mode, systemd unit, Nginx termination, and the operational quirks specific to Sanic's built-in server.

Sanic is an async web framework with a built-in production HTTP server — unlike Flask or FastAPI, you don’t typically front Sanic with Uvicorn or Gunicorn because its own multi-worker mode is the canonical deployment. This article wires Sanic under systemd, picks a worker shape, terminates TLS at Nginx, and covers the operational nuances that catch teams used to the Gunicorn-WSGI model.

How to verify

Confirm the worker shape and that the socket actually answers:

systemctl status sanic-app --no-pager | head
ps -eo pid,ppid,etime,cmd | grep -E "sanic|sanic.app" | head
ss -ltnp | grep -E ':(8000|/run/sanic)'
curl -i http://127.0.0.1:8000/health
journalctl -u sanic-app -n 80 --no-pager | tail -40

If you see only one process and you started with workers=4, Sanic forked silently failed — read journal output, you’ll usually find an import error in a worker child.

What’s happening

Sanic 22+ runs in “fast mode” by default, which spawns one worker per CPU core and a single manager process that supervises them. Each worker is a complete Python process with its own asyncio loop — there’s no shared state, so anything you initialise at module load runs N times. The manager handles graceful shutdown, worker respawn, and SIGHUP-driven reload.

The framework includes its own HTTP server based on httptools, the same C parser Uvicorn uses. Because the server is in-process, you don’t get the Gunicorn benefits of max_requests recycling for free — Sanic does have WORKER_AUTO_RELOAD for development and a manager API for restarting workers, but the operational reflex of “recycle every 1000 requests to bleed off leaks” requires application code.

Sanic also ships an ASGI mode (sanic app --asgi or app.asgi = True), which lets you run it under Uvicorn/Hypercorn if your deployment standard demands it. The native server is faster and exposes more of Sanic’s capabilities (signals, blueprints, the manager API), so default to native unless ops policy forces ASGI.

The procedure

  1. Install Sanic into the project venv. The default install is fine for production — there are no [standard] extras to worry about:

    /opt/venvs/app/bin/pip install 'sanic>=23.0' sanic-ext
    /opt/venvs/app/bin/sanic --version

    sanic-ext adds Pydantic validation, OpenAPI auto-generation, and CORS — strip it if you don’t need any of that.

  2. Make sure the app uses lifecycle signals to open and close resources per worker. In app/main.py:

    from sanic import Sanic
    from sanic.response import json
    
    app = Sanic("MyApp")
    
    @app.before_server_start
    async def setup_db(app, loop):
        app.ctx.db = await create_pool(dsn="postgres://...")
    
    @app.before_server_stop
    async def close_db(app, loop):
        await app.ctx.db.close()
    
    @app.get("/health")
    async def health(request):
        return json({"ok": True})

    before_server_start runs once per worker, not once per app — perfect for connection pools.

  3. Create the systemd unit at /etc/systemd/system/sanic-app.service:

    [Unit]
    Description=Sanic application
    After=network.target
    
    [Service]
    User=deploy
    Group=www-data
    WorkingDirectory=/var/www/sanic-app
    RuntimeDirectory=sanic-app
    RuntimeDirectoryMode=0750
    EnvironmentFile=/etc/sanic-app/env
    Environment=PYTHONUNBUFFERED=1
    ExecStart=/opt/venvs/app/bin/sanic app.main:app \
      --host=0.0.0.0 --port=8000 \
      --workers=4 --access-logs
    ExecReload=/bin/kill -s HUP $MAINPID
    KillMode=mixed
    Restart=on-failure
    RestartSec=2
    
    [Install]
    WantedBy=multi-user.target

    For Unix-socket binding (when fronting with Nginx on the same host):

    ExecStart=/opt/venvs/app/bin/sanic app.main:app \
      --unix=/run/sanic-app/app.sock --workers=4
  4. Enable and verify:

    sudo systemctl daemon-reload
    sudo systemctl enable --now sanic-app
    curl --unix-socket /run/sanic-app/app.sock http://localhost/health
  5. In Nginx, terminate TLS and proxy through:

    upstream sanic_app {
      server unix:/run/sanic-app/app.sock;
    }
    
    server {
      listen 443 ssl http2;
      server_name app.example.com;
    
      location / {
        proxy_pass http://sanic_app;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 60s;
      }
    }
  6. Tell Sanic to trust the proxy headers so request.remote_addr returns the client IP, not the Nginx host:

    app.config.FORWARDED_SECRET = "<random string set in Nginx X-Forwarded-Secret>"
    app.config.PROXIES_COUNT = 1

    PROXIES_COUNT is safer than REAL_IP_HEADER — it strips exactly N hops from X-Forwarded-For rather than trusting the whole chain.

Common pitfalls

  • Initialising shared state at module level (e.g., a global DB pool created with await at import time) — Sanic forks N workers, and each one re-runs imports but await outside an event loop crashes. Use before_server_start.
  • Setting --workers=0 to use all cores: that’s the default in fast mode; the flag passes through but is redundant. Worse, --workers=1 disables the manager entirely and you lose graceful reload.
  • --access-logs writes to stdout and journald, which can spam the journal at high QPS. For production, prefer Nginx access logs and turn Sanic’s off with --no-access-logs.
  • WebSocket support requires pip install 'sanic[websockets]' — the base install drops wss:// upgrades silently with 426.
  • Memory growth without leak — Sanic doesn’t recycle workers. If you see a 100 MB-per-worker climb over a week, add a daily systemctl reload sanic-app cron and look for object retention with objgraph in dev.

For comparison with Uvicorn-based ASGI deployment, see Deploying FastAPI under Uvicorn workers. Stack Harbor’s managed operations practice runs Sanic in its native fast mode behind Nginx — adding Uvicorn or Gunicorn in front gains nothing and loses the manager API.