Publish/Subscribe

Implement real-time messaging in BoxLang applications using Redis Publish/Subscribe.

What is Pub/Sub?

Redis Pub/Sub Architecture

The Redis module provides native messaging capabilities through Redis Publish/Subscribe constructs. This allows your BoxLang applications to implement real-time messaging and event-driven architectures using Redis as the message broker.

Redis Pub/Sub implements the Publish/Subscribe messaging paradigm. This decoupling of publishers and subscribers can allow for greater scalability and a more dynamic network topology.

How it works:

  1. Subscribers express interest in one or more channels (literal channels or pattern channels)

  2. Publishers send messages into channels

  3. Redis pushes these messages to all subscribers that have matched the channel

📋 Pub/Sub BIFs Overview

The module provides two main functions for implementing pub/sub patterns:

Function
Parameters
Returns
Description

redisPublish()

channel, message, cacheName

numeric

Publishes a message to a Redis channel. Returns the number of subscribers that received the message.

redisSubscribe()

subscriber, channels, cacheName

struct

Subscribes to one or more channels using a closure/lambda or listener class. Returns a struct with future and subscriber keys.

📤 Publishing Messages

Use redisPublish() to send messages to a Redis channel. The function returns the number of subscribers that received the message.

Function Signature

Parameters

  • channel - The Redis channel name to publish to

  • message - The message content to send (will be serialized)

  • cacheName - The name of the Redis cache connection to use (default: "default")

Publishing Example

Use Cases for Publishing

  • System notifications - Broadcast status updates

  • Real-time updates - Push data changes to connected clients

  • Event broadcasting - Notify multiple services of events

  • Cache invalidation - Signal cache updates across servers

  • Workflow triggers - Initiate processes across distributed systems

📥 Subscribing to Channels

Use redisSubscribe() to listen for messages on Redis channels. You can subscribe using either a closure/lambda or a listener class.

Function Signature

Parameters

  • subscriber - A closure/lambda function or listener class instance

  • channels - A single channel name (string) or array of channel names

  • cacheName - The name of the Redis cache connection to use (default: "default")

Return Value

Returns a struct with two keys:

  • future - A BoxFuture that is running your subscriber asynchronously

  • subscriber - The Java Redis subscriber object for inspection or unsubscribing

Subscribing with a Closure

Subscribing with a Listener Class

For more complex subscription handling, create a listener class:

Unsubscribing

To stop receiving messages, use the unsubscribe() method on the subscriber:

🎧 Subscriber Listener Class

When using a class as a subscriber, implement one or more of the following callback methods. Each method is optional and will only be called if defined.

Complete Listener Class Example

Listener Method Reference

Method
Parameters
Description
When Called

onMessage()

channel, message

Handles messages from subscribed channels

When a message arrives on a literal channel subscription

onPMessage()

pattern, channel, message

Handles messages from pattern subscriptions

When a message arrives on a pattern-matched channel

onSubscribe()

channel, subscribedChannels

Confirms channel subscription

After successfully subscribing to a channel

onUnsubscribe()

channel, subscribedChannels

Confirms channel unsubscription

After unsubscribing from a channel

onPSubscribe()

pattern, subscribedChannels

Confirms pattern subscription

After successfully subscribing to a pattern

onPUnsubscribe()

pattern, subscribedChannels

Confirms pattern unsubscription

After unsubscribing from a pattern

💡 Pub/Sub Best Practices

Message Design

  • Keep messages small - Pub/sub is optimized for many small messages

  • Use JSON - Serialize complex data structures as JSON for interoperability

  • Include metadata - Add timestamps, message IDs, or version info

  • Document message formats - Maintain a schema for each channel

Channel Naming

  • Use namespaces - Prefix channels by domain: app:notifications, system:alerts

  • Be descriptive - Channel names should indicate purpose: user:login, order:created

  • Avoid special characters - Stick to alphanumeric and basic punctuation

  • Use hierarchy - Structure channels logically: analytics:users:signup

Subscriber Management

  • Handle errors gracefully - Wrap message processing in try/catch

  • Avoid blocking operations - Process messages quickly or queue for async processing

  • Implement reconnection logic - Handle connection failures

  • Monitor subscription health - Track message counts and processing times

Performance Considerations

  • Pub/sub is fire-and-forget - Messages are not persisted; offline subscribers miss messages

  • No delivery guarantees - Unlike queues, pub/sub doesn't guarantee delivery

  • Use streams for reliability - Consider Redis Streams for persistent messaging

  • Limit subscribers - Too many subscribers can impact Redis performance

  • Consider message size - Large messages can slow down the pub/sub system

🔧 Complete Pub/Sub Example

Here's a complete example demonstrating publishing and subscribing in a real-world scenario:

🎯 Use Cases

Real-Time Notifications

Broadcast system notifications, user alerts, or status updates across multiple application servers or clients.

Cache Invalidation

Signal cache updates across a distributed application when data changes:

Event-Driven Architecture

Implement loosely coupled microservices that react to events:

Real-Time Monitoring

Push metrics and monitoring data to dashboards:

Chat Applications

Build real-time chat or messaging features:

Last updated

Was this helpful?