Originally, Redis was developed as a database and cache to temporarily store data in memory. However, with the release of Redis 2.0, the creators introduced the PUBLISH/SUBSCRIBE feature, allowing Redis to function as a message broker.
Today, Redis is widely used to support chat applications and messaging services, as well as for message transmission using the pub/sub model. In this article, we will explore how a message broker works and how it can be used.
A message broker is a tool that simplifies information exchange between systems and applications, even if they run on different languages and platforms. When there are only a few participants, they can exchange data directly. However, as the number of participants grows, the need for greater interactivity arises, making direct exchange inefficient. In such cases, a message broker manages the process and acts as an intermediary between the sender and the recipient.
Message brokers are especially useful for asynchronous interactions between microservices. Asynchronous communication does not require real-time responses. A good example is email, where users can send a message and continue working on other tasks.
There are several ways to implement message exchange. Here, we will examine three main models.
In the P2P model, each message is sent to a specific queue and can be processed by only one recipient. The message broker ensures that undelivered messages remain in the queue until they are processed.
The key advantage of the P2P model is that each transaction is processed only once. A common use case for P2P messaging is transaction processing, where reliability and security are critical.
In the pub/sub pattern, messages are distributed among all users subscribed to a common topic. This is useful for implementing notification mechanisms or distributing independent tasks.
Redis supports different message types, including strings, hashes, lists, and sets, making it suitable for transmitting various types of data.
Some simple examples of this model in action include Telegram channels and online chats. Additionally, Redis can be used to share event information between different application instances. This mechanism helps track database changes and user activity.
This model combines both P2P and Pub/Sub. Messages can be sent either to a specific queue or to a topic-based channel, allowing all subscribers to receive them simultaneously.
To use Redis as a message broker, you first need to download and install it on your server. Once Redis is installed, start it using the redis-server
command and verify that the installation is correct by running redis-cli
.
Finally, check the configuration file to ensure that the Redis Pub/Sub module is enabled. If it is not working for some reason, add the following line to the configuration file:
loadmodule /usr/lib/redis/modules/redisearch.so
Redis provides a convenient data structure called lists, which we can use to create simple queues. Redis Lists support basic operations and can be locked, making them efficient for building high-performance chat systems, comment feeds, news feeds in social networks, and real-time server communication systems.
To create a message queue, use the following commands:
RPUSH <queue_name> <message>
RPUSH <queue_name> <message2>
This creates a queue named queue_name and adds two messages, message and message2.
RPUSH
command adds new elements to the end of the list.LPUSH
instead.LPOP <queue_name>
– Retrieves and removes the first element from the queue.RPOP <queue_name>
– Retrieves and removes the last element from the queue.BLPOP <queue_name> <timeout>
– Blocking retrieval and removal of an element from the beginning of the queue. The timeout (in seconds) is specified as the last argument.BRPOP <queue_name> <timeout>
– Blocking retrieval and removal of an element from the end of the queue.BRPOPLPUSH <source_queue_name> <destination_queue_name> <timeout>
– Blocking retrieval and transfer of an element from the end of one list to the beginning of another.LLEN <queue_name>
– Retrieves the number of elements in the queue.LRANGE <queue_name> <start> <stop>
– Retrieves a list of messages sent to the channel. The start
and stop
parameters define the range of indices.LINDEX <queue_name> <index>
– Retrieves an element from the queue by index.These commands allow for simple message queue creation (LPUSH
/RPUSH
, LPOP
/RPOP
, BLPOP
/BRPOP
, BRPOPLPUSH
) and queue monitoring (LLEN
, LINDEX
).
Reliable queues ensure that messages are delivered in the correct order. This can be implemented using the BLMOVE
command, which transfers elements between lists while maintaining their order and blocking if the list is empty. If the source queue does not fully process messages, BLMOVE
moves the message to a backup destination queue for further processing.
Syntax of BLMOVE
:
BLMOVE source destination LEFT|RIGHT LEFT|RIGHT timeout
source
– The name of the source list from which the element is extracted.destination
– The name of the destination list to which the element will be moved.LEFT|RIGHT
(first instance) – Specifies the direction of element extraction from the source queue.LEFT|RIGHT
(second instance) – Specifies how the operation blocks if the list is empty.timeout
– The blocking time in seconds (0 for infinite blocking).In Redis Pub/Sub, messages sent through channels are called push messages. To subscribe to a channel, use the SUBSCRIBE
command with the channel name:
SUBSCRIBE hostman_channel
To publish a push message to the channel, use the PUBLISH
command:
PUBLISH hostman_channel "Welcome to our channel"
Similarly, you can unsubscribe from a channel using the UNSUBSCRIBE
or PUNSUBSCRIBE
commands.
A stream-based queue offers extended capabilities, including grouping, callbacks, and message consumption using an iterator.
To create a message stream, use the following command:
XADD name_stream * message1 _message2 _message3
Here, XADD
creates a new message in the stream and adds it to the end of the stream.
To read messages from the stream:
XREAD COUNT 3 STREAMS name_stream 1
Where:
XREAD
reads messages from one or multiple streams.COUNT 3
specifies the number of messages to read from the stream.1
defines the starting message index.XGROUP
– Creates a new stream group or updates an existing one.XREADGROUP
– Reads messages from a specified stream group.XDEL
– Deletes messages from the stream.XPENDING
– Retrieves information about unprocessed messages in a stream group.While Redis provides low latency, support for multiple protocols, and diverse data formats, it is not a fully reliable message broker. It does not guarantee 100% message delivery in case of node failures.
Alternatives such as RabbitMQ, Apache Kafka, and ActiveMQ may be more suitable for applications requiring stronger message durability.