The Analogy: A Restaurant Kitchen's Order-Ticket Rail
On a busy line, the waiter who takes your order does not walk into the kitchen and cook it. They write a ticket, clip it to a steel rail above the pass, and go back to the floor to serve the next table. A cook pulls the ticket when a station is free and makes the dish. Taking the order and making the food are two jobs, done by two people, at two different times, and the counter stays fast precisely because the person at the counter never waits for the stove.
The ticket has to carry everything the cook needs: table number, the dish, every modification. The cook reads it minutes later, when the waiter is at the far end of the room and the customer has left the counter for their seat. A ticket that says "the usual for whoever was just here" is worthless by the time it is pulled -- the context it depended on is gone. The rail decouples the two jobs only because the ticket is a complete, self-contained instruction that means the same thing whenever it is read.
Things go wrong, so the kitchen re-fires. A dropped ticket, a dish sent back, a burner that died mid-cook: the ticket goes back on the rail and the kitchen tries again. But re-firing a ticket that was in fact already plated would send the same meal out twice. So each ticket carries a number, and the line cook checks that number against the spike of already-plated tickets before lighting the burner; a re-fire of a finished ticket is binned, not cooked. The kitchen assumes any ticket may be pulled more than once and makes cooking it twice harmless.
The failure is timing. Picture an over-eager expediter who clips the ticket to the rail the instant the waiter calls the order across the room -- before the waiter has written the table number on the check and rung it into the register. A cook pulls the ticket and plates a meal for a table the register does not yet know exists. If the customer then changes their mind and the order is voided, the food has already gone out the pass. Nothing looked wrong; the rail was busy and the line was fast the entire time. That is a background task enqueued before the database transaction commits: the worker runs before the row it needs is visible, and no amount of kitchen speed can fix an instruction that was published too early.
Syntax or Core Structure
Celery splits slow work into three roles. A producer -- your Django view -- calls task.delay(args), which does not run the task; it serializes a message and hands it to a broker (Redis or RabbitMQ), then returns immediately so the request can finish. A separate worker process, running elsewhere, pulls messages off the broker and executes them. The stand-in below is that whole shape reduced to a plain list as the broker and a dict of functions as the task registry, so you can watch the view return before the work has run.
class Broker:
def __init__(self):
self.queue = []
self.next_id = 1
def enqueue(self, name, args):
task_id = self.next_id
self.next_id = self.next_id + 1
self.queue.append({"id": task_id, "name": name, "args": args})
return task_id
SENT = []
def send_email(to):
SENT.append(to)
return "sent to " + to
TASKS = {"send_email": send_email}
def worker_run(broker):
done = 0
while broker.queue:
msg = broker.queue.pop(0)
fn = TASKS[msg["name"]]
fn(*msg["args"])
done = done + 1
return done
broker = Broker()
tid = broker.enqueue("send_email", ["ada@example.com"])
print("view returned, task id: " + str(tid))
print("queued: " + str(len(broker.queue)))
print("emails sent so far: " + str(len(SENT)))
ran = worker_run(broker)
print("worker ran: " + str(ran))
print("emails sent now: " + str(len(SENT)))
Output:
view returned, task id: 1
queued: 1
emails sent so far: 0
worker ran: 1
emails sent now: 1
The order of the lines is the entire lesson. enqueue returns a task id at once, and at that instant the queue holds one message but zero emails have been sent -- the view has finished its work without doing the slow work. The user's request completed in the time it took to append a dict to a list. Only later, when worker_run drains the queue in a separate process, does send_email actually run and the count rise to one. The task id is a receipt, not a result: it lets you look the outcome up later, but the view neither has nor waits for the answer. That decoupling is the point, and it is also the source of every hard problem in the rest of this lesson, because the work now happens somewhere the request cannot see and at a time the request does not control.
Technical Depth: Delivery Guarantees and the Duplicates They Create
Brokers give you at-least-once delivery, not exactly-once. If a worker crashes after doing the work but before acknowledging the message, the broker hands the same message to another worker, which does the work again. This is not a rare edge case you can ignore; it is the contract. The only safe response is to make tasks idempotent -- running one twice must have the same effect as running it once -- usually by carrying a stable key and checking it before acting.
The four pieces that move a task
None of these pieces shares memory with the others, which is why a task argument must be plain serializable data, never a live object.
| Piece | Who plays it | Its job |
|---|---|---|
| Producer | Your Django view | Serializes a call and hands it to the broker |
| Broker | Redis or RabbitMQ | Holds messages until a worker is free |
| Worker | A separate process | Pulls messages and runs the task code |
| Result backend | Redis or a database | Stores return values for later lookup |
Because redelivery is guaranteed rather than exceptional, the demo below imagines the broker handing the same charge message to a worker twice. An idempotency key -- the charge id -- lets the task recognize the repeat and refuse to bill the customer again.
CHARGED = []
PROCESSED = set()
def charge_idempotent(charge_id, amount):
if charge_id in PROCESSED:
return "skip duplicate " + charge_id
PROCESSED.add(charge_id)
CHARGED.append(amount)
return "charge " + charge_id + " for " + str(amount)
DELIVERIES = [("chg-1", 1500), ("chg-1", 1500), ("chg-2", 800)]
for cid, amt in DELIVERIES:
print(charge_idempotent(cid, amt))
print("deliveries: " + str(len(DELIVERIES)))
print("distinct charges: " + str(len(CHARGED)))
print("total charged: " + str(sum(CHARGED)))
Output:
charge chg-1 for 1500
skip duplicate chg-1
charge chg-2 for 800
deliveries: 3
distinct charges: 2
total charged: 2300
Three messages arrived but only two charges landed, and the total of 2300 ignores the repeat entirely. The guard did not need to know why the message came twice -- a retry, a network hiccup, a worker that died after charging but before acknowledging. It only needed a stable key and a record of what it had already done. That is the whole of idempotency: make running a task twice indistinguishable from running it once.
What can go wrong between enqueue and run
| Symptom | Cause | The fix |
|---|---|---|
| Same task runs twice | At-least-once delivery redelivers the message | Guard on an idempotency key |
| Task runs before the row exists | Enqueued inside a still-open transaction | transaction.on_commit(lambda: task.delay(pk)) |
| Work lost when a worker crashes | Message acknowledged before the task finished | acks_late so the ack waits for success |
| Worker sees stale field values | A live model instance was pickled into the args | Pass the pk and refetch inside the task |
| Queue fills with results nobody reads | Return values stored by default | Disable the result backend for fire-and-forget tasks |
Real World Example: The Enqueue-Before-Commit Race and How on_commit Fixes It
A signup view creates a user row and then hands a "send the welcome email" task to the broker. The subtle bug is that the view is still inside a database transaction when it enqueues, and a hungry worker can pull the message and look the user up before the transaction commits -- so the worker queries a row that does not exist yet. The stand-in below models one connection that only sees committed rows, and runs the task either before the commit (eager) or after it (on_commit), so the race becomes a matter of call order instead of luck.
class DB:
def __init__(self):
self.committed = {}
self.pending = {}
def insert(self, uid, name):
self.pending[uid] = name
def commit(self):
for uid in self.pending:
self.committed[uid] = self.pending[uid]
self.pending = {}
def get(self, uid):
return self.committed.get(uid)
SENT = []
MISSED = []
def send_welcome(db, uid):
name = db.get(uid)
if name is None:
MISSED.append(uid)
return "MISS user " + str(uid) + " not found"
SENT.append(uid)
return "OK welcome " + name
def signup(db, uid, name, mode):
db.insert(uid, name)
if mode == "eager":
result = send_welcome(db, uid)
db.commit()
else:
db.commit()
result = send_welcome(db, uid)
return result
db = DB()
print("eager:".ljust(11) + signup(db, 1, "Ada", "eager"))
db2 = DB()
print("on_commit:".ljust(11) + signup(db2, 2, "Bob", "on_commit"))
print("emails sent: " + str(len(SENT)))
print("missed: " + str(len(MISSED)))
Output:
eager: MISS user 1 not found
on_commit: OK welcome Bob
emails sent: 1
missed: 1
The eager run inserts Ada, fires the task while the row is still pending, and the worker's query comes up empty -- so a real customer silently never receives a welcome email and nothing raises an error. The on_commit run commits first, so by the time the task looks, Bob is there to greet. One line of ordering is the entire difference between a lost email and a delivered one.
In real Django you never hand-reorder these calls. You wrap the enqueue in transaction.on_commit(lambda: send_welcome.delay(uid)), and Django holds the callback until the surrounding transaction commits -- or discards it entirely if the transaction rolls back, which is exactly what you want, because there is no user to email if the signup failed. The eager mistake is precisely what happens when you call send_welcome.delay(uid) directly in the middle of the view.
This program has real flaws worth naming. It runs the task synchronously in the same process, so it can only simulate the race by forcing call order -- a genuine worker races the commit on wall-clock timing, and the miss would be intermittent and maddening to reproduce. The task retries nothing, whereas a real Celery task would retry on failure and might accidentally paper over the eager bug on a later attempt, hiding it until load spikes. SENT and MISSED are module-level lists that would not survive across separate worker processes, so this accounting is a teaching fiction. And nothing here is idempotent: pair this commit fix with a redelivery and Bob receives two welcome emails, because the commit ordering and the duplicate guard from the previous section solve two different halves of the same problem.
Common Mistakes
- Enqueuing before the transaction commits. Calling task.delay(pk) inside a view that is still mid-transaction lets a worker read a row that has not been written yet; wrap the call in transaction.on_commit so it fires only after the data is durable.
- Passing the model object instead of the primary key. A pickled instance freezes the field values at enqueue time, so the task acts on stale data and can even operate on a row you have since deleted; pass the pk and refetch inside the task.
- Assuming a task runs exactly once. Brokers guarantee at-least-once delivery, so retries and redelivery mean your task will sometimes run twice; make it idempotent with a stable key rather than hoping duplicates never happen.
- Reading the return value of .delay() as the answer. It hands back an AsyncResult whose id is a receipt, not the computed value; the task has usually not even started when the view returns.
- Calling the task body directly to "just get the result." send_welcome(uid) then runs synchronously in the web process and blocks the response -- the exact latency you added Celery to remove.
- Retrying without backoff or a ceiling. A task that retries immediately and forever turns one failing dependency into a tight loop that hammers it; set max_retries and exponential backoff instead.
- Leaving acks_late off for work that must not be lost. By default the broker acknowledges the message before the task finishes, so a worker crash mid-task drops the work silently; enable acks_late so the acknowledgement waits for success.
- Storing results nobody consumes. The result backend keeps every return value by default, and for fire-and-forget tasks that is pure bloat; disable the backend or set ignore_result on those tasks.
- Putting slow work back in the request because it is quicker to code. The moment a view calls an email API, resizes an image, or hits a slow third party inline, one slow dependency stalls every request; that work belongs in a task.
Best Practices
- Make every task idempotent. Design it so running twice equals running once -- guard on an idempotency key or check current state before acting -- because at-least-once delivery will eventually redeliver a message.
- Enqueue with transaction.on_commit. Defer the .delay() call until the surrounding transaction commits, so a worker never chases a row that has not landed and never fires for a signup that rolled back.
- Pass identifiers, refetch inside the task. Send the pk or a small dict of primitives, then load the fresh object in the worker, so the task always acts on current data rather than a stale pickle.
- Set explicit retries with exponential backoff. Bound attempts with max_retries, use autoretry_for on the specific transient exceptions, and back off so a struggling dependency gets room to recover instead of a hammering.
- Turn on acks_late for work that must not vanish. Let the broker redeliver a message whose worker died mid-task; this pairs naturally with the idempotency you already built to keep redelivery safe.
- Keep tasks small and single-purpose. One task, one unit of work, then chain or group them rather than building a monolith, so a retry re-runs the minimum and a failure is easy to locate.
- Disable the result backend when you never read results. Mark fire-and-forget tasks ignore_result, keeping the backend lean and fast for the few tasks whose return values you actually fetch.
- Monitor queue depth and failure counts. Watch how many messages are waiting and how many reach the dead-letter path; a silently growing queue is the first sign your workers cannot keep up with producers.
Practice Exercises
- Build the receipt, not the result. Write an enqueue(name, args) that appends to a list broker and returns an incrementing task id, plus a worker_run(broker) that drains the queue. Print the id the "view" received, prove the queue holds one message before the worker runs, and prove it is empty afterward.
- Add an idempotency guard. Given a list of deliveries where one charge id repeats, process them through a function that skips any id it has already seen. Print each decision and the final distinct-charge total, then feed a third delivery of the same id and confirm nothing changes.
- Reproduce and fix the commit race. Model a database that only returns committed rows, then write signup(uid, name, mode) that runs the welcome task either before committing or after. Show the eager path missing the user and the on_commit path succeeding, and count sent versus missed.
- Bound the retries. Write a flaky task that fails its first two attempts and succeeds on the third, driven by a retry loop with max_retries set to 3. Print each attempt and the final outcome, then lower max_retries to 1 and show the task giving up instead.