Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 3

Lab: A Worker, a Broker and a Status Endpoint

Build an asynchronous job processing system in FastAPI using a Redis task queue, a standalone background worker daemon, and an HTTP 202 polling status endpoint.

Contentsand lesson path

What you will learn

  • Run a worker on a broker-backed task queue, enqueue jobs from an endpoint and expose job status to clients with 202 Accepted and a status resource.

01. Lab overview and objectives

When a customer clicks "Export all data (CSV)", the server should not hold the request open for 45 seconds while it queries millions of rows, builds the CSV and uploads the file to object storage.

Instead, the API answers at once with HTTP 202 Accepted and a job id, and a separate worker process does the work. The client polls a status URL until the job has finished. This is often called the asynchronous request-reply pattern.

In this lab you build that pipeline with FastAPI, Redis and a worker that does not lose a job when it is killed mid-task, test it with pytest, including a job that must end as failed, and then kill the worker mid-job to watch the recovery. (The next lesson adds idempotent side effects for the redeliveries this design allows.)

You need: Python 3.12 or later and a Redis server of version 6.2 or later (the worker uses BLMOVE), for example docker run -d --name jobs-redis -p 6379:6379 redis:8-alpine. Install the libraries with pip install fastapi==0.165.0 redis==8.2.0 httpx==0.28.1 pytest==9.2.0 (tested with Python 3.13 and Redis 8.10). Keep the redis-py pin: its default timeouts matter in step 2. Lay the files out as app/__init__.py (empty), app/api.py, worker.py, tests/test_exports.py, post_one.py (step 4) and an empty conftest.py in the project root, and run every command from the project root. The root conftest.py puts the project root on sys.path, so plain pytest can import app.

02. Worker crashes and reliability considerations

Before writing code, decide what should happen when things fail. In production, workers run in containers that are stopped often: for autoscaling, for node maintenance, or because they ran out of memory (OOM). A worker that pops a job off the queue and then works on it loses that job if it is killed before it finishes.

This lab uses an atomic move (LMOVE, formerly RPOPLPUSH): instead of removing the job, the worker moves it from the queue to a processing list in one step. If the worker dies, the job is still in that list, and a recovery step puts it back on the queue. Two more techniques are left for the Apply section: heartbeats, so a supervisor can tell a dead worker from a slow one, and a dead-letter queue (DLQ), where a job that keeps failing (a "poison pill") is set aside after a few attempts instead of looping for ever. None of them protects against Redis itself losing data: a Redis without persistence that restarts loses every queued job.

03. Step 1: Enqueuing tasks and returning HTTP 202 Accepted

First, create app/api.py. The endpoint makes a job ID, records the queued state, pushes the ID onto the export_queue list and returns HTTP 202 with a status URL. Both writes go in one MULTI/EXEC transaction (pipeline(transaction=True)), so a crash cannot leave a queued record with no queue entry.

The job state key has a Time-To-Live (TTL) of 24 hours: Redis deletes it a day after the last write, so records of finished exports do not pile up in memory. Pick a TTL longer than any client will poll for.

Python · app/api.py
import json
import uuid
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
import redis.asyncio as redis

app = FastAPI(title="Export Service")
r = redis.Redis(host="localhost", port=6379, decode_responses=True)

class ExportRequest(BaseModel):
    user_id: str
    format: str = "csv"

@app.post("/v1/exports", status_code=status.HTTP_202_ACCEPTED)
async def create_export(req: ExportRequest):
    job_id = f"job_{uuid.uuid4().hex[:10]}"
    job_data = {
        "job_id": job_id,
        "user_id": req.user_id,
        "format": req.format,
        "status": "queued",
        "download_url": None,
    }
    # MULTI/EXEC: the status record (24 h TTL) and the queue entry are
    # written together, so no job is left "queued" without a queue entry
    async with r.pipeline(transaction=True) as pipe:
        pipe.set(f"job:{job_id}", json.dumps(job_data), ex=86400)
        pipe.lpush("export_queue", job_id)
        await pipe.execute()

    return {
        "job_id": job_id,
        "status": "queued",
        "status_url": f"/v1/exports/{job_id}/status",
    }

@app.get("/v1/exports/{job_id}/status")
async def get_export_status(job_id: str):
    raw_data = await r.get(f"job:{job_id}")
    if not raw_data:
        raise HTTPException(status_code=404, detail="Job not found")
    return json.loads(raw_data)

Check that the module imports and that both routes exist. No broker is needed yet: the Redis client connects at its first command.

Terminal 2
python -c "from app.api import app; \
print(sorted(r.path for r in app.routes if 'exports' in r.path))"
Expected output
['/v1/exports', '/v1/exports/{job_id}/status']

04. Step 2: Building the standalone worker daemon

Next, create worker.py, a process of its own, separate from the web server. It waits for work with BLMOVE, the blocking form of the atomic move: Redis hands over the next job ID and parks it in a second list, export_processing, in one step. A plain BRPOP would remove the job outright, so a worker killed mid-job would lose it.

Each BLMOVE waits on the server for up to BLOCK_S (5) seconds and returns None if no job came, so the client must wait longer than that for the reply. redis-py 8 gives every read a 5-second socket timeout by default, the same as the block time, so an idle worker sooner or later gives up just before Redis answers and dies with TimeoutError. Hence socket_timeout=BLOCK_S + 10: still a limit, so a dead connection is noticed, but above the block time.

The worker records processing, then completed with the download URL or failed with the error, and only then removes the job from export_processing. (A worker killed with SIGKILL records nothing; step 4 shows how the processing list covers that.) On start-up it writes its process id to worker.pid for step 4 and moves anything a killed worker left in export_processing back onto the queue:

Python · worker.py
import asyncio
import json
import logging
import os
from pathlib import Path

import redis.asyncio as redis

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("worker")

QUEUE, PROCESSING = "export_queue", "export_processing"
BLOCK_S = 5  # how long one BLMOVE waits on the server for a job


async def save(r: redis.Redis, job: dict) -> None:
    await r.set(f"job:{job['job_id']}", json.dumps(job), ex=86400)


async def process_export_job(r: redis.Redis, job_id: str):
    """Execute CSV compilation and update state in Redis."""
    raw_data = await r.get(f"job:{job_id}")
    if not raw_data:
        return
    job = json.loads(raw_data)
    job["attempts"] = job.get("attempts", 0) + 1

    # 1. Transition state to processing
    job["status"] = "processing"
    await save(r, job)
    logger.info("Started processing job %s for user %s", job_id, job["user_id"])

    try:
        # 2. Simulate heavy CSV compilation and S3 upload
        await asyncio.sleep(2.0)
        if job["format"] != "csv":
            raise ValueError(f"unsupported format {job['format']!r}")
    except Exception as exc:
        # 3a. Record the failure, so the status endpoint can report it
        job["status"] = "failed"
        job["error"] = str(exc)
        await save(r, job)
        logger.error("Job %s failed: %s", job_id, exc)
        return

    # 3b. Transition state to completed with download artifact URL
    job["status"] = "completed"
    job["download_url"] = f"https://storage.example.com/exports/{job_id}.csv"
    await save(r, job)
    logger.info("Completed job %s successfully", job_id)


async def main():
    # redis-py 8 defaults socket_timeout to 5 s, equal to BLOCK_S: a read
    # must be allowed to wait longer than one BLMOVE blocks on the server.
    r = redis.Redis(
        host="localhost", port=6379, decode_responses=True,
        socket_timeout=BLOCK_S + 10,
    )
    Path("worker.pid").write_text(str(os.getpid()))  # used in step 4
    # Recovery: put back jobs that a killed worker left in PROCESSING.
    # Safe with ONE worker; with several, give each its own processing list.
    while job_id := await r.lmove(PROCESSING, QUEUE, "RIGHT", "RIGHT"):
        logger.warning("Re-queued job %s left by a stopped worker", job_id)
    logger.info("Worker started. Waiting for jobs on export_queue...")
    while True:
        # Atomically move the next job into PROCESSING (waits up to BLOCK_S)
        job_id = await r.blmove(QUEUE, PROCESSING, BLOCK_S, "RIGHT", "LEFT")
        if job_id is None:
            continue
        await process_export_job(r, job_id)
        # Finished (completed or failed): only now drop it from PROCESSING
        await r.lrem(PROCESSING, 1, job_id)


if __name__ == "__main__":
    asyncio.run(main())

Start Redis with the docker run command from the setup, then start the worker in terminal 1 and leave it running. It has nothing to recover, so it logs one line and waits. Predict: without socket_timeout, what would this idle worker do within a minute or two? (Answer in the troubleshooting callout.)

Terminal 1 · leave it running
python worker.py
Expected output
INFO:worker:Worker started. Waiting for jobs on export_queue...

05. Step 3: Verification and expected output

With the worker running in terminal 1, run pytest -q in terminal 2. The test drives the API in-process through httpx's ASGI transport, so it needs no web server; the worker is the real one, reached through Redis. It enqueues a job, expects HTTP 202, polls the status every 0.5 s until the job finishes, and checks the download URL. Then it checks the failure path: an unsupported format must end as failed with an error message, not hang in processing:

Python · tests/test_exports.py
import asyncio

import httpx

from app.api import app


async def run_export(client: httpx.AsyncClient, payload: dict) -> dict:
    """Post an export, then poll its status every 0.5 s for up to 10 s."""
    resp = await client.post("/v1/exports", json=payload)
    assert resp.status_code == 202
    status_url = resp.json()["status_url"]
    for _ in range(20):
        job = (await client.get(status_url)).json()
        if job["status"] in ("completed", "failed"):
            return job
        await asyncio.sleep(0.5)
    raise AssertionError(f"job still {job['status']} after 10 s")


async def lifecycle() -> None:
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
        done = await run_export(c, {"user_id": "usr_4401"})
        assert done["status"] == "completed"
        assert done["download_url"].endswith(".csv")
        # Negative path: the worker must record failures, not swallow them
        bad = await run_export(c, {"user_id": "usr_4401", "format": "xlsx"})
        assert bad["status"] == "failed"
        assert bad["download_url"] is None
        assert "unsupported format" in bad["error"]


def test_export_lifecycle():
    # One event loop for the whole test: the Redis client in app.api
    # keeps connections that belong to the loop that opened them.
    asyncio.run(lifecycle())
Illustrative output · terminal 2, pytest -q (the run time differs on every run)
.                                                                        [100%]
1 passed in 5.35s
Illustrative output · terminal 1, the worker (job ids are random, so they differ per run)
INFO:worker:Worker started. Waiting for jobs on export_queue...
INFO:worker:Started processing job job_eadeee5e1b for user usr_4401
INFO:worker:Completed job job_eadeee5e1b successfully
INFO:worker:Started processing job job_4b35434270 for user usr_4401
ERROR:worker:Job job_4b35434270 failed: unsupported format 'xlsx'

What the run shows:

  • The API answered at once: POST /v1/exports returned 202 as soon as the job was queued; the two seconds of work happened in the worker.
  • The idle worker costs little: BLMOVE waits on the Redis server, so an idle worker uses almost no CPU and sends one command every BLOCK_S (5) seconds.
  • The client could follow the job: it saw queued, processing and completed and read the download URL; the second job ended as failed, with the error in its record.

In production you also watch the queue: its length (LLEN export_queue) and the time a job waits before a worker claims it. When the length keeps growing, an autoscaler such as KEDA can add worker replicas.

06. Step 4: Kill the worker mid-job and watch the recovery

Now break it on purpose. post_one.py sends one export through the API in-process and prints the answer. Run it, kill the worker with SIGKILL during its two-second sleep, and ask Redis what is left in the processing list. If you run Redis natively instead of in Docker, drop the docker exec jobs-redis prefix.

Python · post_one.py
"""Post one export through the API in-process and print the immediate answer."""
import asyncio

import httpx

from app.api import app


async def main() -> None:
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
        resp = await c.post("/v1/exports", json={"user_id": "usr_4401"})
        print(resp.status_code, resp.json()["status"])


asyncio.run(main())
Terminal 2 · kill the worker half a second into the job
python post_one.py && sleep 0.5 && kill -9 "$(cat worker.pid)"
docker exec jobs-redis redis-cli LLEN export_processing
Expected output
202 queued
1

The client holds its 202, and the job ID is parked in export_processing with status processing. Start the worker again in terminal 1: it moves the orphaned job back onto the queue, then runs it.

Illustrative output · terminal 1 (the job id differs per run)
WARNING:worker:Re-queued job job_d1fb00fb03 left by a stopped worker
INFO:worker:Worker started. Waiting for jobs on export_queue...
INFO:worker:Started processing job job_d1fb00fb03 for user usr_4401
INFO:worker:Completed job job_d1fb00fb03 successfully
Terminal 2 · a few seconds later
docker exec jobs-redis redis-cli LLEN export_processing
Expected output
0

With BRPOP the same drill loses the job: it is in no list, and its status says processing until the TTL deletes it. The recovery has a cost: the job started twice, which is why the next lesson makes side effects idempotent. It also assumes one worker: with two workers sharing export_processing, a starting worker would re-queue jobs the other is still running.

07. Check your understanding

Practice check · 3 questions

Background workers, brokers, and status endpoints

Three questions on blocking moves, worker crashes, and job state in Redis.

Q1. Why does the worker wait with `BLMOVE ... 5` instead of calling `LMOVE` in a tight `while True` loop?
Q2. A worker that took its job with plain `BRPOP` (no processing list) is killed by the OOM killer halfway through. What happens to that job?
Q3. Why does the lab give every job status key in Redis a Time-To-Live (TTL)?
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend the lab in two directions. First, run two workers at once: give each its own processing list (export_processing:<worker id>) and change the start-up recovery so a worker only re-queues entries from lists whose owner has stopped sending heartbeats. Second, use the attempts counter the worker already records: after three attempts, move the job ID to an export_dead list (a dead-letter queue) and mark it failed.

On the enqueue side, give the API's Redis client a short socket timeout and return 503 when the broker is unreachable, so a broker outage fails requests quickly instead of hanging them.

The next lesson makes a job that runs twice after a crash safe to repeat.

09. Review prompt

Explain why the API answers 202 instead of doing the export in the request. Describe why the worker claims jobs with BLMOVE and a processing list rather than BRPOP, what happens to a job when the worker is killed mid-task, why its socket timeout must exceed the BLMOVE block time, and why job status records carry a TTL.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check