Programming Search⌘K

Patterncore

Publish-Subscribe Channel

Also called Publish-Subscribe Channel pattern, pub/sub channel, pub-sub, topic, fan-out channel.

A publish-subscribe channel gives a copy of each message to each of its subscribers. The publisher sends an event once, and each program that subscribed to the channel gets it.

Family
integration
Intent
Send the event on a channel that gives a copy of each message to each subscriber, so that all the interested programs get it and the publisher does not know them.
Also called
topic, fanout exchange, event bus

Intent

Send the event on a Publish-Subscribe Channel, "which delivers a copy of a particular event to each receiver".1 The publisher sends once. Each program that subscribed gets its own copy.

Problem

The shop places an order. Billing must charge the card, the email program must send a receipt, and the stock program must reserve the items. Next year, an analytics program will want the same event. The question is: "How can the sender broadcast an event to all interested receivers?"1

The forces are these. The shop must not know the list of programs that react to an order, because the list changes. Each program must get every order, not a share of them. And a slow or stopped program must not stop the others.

A Point-to-Point Channel gives each message to one receiver, so billing would get some orders and email the others. A separate queue for each program, filled by the shop, works, but the shop then knows each program and must change for each new one.

Solution

The channel has one input and one output for each subscriber. A message that a publisher sends to the input is copied to each output. Each output has one subscriber, which consumes its copy once.1

                                 +--> [ copy ] --> billing
  shop --publish--> ( orders ) --+--> [ copy ] --> email
                      topic      +--> [ copy ] --> stock

The participants are the publisher, the channel, the subscriptions and the subscribers. In Jakarta Messaging, the channel is a topic, and a subscription "will receive a copy of every message that is sent to the topic after the subscription is created".2 Each copy is a separate message: "acknowledging one does not acknowledge any other".2 Azure Service Bus describes a topic subscription as a virtual queue that receives copies of the messages that are sent to the topic.3 In RabbitMQ, the publisher sends to a fanout exchange, which "just broadcasts all the messages it receives to all the queues it knows", and each subscriber reads its own queue.4

After the subscription, not before. A subscriber gets only the messages that are published while its subscription exists. A non-durable subscription exists only while it has an active consumer.2 A durable subscription "is persisted and continues to accumulate messages until explicitly deleted, even if there are no consumer objects consuming messages from it".2 The book calls a subscriber with a durable subscription a Durable Subscriber.5 The following program shows the difference. billing and audit are durable, and email is not. audit and email disconnect while the shop publishes order 2.

from collections import deque


class Topic:
    """Each subscription gets a copy of each message that is published after it is made."""

    def __init__(self):
        self.subscriptions = {}  # name -> (durable, messages)

    def subscribe(self, name, durable=False):
        self.subscriptions.setdefault(name, (durable, deque()))

    def disconnect(self, name):
        durable, _ = self.subscriptions[name]
        if not durable:
            del self.subscriptions[name]  # the copies that wait for it are gone too

    def publish(self, message):
        for _, messages in self.subscriptions.values():
            messages.append(message)
        return len(self.subscriptions)

    def receive_all(self, name):
        _, messages = self.subscriptions[name]
        out = list(messages)
        messages.clear()
        return out


topic = Topic()
topic.subscribe("billing", durable=True)
topic.subscribe("audit", durable=True)
topic.subscribe("email")
print("order 1: copies", topic.publish("order 1"))

topic.disconnect("audit")
topic.disconnect("email")
print("order 2: copies", topic.publish("order 2"))

topic.subscribe("audit", durable=True)  # the same durable subscription again
topic.subscribe("email")                # a new non-durable subscription
topic.subscribe("analytics")            # a new subscriber
print("order 3: copies", topic.publish("order 3"))

for name in ["billing", "audit", "email", "analytics"]:
    print(f"{name:9}  {topic.receive_all(name)}")
Output
order 1: copies 3
order 2: copies 2
order 3: copies 4
billing    ['order 1', 'order 2', 'order 3']
audit      ['order 1', 'order 2', 'order 3']
email      ['order 3']
analytics  ['order 3']

audit gets all three orders, because its durable subscription kept order 2 while it was away. email loses order 1, which waited for it when it disconnected, and order 2, which was published while it had no subscription. analytics starts with order 3, because a subscription does not see the past. With no subscription at all, a message is lost: the RabbitMQ tutorial says that "The messages will be lost if no queue is bound to the exchange yet".4

Example

Each example file makes a topic with three subscribers, billing, email and stock. Each subscriber has its own queue or channel and its own thread or task. The shop publishes three events, and the topic puts a copy of each event in each queue. Each subscriber gets all three events in the order of publication, and the program counts nine copies.

The examples build the topic from one standard queue for each subscriber, because that is the structure of a broker topic: a fanout exchange with a queue for each subscriber in RabbitMQ, or a topic with subscriptions in Service Bus.43 The publisher puts the copies in the queues and does not wait for the subscribers.

PythonGitHub
import queue
import threading

STOP = None


class Topic:
    """A publish-subscribe channel: one queue for each subscriber."""

    def __init__(self):
        self._queues = {}

    def subscribe(self, name):
        self._queues[name] = queue.Queue()
        return self._queues[name]

    def publish(self, event):
        for q in self._queues.values():
            q.put(event)  # each subscriber gets its own copy
        return len(self._queues)


def subscriber(inbox, seen):
    while (event := inbox.get()) is not STOP:
        seen.append(event)


topic = Topic()
seen = {name: [] for name in ["billing", "email", "stock"]}
threads = [threading.Thread(target=subscriber, args=(topic.subscribe(name), seen[name])) for name in seen]
for t in threads:
    t.start()

copies = sum(topic.publish(f"order {n} placed") for n in range(1, 4))
topic.publish(STOP)
for t in threads:
    t.join()

for name, events in seen.items():
    print(f"{name}: {', '.join(events)}")
print("copies sent:", copies)
Output
billing: order 1 placed, order 2 placed, order 3 placed
email: order 1 placed, order 2 placed, order 3 placed
stock: order 1 placed, order 2 placed, order 3 placed
copies sent: 9
  • Verdict: stdlib. Topic keeps one queue.Queue for each subscriber, and publish puts the event in each queue. Each subscriber thread reads only its own queue.
  • STOP is published like an event, so each subscriber gets one copy of it and ends.
  • With RabbitMQ and Pika, the same program declares a fanout exchange, and each subscriber binds its own queue to it. The broker makes the copies.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {
    static final String STOP = "stop";

    // A publish-subscribe channel: one queue for each subscriber.
    static final class Topic {
        private final Map<String, BlockingQueue<String>> queues = new LinkedHashMap<>();

        BlockingQueue<String> subscribe(String name) {
            BlockingQueue<String> q = new LinkedBlockingQueue<>();
            queues.put(name, q);
            return q;
        }

        int publish(String event) {
            for (BlockingQueue<String> q : queues.values()) {
                q.add(event); // each subscriber gets its own copy
            }
            return queues.size();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Topic topic = new Topic();
        Map<String, List<String>> seen = new LinkedHashMap<>();
        List<Thread> threads = new ArrayList<>();
        for (String name : List.of("billing", "email", "stock")) {
            BlockingQueue<String> inbox = topic.subscribe(name);
            List<String> got = new ArrayList<>();
            seen.put(name, got);
            Thread t = new Thread(() -> {
                try {
                    for (String e = inbox.take(); !e.equals(STOP); e = inbox.take()) {
                        got.add(e);
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            });
            threads.add(t);
            t.start();
        }

        int copies = 0;
        for (int n = 1; n <= 3; n++) {
            copies += topic.publish("order " + n + " placed");
        }
        topic.publish(STOP);
        for (Thread t : threads) {
            t.join(); // join makes the list of each thread visible here
        }

        seen.forEach((name, events) -> System.out.println(name + ": " + String.join(", ", events)));
        System.out.println("copies sent: " + copies);
    }
}
Output
billing: order 1 placed, order 2 placed, order 3 placed
email: order 1 placed, order 2 placed, order 3 placed
stock: order 1 placed, order 2 placed, order 3 placed
copies sent: 9
  • Verdict: stdlib. Topic keeps one LinkedBlockingQueue for each subscriber, and publish adds the event to each.
  • Each thread fills its own list, and join makes the list visible to the main thread, so the lists need no lock.
  • With Jakarta Messaging, the program creates a consumer on a Topic for each subscriber, and the provider makes the copies. A durable subscription needs a name, for example with createDurableConsumer.
using System.Threading.Channels;

var topic = new Topic();
var names = new[] { "billing", "email", "stock" };
var readers = names.Select(name =>
{
    var inbox = topic.Subscribe(name);
    return Task.Run(async () =>
    {
        var got = new List<string>();
        await foreach (var e in inbox.ReadAllAsync())
        {
            got.Add(e);
        }
        return (name, got);
    });
}).ToArray();

var copies = 0;
for (var n = 1; n <= 3; n++)
{
    copies += topic.Publish($"order {n} placed");
}
topic.Complete();

foreach (var (name, got) in await Task.WhenAll(readers))
{
    Console.WriteLine($"{name}: {string.Join(", ", got)}");
}
Console.WriteLine($"copies sent: {copies}");

// A publish-subscribe channel: one channel for each subscriber.
sealed class Topic
{
    private readonly List<Channel<string>> _subs = new();

    public ChannelReader<string> Subscribe(string name)
    {
        var ch = Channel.CreateUnbounded<string>();
        _subs.Add(ch);
        return ch.Reader;
    }

    public int Publish(string e)
    {
        foreach (var ch in _subs)
        {
            ch.Writer.TryWrite(e); // each subscriber gets its own copy
        }
        return _subs.Count;
    }

    public void Complete()
    {
        foreach (var ch in _subs)
        {
            ch.Writer.Complete();
        }
    }
}
Output
billing: order 1 placed, order 2 placed, order 3 placed
email: order 1 placed, order 2 placed, order 3 placed
stock: order 1 placed, order 2 placed, order 3 placed
copies sent: 9
  • Verdict: stdlib. Topic keeps one unbounded Channel<string> for each subscriber, and Publish writes the event to each.
  • Each reader task returns its name and its list, and Task.WhenAll gives the results in the order of the tasks, so the output is stable.
  • With Azure Service Bus, the publisher sends to a topic, and each subscriber receives from its own subscription of the topic.
package main

import (
	"fmt"
	"strings"
	"sync"
)

// Topic is a publish-subscribe channel: one Go channel for each subscriber.
type Topic struct {
	names []string
	subs  map[string]chan string
}

func NewTopic() *Topic { return &Topic{subs: map[string]chan string{}} }

func (t *Topic) Subscribe(name string) <-chan string {
	ch := make(chan string, 16)
	t.names = append(t.names, name)
	t.subs[name] = ch
	return ch
}

// Publish sends a copy of the event to each subscriber and returns the number of copies.
func (t *Topic) Publish(event string) int {
	for _, ch := range t.subs {
		ch <- event
	}
	return len(t.subs)
}

func (t *Topic) Close() {
	for _, ch := range t.subs {
		close(ch)
	}
}

func main() {
	topic := NewTopic()
	seen := map[string][]string{}
	var mu sync.Mutex
	var wg sync.WaitGroup
	for _, name := range []string{"billing", "email", "stock"} {
		inbox := topic.Subscribe(name)
		wg.Add(1)
		go func() {
			defer wg.Done()
			var got []string
			for event := range inbox {
				got = append(got, event)
			}
			mu.Lock()
			seen[name] = got
			mu.Unlock()
		}()
	}

	copies := 0
	for n := 1; n <= 3; n++ {
		copies += topic.Publish(fmt.Sprintf("order %d placed", n))
	}
	topic.Close()
	wg.Wait()

	for _, name := range topic.names {
		fmt.Printf("%s: %s\n", name, strings.Join(seen[name], ", "))
	}
	fmt.Println("copies sent:", copies)
}
Output
billing: order 1 placed, order 2 placed, order 3 placed
email: order 1 placed, order 2 placed, order 3 placed
stock: order 1 placed, order 2 placed, order 3 placed
copies sent: 9
  • Verdict: idiom. Go has no broadcast channel. A value sent on a channel goes to one receiver, so Topic keeps one channel for each subscriber and sends a copy to each.
  • Each channel has a buffer of 16, so Publish does not wait for a slow subscriber until its buffer is full. A full buffer then blocks the publisher, which is the cost of a topic in memory with no broker.
  • topic.names keeps the order of subscription, because the order of a Go map is not specified.

Consequences

Benefits.

  • The publisher does not know the subscribers. A new subscriber subscribes, and the publisher does not change. With the topic as an intermediary, Jakarta Messaging says, "message publishers are kept independent of subscribers and vice versa".2
  • Each subscriber works at its own rate. Each copy waits in its own queue, so a slow subscriber does not slow the others.
  • Eavesdropping for debugging. The book notes that a publish-subscribe channel lets a program watch the traffic on a channel without a change to the flow of messages.1

Liabilities.

  • Copies cost storage. A message with ten subscriptions is stored and delivered ten times.
  • No subscriber, no message. A message that is published before a subscription exists is not delivered to it. Some systems keep messages for replay: Google Cloud Pub/Sub has topic retention, which lets a subscription "seek back in time and replay previously published messages".6 In Kafka, "events are not deleted after consumption", and a topic keeps them for the time that its configuration sets.7 A consumer "can deliberately rewind back to an old offset and re-consume data".8
  • No reply and no single owner. The publisher does not know who did the work, or if anybody did. An event that must be handled needs a subscriber that someone watches.
  • At-least-once and no order. By default, "Pub/Sub offers at-least-once delivery with no ordering guarantees on all subscription types".6 Each subscriber must accept duplicates and out-of-order events, or the system must give an order for each key.

When not to use it

For a command that must run once. A charge or a shipment is a command for one receiver. On a topic, each subscriber would run it. Use a Point-to-Point Channel.

When the publisher needs to know that the work was done. A topic gives no reply. Use a request and a reply, or a process manager that waits for the replies.

For a large audience with a long history. A new subscriber that needs all past events gets nothing from a plain topic. Use a log with replay, such as a Kafka topic, or a store of events.

Durable Subscriber. A subscriber whose subscription keeps the messages while it is offline.52

Competing consumers on a subscription. A subscription can have many consumers that share its copies. In Jakarta Messaging, a shared subscription gives each message in the subscription to only one consumer.2 Kafka does the same with consumer groups: each partition of a topic "is consumed by exactly one consumer within each subscribing consumer group at any given time".8 Google Cloud Pub/Sub has topics for publish-subscribe and subscriptions for competing consumers.1

Message filters on subscriptions. A subscription can take only some messages. In Jakarta Messaging, a subscription with a message selector gets only the messages whose properties match it.2

Observer, inside one program. The Observer pattern gives the same one-to-many shape with method calls in one process, and an Event Aggregator gives one place to publish events. A publish-subscribe channel adds a broker, queues and copies that survive the publisher.

Point-to-Point Channel. The other kind of channel.9 See Point-to-Point Channel.

Known uses

  • Spring Integration: PublishSubscribeChannel.java at v6.5.1 is "A channel that sends Messages to each of its subscribers".10 The reference says that it broadcasts any message sent to it to all of its subscribed handlers.11
  • RabbitMQ fanout exchanges, with a temporary queue for each subscriber.4
  • Azure Service Bus topics and subscriptions.3
  • Kafka topics, which are "always multi-producer and multi-subscriber".7

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Publish-Subscribe Channel (problem and solution under CC BY), problem and solution statements; pattern text; Example, Google Cloud Pub/Sub
  2. Jakarta Messaging 3.1 specification, 4.2.1 Overview; 4.2.2 Topic semantics; 8.3 Subscriptions
  3. Azure Service Bus queues, topics, and subscriptions, Choose between queues and topics; Topics and subscriptions
  4. RabbitMQ tutorial 3, Publish/Subscribe (Python), Exchanges; Temporary queues; Bindings; Putting it all together
  5. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 4, Messaging Channels, Publish-Subscribe Channel; Chapter 10, Messaging Endpoints, Durable Subscriber
  6. Google Cloud Pub/Sub documentation, Subscription overview, Default subscription properties; topic retention
  7. Apache Kafka 4.1.0 documentation source, introduction.html, Main Concepts and Terminology
  8. Apache Kafka 4.1.0 documentation source, design.html, The Consumer, Consumer Position
  9. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Messaging Channels, Message Channel Decisions, One-to-one or one-to-many
  10. Spring Integration 6.5.1 source, PublishSubscribeChannel.java, class PublishSubscribeChannel, lines 29 to 38
  11. Spring Integration reference, Message Channel Implementations, PublishSubscribeChannel

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8TWJAY/text.yaml