Single-recipient messaging is useful, but it doesn’t get us far in replacing the PUBLISH
and SUBSCRIBE commands when we have multiple recipients. To do that, we need to
turn our problem around. In many ways, Redis PUBLISH/SUBSCRIBE is like group chat
where whether someone’s connected determines whether they’re in the group chat.
We want to remove that “need to be connected all the time” requirement, and we’ll
implement it in the context of chatting.
Let’s look at Fake Garage Startup’s next problem. After quickly implementing
their user-to-user messaging system, Fake Garage Startup realized that replacing SMS is good, but they’ve had many requests to add group chat functionality. Like before,
their clients may connect or disconnect at any time, so we can’t use the built-in PUBLISH/SUBSCRIBE method.
Each new group chat will have a set of original recipients of the group messages,
and users can join or leave the group if they want. Information about what users are in
the chat will be stored as a ZSET with members being the usernames of the recipients,
and values being the highest message ID the user has received in the chat. Which
chats an individual user is a part of will also be stored as a ZSET, with members being
the groups that the user is a part of, and scores being the highest message ID that the
user has received in that chat. Information about some users and chats can be seen in
As you can see, user jason22 has seen five of six chat messages sent in chat:827, in
which jason22 and jeff24 are participating.
CREATING A CHAT SESSION
The content of chat sessions themselves will be stored in ZSETs, with messages as members
and message IDs as scores. To create and start a chat, we’ll increment a global
counter to get a new chat ID. We’ll then create a ZSET with all of the users that we want
to include with seen IDs being 0, and add the group to each user’s group list ZSET.
Finally, we’ll send the initial message to the users by placing the message in the chat
ZSET. The code to create a chat is shown here.
By continuing to use this site, you consent to our updated privacy agreement. You can change your cookie settings at any time but parts of our site will not function correctly without them.