Skip to content

Running Celery with Redis as broker and result backend

Set up Celery 5.x with Redis as broker and result backend, supervised by systemd, with prefetch, acks_late, and visibility timeout tuned for production.

Celery on Redis is the workhorse task queue for Python web stacks because both pieces are simple, both have first-party clients, and the operational footprint is small. The combination has sharp edges: visibility timeout, prefetch multiplier, and acks_late semantics all need to be set explicitly or you’ll lose tasks under restart. This article wires Celery 5.x to a Redis broker, supervises it with systemd, and configures the parameters that actually matter.

How to verify

Look at what the broker thinks the queue depth is and what the workers are doing:

systemctl status celery-app.service --no-pager | head
redis-cli -h 127.0.0.1 -n 0 LLEN celery
redis-cli -h 127.0.0.1 -n 0 KEYS 'celery-task-meta-*' | wc -l
/opt/venvs/app/bin/celery -A app.celery inspect active
/opt/venvs/app/bin/celery -A app.celery inspect stats | head -40
journalctl -u celery-app.service -n 100 --no-pager

If LLEN is climbing but inspect active is empty, workers are not consuming — usually a connection error to Redis or a wrong queue name in task_routes.

What’s happening

Celery is a producer-consumer system. Your web process publishes a JSON-encoded task message to a Redis list (by default the key celery), and worker processes use BRPOPLPUSH to atomically move messages from that list to a worker-specific “unacked” list. When the task succeeds, the worker LREM’s the message from its unacked list. If the worker crashes before that, the message sits in the unacked list until the visibility timeout expires — at which point Celery’s reaper moves it back to the main queue for redelivery.

acks_late=True flips the acknowledgement from “received” to “completed.” Without it, a task that the worker pops but crashes mid-execution is lost forever — Redis treats receive-as-ack. With it, the message survives a worker crash because the cleanup only happens on success. The price: any task that doesn’t crash but also doesn’t complete (infinite loop, OOM kill mid-write) gets retried after visibility timeout, so tasks must be idempotent.

worker_prefetch_multiplier=1 is the production setting. The default of 4 means a worker grabs four tasks at once, holding three in memory while it processes the first — under unequal task duration, this leads to one worker hoarding long tasks while others sit idle.

The procedure

  1. Install Celery and the Redis client into the project venv:

    /opt/venvs/app/bin/pip install 'celery[redis]==5.4.*'
    /opt/venvs/app/bin/celery --version
  2. Configure Celery in app/celery.py:

    from celery import Celery
    
    app = Celery(
        "app",
        broker="redis://127.0.0.1:6379/0",
        backend="redis://127.0.0.1:6379/1",
        include=["app.tasks"],
    )
    
    app.conf.update(
        task_acks_late=True,
        task_reject_on_worker_lost=True,
        worker_prefetch_multiplier=1,
        worker_max_tasks_per_child=1000,
        broker_transport_options={"visibility_timeout": 3600},
        result_expires=86400,
        task_default_queue="default",
        task_routes={
            "app.tasks.send_email": {"queue": "email"},
            "app.tasks.process_video": {"queue": "video"},
        },
        timezone="UTC",
        enable_utc=True,
    )

    visibility_timeout must be longer than your longest task — otherwise the reaper redelivers a task that’s still running, and you get duplicate execution.

  3. Write tasks with explicit retries in app/tasks.py:

    from celery import shared_task
    from celery.exceptions import Retry
    
    @shared_task(
        bind=True,
        autoretry_for=(ConnectionError, TimeoutError),
        retry_backoff=True,
        retry_backoff_max=600,
        retry_jitter=True,
        max_retries=5,
    )
    def send_email(self, to, subject, body):
        # idempotent body required
        ...
  4. Create /etc/systemd/system/celery-app.service:

    [Unit]
    Description=Celery worker for app
    After=network.target redis-server.service
    Requires=redis-server.service
    
    [Service]
    Type=forking
    User=deploy
    Group=deploy
    WorkingDirectory=/var/www/app
    EnvironmentFile=/etc/celery-app/env
    RuntimeDirectory=celery-app
    PIDFile=/run/celery-app/worker.pid
    ExecStart=/opt/venvs/app/bin/celery -A app.celery multi start worker1 \
        --pidfile=/run/celery-app/%n.pid \
        --logfile=/var/log/celery/%n.log \
        --loglevel=INFO --concurrency=8 -Q default,email,video
    ExecStop=/opt/venvs/app/bin/celery multi stopwait worker1 \
        --pidfile=/run/celery-app/%n.pid
    ExecReload=/opt/venvs/app/bin/celery multi restart worker1 \
        --pidfile=/run/celery-app/%n.pid
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
  5. Reload and start:

    sudo mkdir -p /var/log/celery
    sudo chown deploy:deploy /var/log/celery
    sudo systemctl daemon-reload
    sudo systemctl enable --now celery-app.service
    journalctl -u celery-app -n 60 --no-pager
  6. From the Django/FastAPI process, dispatch a task to confirm the round-trip:

    from app.tasks import send_email
    res = send_email.delay("test@example.org", "hi", "...")
    print(res.id, res.status)

Common pitfalls

  • Using the same Redis DB for broker and result backend — they share key namespaces and FLUSHDB of one wipes both. Always split: db 0 for broker, db 1 for results.
  • Setting visibility_timeout lower than your longest task: a 30-minute video transcode under a 600s visibility timeout will be re-queued and run twice in parallel. Set the timeout to comfortably exceed the 99th-percentile runtime.
  • Forgetting worker_max_tasks_per_child: a long-running worker with a small leak (common with libraries that hold image buffers) will OOM. Restarting the worker after 1000 tasks bounds the damage.
  • Storing large results in Redis: every task with a non-None return goes to celery-task-meta-* and stays for result_expires. If you don’t read the result, set ignore_result=True on the task or you’ll fill Redis with junk.
  • Running Beat and worker in the same systemd unit — they have different lifecycles. Use a separate celery-beat.service; see Celery Beat scheduling for the schedule side.

For the periodic scheduling side of Celery, see Celery Beat scheduling. Stack Harbor’s managed operations practice runs this exact shape — Celery workers under systemd, Redis on a dedicated host with persistence enabled, Flower or Prometheus celery-exporter for queue-depth alerts — as the default Python task-queue stack for clients.