The Asynchronous Task Offloading Mandate
A web request should ideally complete in under 200 milliseconds. When an API endpoint triggers long-running operations—transcoding video files, generating PDF financial invoices, training machine learning classifiers, or sending batch transactional emails—running those tasks within the synchronous HTTP request/response cycle is an anti-pattern that exhausts web server worker pools.
The standard architectural solution is an asynchronous distributed task queue: the web handler validates the request, pushes a serializable job payload to a message broker (Redis or RabbitMQ), returns an immediate 202 Accepted to the client, and worker processes (Celery) consume and process jobs in the background.
In this guide, we architect a resilient background worker system with exponential backoff retries, dead letter queues (DLQs), and Celery Beat periodic scheduling.
Distributed Queue Architecture
Distributed Asynchronous Task Architecture:
Client ──► FastAPI / Django ──(Task Dispatch)──► Redis Message Broker
│ │
(202 Accepted) (Queue: default)
▼ ▼
Instant Client Response Celery Worker Pool
│
PostgreSQL / S3
(Persist Job Results)1. Configuring Celery with Redis Broker
# celery_app.py
from celery import Celery
app = Celery(
"tasks",
broker="redis://localhost:6379/0",
backend="redis://localhost:6379/1"
)
app.conf.update(
task_serializer="json",
accept_content=["json"],
result_serializer="json",
timezone="Asia/Kolkata",
enable_utc=True,
task_acks_late=True, # Prevent job loss on worker crash
task_reject_on_worker_lost=True,
worker_prefetch_multiplier=1, # Fair queue dispatching
)2. Resilient Task Definition with Exponential Backoff
# tasks.py
import logging
from celery_app import app
import httpx
logger = logging.getLogger(__name__)
@app.task(
bind=True,
max_retries=5,
default_retry_delay=5,
autoretry_for=(httpx.RequestError,),
retry_backoff=True, # Exponential backoff: 5s, 10s, 20s, 40s...
retry_backoff_max=600,
retry_jitter=True # Random jitter prevents thundering retry herd
)
def send_webhook_notification(self, webhook_url: str, payload: dict):
logger.info(f"Executing webhook task {self.request.id} to {webhook_url}")
with httpx.Client(timeout=10.0) as client:
response = client.post(webhook_url, json=payload)
response.raise_for_status()
return {"status": "delivered", "status_code": response.status_code}3. Running Celery Workers in Production
# Run worker pool with gevent or prefork concurrency
celery -A celery_app worker --loglevel=INFO --concurrency=4 -n worker1@%h
# Run Celery Beat for cron-like periodic scheduling
celery -A celery_app beat --loglevel=INFOFrequently Asked Questions (FAQ)
Why is task_acks_late=True critical for production?
By default, Celery acknowledges a task the instant it pulls it from Redis before executing it. If the worker process crashes midway through execution, that job is lost forever. Setting task_acks_late=True ensures the task is only acknowledged after it successfully completes, re-queueing it if the worker terminates unexpectedly.
What is worker_prefetch_multiplier=1?
By default, Celery pre-fetches 4 tasks per worker thread. If some tasks take 20 minutes while others take 20 milliseconds, long tasks starve behind fast tasks. Setting prefetch to 1 ensures true fair dispatching across workers.
Related Architectural Deep Dives
Continue expanding your technical depth with our related engineering guides:
- MySQL vs PostgreSQL Architecture Guide: InnoDB vs Postgres MVCC, JSONB vs JSON, and replication topologies. Explore the complete guide: MySQL vs PostgreSQL Architecture Guide.
- MySQL Query Optimization Masterclass: Diagnosing slow queries with EXPLAIN ANALYZE, B-Trees, and slow query logs. Explore the complete guide: MySQL Query Optimization Masterclass.
Published by Mohit Kumar under Python Backend & APIs. Explore our guide on Redis Caching Strategies for High-Traffic Applications.




