# Listen first, then check: a Redis Pub/Sub race in an AI feature

By Farhad Rezaei (https://farhad-rezaei.com) · Published 2026-11-23
Canonical: https://farhad-rezaei.com/blog/listen-first-then-check-redis-pubsub-race
Product: Talkemi (https://talkemi.com/en)

> Redis Pub/Sub only delivers to whoever is subscribed at that moment, so a stream that reads the status and then subscribes can miss a result published in between. Subscribe first, wait for Redis to confirm the subscription, then read the status again. Waiting streams also held all twelve gthread slots; gevent workers, with each stream closing its Postgres connection before it waits, kept the rest of the API responsive.

[Talkemi](https://talkemi.com/en) is a language-learning platform I built, where students take live classes with real teachers and practise with Emi, an AI mentor, in between. In an earlier piece I followed a roleplay message, where Emi's reply comes back in the same request; scored answers take a different route. When a student submits a spoken or written answer to Emi, an AI model scores it in the background. A worker saves the score and announces it through Redis, while the student's browser keeps a live connection open to the server, waiting for that announcement so the score can appear the moment it's ready.

I wanted to be sure that handoff could never miss, so I replayed it against the real stream code with one twist: the worker finishes at the worst possible moment, after the stream has checked the status but before it has started listening. The stream kept waiting. It sent a keep-alive every 15 seconds, twenty of them, then gave up after five minutes and told the browser it had timed out, while the score sat in the database the whole time.

The fix comes down to one rule, listen first and then check, and getting there also showed me what all that waiting was costing the server.

## Why the announcement got lost

The live connection is a Server-Sent Events stream, a single long HTTP response the server keeps writing to. Its first version read the attempt's status from Postgres, subscribed to the attempt's Redis channel and then waited. If the status was already final it answered straight away, which covered a browser that connected late, but it didn't cover a worker that finished between the read and the subscribe.

That gap comes from how Redis Pub/Sub works. A message goes only to whoever is subscribed at that moment; nothing is queued and nothing is replayed. A publish that arrives in the gap is dropped, and the stream ends up waiting for news that has already gone out.

![Left: the publish arrives before the subscription and is lost. Right: subscribe, wait for Redis to confirm, then read again.](https://farhad-rezaei.com/images/blog/listen-first-then-check-redis-pubsub-race/race.svg)

## Listen first, then check

The rule is to start listening before you read the current state, never after. Postgres holds the truth, and Redis is only a nudge to go and look.

```python
pubsub.subscribe(channel)
wait_for_subscription(pubsub)      # Redis has confirmed it
status = recheck_status(attempt_id)
if status in ("completed", "failed"):
    send(status)
    close()
```

Once the subscription exists, every ordering is covered: if the worker saved before the second read, the read sees it, and if it saves afterwards, its message reaches a subscription that's already in place.

The middle line is the subtle part. In redis-py, `subscribe()` sends the command but doesn't wait for Redis to register it; the confirmation comes back later as the first message on the connection. Reading the database before that confirmation would leave a smaller gap where the message can still be lost, so the stream waits for it, up to five seconds, and only then reads again. The materials-upload stream had the same pattern and got the same fix.

The cost is one extra database read per stream, and the alternatives were heavier. Redis Streams keep history, so a late reader could catch up from an ID, but that means managing a stream per attempt to deliver one final status. Polling alone would drop Redis entirely, at the price of a query every second for every waiting student. Since the browser only needs the final state, Pub/Sub plus a second read is enough.

Two safety nets sit around it. Every keep-alive also rereads Postgres, which catches a message lost for any other reason, such as a Redis reconnect. And if an attempt is still processing after three minutes, the stream marks it failed, because a restarted worker can lose a job, and then nothing will ever announce it.

My replay is now a test in the backend: a fake worker saves its result while the subscription is still unconfirmed, and the test checks that the stream reports the score and closes, and that it only reads again after Redis confirms. The old version fails that last check because it read too early, while the new one passes along with the rest of the AI module's 117 tests.

## When waiting starved the server

A stream is a request that can stay open for minutes, and the server ran Gunicorn with gthread workers: three processes with four threads each, so twelve requests at a time. A thread waiting on Redis is still a busy thread, which meant twelve students waiting for scores could take every slot and leave everyone else's requests in a queue.

I measured it with a small app of the same shape, a 20-second stream next to a normal endpoint under the same settings. With twelve streams open, a normal request waited 18.1 seconds, until the streams ended. One run spread the streams unevenly and left a thread free, but most runs blocked. With gevent workers, the same request took under a millisecond.

![Before: twelve thread slots, all held by waiting streams. After: gevent, with each stream closing its Postgres connection before it waits.](https://farhad-rezaei.com/images/blog/listen-first-then-check-redis-pubsub-race/capacity.svg)

gevent runs each request as a greenlet, a lightweight task that steps aside while it waits on the network, so one worker can hold up to 1,000 idle streams and still serve everything else. The switch exposed one more limit: each greenlet keeps its own Postgres connection, and enough idle streams would use up the database's connections. So the stream now closes its connection before every wait, and psycogreen keeps the Postgres driver from freezing the whole worker.

## What students get now

A score now reaches the student as soon as it's saved, whichever side gets there first. A lost announcement costs at most one 15-second keep-alive, a lost job ends after three minutes instead of spinning forever, and students waiting on a score no longer hold up everyone else.

## Further reading

- Redis Pub/Sub, including its at-most-once delivery: https://redis.io/docs/latest/develop/interact/pubsub/
- Server-sent events on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events
- Gunicorn's design and worker types: https://gunicorn.org/design/
- gevent: https://www.gevent.org/
