Why some work runs later
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.
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.
user = save_user(data)send_welcome_email(user.email)resize_avatar(user.id)return {"id": user.id}, 201
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.
- just added
- worker busy
- waiting or done
Two workers wait on an empty queue. Nobody has signed up yet.
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.
| State | Meaning | Next |
|---|---|---|
| queued | Written to the queue, no worker has it yet | running |
| running | A worker took it and is doing the work | done or failed |
| done | Finished without an error | — |
| failed | Raised an error or the worker died | queued again, after a delay |
| dead | Failed too many times | a 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.
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
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.