lesson depth
Mastery
not started · 0%

Message Queues & Celery Task Pools

Celery asynchronous task distribution, Redis Streams, and background worker queues.

Freshness: current15 min readSoftware and Web Engineering

Key Learning Outcomes

  • Offload long-running computations to background Celery workers
  • Manage task result backends and worker prefetches

Mental model

Message queues decouple HTTP request-response cycles from slow background tasks (e.g. video processing, email generation, PDF rendering). Web apps push task payloads into a queue broker (Redis), while worker processes execute tasks asynchronously.

HTTP POST Request
FastAPI enqueues task in Redis
Return Instant 202 Accepted
Celery Worker Prefetches Task
Execute Task & Persist Result
Conceptual teaching model synthesized from:FastAPI Framework Architecture & Dependency Injection Specification

Theory

Celery connects to a Broker (Redis / RabbitMQ) for task transport and a Result Backend (Redis / PostgreSQL) to record task completion states (PENDING, STARTED, SUCCESS, FAILURE).

python(25 lines)
1# Celery worker configuration
2from celery import Celery
3
4celery_app = Celery(
5 "tasks",
6 broker="redis://localhost:6379/0",
7 backend="redis://localhost:6379/1"
8)
9
10celery_app.conf.update(
11 task_serializer="json",
12 accept_content=["json"],
13 result_serializer="json",
14 worker_prefetch_multiplier=1, # Prevent long-running task starvation
15 task_acks_late=True, # Ack only after execution completes
16)
17
18@celery_app.task(name="generate_pdf_report", bind=True, max_retries=3)
19def generate_pdf_report(self, user_id: str):
20 try:
21 # Long-running PDF generation logic
22 return {"user_id": user_id, "status": "completed"}
23 except Exception as exc:
24 raise self.retry(exc=exc, countdown=10)

Alternatives and trade-offs

  • FastAPI BackgroundTasks: Runs in-process on the Uvicorn worker process; lost if process crashes mid-task, unsuitable for heavy CPU loads.
  • Celery + Redis: Out-of-process distributed scaling, task persistence, retries; requires maintaining extra worker infrastructure.

Failure modes and misconceptions

  1. Default worker_prefetch_multiplier = 4 Starvation: When tasks take minutes to complete, a worker prefetching 4 long tasks starves other idle workers. Set worker_prefetch_multiplier = 1 for long-running tasks.
  2. Missing task_acks_late: Default early acknowledgment removes messages from the broker before execution; if the worker container crashes mid-task, the message is permanently lost.
Reflect before revealing the guide

Decision scenario

Use Celery with Redis broker and task_acks_late=True for processing expensive asynchronous tasks (PDF generation, bulk emails, audio transcription) to ensure task durability and worker load balancing.

Learning outcomes

  • Structure out-of-process background task execution with Celery and Redis.
  • Configure prefetch multipliers and late acknowledgment for long-running tasks.
  • Implement task retries with exponential backoff and jitter.

Trade-offs

Celery enables reliable out-of-process task execution, but introduces broker operational management and serialization overhead.

Prerequisites & Related Concepts (2)

Private notes

0 words
Next