Publish-Subscribe

Event bus, Event loop

Definition
Any component (publisher) can notify all interested other components (subscribers) of the occurrence of an event, by sending a message to the event bus. Components that have registered themselves with the registry will receive the message and act upon it. The publisher is not informed when the message is handled.

How does it work?

Components may register themselves with the registry at any time. When a component notifies other components of an event, it places a message on the event bus. The event bus takes care of delivering the message to the registered recipients.

Event-bus architecture diagram

Variants

There are several types of communication that may occur on the Event Bus:

  • Publish-Subscribe: Modules may subscribe to certain message types. Whenever a module publishes a message to the bus, it will be delivered to all modules that subscribed to its message type.
  • Broadcast: The message will be delivered to all (other) modules.

Messages may be handled synchronously (immediately), or placed in a queue to be handled at the first convenient time. In that case an event loop handles the pending messages one by one. The loop remains idle at times when there are no messages to handle.

Examples

  • Ethernet handles point-to-point messages and broadcasts
  • A graphical user interface (GUI) handles user events (keyboard, mouse) and system events (time) by passing messages to event handlers

When should you use it?

Use it when your application can be factored in functionally separable modules that are capable of communicating through simple messages.

Problems

  • There is an element of uncertainty introduced when messages are handled asynchronously. You can't be sure if and when they are handled.
  • If the modules share large amounts of data, it may not be a good idea to pump these over the bus all the time. If you choose to share the data between the modules, make sure no synchronization issues occur.

Common implementation techniques

  • Relates to the Observer Design Pattern, with added functionality.
  • Modules may run in the same process or in different processes (as is the case with Microservices)
  • The event bus may be part of the same process or it may be another process. It may use the internet as its substrate.

Links