The publish-subscribe pattern means that a message sent by a producer will be received by multiple consumers. Since a message will be consumed and processed by multiple consumers, it is also called the broadcast pattern or one-to-many pattern.

Note: Because RabbitMQ implements the publish-subscribe pattern using the fanout exchange type, it is also called the fanout pattern.

Architecture Diagram

fanout pattern

Explanation:

  • P represents the producer, C1 and C2 represent consumers, red represents queues, and X represents the exchange.
  • The exchange is responsible for forwarding messages to all queues bound to the exchange.
  • Multiple queues can be defined, each bound to the same exchange.
  • Each queue can have one or more consumers.

Tip: In the same queue, a message can only be processed by one consumer. The reason why the fanout pattern can achieve message broadcasting is essentially through multiple message queues.

Use Cases

The publish-subscribe pattern is a commonly used one-to-many consumption pattern. For example, after an e-commerce order is placed, an order message is generated. The warehouse module subscribes to the order message to process shipments, the notification module subscribes to the order message to send text messages, the points module subscribes to the order message to process points, etc. By subscribing to messages as needed, business expansion is achieved, and it is a low-coupling design pattern.