Skip to content

Lesson 23 of 59Async and background work

Task Queues with Celery

Move slow and unreliable work out of requests with Celery and Redis, with retries, backoff, idempotent tasks, schedules and monitoring.

17 min read0/4 questions

Some work does not belong in a request. Sending an email depends on a provider that can be slow or down. Generating a PDF report takes thirty seconds. Charging a card must be retried if the payment API times out, and must never happen twice. You also have work nobody asks for: nightly reports, cleanup jobs, syncing data every ten minutes. A task queue handles all of this. The API records "this needs doing" in milliseconds and separate worker processes do it, retry it and report on it. Celery is the long-standing standard in Python, and the ideas carry over to every other queue.

Why a queue

You met FastAPI's BackgroundTasks earlier: it runs a function after the response, in the same process. It is fine for small best-effort work, but it loses tasks when the process restarts, has no retries, and slow tasks compete with your requests. A real queue gives you:

  • Durability. Jobs wait in a broker, so a deploy or crash does not lose them.
  • Retries. A failed job runs again later, with backoff.
  • Scaling. Workers are separate processes you can add on separate machines, without touching the API.
  • Scheduling. Run a job in an hour, or every night at 02:00.
  • Visibility. See what is queued, running, failed and how long it took.

The cost is real, though: a broker to run, worker processes to deploy and monitor, and a new class of bugs where the API and the worker disagree. If the work takes 50 milliseconds and nothing bad happens when it is occasionally lost, BackgroundTasks is still the right tool. Reach for a queue when the work is slow, must not be lost, needs retries, or has to run on a schedule.

Broker, workers and the flow

Celery has three moving parts. Your app (FastAPI here) sends messages describing tasks. A broker stores those messages; Redis and RabbitMQ are the usual choices. Workers are long-running Celery processes that pull messages from the broker and run the matching Python function. Optionally, a result backend (often Redis too) stores each task's state and return value.

A Celery task from request to result
ClientClientFastAPI: calls .delay()FastAPIcalls .delay()Redis broker: task messagesRedis brokertask messagesCelery workers: run the tasksCelery workersrun the tasksCelery beat: the schedulerCelery beatthe schedulerEmail APIEmail APIResult backend: state, resultsResult backendstate, resultsPOST /orderssend messagefetchsend receiptSUCCESSevery night

An order is placed. The API saves it to Postgres and commits.

1/6

Defining and calling tasks

uv add "celery[redis]"
app/worker.py
from celery import Celery
 
from app.config import get_settings
 
settings = get_settings()
 
celery_app = Celery(
    "shop",
    broker=settings.redis_url,             # e.g. redis://localhost:6379/0
    backend=settings.redis_result_url,     # optional: store task results
    include=["app.tasks"],
)
celery_app.conf.update(
    task_acks_late=True,                   # acknowledge after the task finishes
    worker_prefetch_multiplier=1,          # fetch one task at a time per process
)
app/tasks.py
from app.worker import celery_app
 
 
@celery_app.task
def send_receipt(order_id: int) -> None:
    order = load_order(order_id)
    email_client.send(to=order.email, template="receipt", data={"order": order_id})

Start a worker in its own terminal, next to fastapi dev:

uv run celery -A app.worker.celery_app worker --loglevel=INFO

Then call the task from your API. .delay(...) is a shortcut for .apply_async(args=...), which takes extra options:

app/api/orders.py
@router.post("/orders", status_code=201)
def create_order(body: OrderCreate, db: DB) -> OrderRead:
    order = save_order(db, body)
    db.commit()                                           # commit first, so workers can see the row
    send_receipt.delay(order.id)                          # then enqueue
    remind_review.apply_async(args=[order.id], countdown=7 * 24 * 3600)
    return order

Two habits in that code matter. Pass ids, not objects. Arguments are serialised to JSON, and by the time the task runs, the order in the database is the fresh truth; a copied object may be stale. Enqueue after the commit. A worker can pick up the message within milliseconds. If the transaction has not committed yet, the task loads the order, finds nothing, and fails. .delay() returns an AsyncResult whose .id you can hand to the client so it can poll for status.

Quick check
A route calls send_receipt.delay(order.id) and only commits the transaction afterwards. Sometimes the task fails with "order not found". Why?
Need a nudge? A hint rules out a wrong answer.

Retries with backoff

External services fail, often for a few seconds. Celery can retry a task automatically when it raises certain exceptions:

app/tasks.py
import httpx
 
 
@celery_app.task(
    autoretry_for=(httpx.HTTPError,),
    retry_backoff=True,          # wait 1s, 2s, 4s, 8s... between attempts
    retry_backoff_max=600,       # never wait more than 10 minutes
    retry_jitter=True,           # randomise waits so retries do not arrive in sync
    retry_kwargs={"max_retries": 5},
)
def sync_to_crm(customer_id: int) -> None:
    customer = load_customer(customer_id)
    response = httpx.post(CRM_URL, json=customer.to_crm(), timeout=10)
    response.raise_for_status()

Exponential backoff gives a struggling service room to recover instead of hammering it. Jitter stops a thousand failed tasks from all retrying at the same second. When retries run out, the task ends in FAILURE; log it, alert on it, and make sure someone can rerun it. For full control, use bind=True and call raise self.retry(exc=exc, countdown=...) yourself. Only retry errors that can succeed later: a timeout, yes; a validation error, no.

Idempotency

Retries and redelivery mean a task can run more than once. A worker can crash after sending the email but before acknowledging the message, and with task_acks_late=True the broker then hands the message to another worker. Celery, like every practical queue, gives you at-least-once delivery. So design every task to be idempotent: running it twice has the same effect as running it once.

Common techniques: check a status column first (if order.receipt_sent_at: return), use a unique constraint on something like (order_id, kind) so a second insert fails, and pass an idempotency key to payment APIs, which most providers support so a repeated charge request is ignored.

This simulation shows retries with exponential backoff, plus a duplicate message that the idempotency check catches:

Pythontoy_queue.py
import heapq queue = [] # the "broker": (run_at, seq, job)seq = 0clock = 0 def delay(task, *args, countdown=0, retries=0): global seq seq += 1 heapq.heappush(queue, (clock + countdown, seq, {"task": task, "args": args, "retries": retries})) class Retry(Exception): pass def worker(max_retries=4): global clock while queue: clock, _, job = heapq.heappop(queue) try: job["task"](*job["args"]) except Retry as exc: n = job["retries"] if n >= max_retries: print(f"t={clock:>2}s giving up: {exc}") continue wait = 2 ** n # exponential backoff: 1, 2, 4, 8... print(f"t={clock:>2}s {exc}, retry {n + 1} in {wait}s") delay(job["task"], *job["args"], countdown=wait, retries=n + 1) # --- the "app" ---flaky_calls = {"count": 0}sent_receipts = set() # stands in for a table with a unique order_id def send_receipt(order_id): if order_id in sent_receipts: # idempotency check print(f"t={clock:>2}s receipt for order {order_id} already sent, skipping") return flaky_calls["count"] += 1 if flaky_calls["count"] <= 2: # the email provider fails twice raise Retry("email provider timed out") sent_receipts.add(order_id) print(f"t={clock:>2}s sent receipt for order {order_id}") delay(send_receipt, 42)delay(send_receipt, 42, countdown=10) # a duplicate, e.g. a redelivered messageworker()
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

In the simulation, the worker waits 2 ** n seconds before retry number n + 1. What is the total waiting time across the first four retries?

print(sum(2 ** n for n in range(4)))
Need a nudge? Hints walk you through it.
Quick check
Which task is safe to retry?
Need a nudge? A hint rules out a wrong answer.

Reporting status back to the client

For long jobs the client usually wants to know how it is going. The simplest reliable design is your own status row: the route creates a Report row with status="pending", passes its id to the task, and the task updates the row to running, then done with a file URL, or failed with an error message. The client polls GET /reports/{id}, which is an ordinary database read. You can also read Celery's own state with celery_app.AsyncResult(task_id).state if you configured a result backend, but results there expire and only Celery understands them, so most teams keep the source of truth in Postgres.

Keep tasks small and focused. A task that loops over 50,000 customers and fails at number 30,000 has to start over. Instead, have one task enqueue one small task per customer (or per batch of a few hundred), so each piece retries on its own. Celery's canvas tools (chain, group and chord) combine tasks into pipelines when you need ordering or a final step after a batch, but plain small tasks cover most needs.

One more detail: .delay() talks to the broker over the network, which is blocking I/O. It is usually fast, so calling it from a plain def route (which runs in the threadpool) is fine. From an async def route, wrap it with await asyncio.to_thread(send_receipt.delay, order.id) if you want to keep the event loop completely free.

Periodic tasks with beat

Celery beat is a scheduler process. You give it a schedule and it sends tasks to the broker at the right times:

app/worker.py
from celery.schedules import crontab
 
celery_app.conf.beat_schedule = {
    "nightly-sales-report": {
        "task": "app.tasks.build_sales_report",
        "schedule": crontab(hour=2, minute=0),     # every day at 02:00
    },
    "expire-stale-carts": {
        "task": "app.tasks.expire_carts",
        "schedule": 600.0,                         # every 10 minutes
    },
}
uv run celery -A app.worker.celery_app beat --loglevel=INFO

Run exactly one beat process. Two beat processes send every scheduled task twice. Times use UTC unless you configure a timezone, so a "02:00" job may run at a surprising local hour.

Put it in order5 steps

Put the life of a retried task in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Monitoring and running in production

Flower (uv add flower, then celery -A app.worker.celery_app flower) is a web dashboard showing workers, queued and failed tasks, and timings. In production, also watch queue length: a growing queue means workers cannot keep up, so add workers or find the slow task.

A few production habits:

  • Run the API, workers and beat as separate processes (separate containers), from the same image.
  • Use separate queues for different kinds of work, like emails and reports, so one slow report cannot delay every password reset. Route tasks with task_routes and start workers with -Q emails.
  • Set time limits (task_time_limit, task_soft_time_limit) so a stuck task cannot hold a worker forever.
  • Remember that workers run the same code as your API, so deploy them together.

Celery is powerful but large. RQ is simpler and Redis-only, arq is small and built on asyncio, and Dramatiq offers similar features with fewer surprises; managed queues like Amazon SQS are another option when you already live in one cloud.

Key terms
broker
Stores task messages until a worker takes them. Redis or RabbitMQ for Celery.
worker
A long-running process that fetches tasks from the broker and runs them.
result backend
Optional storage for each task's state and return value.
exponential backoff
Waiting longer between each retry (1s, 2s, 4s...), usually with a cap and random jitter.
at-least-once delivery
A task is guaranteed to run, but may run more than once. The reason tasks must be idempotent.
idempotent
Safe to run more than once: the second run has no extra effect.
Celery beat
The scheduler process that sends periodic tasks to the broker. Run exactly one.