StackPractices
intermediate By Mathias Paulenko

Distribute Background Tasks with Python Celery and Redis

Set up Celery with Redis broker for distributed task processing including task chaining, groups, chords, retry strategies, scheduled tasks with Celery Beat, and result backends.

Overview

Celery is Python’s most widely used distributed task queue. It runs background jobs, scheduled tasks and multi-step workflows (chains, groups, chords) across a pool of worker processes. With Redis as broker and result backend, setup is minimal. Below: configuring Celery, defining tasks with retry strategies, composing workflows, scheduling with Celery Beat, and monitoring with Flower.

When to Use This

  • Background processing (email sending, report generation, file conversion)
  • Periodic or scheduled tasks (daily reports, cleanup jobs, data sync)
  • Workflows where one step depends on the output of earlier steps
  • Spreading CPU-heavy work across a worker pool on several machines

Prerequisites

  • Python 3.10+
  • Redis server (local or cloud)
  • celery[redis] and flower packages

Solution

1. Celery Configuration

# celery_app.py
from celery import Celery

app = Celery(
    'myapp',
    broker='redis://localhost:6379/0',
    backend='redis://localhost:6379/1',
)

app.conf.update(
    # Serialization
    task_serializer='json',
    result_serializer='json',
    accept_content=['json'],

    # Timezone
    timezone='UTC',
    enable_utc=True,

    # Reliability
    task_acks_late=True,
    task_reject_on_worker_lost=True,
    worker_prefetch_multiplier=1,

    # Results
    result_expires=3600,  # results expire after 1 hour
    task_track_started=True,

    # Time limits: soft raises an exception, hard kills the worker
    task_soft_time_limit=240,
    task_time_limit=300,
)

# Task-level retry defaults live in task_annotations, not app.conf.
# There is no task_default_retry_delay/task_default_max_retries setting.
app.conf.task_annotations = {
    '*': {'max_retries': 3, 'default_retry_delay': 60},
}

# Auto-discover tasks.py inside each listed package
app.autodiscover_tasks(['myapp'])

2. Tasks with Retry

# tasks.py
from celery_app import app
import time
import logging

logger = logging.getLogger(__name__)

@app.task(
    bind=True,
    max_retries=3,
    default_retry_delay=60,
    autoretry_for=(ConnectionError, TimeoutError),
    retry_backoff=True,
    retry_backoff_max=600,
    retry_jitter=True,
)
def send_email(self, to: str, subject: str, body: str):
    try:
        smtp = connect_smtp()
        smtp.sendmail(to, subject, body)
        logger.info("Email sent to %s", to)
        return {'status': 'sent', 'to': to}
    except Exception as exc:
        # autoretry_for already handles transient errors; this branch
        # only runs for non-transient failures
        logger.error("Failed to send email to %s: %s", to, exc)
        raise

@app.task
def generate_report(report_type: str, params: dict) -> dict:
    time.sleep(5)  # simulate work
    return {
        'reportType': report_type,
        'params': params,
        'url': f'https://reports.example.com/{report_type}/{params["id"]}.pdf',
    }

@app.task
def send_report_email(report: dict, to: str, subject: str):
    """Chain target: receives the previous task's result as first arg."""
    body = f"Your {report['reportType']} report is ready: {report['url']}"
    return send_email.delay(to, subject, body).get()

3. Task Chaining (Sequential)

A chain injects the previous task’s return value as the first positional argument of the next task, so the second signature must accept it.

from celery import chain
from tasks import generate_report, send_report_email

# generate_report returns the report dict; send_report_email gets it
# as `report`, then 'user@example.com' fills `to`.
workflow = chain(
    generate_report.s('monthly', {'id': 'report-123', 'month': '2026-06'}),
    send_report_email.s('user@example.com', 'Your Monthly Report'),
)

result = workflow.apply_async()
print(f"Workflow ID: {result.id}")

final_result = result.get(timeout=30)
print(f"Final result: {final_result}")

Use .si() (immutable signature) when the next task should ignore the previous result entirely.

4. Task Groups (Parallel)

from celery import group
from tasks import generate_report

reports = [
    {'type': 'sales', 'params': {'month': '2026-06'}},
    {'type': 'traffic', 'params': {'month': '2026-06'}},
    {'type': 'revenue', 'params': {'month': '2026-06'}},
]

workflow = group(
    generate_report.s(r['type'], r['params']) for r in reports
)

result = workflow.apply_async()

# result.get() returns the task results as a list
results = result.get(timeout=60)
for r in results:
    print(f"Report ready: {r['url']}")

5. Chord (Parallel + Callback)

A chord runs a group in parallel, then calls a task with the list of results. The callback must be a registered task — a plain function has no .s() signature.

from celery import chord, group
from tasks import generate_report, send_email

@app.task
def summarize_reports(results: list, to_email: str):
    summary = f"Generated {len(results)} reports:\n"
    for r in results:
        summary += f"  - {r['reportType']}: {r['url']}\n"
    send_email.delay(to_email, 'Report Summary', summary)
    return {'sent': True, 'count': len(results)}

header = group(
    generate_report.s(r['type'], r['params'])
    for r in fetch_report_requests()
)

# chord(header)(callback) returns the callback's AsyncResult
workflow = chord(header)(summarize_reports.s('admin@example.com'))
result = workflow.get(timeout=120)
print(f"Summary sent: {result}")

6. Celery Beat (Scheduled Tasks)

# celery_app.py
from celery import Celery
from celery.schedules import crontab

app = Celery('myapp', broker='redis://localhost:6379/0')

app.conf.beat_schedule = {
    # Every morning at 6 AM
    'daily-report': {
        'task': 'tasks.generate_report',
        'schedule': crontab(hour=6, minute=0),
        'args': ('daily', {'date': 'today'}),
    },
    # Every Monday at 9 AM
    'weekly-cleanup': {
        'task': 'tasks.cleanup_expired_sessions',
        'schedule': crontab(hour=9, minute=0, day_of_week=1),
    },
    # Every 5 minutes
    'health-check': {
        'task': 'tasks.check_service_health',
        'schedule': 300.0,  # seconds
    },
    # First day of every month at midnight
    'monthly-billing': {
        'task': 'tasks.process_monthly_billing',
        'schedule': crontab(hour=0, minute=0, day_of_month=1),
    },
}

7. Task State and Results

from celery_app import app
from celery.result import AsyncResult

def check_task(task_id: str) -> dict:
    result = AsyncResult(task_id, app=app)
    return {
        'task_id': task_id,
        'status': result.status,  # PENDING, STARTED, SUCCESS, FAILURE, RETRY
        'result': result.result if result.successful() else None,
        'traceback': result.traceback if result.failed() else None,
        'date_done': result.date_done,
    }

def cancel_task(task_id: str):
    app.control.revoke(task_id, terminate=True, signal='SIGTERM')

task_info = check_task('some-task-id')
print(f"Status: {task_info['status']}")

RETRY shows up while a task waits between attempts, and PENDING means either “queued” or “unknown id” — combine it with date_done or your own tracking to tell them apart.

8. Running Workers and Beat

# Start a worker
celery -A celery_app worker --loglevel=info --concurrency=4

# Start Beat (scheduler) — run exactly one instance
celery -A celery_app beat --loglevel=info

# Start Flower (monitoring dashboard)
celery -A celery_app flower --port=5555

# Run a task from the CLI
celery -A celery_app call tasks.send_email --args='["user@example.com", "Welcome", "Hello!"]'

How It Works

Mermaid flowchart LR diagram
  1. Broker: Celery pushes serialized task messages to a Redis list (or a RabbitMQ exchange). Workers pop messages from that queue. Redis is the simplest option; switch to RabbitMQ when you need real per-message priority.
  2. Result backend: results go back to Redis so result.get() can block until the task finishes. Without a backend, results are discarded and get() raises an error.
  3. Prefetch: worker_prefetch_multiplier=1 makes each worker process hold one task at a time. Higher values raise throughput for sub-second tasks but let one worker hoard long tasks while others sit idle.
  4. acks_late: with task_acks_late=True, the broker keeps the message until the task finishes. If the worker dies mid-task, the message goes back to the queue instead of being lost — which is why tasks must be idempotent.
  5. Canvas: chains pass each result into the next signature’s first argument. Groups dispatch everything at once and return a GroupResult. Chords wait for every task in the group, then run a single callback with the full results list.

Workers default to the prefork pool, where --concurrency is the number of child processes. That suits CPU-bound tasks because each process gets its own GIL. For I/O-bound tasks (HTTP calls, database waits), celery -A celery_app worker -P gevent --concurrency=100 runs far more concurrent tasks in one process — just remember that greenlet-based pools break on tasks that call blocking C extensions like psycopg2 without monkey-patching.

Monitoring the Queue

Flower gives you the live picture — active, reserved and failed tasks per worker — but the CLI covers the same ground when you can’t open a browser:

# Registered tasks on each worker
celery -A celery_app inspect registered

# Tasks currently executing
celery -A celery_app inspect active

# Workers that answered the broadcast ping
celery -A celery_app inspect ping

# Queue lengths from the broker side
redis-cli -n 0 llen celery

Watch the reserved count, not just the active one: a worker with many reserved tasks and worker_prefetch_multiplier=1 misconfigured is the classic “everything queued, nothing running” symptom.

Result Backend Caveats

result_expires deletes results after the TTL, so a PENDING status on an old task id usually means the result already expired rather than the task never ran. For anything you need to query days later, write your own completion record (a row, a log entry) inside the task instead of trusting the backend.

Variants

Canvas: Chain with Error Handling

from celery import chain
from tasks import generate_report, send_report_email

def on_failure(request, exc, traceback):
    logger.error("Task %s failed: %s", request.id, exc)

workflow = chain(
    generate_report.s('monthly', {'id': '123'}).on_error(on_failure),
    send_report_email.s('user@example.com', 'Report'),
)

result = workflow.apply_async()

Routing to Different Queues

app.conf.task_routes = {
    'tasks.send_email': {'queue': 'email'},
    'tasks.send_report_email': {'queue': 'email'},
    'tasks.generate_report': {'queue': 'reports'},
    'tasks.cleanup_*': {'queue': 'maintenance'},
}

# Start workers for specific queues
# celery -A celery_app worker -Q email --concurrency=2
# celery -A celery_app worker -Q reports --concurrency=4

Queue routing doubles as a lightweight priority scheme: give email more workers and reports fewer, and emails win the pool’s attention during spikes.

Periodic Tasks with Database Scheduler

# pip install django-celery-beat — schedules live in the DB,
# editable from Django admin without restarting Beat
app.conf.beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler'

Best Practices

  • For related messaging patterns, see Implement Redis Pub/Sub Messaging in Python and Consume RabbitMQ Messages with Python Pika.
  • Use acks_late=True: redelivers a task if the worker crashes mid-flight. Without it, a crash silently drops the task.
  • Set worker_prefetch_multiplier=1 for long tasks: stops one worker from hoarding work while others idle. For fast tasks (under a second), a higher multiplier cuts round-trip overhead.
  • Use retry_backoff=True: exponential backoff prevents retry storms on transient failures. retry_jitter=True spreads retries so restarted tasks don’t all hit at once.
  • Keep tasks idempotent: retries and crash recovery can run a task twice. Design so re-running is safe — upserts, unique job keys, or deduplication checks.
  • Use autoretry_for for known transient errors: cleaner than a manual self.retry() loop, and it can’t forget raise or miscount attempts.
  • Monitor with Flower: the web UI shows task progress, worker state and queue depth — the fastest way to spot a stuck queue in production.

Common Mistakes

  • Passing non-serializable arguments: with JSON serialization, ORM objects, file handles and custom classes won’t go through. Pass IDs and fetch inside the task.
  • Chaining into a signature that doesn’t take the previous result: every non-immutable .s() in a chain gets the upstream return value prepended. If the signature doesn’t account for it, arguments shift and the task corrupts data silently.
  • Calling .s() on a plain function: signatures only exist on registered tasks. A chord callback defined as def foo(...) fails with AttributeError — decorate it with @app.task.
  • Not setting a result backend: result.get() raises without one. Set result_backend='redis://...' when you need results.
  • Blocking on result.get() inside a request: it parks the request until the task finishes. Poll a task-id endpoint or use webhooks instead.
  • Running more than one Beat process: duplicate schedulers fire duplicate tasks. Run Beat on exactly one instance, or use a scheduler with leader election.
  • Trusting task_default_retry_delay in app.conf: those retry defaults are per-task options, not global settings — they go in the @app.task decorator or task_annotations.
  • Long-running tasks vs Redis visibility timeout: Redis redelivers unacknowledged messages after broker_transport_options.visibility_timeout (1 hour by default). A task that legitimately runs longer gets duplicated — raise the timeout or split the task.
  • Letting the queue grow unbounded: a stalled worker plus a busy producer means Redis memory climbs until eviction. Alert on redis-cli llen celery and give tasks a soft_time_limit so nothing holds a slot forever.

Further Reading

Frequently Asked Questions

Celery vs RQ — which should I use?

RQ is a thin enqueue-and-run layer on Redis; Celery adds canvas workflows, scheduling and several broker choices. Pick Celery when you need chords or Beat, RQ when you just need "run this later."

How do I run Celery in production?

Run celery worker under a process manager (systemd, Supervisor or a container orchestrator), size --concurrency to your CPU cores, keep Flower reachable for monitoring, and put Redis behind Sentinel or a managed service for broker HA.

What happens when a task exceeds its time limit?

task_soft_time_limit raises a SoftTimeLimitExceeded inside the task so it can clean up; task_time_limit is the hard cap that kills the worker process if the task still won't stop. Set both, with the hard limit slightly above the soft one.

Can I use Celery with Django?

Yes. Install django-celery-results for a database result backend and django-celery-beat for admin-managed schedules. Celery auto-discovers tasks.py in each installed app.

How do I prioritize tasks?

Redis has no native priority queues, so route tasks to separate queues and give high-priority queues more workers. For real per-message priority, switch the broker to RabbitMQ.