Have you ever built a website or web based application with long running processes in the background? It is common for a background process to be triggered by your frontend and usually you want to update when there is a status change. I want to show you a method that combines WebSockets and Redis that is easy to set up.
Prerequisites
- An understanding of how to use Node.js
- You need a Redis server, redis.io
- Understanding of Redis commands, this article will use pub/sub
- You need a WebSocket server and a front end app, I wrote an article about setting up WebSockets With SvelteKit
- An understanding of Socket.IO rooms
Overview
Here's an overview of the problem that we need to solve. A user triggers a background process by doing something, uploading a document, filling out a form, clicking a button, etc. Your background process starts operating asynchronously and the user can't really see what's going on anymore. So we need a way for the front end to inform the user that something is happening, such as a process successfully finishes or has reached another step.
Assuming a background process has been initiated by a user on the front end, the flow for the solution we'll walk through below looks like this:
1) The front end establishes a connection to a WebSocket server
2) The WebSocket server joins a room to isolate messages by user
3) The WebSocket server subscribes to a user specific pub/sub channel
4) The background process publishes a message to the user specific pub/sub channel
5) The subscribed WebSocket server sends a message to the user via the front end
This is actually not too hard, there will only be one code block below. And step 4 in the flow above can be done in any Redis client, you can test by sending a pub/sub message using Redis Insight. If you already have a back end that can send a message, then you should be able to use the Redis library for the language your service is written in, and the WebSocket server will work with it.
Install Dependencies
First thing we will need is redis and socket.io npm packages:
Configure the WebSocket Server
Next step is to set up the WebSocket server to receive messages from the background service and then forward them on to the front end user:
This code is the majority of the implementation, it implements step 1-3 and 5 in the flow described in the overview above. The front end needs to emit an event named "register" with a unique channel id and this will in turn subscribe to a pub/sub channel so the front end can receive a message from your back end service.
Note: This requires an environment variable with the value of the url for your Redis server, called REDIS_URI.
And that's all there really is to it! Again, if you'd like to try dropping this into SvelteKit, I've already written a short guide on how to do that here! Happy coding 👋