Skip to content

Why some work runs later

BasicsConcept

Your sign-up page hangs for seconds while it sends a welcome email. The fix is to answer the user now and hand the slow part to another process that does it a moment later.

01 The sign-up that makes people wait

A sign-up handler saves the user, then sends a welcome email. Saving takes a few milliseconds. Sending means a network call to a mail provider, which can take a second, or hang, or fail. The user stares at a spinner for all of it.

app.py
@app.post("/signup")
def signup():
user = save_user(request.json) # fast: one INSERT
send_welcome_email(user.email) # slow: talks to the mail provider
resize_avatar(user.id) # slow: CPU work on an image
return {"id": user.id}, 201

Nothing in the reply depends on the email or the avatar. The user only needs to know the account exists. The other two calls are work that has to happen, but not before the reply.

02 Answer now, finish later

A background job is a small note that says “do this, with these arguments”. The web handler writes the note to a queue and replies. A separate long-running process, the worker, takes notes off the queue one at a time and does the work.

In the request
user = save_user(data)
send_welcome_email(user.email)
resize_avatar(user.id)
return {"id": user.id}, 201
In a worker
user = save_user(data)
queue.enqueue(send_welcome_email, user.id)
queue.enqueue(resize_avatar, user.id)
return {"id": user.id}, 201

Pushing onto the queue is one quick write, usually to Redis or a database table. The reply now goes out after the INSERT and two small writes. The enqueue call above is the RQ library for Python; Celery, Sidekiq (Ruby) and BullMQ (Node) look much the same.

03 Three sign-ups, two workers

Follow three sign-ups through the system. Watch the replies: each user is answered the moment their job is queued, even when every worker is busy.

A queue between the web handler and the workers
Step 1 of 10
jobs queue
Empty
workers
w1 · free
w2 · free
finished jobs
Empty
  • just added
  • worker busy
  • waiting or done

Two workers wait on an empty queue. Nobody has signed up yet.

nobody replied to

The queue is a buffer. When sign-ups arrive faster than emails go out, jobs pile up in the queue instead of piling up as open requests. To drain it faster, you start more workers; the web servers do not change.

04 What goes in a job

A job is stored as data, usually JSON: the name of the function and its arguments. Pass ids, not objects. By the time the worker runs, the user may have changed their email; loading the row fresh means the worker sees the current value.

JSON
{
"id": "job_8f2c",
"func": "send_welcome_email",
"args": [42],
"attempts": 0,
"enqueued_at": "2026-11-02T09:14:03Z"
}
The life of one job
StateMeaningNext
queuedWritten to the queue, no worker has it yetrunning
runningA worker took it and is doing the workdone or failed
doneFinished without an error—
failedRaised an error or the worker diedqueued again, after a delay
deadFailed too many timesa person looks at it

05 Jobs fail, so they run again

The mail provider will sometimes time out. A job system handles this by retrying: it puts the job back with a growing delay (for example 10 s, then a minute, then ten minutes), and after a set number of attempts moves it to a dead-letter list for a person to inspect.

Retries have a cost. If a worker sends the email and then crashes before marking the job done, the job runs again and the user gets two emails. Most queues promise at-least-once delivery: a job may run more than once, never zero times. So write jobs that are safe to repeat, which is called idempotent.

jobs.py
def send_welcome_email(user_id):
user = load_user(user_id)
if user.welcome_sent_at: # already done on an earlier attempt
return
mailer.send(user.email, "Welcome!")
mark_welcome_sent(user_id)

Queue the job after the database transaction commits. If you enqueue inside the transaction, a fast worker can load user 42 before the row is visible and fail with “not found”. If the commit then rolls back, the job refers to a user who never existed.

06 What belongs in the background

Keep in the requestThe reply needs itChecking the password, saving the order, reading the page’s data. The user cannot go on without the result.
Move to a workerThe reply does notEmails, push notifications, thumbnails, PDF invoices, webhooks to other services, search index updates.

A good test: if this step failed, would you still tell the user “done”? If yes, it can run later and be retried. If the user needs to see the result, such as a generated report, return 202 Accepted with a job id and let the page poll for it.

07 When it bites

queue.enqueue(send_email, user)Passing whole objectsThe object is copied into the job when you enqueue it, and can be out of date when the job runs. Pass user.id and load the row in the worker.
charge_card(order_id)A job that is not safe to repeatWith at-least-once delivery, a retried payment job can charge twice. Record what you did, or pass an idempotency key to the payment provider.
No one watches the queueIf workers crash or fall behind, jobs pile up silently while the site looks fine. Alert on queue length and on the age of the oldest job.
Workers run old codeWorkers are separate processes. Deploy them with the web servers, or a renamed function will leave queued jobs pointing at code that no longer exists.

08 Check yourself

Question

Sign-ups spike and the queue grows to 5,000 email jobs. What does a new user notice?

Question

A worker sends an email, then is killed before it marks the job done. What does a typical queue do?

Question

Which job argument is the safest choice?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?