Server-Sent Events in FastAPI using Redis Pub/Sub
Whenever you want real-time updates of your client, and you only need to push changes to the client (one-way traffic), there is a great alternative to WebSockets, called Server-Sent Events.
Server-Sent Events (SSE) basically means the HTTP response of a GET request is a never-ending stream, and you get to push changes down this stream to the client.
In this article, I would like to show how you can set up SSE in FastAPI using Redis Pub/Sub.
There is a neat little SSE library called sse-starlette, that already provides a Server-Sent Events response type, like so:
It takes a generator, in this case a method, called subscribe
and will pass everything the generator yields to the client down the line.
The question is, to which client? In some use cases, it’s OK to push changes to all listeners, but sometimes you want to specify a topic or a channel. You can even use this to limit the receiver to one particular user.
Enter Redis Pub/Sub. With Redis Pub/Sub you publish to channels and have subscribers receive these updates. You can probably see where this is going.
What if we create a generator that is, in fact, a Redis Pub/Sub subscription?
Now, all we have to do to send updates to one or more subscribers is to publish a message to the right channel.
As you can see we are using a dependency here for our Redis connection (dependency injection being one of the great improvements of FastAPI). It is actually a third-party dependency, called fastapi-plugins. It’s great because it is based on aioredis, a fully async Redis client.
Here is the full source code that combines the above examples into a working FastAPI application, including a demo JavaScript listener that prints incoming messages to the console.
Make sure to install the correct dependencies:
pip install fastapi
pip install fastapi-plugins
pip install sse-starlette
pip install uvicorn
Then run the application, assuming you have a Redis instance running on the default port:
uvicorn sse-fastapi-redis:app --reload
Big thanks to Sairam Krish for writing https://sairamkrish.medium.com/handling-server-send-events-with-python-fastapi-e578f3929af1, on which this article is based.