Background Jobs with Celery and RQ

Background Jobs with Celery and RQ in Flask: --- In a large office nobody walks their own parcels across the city.


The Analogy: The Office Mailroom's Outbound Dispatch Desk

In a large office nobody walks their own parcels across the city. You carry a parcel to the mailroom's outbound dispatch desk, fill in a docket with the address and contents, drop it in the outbound bin, and are handed a tracking stub. Then you go straight back to your own desk. You do not stand and wait for the delivery, because that could take hours. The dispatch clerk is not the courier; the desk only accepts the job and records it. A courier empties the outbound bin on a later round and makes the actual deliveries. Bringing the parcel is enqueuing a task from a request; the docket is the task's serialised arguments; the outbound bin is the queue; the tracking stub is the immediate response; going back to your desk is the view returning at once; the courier is the worker process.

The whole point is that the slow part -- the courier's round across town -- happens outside the moment you are standing at the desk. If the desk made every person wait until their parcel had actually been delivered, one slow delivery would block the queue of people behind them, and the desk could serve only as many callers per hour as the courier could complete deliveries. By separating accept-the-job from do-the-job, the desk stays fast no matter how slow or numerous the deliveries become. That is exactly why a web request should enqueue work and return, rather than performing the work inline while the browser waits.

The courier reads only what is written on the docket; they cannot phone you back for the address, because by the time the round runs you may have gone home. So the docket must carry every fact the delivery needs, written down -- not "the box Priya mentioned." If a delivery fails, nobody home or wrong floor, the courier does not give up and does not hammer the door; the parcel goes back in the bin to be attempted again on a later round, after a sensible gap. And a parcel is only ticked off the courier's log once it has actually been handed over, because a busy courier might run the same round twice, and without the log they would deliver the same parcel again.

The failure that quietly loses work is a docket that names a live thing instead of a written fact. Someone scrawls "deliver the contract that is on my desk" and drops it in the bin. Hours later the courier reads it, walks to the desk, and the contract has been moved, or replaced with a newer draft, or the desk cleared for the night. The courier delivers nothing, or delivers the wrong document, and no one notices until the client complains. The dispatch system worked perfectly; the docket simply referred to something that no longer meant what it did when the docket was written. A docket must carry the contract's file number so the courier fetches the current, correct copy at delivery time.


Syntax or Core Structure

A background job has two halves that live in different processes: the view enqueues a task and returns immediately, and a separate worker performs it later. Celery and RQ supply the broker and the worker for real; here a plain list stands in for the queue and a direct call stands in for the worker, so the mechanics are visible and the output is deterministic.

from flask import Flask, jsonify

app = Flask(__name__)
QUEUE = []
SENT = []


def send_receipt(order_id):
    SENT.append(order_id)


@app.post("/orders/<int:order_id>/receipt")
def receipt(order_id):
    QUEUE.append(("send_receipt", {"order_id": order_id}))   # enqueue an id, not an object
    return jsonify(status="queued"), 202


client = app.test_client()
r = client.post("/orders/42/receipt")
print("response:", r.status_code, r.get_json())
print("queued:", len(QUEUE), "sent so far:", SENT)

name, kwargs = QUEUE.pop(0)                # a worker drains the queue later
{"send_receipt": send_receipt}[name](**kwargs)
print("after worker: queued:", len(QUEUE), "sent:", SENT)

Output:

response: 202 {'status': 'queued'}
queued: 1 sent so far: []
after worker: queued: 0 sent: [42]

The view returned 202 with sent so far: [] -- nothing had been emailed yet; the work was only recorded in the queue. Only when the worker later drained the queue did the receipt actually go out, leaving sent: [42]. Crucially the task was enqueued as an order id, not an order object, so the worker re-loads the order itself when it runs. The 202 status code means "accepted for processing," which is the honest answer when you have queued work rather than finished it.


Technical Depth: Dockets, Retries, and Delivering At Least Once

Inline versus queued: what moves off the request path

ConcernDoing it inlineHanding it to a worker
Response latencyWaits for the whole jobReturns as soon as it is queued
Worker occupancyOne slow job blocks a request slotRequest slots stay free
FailureA crash fails the user's requestRetried out of band, user unaffected
ScalingBounded by request throughputAdd workers independently of web boxes

The rule of thumb: if a step is slow, unreliable, or not needed for the response the user is waiting on -- sending mail, rendering a PDF, calling a third party, resizing an upload -- it belongs in a job. Keep in the request only what the response actually depends on.

Pass ids, not objects

A task's arguments are serialised, shipped to the broker, and deserialised in another process minutes later. Anything that does not survive that trip unchanged is a bug. The demo enqueues the same record two ways -- by id and by a snapshot copied at enqueue time -- then changes the world before the worker runs.

DB = {42: {"status": "pending"}}
QUEUE = []


def by_id(order_id):          # reloads current state inside the worker
    return DB[order_id]["status"]


def by_snapshot(snap):        # frozen at enqueue time
    return snap["status"]


QUEUE.append(("id", 42))
QUEUE.append(("snap", dict(DB[42])))     # a snapshot copied at enqueue time
DB[42]["status"] = "paid"                # the world changes before the worker runs

for kind, arg in QUEUE:
    if kind == "id":
        print("by id      ->", by_id(arg))
    else:
        print("by snapshot->", by_snapshot(arg))

Output:

by id      -> paid
by snapshot-> pending

The id-based task read paid, the current truth, because it re-loaded the record when it ran. The snapshot-based task read pending, the world frozen at enqueue time, which is now wrong. A live ORM object is worse than a snapshot: it serialises to a reference that is detached or stale in the worker, or fails to serialise at all. Pass the primary key and let the task fetch the row.

Idempotency and at-least-once delivery

Brokers guarantee at-least-once delivery, not exactly-once: a worker can crash after doing the work but before acknowledging it, so the same job is redelivered and runs again. A task must therefore be safe to run more than once. The guard below makes a repeated send harmless.

SENT = set()
deliveries = []


def send_once(order_id):
    if order_id in SENT:          # idempotency guard
        deliveries.append("skip")
        return
    SENT.add(order_id)
    deliveries.append("send")


for _ in range(3):                # at-least-once: the broker redelivers the same job
    send_once(42)

print("deliveries:", deliveries)
print("emails actually sent:", len(SENT))

Output:

deliveries: ['send', 'skip', 'skip']
emails actually sent: 1

The job was delivered three times but the email went out once, because the guard checked a record of what had already been sent before acting. Design every task so that running it twice equals running it once: check-and-skip on a stored marker, use a database upsert, or carry an idempotency key the downstream service deduplicates on. "It will only run once" is never true.

Retry with backoff

AttemptTypical delayWhy
1immediatethe first try
2a few secondsride out a brief blip
3tens of secondslet a struggling service recover
finalroute to a dead-letter queuestop hammering and alert a human

Retrying immediately and forever turns one failing dependency into a self-inflicted denial of service. Grow the delay between attempts (exponential backoff), add a little randomness (jitter) so a fleet of workers does not retry in lockstep, cap the attempts, and route the exhausted job to a dead-letter queue for a person to inspect.

The real frameworks (illustrative)

In production you do not hand-roll the queue. Celery and RQ both give you the broker connection, the worker command, retries, and result storage; your job is to write tasks that take ids and are idempotent. Celery's decorator carries the retry policy:

# tasks.py -- Celery (illustrative; needs a broker and a running worker)
import os
from celery import Celery

celery_app = Celery("myapp", broker=os.environ["BROKER_URL"])


@celery_app.task(bind=True, max_retries=5, retry_backoff=True)
def send_receipt(self, order_id):        # an int, never an ORM object
    order = Order.query.get(order_id)    # re-load inside the worker
    mailer.send(order.customer_email, render_receipt(order))

RQ keeps the enqueue side even smaller -- it ships the function path plus the arguments to Redis:

# enqueue side -- RQ (illustrative)
import os
from redis import Redis
from rq import Queue

queue = Queue(connection=Redis.from_url(os.environ["REDIS_URL"]))
queue.enqueue(send_receipt, order_id)    # ships the function path plus the id

Both call the view side "enqueue" and run a separate worker process (celery -A myapp worker or rq worker). The Flask-specific wrinkle is the application context: a task runs outside any request, so anything touching current_app, the database session, or config must push an app context itself -- usually through a custom task base class or Celery's Flask integration -- because none of the request-time globals exist in the worker.


Real World Example: A Receipt Pipeline That Survives a Flaky Mail Provider

A paid order should trigger a receipt email. Mail providers time out, so the job must retry; retries mean the job can run more than once, so it must be idempotent. This worker-side simulation reloads the order by id, guards on a receipt_sent_at marker, does the risky send before recording success, and lets the broker redeliver on failure up to a cap. The provider fails once, then succeeds.

DB = {42: {"paid": True, "receipt_sent_at": None}}
log = []


class Provider:
    def __init__(self):
        self.calls = 0

    def send(self, order_id):
        self.calls += 1
        if self.calls == 1:
            raise RuntimeError("smtp timeout")   # a transient failure, once
        log.append(("sent", order_id))


provider = Provider()
MAX_RETRIES = 3


def send_receipt(order_id):
    order = DB[order_id]                      # reload by id inside the worker
    if order["receipt_sent_at"] is not None:  # idempotency guard
        log.append(("skip", order_id))
        return
    provider.send(order_id)                   # do the risky work first
    order["receipt_sent_at"] = "recorded"     # mark only after it succeeds


attempt = 0
while attempt < MAX_RETRIES:                  # broker redelivers until success, capped
    attempt += 1
    try:
        send_receipt(42)
        break
    except RuntimeError as e:
        log.append(("retry", attempt, str(e)))

print("log:", log)
print("attempts:", attempt, "provider calls:", provider.calls)
print("receipt_sent_at:", DB[42]["receipt_sent_at"])

Output:

log: [('retry', 1, 'smtp timeout'), ('sent', 42)]
attempts: 2 provider calls: 2
receipt_sent_at: recorded

The task takes an order id and reloads the record, so it always acts on current state. The idempotency guard returns early if the receipt is already marked sent. The order of the last two statements is deliberate: provider.send runs first, and receipt_sent_at is written only after it returns without raising -- so a failure leaves the marker untouched and the job stays eligible for retry.

Walk the output. The first delivery calls the provider, which times out; the exception is caught and logged as a retry, and the marker is still None. The broker redelivers; the second call reaches the provider, which now succeeds, logs the send, and records the marker. Two provider calls, one email, one marker -- the transient failure was absorbed without human intervention and without a duplicate.

Why the ordering matters: had the marker been set before the send, the first attempt would have marked the receipt "sent" and then failed. The retry's guard would see the marker and skip, and the customer would never get a receipt that the system believes was delivered -- a lost job wearing a "done" badge. Recording success only after the effect is the safe order.

The genuine flaw is the gap between those two safe-looking statements. At-least-once delivery means the worker can die in the instant after provider.send succeeds but before receipt_sent_at is written. On redelivery the guard still sees None, and the receipt is sent a second time -- the customer gets two emails. No amount of reordering closes this window, because the send and the marker are not one atomic step across a process crash. The real fix lives at the provider: pass a stable idempotency key (the order id plus a purpose) with the send, so the mail service itself refuses the duplicate; where the effect is a database row, do the effect and the marker in the same transaction. At-least-once plus an idempotent effect is how you approximate exactly-once -- the queue alone never gives it to you.


Common Mistakes

  1. Doing slow work inside the view. Rendering PDFs, sending mail, or calling third parties in a request ties up a worker slot and blows your latency budget. Enqueue it and return.
  1. Passing an ORM object or model instance as a task argument. It serialises to a stale or detached reference in the worker, or fails to serialise at all. Pass the primary key and reload inside the task.
  1. Assuming a task runs exactly once. Brokers deliver at least once; a crash before acknowledgement causes a redelivery. Make every task idempotent instead of hoping.
  1. Retrying immediately and without a cap. A tight retry loop against a downed dependency is a self-inflicted denial of service. Use exponential backoff, jitter, and a maximum.
  1. Marking work done before it succeeds. Set the "sent" or "processed" flag only after the effect returns without error, or a failure leaves a job that looks finished but is not.
  1. Touching current_app, g, or the request inside a task. A worker runs outside any request; push an application context explicitly and never expect request or session state to be there.
  1. Swallowing task exceptions. A task that catches everything and returns cannot be retried and produces no dead-letter entry. Let retryable errors propagate so the framework can act.
  1. Returning huge results through the broker. The result backend is not a file store; return an id or a URL, not a multi-megabyte payload.
  1. No dead-letter path. Without a terminal destination for exhausted jobs, permanent failures either retry forever or vanish silently. Route them somewhere a human will look.

Best Practices

  • Enqueue a primitive id and reload the record inside the task, so the worker always acts on current state rather than a stale snapshot.
  • Make every task idempotent -- safe to run twice -- with a stored marker, a database upsert, or a downstream idempotency key.
  • Configure exponential backoff with jitter and a retry cap, and send exhausted jobs to a dead-letter queue instead of retrying forever.
  • Record success only after the side effect completes, and pair it with a provider-side idempotency key to survive a crash in the gap.
  • Push an application context in the worker so tasks can use config and the database session without request-time globals.
  • Keep task arguments small and serialisable, and return references such as an id or URL rather than large payloads.
  • Make tasks short and single-purpose; chain or group them rather than building one long-running job that is hard to retry.
  • Monitor queue depth, failure rate, and job age, and alert on a growing backlog before it becomes an outage.

Practice Exercises

  1. A view renders a PDF invoice and emails it before returning. Rewrite it so the request returns immediately, and state exactly what the response status and body should now be and why.
  1. The receipt task in the example can still send a duplicate if the worker crashes after the provider call but before the marker is written. Describe the idempotency-key change on the provider side that closes the window, and explain why the queue alone cannot.
  1. A colleague passes order (an ORM instance) into a Celery task; it works locally but fails in production. Explain what serialisation does to that argument, and rewrite both the enqueue call and the task signature correctly.
  1. Design the retry policy for a task that calls a third-party API with a strict rate limit. Give the backoff schedule, the cap, and what should happen to a job that exhausts its retries, and justify each choice.