Celery is the default async task framework for Python and Django — task decorators, a worker daemon, a scheduler (celery beat), and a broker. With Redis as both broker and result backend you get a simple two-process setup that covers 80% of background-job needs. This article is the Celery install we run for Django clients: settings configured, tasks autodiscovered, a worker and a beat scheduler under systemd, retries with jitter, periodic tasks via beat, and a result-backend strategy that does not silently fill Redis.
How to verify
Check Python, Django, Celery, and Redis are ready:
python --version
python -c "import django; print(django.get_version())"
python -c "import celery; print(celery.__version__)"
redis-cli ping
redis-cli CONFIG GET maxmemory-policy # should NOT be allkeys-lru for the broker DB
If Redis is shared with cache, the broker DB needs noeviction. Cache is fine on allkeys-lru. Use separate DB numbers (/0 for cache, /1 for broker, /2 for results) or — better — separate Redis instances.
What’s happening
Celery has three roles:
- Producer (your Django views/management commands) — calls
my_task.delay(args)which serializes the args andLPUSHes onto a Redis list named for the queue. - Worker — runs
celery -A myproject worker. Blocks on Redis (BLPOP) waiting for tasks, deserializes, and runs the task function in a process or thread pool. - Beat — runs
celery -A myproject beat. Reads the periodic-task schedule (from settings ordjango-celery-beatDB models) and enqueues tasks at the right time.
The result backend is optional. If a task returns a value and the caller wants it, Celery stores the result in Redis under a key keyed by task ID. Results have a configured TTL (result_expires). If no caller cares, set ignore_result=True on the task and Celery does not write the result at all — saves a lot of Redis writes for fire-and-forget tasks.
Queues and routing. By default every task goes to celery. You add queues with task_routes in settings, then start workers with -Q queue1,queue2. Common pattern: separate workers for mailers, reports, default so a slow report task does not block a customer-facing email.
Concurrency model. Celery’s default prefork runs N worker processes (CPU-bound work). eventlet and gevent give you green-thread concurrency for I/O-bound work. solo is single-threaded, useful for debugging. Pick prefork for CPU work, gevent for I/O-heavy work; never solo in production.
The procedure
-
Install Celery and the Redis transport:
pip install 'celery[redis]>=5.4' django-celery-beat django-celery-resultsdjango-celery-beatputs the periodic-task schedule in the Django DB so it can be edited via the admin instead of code-pushed;django-celery-resultsputs results in the DB if you want SQL queries against them. -
Add to
INSTALLED_APPS:INSTALLED_APPS = [ # ... 'django_celery_beat', 'django_celery_results', ] -
Configure Celery in
myproject/celery.py:import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()And in
myproject/__init__.py:from .celery import app as celery_app __all__ = ('celery_app',) -
Configure in Django settings:
CELERY_BROKER_URL = os.environ['CELERY_BROKER_URL'] # redis://redis:6379/1 CELERY_RESULT_BACKEND = 'django-db' # or redis://redis:6379/2 CELERY_CACHE_BACKEND = 'default' CELERY_RESULT_EXTENDED = True CELERY_TASK_ALWAYS_EAGER = False CELERY_TASK_ACKS_LATE = True CELERY_TASK_REJECT_ON_WORKER_LOST = True CELERY_WORKER_PREFETCH_MULTIPLIER = 1 CELERY_TASK_TIME_LIMIT = 300 CELERY_TASK_SOFT_TIME_LIMIT = 270 CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TIMEZONE = 'America/Toronto' CELERY_ENABLE_UTC = Trueacks_late=True+reject_on_worker_lost=Trueis the at-least-once configuration: a task is acked only after the worker finishes, so a worker crash returns the task to the queue. The default is at-most-once, which silently loses tasks on crashes. -
Write a task:
# myapp/tasks.py from celery import shared_task from celery.exceptions import Retry @shared_task(bind=True, autoretry_for=(ConnectionError, TimeoutError), retry_kwargs={'max_retries': 5}, retry_backoff=True, retry_backoff_max=300, retry_jitter=True) def send_welcome(self, user_id): user = User.objects.get(pk=user_id) # send email via SMTP or an API return {'sent_to': user.email} -
Enqueue from views or signals:
from myapp.tasks import send_welcome send_welcome.delay(user.id) send_welcome.apply_async((user.id,), countdown=60) # run in 60 seconds -
Write the worker systemd unit at
/etc/systemd/system/celery-worker.service:[Unit] Description=Celery worker After=network-online.target redis-server.service [Service] Type=simple User=app Group=app WorkingDirectory=/srv/myapp/current Environment="DJANGO_SETTINGS_MODULE=myproject.settings" EnvironmentFile=/etc/myapp.env ExecStart=/srv/myapp/venv/bin/celery -A myproject worker \ --loglevel=INFO \ --concurrency=4 \ -Q default,mailers Restart=always RestartSec=10 KillSignal=SIGQUIT TimeoutStopSec=120 LimitNOFILE=65536 [Install] WantedBy=multi-user.targetKillSignal=SIGQUITis the warm-shutdown signal — Celery finishes in-flight tasks then exits. -
Write the beat systemd unit at
/etc/systemd/system/celery-beat.service:[Unit] Description=Celery beat After=network-online.target [Service] Type=simple User=app Group=app WorkingDirectory=/srv/myapp/current EnvironmentFile=/etc/myapp.env ExecStart=/srv/myapp/venv/bin/celery -A myproject beat \ --loglevel=INFO \ --scheduler django_celery_beat.schedulers:DatabaseScheduler Restart=always RestartSec=10 [Install] WantedBy=multi-user.targetOnly one beat process per Django site — running two creates duplicate enqueues. Pin it to a specific host or use a lock.
Operational notes
result_expiresdefaults to 1 day; if you store results in Redis and have high task volume, this can swell quickly. Set it lower or useignore_result=Truefor tasks whose results are never read.worker_prefetch_multiplier=1is critical for fairness when tasks have varying durations; the default of 4 means a worker that picks up a slow task also reserves three more behind it.- Periodic tasks in
django-celery-beatare stored in the DB; editing the schedule via Django admin takes effect within a minute without restarting beat. This is the main reason to use the DB scheduler over the file scheduler. - A task that imports the Django settings at module load is fine; one that calls into Django code at worker boot before
app.autodiscover_tasks()runs causes circular-import grief. Keep tasks defined intasks.pyand let autodiscover find them. - Flower (
pip install flower; celery -A myproject flower) is the canonical web UI for Celery; mount it behind your auth, never exposed publicly.
Stack Harbor stands up Celery for Django clients as the async-task tier — workers and beat under systemd, Redis or RabbitMQ as broker isolated from cache, periodic tasks editable from the admin, and result-backend retention sized to what is actually queried. If your Celery setup grew from a tutorial into the engine that runs invoices, exports, and mailers, this is the work covered by our Managed Operations practice.