Job Progress: Polling vs Server-Sent Events, with Redis Pub/Sub and a Reconnect That Doesn't Lose the Bar
Polling a 100-second job asked 50 times and got news 11 times. Instead, the worker writes progress to the database and publishes it on a Redis channel, and FastAPI streams it as SSE on one open request. Pub/sub has no memory, so a dropped connection misses updates until the endpoint listens first, then reads the board.
What you will learn
- Count what polling costs for one long job
- Have the worker save progress and publish it on a Redis channel
- Stream it from FastAPI as Server-Sent Events and read it with EventSource
- Fix the lost-update gap by listening first, then reading the current state
Before you start
- Celery and Redis for background tasks
- A layered FastAPI project
The kitchen is cooking. How does the customer know how far along the order is? Today the subtitle page asks the server every two seconds. Here the worker publishes each change instead, and FastAPI streams it to the browser. Then the connection is dropped mid-job to see what the page misses.
You order a pizza, so you phone the shop. Any news? Not yet. A minute later, not yet. Now think of the delivery tracker in the app: it simply updates itself. Phoning the shop is polling, and the tracker is Server-Sent Events, SSE. It needs one thing from you: keep the page open.
Count the polling
asked, changed, last = 0, 0, None
while True:
now = httpx.get(f"{BASE}/projects/{project_id}").json()
asked += 1
if now != last:
changed += 1
last = now
if now["status"] in ("COMPLETED", "FAILED"):
break
time.sleep(2)
print(f"asked {asked} times, changed {changed} times, "
f"same answer {asked - changed} times")
On a job of about a hundred seconds:
asked 50 times, changed 11 times, same answer 39 times
The subtitle page does the same with a setInterval of 2,000 milliseconds. It works. It's just a lot of phone calls.
Write it down, then ring the bell
def channel(project_id):
return f"progress:{project_id}"
def report(project_id, status, percent):
seq = store.save(project_id, status, percent)
event = {"seq": seq, "status": status,
"percent": percent}
heard = r.publish(channel(project_id),
json.dumps(event))
store.set_heard(project_id, seq, heard)
return heard
After every chunk, the task calls report. store.save writes the progress to the database, the order board in the kitchen. Then r.publish rings the bell on a Redis channel, and returns how many heard it (the report said heard by 1). Two steps, on purpose. The board remembers; the bell only rings.
One request that stays open
import redis.asyncio as aioredis
from fastapi import APIRouter
from fastapi.sse import EventSourceResponse, ServerSentEvent
r = aioredis.from_url(URL, decode_responses=True)
def sse(event):
return ServerSentEvent(data=event, id=str(event["seq"]))
@router.get("/bare/{project_id}",
response_class=EventSourceResponse)
async def bare(project_id: str):
pubsub = r.pubsub()
await pubsub.subscribe(channel(project_id))
try:
async for msg in pubsub.listen():
if msg["type"] != "message":
continue
event = json.loads(msg["data"])
yield sse(event)
if event["status"] in DONE:
return
finally:
await pubsub.aclose()
The endpoint subscribes to the channel, keeps the response open, and yields each message on that one request. With curl, each event is a data: line, an id: line and one blank line. When idle, FastAPI sends a small ping every 15 seconds so a proxy doesn't cut the connection. The text/event-stream content type is what makes it a stream.
redis.asyncio.One job, watched twice
To be fair, polling is simple and fine for a short job, and the stream does hold one connection open.
The page, and the reconnect
<progress id="bar" max="100" value="0"></progress>
<span id="label">connecting</span>
<script>
const q = new URLSearchParams(location.search);
const es = new EventSource(`/events/${q.get("id")}`);
es.onmessage = (e) => {
const p = JSON.parse(e.data);
bar.value = p.percent;
label.textContent = `${p.status} ${p.percent}%`;
if (p.status === "COMPLETED" || p.status === "FAILED") {
es.close(); // or the browser reconnects for ever
}
};
</script>
new EventSource opens the stream and the bar moves with each message. Kill the API at 40 percent, and the browser tries again every three seconds on its own. When the API is back, the browser sends Last-Event-ID: 6, and the bar jumps to 60. Forget es.close() at the end, and the browser treats the end of the stream as a drop: seven reconnects in twenty seconds. A React page uses the same EventSource.
The bell has no memory
That jump to 60 needed something the first endpoint doesn't have. With /bare, the client got 10, 20, 30, each heard by 1. Then the connection dropped. 40, 50 and 60 were published and publish returned 0. They're gone for good. Back at 37 seconds, the page still said 30 percent for nearly five seconds, until the next event. And if the job ends while the page is away, the report says completed and the page gets nothing (it waited 30 seconds and gave up). Redis pub/sub is at most once: nobody listening means nobody ever gets it.
Listen first, then read
async def events(project_id: str):
pubsub = r.pubsub()
await pubsub.subscribe(channel(project_id))
try:
await pubsub.get_message(timeout=5) # subscribed
now = await asyncio.to_thread(
store.get_progress, project_id)
seen = now["seq"]
yield sse(now)
if now["status"] in DONE:
return
async for msg in pubsub.listen():
if msg["type"] != "message":
continue
event = json.loads(msg["data"])
if event["seq"] <= seen:
continue # already in what we read
yield sse(event)
if event["status"] in DONE:
return
finally:
await pubsub.aclose()
The order matters. First listen: subscribe, and wait until Redis confirms. Second, read the board and send the current progress at once. Third, stream, skipping any sequence number already sent. Now the client came back at 31 seconds and saw 50 percent within a tenth of a second, and a job that ended while it was away showed completed straight away. The other order, read then listen, with one update in the gap, left the page at 10 percent while the job was really at 20. The bar skipped 30 and 40, which is fine for a bar. If you need every event, a Redis Stream keeps history.
Or WebSockets?
| SSE | WebSockets | |
|---|---|---|
| Direction | Server to page | Both ways |
| Reconnect | Built into the browser | On you |
| Good for | Progress, notifications, AI text | Chat, shared editing, games |
Two limits of SSE. On HTTP/1.1 a browser allows six connections per site, and a seventh stream just waited; HTTP/2 lifts that. And EventSource can't send an Authorization header, so you'd use a cookie. Streaming LLM tokens over both is in streaming LLM answers over SSE and WebSockets.
Common mistakes
- A blocking Redis client inside an async endpoint.
- Publishing without saving. The bell has no memory.
- Reading the state before subscribing.
- Not closing the EventSource when the job is done or failed.
Quick recap
- Polling works, but 39 of 50 answers said nothing new.
- The worker saves, then publishes; the board remembers and the bell rings.
- Listen first, then read, then stream and skip what you've already sent.
- A failed task should stop the page and close the stream.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
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.
