Scrivio Interview library
CodingFoundations7 min read · updated 13 November 2026

A chat service runs eight Spring Boot instances; each user holds a WebSocket connection to one instance, and a message from one user must reach the other members of a room wherever they are connected.

Show how to deliver room messages across instances with Redis pub/sub and RedisMessageListenerContainer, and say what is lost when an instance disconnects from Redis.

When a user sends a message, the instance publishes it with redisTemplate.convertAndSend("room:" + roomId, message); every instance subscribed to that channel receives it through RedisMessageListenerContainer and writes it to its own WebSocket sessions in that room. Instances subscribe either to the pattern room:* or, better, per channel when their first local user joins a room. Pub/sub is fire-and-forget, so anything published while an instance is disconnected is lost, and we store messages durably so clients can fetch what they missed on reconnect.

Why this question is asked

Once a chat service runs on more than one instance, a message from a user connected to instance 3 has to reach room members connected to instances 1, 5 and 8. Redis pub/sub is the most common way to bridge them in Spring Boot, and it is only a few lines of code. Interviewers ask for it to check that we can wire it correctly and, just as important, that we know what pub/sub does not promise. In this answer, we will recap pub/sub, configure the listener container, publish and deliver room messages, choose between pattern and per-room subscriptions, deal with what is lost on disconnect, and keep the subscription connection healthy.

1A Quick Recap of Redis Pub/Sub

In Redis pub/sub, a client publishes a message to a named channel with PUBLISH, and Redis immediately pushes it to every client currently subscribed to that channel with SUBSCRIBE, or to a matching pattern with PSUBSCRIBE. Redis does not store the message anywhere: if nobody is subscribed at that moment, it is gone. PUBLISH returns the number of clients that received it.

For our chat, each instance is a subscriber, not each user. Users hold WebSocket connections to one instance, and the instance relays messages between Redis and its local sessions.

Step throughA room message crossing instances
Alice (on A)Instance ARedisInstance BBob (on B)
send 'hi' to room 42 (WebSocket)
PUBLISH room:42 'hi'
message on room:42
message on room:42
deliver to local members of room 42
deliver to local members of room 42

6 messages in order. Play them, or step through them one at a time.

Every instance with a subscriber for room:42 gets the message, including the sender's own instance.

2Configuring the Listener Container

Spring Data Redis provides RedisMessageListenerContainer. It holds a dedicated connection for subscriptions, receives messages on it, and hands each one to our listener on a task executor. We give it its own executor so that listener work does not block the thread that reads from Redis.

Java
@Configuration
class ChatRedisConfig {
@Bean
RedisMessageListenerContainer chatContainer(RedisConnectionFactory cf) {
var container = new RedisMessageListenerContainer();
container.setConnectionFactory(cf);
container.setTaskExecutor(Executors.newVirtualThreadPerTaskExecutor()); // listener calls run here
return container;
}
}

Virtual threads are a good fit since Java 21, because writing to WebSockets is blocking I/O; a bounded thread pool works too. With a pattern subscription, we would add container.addMessageListener(relay, new PatternTopic("room:*")) here and be done.

3Publishing and Delivering Room Messages

The relay component keeps a map from room id to the WebSocket sessions connected to this instance. Sending publishes to Redis; receiving looks up local sessions and writes to them. Subscriptions are added when the first local user joins a room and removed when the last one leaves, so each instance only receives messages for rooms it has members in.

Java
@Component
class RoomRelay implements MessageListener {
private final StringRedisTemplate redis;
private final RedisMessageListenerContainer container;
private final Map<String, Set<WebSocketSession>> local = new ConcurrentHashMap<>();
RoomRelay(StringRedisTemplate redis, RedisMessageListenerContainer container) {
this.redis = redis; this.container = container;
}
void send(String roomId, String json) {
Long receivers = redis.convertAndSend("room:" + roomId, json); // e.g. 3 instances received it
}
synchronized void join(String roomId, WebSocketSession s) {
Set<WebSocketSession> set = local.computeIfAbsent(roomId, k -> ConcurrentHashMap.newKeySet());
if (set.isEmpty()) container.addMessageListener(this, new ChannelTopic("room:" + roomId));
set.add(s);
}
synchronized void leave(String roomId, WebSocketSession s) {
Set<WebSocketSession> set = local.get(roomId);
if (set == null) return; // already gone
set.remove(s);
if (set.isEmpty() && local.remove(roomId) != null)
container.removeMessageListener(this, new ChannelTopic("room:" + roomId));
}
@Override
public void onMessage(Message message, byte[] pattern) {
String roomId = new String(message.getChannel(), StandardCharsets.UTF_8).substring("room:".length());
TextMessage text = new TextMessage(new String(message.getBody(), StandardCharsets.UTF_8));
for (WebSocketSession s : local.getOrDefault(roomId, Set.of())) {
try { s.sendMessage(text); } catch (IOException e) { leave(roomId, s); } // dead session
}
}
}

Notice that the sender's own instance also receives the message from Redis, which is convenient: local members are served by the same code path as remote ones. A WebSocketSession must not be written to from several threads at once, so in production we wrap each session in Spring's ConcurrentWebSocketSessionDecorator, which also bounds the send buffer for slow clients.

4Pattern Subscription Versus Per-Room Channels

Subscribing every instance to room:* is the simplest option: one line, no join or leave bookkeeping. The cost is that every instance receives every message of every room and discards most of them. With eight instances, Redis sends each message eight times, and each instance parses traffic it does not need. That is fine for a few hundred messages a second and wasteful at a hundred thousand.

Per-room channels send each message only to instances with members in that room. The cost is the subscribe and unsubscribe calls as users move, which are cheap, and the bookkeeping above. For a large service, per-room is the better default.

5What Is Lost When an Instance Disconnects

Pub/sub is fire-and-forget. If instance B loses its Redis connection for three seconds, during a network blip or a Redis failover, every message published to its rooms in those three seconds is simply never delivered to B, and Bob never sees them. Redis does not queue them, and PUBLISH only reports how many subscribers received each message at that moment. The listener container reconnects and resubscribes, but the gap is permanent.

The fix is to store messages durably as well as broadcasting them. Before publishing, the instance writes the message to the database, or to a Redis Stream per room, such as XADD chat:room:42 MAXLEN ~ 1000 * body ..., and includes the message id in the broadcast. Clients track the last id they received; on reconnect, or when they notice a gap, they ask for everything after it, for example XRANGE chat:room:42 (1762942800123-0 + COUNT 200, where the parenthesis makes the start exclusive. Pub/sub then provides speed, and the store provides completeness.

6Keeping the Subscription Connection Healthy

All subscribed messages arrive on one connection per container. If our listener did slow work on the thread reading that connection, such as writing to a slow client's socket, messages would pile up in Redis's output buffer for our connection, and Redis disconnects subscribers whose buffer exceeds client-output-buffer-limit for pubsub (32 MB hard limit by default, check your configuration). The container's task executor keeps reading separate from handling, and the session decorator keeps one slow client from blocking a room. If handling becomes expensive, we hand it to another executor and return quickly.

7Follow-up questions

How would you route a message to a single user rather than a room?

Give each user a channel, such as user:4711, which the instance holding that user's WebSocket subscribes to when the user connects and unsubscribes from when they leave. Sending to the user is then a PUBLISH to user:4711, and only the right instance receives it. With many users per instance, a per-instance channel plus a registry of which instance holds which user (a hash with TTLs refreshed by heartbeats) is an alternative that keeps subscriptions few.

Why not use Redis Streams instead of pub/sub for delivery too?

We can: each instance reads the room streams it cares about with XREAD and blocking. Streams keep messages, so a reconnecting instance resumes from its last id. The cost is more work per room and per instance, and many blocking reads; for live fan-out, pub/sub is simpler, and the stream is used as the catch-up store.

Does the container recover automatically after a Redis failover?

It attempts to reconnect and re-establish its subscriptions with a back-off (check your Spring Data Redis version for the exact recovery behaviour), but it cannot recover messages published while it was disconnected. That is why the durable store and client catch-up are part of the design.

8Conclusion

In this answer, we bridged eight chat instances with Redis pub/sub: an instance publishes with convertAndSend to room:<id>, and every subscribed instance receives the message through RedisMessageListenerContainer and writes it to its local WebSocket sessions. A pattern subscription is simple but sends every message to every instance, while per-room channels added on the first join and removed on the last leave send it only where needed. Pub/sub loses messages published while an instance is disconnected, so we also store messages durably and let clients fetch everything after their last id, and we keep slow work off the subscription connection.

What to say in the interviewAbout 80 seconds aloud

Open with

When a user sends a message, the instance calls redisTemplate.convertAndSend with the channel room: plus the room id and the message, after storing it durably. Each instance registers a MessageListener with RedisMessageListenerContainer, which keeps a dedicated subscription connection and dispatches messages to my listener on a task executor.

Then, if they want more

In onMessage, I take the room id from the channel name and write the message to the WebSocket sessions in that room that are connected to this instance, including the sender's instance.

For subscriptions I can use the pattern room:*, which is simple but means every instance receives every message, or subscribe per channel when the first local user joins a room and unsubscribe when the last one leaves, which scales much better.

The key limitation is that pub/sub is fire-and-forget: if an instance is disconnected or reconnecting, messages published in that window are lost for its users, and PUBLISH only tells me how many subscribers received it.

So I also persist messages, in the database or a Redis Stream per room, and clients fetch everything after their last message id when they reconnect. Finally I keep slow work off the subscription connection, using the container's executor and a concurrent session decorator, so a slow client can't make Redis drop our subscriber.

About this answer

Last updated
13 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to deliver room messages across instances with Redis pub/sub and...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/eeb0f38a60/