Programming Search⌘K

Patterncore

Message Channel

Also called Message Channel pattern, messaging channel, named channel, message destination.

A message channel is a named path in a messaging system. One program writes messages to it and other programs read them, so the sender knows the name of the channel, not the receiver.

Family
integration
Intent
Connect two programs through a named channel in a messaging system, so that one program writes messages to the channel and the other reads them from it.
Also called
queue, topic, destination, exchange

Intent

Connect the programs through a named channel, "where one application writes information to the channel and the other one reads that information from the channel".1 The sender knows the name of the channel. It does not know which program reads it, or when.

Problem

A shop program takes orders, and a warehouse program packs them. The two programs run on different computers, are written by different teams, and stop and start at different times. The question that the pattern answers is: "How does one application communicate with another using messaging?"1

The forces are these. The shop must not wait for the warehouse: "Sending a message does not require both systems to be up and ready at the same time."2 The shop must not need the address of the warehouse, because the warehouse can move, or become three programs. And the warehouse must get only the messages that it can use, not every message in the system.

A direct call, such as an HTTP request from the shop to the warehouse, fails all three. It needs both programs to run at the same time, it needs the address, and it carries no type of message other than the one that the call defines.

Solution

The messaging system keeps a set of named channels. A sender writes each message to the channel for that kind of message. A receiver reads from the channels for the kinds of messages that it wants. The channel holds a message until a receiver takes it.

  shop ----send----> [ orders.new       ] ----receive----> warehouse
  shop ----send----> [ orders.cancelled ] ----receive----> billing
                     messaging system: named channels

The participants are the sender, the receiver, the channel and the messaging system that keeps the channels. A broker such as RabbitMQ, a JMS provider, Azure Service Bus or Kafka is the messaging system. The names differ: a queue or a topic in JMS and Service Bus,34 an exchange and its queues in RabbitMQ,5 and a topic in Kafka.6

The following program shows the idea without a broker. A deque is one channel. The shop sends three messages while no receiver runs, and the warehouse reads its channel later. The message on the other channel stays where it is. A send to a name that does not exist fails.

from collections import deque


class Broker:
    """A messaging system with named channels. Each channel keeps its messages in order."""

    def __init__(self, *names):
        self.channels = {name: deque() for name in names}

    def send(self, channel, message):
        if channel not in self.channels:
            raise LookupError(f"no channel named {channel}")
        self.channels[channel].append(message)

    def receive(self, channel):
        waiting = self.channels[channel]
        return waiting.popleft() if waiting else None


broker = Broker("orders.new", "orders.cancelled")

# The shop sends. The warehouse program is not running yet.
broker.send("orders.new", {"order": 1, "sku": "A-7", "qty": 2})
broker.send("orders.new", {"order": 2, "sku": "B-1", "qty": 1})
broker.send("orders.cancelled", {"order": 1})
print("waiting:", {name: len(q) for name, q in broker.channels.items()})

# Later, the warehouse starts. It reads only the channel that it knows.
while (message := broker.receive("orders.new")) is not None:
    print("warehouse got", message)
print("waiting:", {name: len(q) for name, q in broker.channels.items()})

try:
    broker.send("order.new", {"order": 3})
except LookupError as e:
    print("send failed:", e)
Output
waiting: {'orders.new': 2, 'orders.cancelled': 1}
warehouse got {'order': 1, 'sku': 'A-7', 'qty': 2}
warehouse got {'order': 2, 'sku': 'B-1', 'qty': 1}
waiting: {'orders.new': 0, 'orders.cancelled': 1}
send failed: no channel named order.new

Hohpe and Woolf list the decisions that a set of channels must make.7 These are the main ones:

  • One receiver or all receivers. A Point-to-Point Channel gives each message to one receiver. A Publish-Subscribe Channel gives a copy to each subscriber.
  • One type of data for each channel. The receiver must know the structure of the message. If each channel carries one type of message, the name of the channel tells the receiver the type. This is the main reason why a system has many channels.7 The book calls it Datatype Channel.
  • Messages that a receiver cannot use, or that cannot be delivered. A receiver puts a message that it does not understand on an Invalid Message Channel. The messaging system puts a message that it cannot deliver on a Dead Letter Channel.7
  • A crash of the messaging system. If the messages must survive a crash, the channel must keep them on disk. The book calls this Guaranteed Delivery.7

A channel is in practice one-way: a program that reads the channel that it writes would read its own messages. Two programs that talk in both directions use two channels, as in Request-Reply.7 And the set of channels is usually fixed when the system is designed. The book gives two exceptions: a reply channel that a requester makes for its replies, and hierarchical channels, where a receiver subscribes to a parent and gets the messages of new child channels.7

Example

Each example file makes two channels, orders and payments, with the queue or channel type of its language. The shop and the bank send three messages before any receiver runs. Then a warehouse thread reads orders and an accounting thread reads payments, and each one sees only its own channel. The last line sends to the name order, which is not a channel, and gets an error.

The examples use the queues of the standard libraries in place of a broker, so that they run with no server. Each language has a type for the job. Go has channels in the language.8 .NET has System.Threading.Channels, which the documentation calls "an implementation of the producer/consumer conceptual programming model".9 Java has BlockingQueue, and its documentation says that implementations "are designed to be used primarily for producer-consumer queues".10 Python has the queue module.11 A broker client keeps the same shape: a send to a named destination and a receive from one.

PythonGitHub
import queue
import threading


class Channels:
    """Named channels. Senders and receivers share only the names."""

    def __init__(self, *names):
        self._channels = {name: queue.Queue() for name in names}

    def send(self, name, message):
        if name not in self._channels:
            raise LookupError(f"no channel named {name}")
        self._channels[name].put(message)

    def receive(self, name, timeout=0.1):
        try:
            return self._channels[name].get(timeout=timeout)
        except queue.Empty:
            return None

    def depth(self, name):
        return self._channels[name].qsize()


def drain(channels, name, who):
    while (message := channels.receive(name)) is not None:
        print(f"{who}: {message}")


channels = Channels("orders", "payments")
channels.send("orders", "order 1: 2 x A-7")
channels.send("orders", "order 2: 1 x B-1")
channels.send("payments", "payment for order 1: 30.00")
print(f"waiting: orders={channels.depth('orders')} payments={channels.depth('payments')}")

for name, who in [("orders", "warehouse"), ("payments", "accounting")]:
    receiver = threading.Thread(target=drain, args=(channels, name, who))
    receiver.start()
    receiver.join()

try:
    channels.send("order", "order 3: 1 x C-2")
except LookupError as e:
    print(f"error: {e}")
Output
waiting: orders=2 payments=1
warehouse: order 1: 2 x A-7
warehouse: order 2: 1 x B-1
accounting: payment for order 1: 30.00
error: no channel named order
  • Verdict: stdlib. The queue module gives a thread-safe FIFO queue for each channel, and Channels maps the names to the queues.
  • receive waits 0.1 seconds and then returns None, so a receiver can stop when its channel is empty. A broker client, such as Pika for RabbitMQ, gives the same two calls: publish to a name, and consume from a name.
  • The queues are in memory. When the process stops, the messages are gone, and a broker keeps them in its own process or on disk.
JavaGitHub
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Main {
    // Named channels. Senders and receivers share only the names.
    static final class Channels {
        private final Map<String, BlockingQueue<String>> byName = new LinkedHashMap<>();

        Channels(String... names) {
            for (String n : names) {
                byName.put(n, new LinkedBlockingQueue<>());
            }
        }

        void send(String name, String message) {
            BlockingQueue<String> q = byName.get(name);
            if (q == null) {
                throw new IllegalArgumentException("no channel named " + name);
            }
            q.add(message);
        }

        String receive(String name, long millis) throws InterruptedException {
            return byName.get(name).poll(millis, TimeUnit.MILLISECONDS);
        }

        int depth(String name) {
            return byName.get(name).size();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Channels channels = new Channels("orders", "payments");
        channels.send("orders", "order 1: 2 x A-7");
        channels.send("orders", "order 2: 1 x B-1");
        channels.send("payments", "payment for order 1: 30.00");
        System.out.printf("waiting: orders=%d payments=%d%n", channels.depth("orders"), channels.depth("payments"));

        String[][] receivers = {{"orders", "warehouse"}, {"payments", "accounting"}};
        for (String[] r : receivers) {
            Thread t = new Thread(() -> {
                try {
                    String m;
                    while ((m = channels.receive(r[0], 100)) != null) {
                        System.out.println(r[1] + ": " + m);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            t.start();
            t.join();
        }

        try {
            channels.send("order", "order 3: 1 x C-2");
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}
Output
waiting: orders=2 payments=1
warehouse: order 1: 2 x A-7
warehouse: order 2: 1 x B-1
accounting: payment for order 1: 30.00
error: no channel named order
  • Verdict: stdlib. LinkedBlockingQueue is a thread-safe queue, and poll with a timeout lets a receiver stop when its channel is empty.
  • send throws IllegalArgumentException for an unknown name. In Jakarta Messaging, a client gets a Queue or Topic object for the name, and then a producer or consumer for it.
  • The map is a LinkedHashMap only so that the order of the channels is stable. The receivers do not depend on it.
using System.Threading.Channels;

var channels = new NamedChannels("orders", "payments");
channels.Send("orders", "order 1: 2 x A-7");
channels.Send("orders", "order 2: 1 x B-1");
channels.Send("payments", "payment for order 1: 30.00");
int orders = channels.Depth("orders"), payments = channels.Depth("payments");
Console.WriteLine($"waiting: orders={orders} payments={payments}");
channels.Complete();

foreach (var (name, who) in new[] { ("orders", "warehouse"), ("payments", "accounting") })
{
    await Task.Run(async () =>
    {
        await foreach (var m in channels.Reader(name).ReadAllAsync())
        {
            Console.WriteLine($"{who}: {m}");
        }
    });
}

try
{
    channels.Send("order", "order 3: 1 x C-2");
}
catch (KeyNotFoundException e)
{
    Console.WriteLine($"error: {e.Message}");
}

// Named channels. Senders and receivers share only the names.
sealed class NamedChannels
{
    private readonly Dictionary<string, Channel<string>> _byName = new();

    public NamedChannels(params string[] names)
    {
        foreach (var n in names)
        {
            _byName[n] = Channel.CreateUnbounded<string>();
        }
    }

    private Channel<string> Get(string name) =>
        _byName.TryGetValue(name, out var ch) ? ch : throw new KeyNotFoundException($"no channel named {name}");

    public void Send(string name, string message)
    {
        if (!Get(name).Writer.TryWrite(message))
        {
            throw new InvalidOperationException($"channel {name} is closed");
        }
    }

    public ChannelReader<string> Reader(string name) => Get(name).Reader;

    public int Depth(string name) => Get(name).Reader.Count;

    public void Complete()
    {
        foreach (var ch in _byName.Values)
        {
            ch.Writer.Complete();
        }
    }
}
Output
waiting: orders=2 payments=1
warehouse: order 1: 2 x A-7
warehouse: order 2: 1 x B-1
accounting: payment for order 1: 30.00
error: no channel named order
  • Verdict: stdlib. Channel.CreateUnbounded<string>() from System.Threading.Channels makes a channel with a writer side and a reader side, and NamedChannels maps the names to the channels.
  • Complete tells the readers that no more messages will come, and ReadAllAsync then ends. A broker client, such as the Azure Service Bus client, has a sender and a receiver for each queue or topic name in the same way.
  • Reader.Count is available because an unbounded channel can count its items.
package main

import (
	"fmt"
	"sync"
)

// Channels maps a name to a buffered Go channel.
// Senders and receivers share only the names.
type Channels struct{ byName map[string]chan string }

func NewChannels(capacity int, names ...string) *Channels {
	c := &Channels{byName: map[string]chan string{}}
	for _, n := range names {
		c.byName[n] = make(chan string, capacity)
	}
	return c
}

func (c *Channels) Send(name, message string) error {
	ch, ok := c.byName[name]
	if !ok {
		return fmt.Errorf("no channel named %s", name)
	}
	ch <- message
	return nil
}

func (c *Channels) Depth(name string) int { return len(c.byName[name]) }

// Close tells the receivers that no more messages will come.
func (c *Channels) Close() {
	for _, ch := range c.byName {
		close(ch)
	}
}

func main() {
	channels := NewChannels(10, "orders", "payments")
	channels.Send("orders", "order 1: 2 x A-7")
	channels.Send("orders", "order 2: 1 x B-1")
	channels.Send("payments", "payment for order 1: 30.00")
	fmt.Printf("waiting: orders=%d payments=%d\n", channels.Depth("orders"), channels.Depth("payments"))
	channels.Close()

	for _, r := range []struct{ name, who string }{{"orders", "warehouse"}, {"payments", "accounting"}} {
		var wg sync.WaitGroup
		wg.Add(1)
		go func() {
			defer wg.Done()
			for m := range channels.byName[r.name] {
				fmt.Printf("%s: %s\n", r.who, m)
			}
		}()
		wg.Wait()
	}

	if err := channels.Send("order", "order 3: 1 x C-2"); err != nil {
		fmt.Println("error:", err)
	}
}
Output
waiting: orders=2 payments=1
warehouse: order 1: 2 x A-7
warehouse: order 2: 1 x B-1
accounting: payment for order 1: 30.00
error: no channel named order
  • Verdict: native. A Go channel is a typed channel between goroutines, and Channels gives each one a name. The type chan string is the Datatype Channel idea in the type system: a channel carries values of one type.
  • The channels have a buffer of 10, so the sends do not block before a receiver runs. With no buffer, a send waits until a receiver is ready.
  • Close tells the receivers that no more messages will come, and the range loops then end. A broker channel does not close in this way: a consumer waits for the next message, or stops on a timeout.

Consequences

Benefits.

  • The sender and the receiver do not need to know each other. They agree on the name of the channel and the format of the messages. A new receiver can read the channel with no change to the sender.
  • The sender and the receiver do not need to run at the same time. The channel holds the messages. Jakarta Messaging says that a queue "is always available to hold messages sent to it, whether or not the client that consumes its messages is active".3
  • The name of the channel tells the receiver what it gets. With one type of message for each channel, the receiver does not test each message to find out what it is.

Liabilities.

  • The channels are a design that all programs share. A channel name is an interface. A change of a name or a format must reach all the programs that use it, as with an API.
  • A wrong name can lose messages without an error. The program above fails on an unknown name, but a broker may not. In RabbitMQ, a producer sends to an exchange, not to a queue, and a message to an exchange with no bound queue is lost. The RabbitMQ tutorial says that "The messages will be lost if no queue is bound to the exchange yet".5 Declare the channels before the programs start, and watch the channels for messages that nobody reads.
  • Each channel costs something. Jakarta Messaging says that "creating and maintaining each queue is somewhat costly", and that most queues are made by an administrator.3 Many short-lived channels are a load on the broker.
  • The communication is asynchronous. The sender does not get an answer, or an error from the receiver. A reply needs a second channel, and a failure in the receiver needs a Dead Letter Channel or an alert.

When not to use it

When the caller needs the answer now. A price check on a web page waits for the answer. A direct call with a timeout is simpler than a request channel, a reply channel and a correlation identifier.

Inside one program. Two parts of one program can call each other. A channel between them adds a copy of each message, a thread or task to read it, and an order of events that is harder to follow. A queue in memory inside one program is the Producer-consumer pattern, not a messaging system: when the program stops, the messages are gone.

One channel for all messages. A single channel that carries every kind of message makes each receiver read, test and skip messages that it does not want. It is a sign that the design of the channels has not started.

Point-to-Point Channel and Publish-Subscribe Channel. The two kinds of channel: one receiver for each message, or a copy for each subscriber.7 See Point-to-Point Channel and Publish-Subscribe Channel.

Datatype Channel. One type of message for each channel.7

Invalid Message Channel and Dead Letter Channel. Channels for the messages that a receiver cannot use, and for the messages that the system cannot deliver.7

The other root patterns. In the chapter on messaging systems, Message Channel comes first, and Message, Pipes and Filters, Message Router, Message Translator and Message Endpoint follow it.12 The book gives the full text of each one.13

Channels in a language. Go channels, .NET channels and the Channel of other languages are channels between the threads or tasks of one program, with no names and no broker. See also Message passing and the Actor model, where each actor has a mailbox.

Work queues. A channel whose messages are tasks for a pool of workers. See Work queue.

Known uses

  • Spring Framework: MessageChannel.java at v6.2.10 is the interface for a channel inside a Spring application. Its comment says that it "Defines methods for sending messages", and send returns false when a message cannot be sent for a reason that is not fatal.14 Spring Integration builds its channels on it, for example QueueChannel and PublishSubscribeChannel.15
  • Jakarta Messaging calls a channel a destination: a Queue or a Topic.3
  • Kafka calls a channel a topic, and its documentation says that "Topics in Kafka are always multi-producer and multi-subscriber".6

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Message Channel (problem and solution under CC BY), problem and solution statements; pattern text
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Messaging, problem and solution statements
  3. Jakarta Messaging 3.1 specification, 4.1.2 Queue semantics; 4.1.8 Reliability; 4.2.2 Topic semantics
  4. Azure Service Bus queues, topics, and subscriptions, Choose between queues and topics; Queues
  5. RabbitMQ tutorial 3, Publish/Subscribe (Python), Exchanges; Temporary queues; Putting it all together
  6. Apache Kafka 4.1.0 documentation source, introduction.html, Main Concepts and Terminology
  7. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Introduction to Messaging Channels, Message Channel Themes; Message Channel Decisions
  8. The Go Programming Language Specification, Channel types, Channel types
  9. .NET documentation, System.Threading.Channels library, Producer/consumer conceptual programming model; Unbounded creation strategies
  10. Java SE 21 API, Interface BlockingQueue, interface description
  11. The Python Standard Library, queue, Python 3.14, module introduction
  12. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Table of Contents, Messaging Systems
  13. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 3, Messaging Systems, Message Channel; Chapter 4, Messaging Channels
  14. Spring Framework 6.2.10 source, MessageChannel.java, interface MessageChannel, lines 19 to 58
  15. Spring Integration reference, Message Channel Implementations, PublishSubscribeChannel; QueueChannel; DirectChannel

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/DABD4B/text.yaml