Video in progress

How does Redis Pub/Sub work, and what is the risk of using it as a message queue?

A publisher sends a message to a channel, and Redis immediately fans it out to every client subscribed at that moment. The message is not stored anywhere: if a subscriber is disconnected or hasn't connected yet, it never receives it.

📖 Answer

SUBSCRIBE cache-invalidation
PUBLISH cache-invalidation "product:42"   # returns how many subscribers received it

In Spring:

@Bean
RedisMessageListenerContainer container(RedisConnectionFactory cf, LocalCacheEvictor evictor) {
    var c = new RedisMessageListenerContainer();
    c.setConnectionFactory(cf);
    c.addMessageListener((msg, pattern) -> evictor.evict(new String(msg.getBody())),
        new ChannelTopic("cache-invalidation"));
    return c;
}

Pub/Sub is "fire and forget". What it lacks: acks, redelivery, history, consumer groups. If a subscriber is slow, Redis fills its output buffer and drops the connection once it hits client-output-buffer-limit, and the messages are lost.

So it suits signals that are fine to lose: a command to clear a local cache, "online" status, a real-time notification over WebSocket. For events where every single one must arrive, like orders and payments, use Redis Streams or Kafka/RabbitMQ.