Redis pattern subscriptions

You route messages from user:* to the matching local hub connection so each API instance can receive events published by the worker.

Learning outcomes

  • Explain how Redis Publish sends order events to customer-specific channels.
  • Distinguish exact channel subscriptions from pattern subscriptions using PSubscribe.
  • Trace how Redis pub/sub distributes an event across API instances and how the local hub delivers it to a connection.
  • Explain why Redis pub/sub does not retain messages and how the subscription follows the API process lifecycle.

In Week 4, the customer orders screen polls the API every 10 seconds to check for order updates. In Week 5, the API pushes updates over WebSockets, but a customer can be connected to a different API instance from the one processing their order event. You need a way for the worker to deliver an event across those processes without knowing which instance owns the customer's connection.

Redis provides that communication mechanism through Redis pub/sub.

Publishing to customer channels

A Redis pub/sub channel is a named destination for messages. A publisher sends a payload to a channel, and Redis forwards it to subscribers that are currently listening.

For this project, each customer gets a channel based on their user ID:

user:42
user:87
user:105

An order event for customer 42 goes to user:42. The channel identifies the intended customer, while the payload contains the order update.

For example, the worker can publish an event like this:

go
err := client.Publish(
    ctx,
    "user:42",
    `{"order_id":42,"to":"ACCEPTED"}`,
).Err()

The Publish method sends the supplied payload to the specified channel. It returns a command whose Err() method reports whether the Redis operation failed.

Notice that publishing does not require a Redis key. A channel is not persistent storage. Redis forwards the message to active subscribers without creating a stored record that subscribers can retrieve later.

The worker needs the customer's ID to construct the destination channel. It does not need to know anything about WebSocket connections.

Exact channel subscriptions

A subscriber can listen to an exact channel using Subscribe.

For example:

go
sub := client.Subscribe(ctx, "user:42")
defer sub.Close()

This subscription receives messages published to user:42. It does not receive messages published to user:87.

An exact subscription would require the API to subscribe separately for every customer. That is not what you need. Each API instance must receive notifications for every customer because any customer might have a connection registered in its local hub.

Redis supports pattern subscriptions for this purpose.

Pattern matching with PSubscribe

A pattern subscription listens to channels whose names match a supplied pattern. The PSUBSCRIBE command accepts patterns containing wildcards.

For example:

PSUBSCRIBE user:*

The * wildcard matches any sequence of characters, including an empty sequence. Therefore, this pattern matches all of these channel names:

user:42
user:87
user:105
user:abc
user:

This last detail matters. Redis performs pattern matching on channel names. It does not understand that the suffix represents a customer ID.

In go-redis v9, use PSubscribe to create the pattern subscription:

go
sub := client.PSubscribe(ctx, "user:*")
defer sub.Close()

The returned PubSub object represents the active subscription. Calling Channel() provides a Go receive-only channel through which your application reads incoming messages.

Each received message contains two fields you need:

  • Channel: the Redis channel on which the message was published.
  • Payload: the content sent by the publisher.

For example, a publication to user:42 produces a message containing:

Channel: user:42
Payload: {"order_id":42,"to":"ACCEPTED"}

The channel identifies the customer. The payload carries the order event that the customer's app needs.

A pattern subscription does not validate the channel suffix. Your application must parse the suffix before forwarding the payload to the hub.

For this project, the suffix must represent an integer user ID:

go
suffix := strings.TrimPrefix(msg.Channel, "user:")
userID, err := strconv.ParseInt(suffix, 10, 64)

If parsing fails, ignore the message and continue reading. A malformed channel such as user:abc or user: must not terminate the subscription.

Redis message delivery

Redis pub/sub is an immediate delivery mechanism, not a durable message queue.

A subscriber receives messages while its subscription is active. Redis does not retain messages for subscribers that are disconnected or not yet listening.

Consider this sequence:

  1. API instance A subscribes to user:*.
  2. API instance A loses its Redis connection.
  3. The worker publishes an event to user:42.
  4. Redis has no active subscription from API instance A.
  5. API instance A reconnects and subscribes again.

The missed event is not replayed after reconnection. Redis does not maintain subscriber offsets or a message history for pub/sub.

This is called at-most-once delivery behavior. Redis delivers a message to active subscribers, but it does not guarantee that an offline subscriber receives it later.

Kafka solves a different problem. Kafka stores records in topics and uses consumer groups to track consumption progress through committed offsets. A consumer group can resume processing from its committed position. Redis pub/sub has no equivalent replay mechanism.

The worker already consumes order events from Kafka. For realtime delivery, it uses a separate consumer group named realtime on the existing order-events topic. This gives the realtime consumer its own consumption progress rather than sharing offsets with the notifier consumer group.

Keep the distinction between the two systems clear:

ComponentResponsibility
KafkaStores order events and tracks consumer progress.
WorkerReads order events and publishes customer notifications.
Redis pub/subDistributes notifications to active API subscriptions.
WebSocket hubDelivers notifications to local customer connections.

The worker publishes the notification after identifying the customer associated with the order event. The event itself does not replace the persisted order transition.

MySQL as the source of truth

Losing a notification must not mean losing an order update.

MySQL stores the authoritative order state. The order state machine governs transitions such as ACCEPT, START_PREP and MARK_READY. When a transition succeeds, the resulting state remains persisted independently of Redis notification delivery.

Redis pub/sub only tells connected customers that something has changed.

Consider an order that moves to the accepted state:

  1. The restaurant sends the ACCEPT event.
  2. The API processes the transition and persists the new order state.
  3. The worker reads the corresponding order event from Kafka.
  4. The worker publishes the customer notification to user:42.
  5. An API instance forwards the notification to the customer's WebSocket connection.

Suppose the notification is lost between steps 3 and 5. The order is still accepted in MySQL.

When the customer reconnects or refreshes the order screen, the app can fetch the current order state from the API. The API reads MySQL and returns the latest state.

The notification was lost, but the business operation was not.

This distinction lets you use Redis pub/sub for realtime updates without making it responsible for durable order processing.

Fan-out across API instances

Every API instance maintains its own in-memory WebSocket hub. The hub knows about connections registered in that particular process. It cannot directly access another instance's connections.

Suppose your backend has three API instances:

  • Instance A has an active connection for customer 42.
  • Instance B has an active connection for customer 87.
  • Instance C has no connection for either customer.

The worker processes an order event belonging to customer 42 and publishes it to user:42.

All three API instances receive the message because they subscribe to the user:* pattern. Each instance then passes the message to its local hub.

The result is:

API instanceLocal connection for customer 42Result
AYesSends the event.
BNoHas no matching connection.
CNoHas no matching connection.

Only instance A delivers the message over a WebSocket.

This architecture is pub/sub fan-out across instances. One published message reaches multiple subscribing processes. Each process independently determines whether its local hub has the intended recipient.

Redis and the hub have separate responsibilities:

  • Redis distributes messages between processes.
  • The hub routes messages to connections inside one process.

The subscriber does not need to know how a WebSocket is written to or how a connection is managed. It only needs to identify the target user and pass the payload to the hub.

One subscription per API process

A common mistake is creating a Redis subscription whenever a customer establishes a WebSocket connection.

Imagine an API instance with 5,000 active WebSocket connections. If every connection creates its own PSubscribe, the process creates 5,000 Redis subscriptions listening for the same category of messages.

That work is unnecessary. Every connection on the instance can share one process-level subscription.

The process creates a pattern subscription during startup:

go
sub := client.PSubscribe(ctx, "user:*")
defer sub.Close()

The application reads messages from the subscription's channel and passes them to the local hub. This work runs in one background Goroutines for the lifetime of the API process.

The responsibilities remain separate:

  1. API startup initializes Redis and the WebSocket hub.
  2. The process starts its Redis subscriber.
  3. The subscriber reads matching messages.
  4. Each message is routed to the local hub.
  5. The hub handles delivery to the appropriate connection.
  6. API shutdown cancels the subscriber and waits for it to exit.

This means the subscription belongs to the API process, not to an individual WebSocket connection.

Cancellation and subscription lifecycle

A Redis subscription is a long-running operation. It needs a clear shutdown path.

The application should pass its process context to PSubscribe. When the process begins graceful shutdown, it cancels that context. The subscriber can then stop reading messages and close the Redis subscription.

Go's select statement lets the subscriber wait for either cancellation or an incoming message:

go
select {
case <-ctx.Done():
    return nil

case msg, ok := <-messages:
    if !ok {
        return nil
    }
    // Validate and forward the message.
}

The ctx.Done() channel becomes ready when the context is cancelled. This gives the background task a way to exit even when no Redis messages are arriving.

The ok value matters too. A receive from a closed channel returns the zero value and false. Do not treat that zero value as a real Redis message.

The Redis subscription should be closed before the subscriber returns. A deferred Close is useful because it runs whether the function exits through cancellation or another return path.

The application should also manage the goroutine's lifetime. Starting a background task does not mean the application can forget about it. During shutdown, cancel the context and wait for the task to finish before closing resources it depends on.

The event bridge

The worker and the API instances have different responsibilities. The worker knows which customer owns an order event, but it does not know which API instance owns that customer's connection. Redis pub/sub connects those two parts of the system.

The next exercise, Per-user order event bridge, brings these ideas together. You will publish events to customer-specific channels, subscribe to user:* in each API process, and forward valid messages through the existing WebSocket hub.

Pay particular attention to channel parsing and cancellation. Pattern matching accepts malformed suffixes, and a process-level subscription must stop when the API shuts down. The customer app can then use socket-based updates instead of its previous 10-second polling interval.

Check your understanding

Question 1 of 4

API instance A has a WebSocket connection for customer 42. API instance B has no connection for that customer. Both instances subscribe to user:*. The worker publishes an event to user:42. What happens?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from.

Finished Lesson 5.4?