What Belongs Outside the Request, and Which Broker Fits
Decide which work stays in the request and which becomes a background job, see why in-process background tasks are lost when the process dies, and choose between a task queue, a pub/sub topic and an event log.
Contentsand lesson path
On this page
- Why it matters
- What stays in the request and what moves out
- Why in-process background tasks are not durable
- Where durable jobs live: Redis, RabbitMQ, PostgreSQL and Kafka
- Task queue, pub/sub topic or event log?
- Check your understanding
- Apply it
- Review prompt
Lessons of Background Jobs & Task Queues
- What Belongs Outside the Request, and Which Broker Fits Concept · 20 min
- Lab: A Worker, a Broker and a Status Endpoint Lab · 30 min
- Designing Jobs for At-Least-Once Delivery Concept · 20 min
- Enqueue After Commit with an Outbox Table Worked example · 25 min
- Scheduled Jobs and Running Workers Day to Day Concept · 15 min
- Check: What Happens When the Worker Dies? Knowledge check · 8 questions
What you will learn
- Decide which work belongs in the request path and which in a background job, explain why in-process background tasks are not durable, and say when a pub/sub topic or event log fits better than a task queue.
01. Why it matters
A web server has a limited pool of workers (processes, threads or event-loop slots). Every request holds one of them until the response is sent. If a handler sends emails, builds a large PDF or waits on a slow partner API before it answers, each of those requests holds a worker for seconds instead of milliseconds. Under load the pool runs out, new requests wait in the socket backlog, health checks time out and the whole API looks down, even though the database is fine.
Slow work in the request also couples the user to systems they do not care about. If the mail provider is having a bad day, the user who just placed an order sees an error, although the order itself was saved.
Moving that work to a background job fixes both problems: the request records what must happen and returns, and a separate worker process does the slow part later. This lesson covers three decisions you make before writing any worker code: what moves out of the request, where the job is kept so that it survives a crash, and which kind of broker carries it.
02. What stays in the request and what moves out
Keep work in the request when the response depends on it. Validating the body, checking who the caller is and what they may do, and writing the core record (the order with status pending) all stay inline, because the client needs their result to know whether the request worked.
Move work out when the client does not need its result right now:
- calls to outside systems: transactional emails, SMS, customer webhooks;
- heavy processing: resizing images, rendering reports, exporting a CSV;
- telling other systems that something happened: search indexing, analytics.
A background job needs a visible lifecycle so that the client and your team can follow it: queued (stored, no worker has it yet), processing (a worker claimed it), completed (the result or a download link is stored) and failed (it gave up after its retries). The endpoint answers 202 Accepted with a status URL, and the client polls that URL. You build this contract in the next lesson.
One coupling remains: the enqueue itself. If the broker is slow or down, the request still waits or fails, so give the enqueue a short timeout and a clear error (for example 503 with Retry-After).
03. Why in-process background tasks are not durable
Frameworks make it easy to run something "after the response" without any broker. FastAPI has BackgroundTasks, asyncio has asyncio.create_task, and any Python program can start a thread. All three run the work inside the web process, and the only record that the work exists is an object in that process's memory. Nothing is written down anywhere else.
The small app below shows the difference. /in-process/{id} schedules a five-second receipt email with BackgroundTasks. /durable/{id} writes a job row to a SQLite file and commits it before answering. The script then kills the server with SIGKILL, the way the kernel's out-of-memory killer or a forced restart does. You need Python 3.12 or later with fastapi and uvicorn (tested with Python 3.13, FastAPI 0.163.1 and Uvicorn 0.54.0) and curl.
import sqlite3
import time
from pathlib import Path
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
SENT = Path("sent.log")
db = sqlite3.connect("jobs.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS jobs (order_id INTEGER, kind TEXT)")
def send_receipt(order_id: int) -> None:
time.sleep(5) # stands in for a slow call to the mail provider
with SENT.open("a") as f:
f.write(f"receipt sent for order {order_id}\n")
@app.post("/in-process/{order_id}", status_code=202)
def in_process(order_id: int, tasks: BackgroundTasks):
tasks.add_task(send_receipt, order_id) # lives in this process only
return {"order_id": order_id, "receipt": "queued in memory"}
@app.post("/durable/{order_id}", status_code=202)
def durable(order_id: int):
with db: # commits before the 202 is sent
db.execute("INSERT INTO jobs VALUES (?, 'receipt')", (order_id,))
return {"order_id": order_id, "receipt": "queued in jobs.db"}rm -f sent.log jobs.db
uvicorn app:app --port 8765 --log-level warning &
PID=$!
until curl -s -o /dev/null http://127.0.0.1:8765/docs; do sleep 0.2; done
curl -s -X POST http://127.0.0.1:8765/in-process/1; echo
curl -s -X POST http://127.0.0.1:8765/durable/2; echo
kill -9 "$PID" # what an OOM kill or a forced restart does
wait "$PID" 2>/dev/null
sleep 6
cat sent.log 2>/dev/null || echo "sent.log: no receipt was ever sent"
python - <<'PY'
import sqlite3
print(sqlite3.connect("jobs.db").execute("SELECT * FROM jobs").fetchall())
PY{"order_id":1,"receipt":"queued in memory"}
{"order_id":2,"receipt":"queued in jobs.db"}
sent.log: no receipt was ever sent
[(2, 'receipt')]Both clients got a 202, so neither will send its request again. Receipt 1 is simply gone: it existed only in the memory of the process that died. Job 2 is still on disk, and a worker started after the crash can run it. Note that the queue is durable, not finished: something still has to process the row.
Change kill -9 to a plain kill (SIGTERM) and run the script again. This time Uvicorn shuts down gracefully, waits for the running task and the receipt is sent. That is why the problem hides in testing: a polite restart often works. A crash, an out-of-memory kill, a node failure, or a shutdown that runs past the platform's grace period still loses the tasks. And if the task raises an exception, the error is logged and nothing tries again.
asyncio.create_task and threads have the same limits. asyncio adds one more: the event loop keeps only a weak reference to a task, so the Python documentation tells you to keep your own reference, or the task can be garbage-collected before it finishes.
Use in-process tasks only for best-effort work whose loss does no harm, such as refreshing a cache entry that the next request would rebuild anyway. Anything that must happen at least once, such as a receipt, a charge or an export, needs a job stored outside the process: a broker or a database table.
04. Where durable jobs live: Redis, RabbitMQ, PostgreSQL and Kafka
A broker is the service that stores jobs or messages between the process that sends them and the process that handles them. The common choices trade speed, durability and how much you must operate:
- Redis (used by Celery, RQ, BullMQ): keeps jobs in lists or streams in memory. It is fast and simple to run, but memory bounds the queue, and a restart without append-only file (AOF) persistence can lose jobs.
- RabbitMQ: a dedicated broker with routing exchanges, per-message acknowledgements and dead-letter queues. It suits complex routing and backpressure, at the cost of running and clustering another service.
- PostgreSQL with
SKIP LOCKED(Procrastinate or PgQueuer in Python, Graphile Worker for Node.js, Oban for Elixir): jobs are rows, and workers claim them withSELECT ... FOR UPDATE SKIP LOCKED, so two workers cannot claim the same row at the same time. The job can be written in the same transaction as the business data. High job rates add write churn and VACUUM work to your main database. - Kafka (or AWS Kinesis): a partitioned, append-only log that keeps messages for a configured time. Classic consumer groups track one offset per partition, not an acknowledgement per message, so one slow record holds up its partition. Kafka 4.2 (2026) made share groups (KIP-932) production-ready, adding per-record acknowledgement for queue-style use; check that your client library supports them before relying on it.
05. Task queue, pub/sub topic or event log?
Brokers differ less in brand than in the delivery shape they offer. There are three shapes, and picking the wrong one causes bugs that no amount of worker tuning fixes.
Task queue producer -> [queue] -> worker A or worker B (one of them)
each message is handled once by the pool, then deleted
Pub/sub topic producer -> (topic) -> billing queue -> billing workers
-> email queue -> email workers
-> analytics queue -> analytics workers
every subscription gets its own copy of every message
Event log producer -> |0|1|2|3|4|5| ... kept for N days
billing group reads at offset 5, analytics at offset 2,
a new group can start at offset 0 and replay historyA task queue uses competing consumers: the workers of one pool share the queue, and each job goes to exactly one of them. That is right for commands such as "build export 77". If billing, email and analytics all read from the same queue, each would see only some of the orders.
A pub/sub topic delivers each message to every subscription. In practice each subscribing service gets its own queue, and inside that queue its workers compete as usual: SNS fanning out to one SQS queue per service, or a RabbitMQ fanout exchange bound to one queue per service. The producer does not know who listens, so adding a consumer is a new subscription, not a code change in the order service. A subscription only receives messages published after it was created.
An event log such as Kafka or Redis Streams appends events and keeps them until a retention limit (an age or a size) removes them. Kafka's documentation puts it plainly: events are not deleted after consumption. Each consumer group tracks its own position (offset), so a service added next month can start from the oldest retained event and rebuild its state, and a service with a bug can rewind and reprocess.
A short rule: one job that one worker must do is a queue; one fact that several independent services react to is a topic; reactions that must be replayable, or that new consumers must catch up on, need a log. A log is also the heaviest to operate, so do not pick it for plain work queues.
06. Check your understanding
07. Apply it
For the "export my data" practice project, list every piece of work the export endpoint does today. Mark each one as inline (validation, authorisation, creating the export record) or background (querying and writing the CSV, emailing the link). For each background item, write down what happens if the web process is killed one second after the response: if the answer is "the user never gets their export", it must become a stored job, not an in-process task.
Then write one sentence per message type saying which shape it needs. "Build export 77" is a command for one worker: a task queue. "Export 77 finished" may interest the notification service and an audit service, so it could be published to a topic. In the next lesson you build the queue, the worker and the status endpoint.
08. Review prompt
Without looking back: name two kinds of work that must stay in the request and two that should move out, and say why. Explain what happens to a FastAPI BackgroundTasks job when the process receives SIGKILL, and why a graceful restart can hide the problem. Finally, describe the difference between a task queue, a pub/sub topic and an event log, and give one situation where each is the right choice.
References
- FastAPI: Background Tasks
- Python documentation: asyncio.create_task (keep a reference to tasks)
- PostgreSQL Documentation: Explicit Locking - SKIP LOCKED
- RabbitMQ Tutorials: Work Queues
- RabbitMQ Tutorials: Publish/Subscribe
- Apache Kafka: Introduction (events, topics, retention)
- Apache Kafka 4.2.0 release announcement (share groups)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.