Adding a Subscriber
The publisher does not know its subscribers. So we can add a subscriber without changing the publisher.
The analytics service
Suppose we add an analytics service that counts orders as they are placed. The analytics service subscribes to order-placed, so the broker adds the analytics queue to the topic’s list. From then on, the broker copies every placed order to the analytics queue. The commerce service does not change.
graph TD
W[Commerce service: order worker] -->|publish| T
subgraph B[Broker]
T[order-placed topic] -->|copy| EQ[Email queue]
T -->|copy| SQ[Shipping queue]
T -->|copy| AQ[Analytics queue]
end
EQ --> N[Notification service]
SQ --> Sh[Shipping service]
AQ --> A[Analytics service]
Without pub/sub, the order worker would have to put a third message on the analytics queue. The commerce service’s team would change the order worker and release the commerce service again. With pub/sub, only the analytics service’s team makes a change: the analytics service subscribes to order-placed.
The analytics service is worth adding when the counts are needed right away. If a report once a day is enough, a program can read the day’s orders from the database instead.
Shipped orders
Shopend adds a new requirement. When a parcel leaves, the customer should get an email that says the order was shipped. The analytics service should also count the shipped order.
The shipping service knows when a parcel leaves. So the shipping service publishes to a new topic, order-shipped:
{ "shopId": "mugshop", "orderId": "93" }
Two services subscribe to order-shipped:
- The notification service, to send the email. Its email queue is now on the lists of two topics. Each copy arrives with the name of its topic. The name tells the notification service which email to send.
- The analytics service, to count shipped orders. The analytics queue is also on the lists of both topics.
You might suggest that the shipping service put one message on the email queue and another on the analytics queue. That works, but then the shipping service has to know both queues. The order worker had the same problem: it had to know one queue for each service that acts on a placed order.
Two topics
Here is the broker with both topics:
graph TD
W[Commerce service: order worker] -->|publish| OP
Sh[Shipping service] -->|publish| OS
subgraph B[Broker]
OP[order-placed topic] --> EQ[Email queue]
OP --> SQ[Shipping queue]
OP --> AQ[Analytics queue]
OS[order-shipped topic] --> EQ
OS --> AQ
end
EQ --> N[Notification service]
SQ --> Sh
AQ --> A[Analytics service]
The shipping service is now a subscriber and a publisher. It subscribes to order-placed and publishes to order-shipped.