Log inSign up

Background jobs in Python with Celery and a Redis broker

Install Redis from your distribution, protect it with a password on localhost, add celery[redis] to your virtual environment and point the app at redis://:password@127.0.0.1:6379/0. Your web code calls task.delay(), a Celery worker running as a systemd service executes the job, and a separate beat service triggers scheduled tasks. celery -A proj inspect ping tells you the worker is alive.

Topic: Python · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

Why put work into a Celery queue?

A queue lets a web request answer in milliseconds while slow work, such as sending mail, resizing images, calling a remote API or building a report, happens in another process. The application drops a message into the broker, a worker picks it up, and an optional result backend stores the return value. Celery supplies the worker and the task API; Redis is a light, fast broker that fits well on a single server next to a Django, Flask or FastAPI app. Celery 5 needs Python 3.8 or newer, so every current image qualifies; the Python and pip guide covers venv setup.

How do you install and secure Redis as the broker?

Use the Redis package from the distribution and keep it bound to localhost with a password.

# Ubuntu and Debian
sudo apt update
sudo apt install -y redis-server
apt policy redis-server

# Rocky Linux 9 and AlmaLinux 9
sudo dnf module list redis
sudo dnf install -y redis
sudo systemctl enable --now redis

Edit /etc/redis/redis.conf (the path is the same on both families) and confirm or set these lines:

bind 127.0.0.1 -::1
protected-mode yes
requirepass a-long-random-broker-password

On Ubuntu and Debian also set supervised systemd. Restart with sudo systemctl restart redis-server (Ubuntu, Debian) or sudo systemctl restart redis (Rocky, Alma), then test:

redis-cli -a a-long-random-broker-password ping
ss -ltnp | grep 6379

The reply should be PONG and the socket should list only 127.0.0.1 and ::1. Never open port 6379 in the firewall for a broker used by local workers. The Redis guide covers memory limits and persistence.

How do you install Celery and write a first task?

Install Celery with the Redis extra inside the project virtual environment, then define an app and a task.

cd /srv/proj
source .venv/bin/activate
pip install "celery[redis]"
celery --version

Create proj/tasks.py:

import os
import time
from celery import Celery

app = Celery(
    "proj",
    broker=os.environ["CELERY_BROKER_URL"],
    backend=os.environ.get("CELERY_RESULT_BACKEND"),
)
app.conf.update(
    task_acks_late=True,
    worker_prefetch_multiplier=1,
    task_time_limit=300,
    timezone="UTC",
)

@app.task(bind=True, max_retries=3, default_retry_delay=30)
def build_report(self, account_id):
    try:
        time.sleep(5)  # stand-in for real work
        return {"account": account_id, "status": "done"}
    except ConnectionError as exc:
        raise self.retry(exc=exc)

Put the connection strings in an environment file such as /etc/proj.env, mode 640 and group deploy:

CELERY_BROKER_URL=redis://:a-long-random-broker-password@127.0.0.1:6379/0
CELERY_RESULT_BACKEND=redis://:a-long-random-broker-password@127.0.0.1:6379/1

If the password contains characters such as @ or /, percent-encode them in the URL or pick a password made only of letters and digits.

How do you queue a task and read the result?

Call .delay() or .apply_async() from your application; the call returns at once with a task id. Try it interactively while a worker runs in another terminal:

set -a; source /etc/proj.env; set +a
celery -A proj.tasks worker --loglevel=INFO      # terminal one

python                                           # terminal two
>>> from proj.tasks import build_report
>>> r = build_report.delay(42)
>>> r.get(timeout=30)

The worker log shows the task being received and succeeding, and r.get() returns the dictionary. Inside a web request, do not wait on get(); store the id and let the page poll, or have the task write its outcome to your database. Use apply_async(args=[42], countdown=60) to delay execution or queue="reports" to send work to a dedicated worker.

How does Celery plug into a Django project?

Django projects conventionally keep the Celery app in mysite/celery.py and read settings prefixed with CELERY_.

import os
from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
app = Celery("mysite")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

Import it in mysite/__init__.py with from .celery import app as celery_app, put tasks in each app as tasks.py decorated with @shared_task, and set CELERY_BROKER_URL = os.environ["CELERY_BROKER_URL"] in settings. Pass database ids to tasks rather than model objects, because arguments are serialised to JSON and the row may change before the worker runs.

How do you run the worker and beat under systemd?

Give the worker and the scheduler their own unit files so each restarts independently. Create /etc/systemd/system/celery-worker.service:

[Unit]
Description=Celery worker for proj
After=network.target redis-server.service redis.service

[Service]
User=deploy
Group=deploy
WorkingDirectory=/srv/proj
EnvironmentFile=/etc/proj.env
ExecStart=/srv/proj/.venv/bin/celery -A proj.tasks worker --loglevel=INFO --concurrency=2
Restart=on-failure
KillSignal=SIGTERM
TimeoutStopSec=300

[Install]
WantedBy=multi-user.target

And /etc/systemd/system/celery-beat.service for periodic jobs:

[Unit]
Description=Celery beat for proj
After=network.target

[Service]
User=deploy
Group=deploy
WorkingDirectory=/srv/proj
EnvironmentFile=/etc/proj.env
StateDirectory=celery-beat
ExecStart=/srv/proj/.venv/bin/celery -A proj.tasks beat --loglevel=INFO --schedule /var/lib/celery-beat/schedule
Restart=on-failure

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now celery-worker celery-beat
journalctl -u celery-worker -f

The long stop timeout lets a worker finish its current task during a restart. Run exactly one beat process, otherwise scheduled jobs fire twice.

How do you define scheduled tasks?

Add a beat schedule to the app configuration; beat reads it at start and sends the tasks at the given times.

from celery.schedules import crontab

app.conf.beat_schedule = {
    "nightly-report": {
        "task": "proj.tasks.build_report",
        "schedule": crontab(hour=2, minute=30),
        "args": (42,),
    },
    "every-five-minutes": {
        "task": "proj.tasks.build_report",
        "schedule": 300.0,
        "args": (7,),
    },
}

Restart beat after changing the schedule. For a handful of jobs that do not need retries or queues, a plain cron job may be simpler.

How do you check health and size the workers?

Celery ships inspection commands that talk to live workers through the broker:

set -a; source /etc/proj.env; set +a
celery -A proj.tasks inspect ping
celery -A proj.tasks inspect active
celery -A proj.tasks status
redis-cli -a a-long-random-broker-password llen celery

The last command shows how many messages wait in the default queue. A queue that keeps growing means you need more concurrency or faster tasks. The default pool uses processes, one per --concurrency slot, and each loads your code, so start with the number of vCPUs and adjust after watching memory. For tasks that mostly wait on the network, more slots than cores is fine. The optional Flower dashboard (pip install flower) should stay on localhost and be reached through an SSH tunnel.

What goes wrong most often?

  • Worker cannot connect: wrong password or URL encoding in CELERY_BROKER_URL; test with redis-cli first.
  • Task received but never runs: the worker listens on a different queue; start it with -Q celery,reports.
  • NotRegistered error: the worker did not import the module that defines the task; check -A and autodiscover_tasks().
  • Duplicate scheduled runs: two beat processes, or beat started inside the worker with -B as well as its own service.
  • Old code still running: workers keep code in memory; restart celery-worker after every deploy.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2web app plus one small worker1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4two worker slots and Redis with headroom2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8several queues or CPU heavy tasks4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about Background tasks with Celery and Redis

Do I need a result backend?

Only if you read return values or task states. Many tasks write their outcome to the application database instead, and then you can leave CELERY_RESULT_BACKEND unset and save Redis memory.

Can I use RabbitMQ instead of Redis?

Yes. Celery supports RabbitMQ as a broker with amqp:// URLs, and it gives stronger delivery guarantees. Redis is lighter and is often already installed for caching, which is why it is common on a single server.

Is it safe to run Celery as root?

No. Celery warns about it and a bug in a task would have full control of the server. Run workers as the same unprivileged user as the web app, as the unit files above do.

How do I stop a task that runs forever?

Set task_time_limit (hard kill) and optionally task_soft_time_limit, which raises an exception the task can catch to clean up. You can also revoke a running task with celery -A proj.tasks control revoke <id> --terminate.

Can Celery, Redis and the web app share one small server?

Yes, for modest workloads. Keep concurrency low on 1 to 2 GB plans, cap Redis memory with maxmemory, and move up a plan when memory graphs stay high.