What is a Redis Pub/Sub?

Many of the applications we use daily are dynamic and responsive, delivering large amounts of data instantly. Just think of live updates in a chat application, notifications in a collaborative workspace, or real-time sports updates. The ability to push data as it happens is simply a feature today's users expect. Developers often achieve this through the publish/subscribe concept, also known as pub/sub.

Publishers send out messages, and subscribers receive them. This information delivery takes place in things known as channels. Although it's a simple and elegant pattern, it gets complex when dealing with high-performance distributed applications. Each component in a tech stack must keep up with pub/sub activities across multiple channels, distributed across multiple servers or application clusters. That's why developers turn to the fast in-memory data store Redis for pub/sub.

Why Use Redis for Pub/Sub?

So, why is Redis preferred for applications that depend on reliable pub/sub operations? Of course, Redis is fast since it operates primarily in memory—storing data in RAM instead of slower disk storage. However, other database solutions can make the same claim. Redis stands out from the crowd because it isn't simply a fast key-value database but a powerful data store with a versatile feature set that's perfect for lightning-fast message delivery with low latency, which is critical for real-time applications.

In particular, Redis excels in coordinating pub/sub actions across distributed systems. High-performance applications typically run off of a distributed architecture, with regional clusters providing fast response times to local users around the globe. Some database systems become too complex to manage in a distributed environment, while others start to suffer in performance when more nodes are added. Redis, on the other hand, is built for top performance across distributed systems.

Redis is designed for scalability and built-in support for clustering and other high-availability options. It supports message persistence and sharding to distribute pub/sub workloads across multiple Redis instances. Redis also offers robust features such as pattern-based subscriptions and support for multiple channels, all of which are important foundations for a robust pub/sub infrastructure.

Core Concepts of Redis Pub/Sub

Pub/sub in Redis is built on four core concepts. First is the basic idea of publishers and subscribers:

  • Publishers are responsible for sending messages. They don't need to know who's listening; they simply broadcast messages to specific channels.
  • Subscribers express interest in receiving messages. They subscribe to channels, and whenever a message is published to those channels, they receive it.

The second concept is channels, which act as the conduits for messages. Channels are essentially named pipes to which publishers send messages and subscribers listen. Each channel has a unique name, and subscribers can choose which channels they want to subscribe to, based on their interests.

Redis expands on the basic pub/sub features with patterns. With patterns, subscribers can express interest in multiple channels using wildcard characters like an asterisk. For example, a subscriber might use the pattern news* to receive messages from all channels starting with "news." Redis also supports more advanced patterns so developers can build unique user experiences.

Finally, Redis is scalable because it supports sharded publishers and subscribers. As an application's user base grows and the volume of messages following through the pub/sub system increases dramatically, sharding allows developers to distribute publishers and subscribers across multiple Redis instances.

Pub/Sub on Java with Redisson

Java developers can build high-performance, distributed applications on the Redis pub/sub mechanism with the Redisson library and its RTopic object. With Redisson, users can subscribe to events published with multiple instances of an RTopic object with the same name. Listeners are resubscribed automatically after reconnection to Redis or a Redis failover event.

Here's a code example:

RTopic topic = redisson.getTopic("myTopic");
int listenerId = topic.addListener(SomeObject.class, new MessageListener() {
    @Override
    public void onMessage(String channel, SomeObject message) {
        //...
    }
});


// in another thread or JVM
RTopic topic = redisson.getTopic("myTopic");
long clientsReceivedMessage = topic.publish(new SomeObject());

Redisson also provides support for reliable topics, a feature not otherwise available in Redis. Unlike RTopic, reliable topics or RReliableTopic objects guarantee that messages are delivered to subscribers at least once—even if there are network failures or Redis crashes.

Here's a code sample that shows how to use reliable topics with Redisson:

// Create a reliable topic
RReliableTopic reliableTopic = redisson.getReliableTopic("myReliableTopic");
// Subscribe to the reliable topic
reliableTopic.addListener(new MessageListener() {
    @Override
    public void onMessage(CharSequence message, String shardId) {
        System.out.println("Received message: " + message + " on shard: " + shardId);
    }
});


// Publish a message to the reliable topic
reliableTopic.publish("Hello, reliable world!");

Redisson also offers the RPatternTopic class, which implements Redis's powerful pattern capabilities. RPatternTopic can include wildcards, and listeners are automatically resubscribed after reconnecting to Redis in the event of a crash or a Redis failover.

The Redisson RShardedTopic class implements the Redis sharded pub/sub mechanism. It allows users to subscribe to events published with multiple instances of RShardedTopic with the same name. Unlike RTopic, messages published via RShardedTopic are not broadcast across all Redis nodes. This helps reduce network traffic and reduces the load on Redis.

To learn more about Redisson and its Redis pub/sub features, visit the Redisson website today.

Similar terms