Celery and Redis for Background Tasks: Answer 202, Hand the Job to a Worker, and Poll for the Result
A thirty-minute recording takes minutes to transcribe, and a web request can't wait that long. The fix: the API answers 202 with a task ID, a Celery worker takes the job from Redis, and the client polls. One small task, sent with delay, followed from PENDING to STARTED to SUCCESS.
What you will learn
- Explain why a long job like transcription doesn't belong inside one HTTP request
- Use the 202 Accepted plus task ID plus polling pattern
- Write a Celery task, queue it with delay, and watch a worker run it through Redis
- Read task states, and know when Celery beats a serverless GPU and when it doesn't
Before you start
- A layered FastAPI project
- Docker basics
Some jobs are slow by nature. Making subtitles for a thirty-minute recording can take minutes, not milliseconds. Now imagine the browser sends that file and then waits on the same request while the server transcribes it. After a while the browser, a proxy or a load balancer gives up and the user sees a timeout. Meanwhile the server is still busy with that one job, so it has less room for everyone else. And if the server restarts in the middle, the work is lost.
The pattern: accept now, finish later
The API takes the request and answers right away: got it, I'm working on it. The status code for that is 202 Accepted, meaning the request was accepted but the work isn't finished. You'll sometimes see 201 Created used here, but 201 says the new thing already exists in full. For a job still running, 202 is the honest answer.
Along with it, the API returns a task ID. The client checks back with that ID every few seconds and asks for the status. That's polling. When the state says success, the result is ready to collect.
A restaurant kitchen
A waiter takes your order in a few seconds, clips the ticket onto the kitchen rail and walks away. A chef picks up the ticket and cooks, while the waiter is already taking the next table's order. In the app, the waiter is the API, the ticket rail is Redis, and the chef is the Celery worker. The waiter never stands in the kitchen waiting for the food, and the API never waits for Whisper.
Redis holds the tickets
Celery needs a message broker, a place that holds the jobs until a worker takes them. Here it's Redis, an in-memory key-value store, so reads and writes are fast. It runs in Docker with docker compose up, and a ping gives back PONG. RabbitMQ and Amazon SQS work too, but Redis is the easiest one to start with. (Choosing between them is in choosing a broker.)
The demo has three small files. The snippets below are a sketch built from the lecture's names and values. In celery_app.py:
# sketch of the lecture's celery_app.py
from celery import Celery
REDIS_URL = "redis://localhost:6379/0"
celery_app = Celery("subly", broker=REDIS_URL, backend=REDIS_URL)
celery_app.conf.task_track_started = True
The app is named subly. Redis is the broker, and the same URL is the backend, where Celery stores each task's state and result so the API can read them later. task_track_started tells the worker to report when it begins a task; you'll see why in a moment.
A task, and delay
# sketch of the lecture's tasks.py
import time
from app.celery_app import celery_app
@celery_app.task
def transcribe_audio(audio_id):
time.sleep(5) # stands in for the long transcription
return {"audio_id": audio_id, "status": "subtitles ready"}
A task is a Python function with the task decorator on top. The decorator is what turns a normal function into something Celery can queue and run on a worker. Later, Whisper goes where the sleep is.
To send a task, you don't call the function. You call transcribe_audio.delay(42). delay returns at once with a task ID; the function hasn't run at all yet. With no worker running, asking for the state gives PENDING. Look inside Redis and the list named celery now holds one item, a JSON message carrying the task name transcribe_audio, the task ID and a retry count of zero. That's the ticket on the rail. delay only writes a message; running it is the worker's job.
Start a worker
celery -A app.tasks worker --pool=solo --loglevel=info
On Windows, Celery's default pool doesn't run well, so the solo pool is used. The banner says the worker is connected to Redis, listens to the queue named celery and knows one task, transcribe_audio. Straight away it finds the ticket left earlier and logs task received. About five seconds later it logs succeeded, with the result: audio ID 42 and subtitles ready. The list in Redis is empty again.
Notice that the task was queued before the worker even existed, and nothing was lost. Redis held it until a worker came.
Connect it to FastAPI
Two routes in main.py:
POST /subtitles/{audio_id}with its status code set to 202. It callstranscribe_audio.delay(audio_id)and returns the task ID straight away.GET /tasks/{task_id}creates anAsyncResultfor that ID and returns the state, and the result only once the task is ready. Until then the result is null.
So the API has two small jobs: hand the work off, and report on it. Posting to /subtitles/44 gave 202 Accepted with the task ID. Then polling:
| Time | State | Result |
|---|---|---|
| about 0.3 s | STARTED | null |
| 2 s later | STARTED | null |
| about 6 s | SUCCESS | audio ID 44, subtitles ready |
You only see STARTED because of task_track_started. Without it, the state stays PENDING until the task finishes. The result is stored in Redis under a key that starts with celery-task-meta- followed by the task ID, holding the status, the result and a traceback of null.
The whole flow
Because they only meet through Redis, the API and the worker can run from separate Docker images and scale on their own. If ten audio files arrive together, start more worker containers and process them side by side while the API stays as it is. The API mostly takes requests and reads Redis, so a small CPU machine is enough. The worker runs Whisper, where a GPU makes a big difference. GPU machines cost a lot more than CPU ones, so you rent a GPU only for the worker. In one big monolith everything would sit on the GPU machine.
Celery or a serverless GPU?
| Celery + Redis | Serverless GPU | |
|---|---|---|
| Start | Worker always warm, job starts at once | May need time to start up |
| Idle cost | The warm worker costs money while idle | Zero |
| Retries and scheduling | Built in | Usually extra code |
| Running it | You run the workers | Deploy once, the provider scales it |
| Suits | Steady, predictable jobs | Spiky, occasional jobs |
A general serverless function like AWS Lambda is meant for shorter tasks and has no GPU, so for Whisper you'd look at the GPU providers. This app goes with Celery.
Common mistakes
- Calling the task function directly. It runs inside the request; use
delay. - Reading PENDING as "queued". It can also mean the ID is unknown.
- Expecting STARTED without
task_track_started. - Running the default worker pool on Windows. Use
--pool=solo.
Quick recap
- A long job doesn't belong in one HTTP request: reply 202 with a task ID, and let the client poll.
- Redis is the broker in the middle and also keeps the results.
delayputs a message on the queue, the worker picks it up, and the result goes back into Redis.
Try it yourself
Send three tasks with delay before you start the worker, then start it, and watch it work through all three.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
