Most of what I discuss here is culled from https://docs.microsoft.com/en-us/learn/modules/choose-a-messaging-model-in-azure-to-connect-your-services/2-choose-whether-to-use-message-queues-or-events.
If you are building a distributed application you will want to ensure the application is both reliable and scalable. You will often leverage communication components to accomplish these objectives. This will necessitate a choice between messages, events or some combination of both? So how do you choose?
Let’s first define what we mean by messages and events.
Messages have the following characteristics:
- Contains the raw data, all of it, just not a reference to the data, that the receiving component will consume.
- The sending component expects the receiving component to process the message content in a specific way.
- Integrity of the system may depend on the both the sending component and receiving component doing their job.
Events have the following characteristics:
- Lightweight notifications that indicate something occurred within the system.
- May be sent to multiple receiving components or none at all.
- Intended to “fan out”, multiple receiving components (subscribers) for each sending component (publisher).
- No processing expectations from the sending component.
- Some events are discrete and unrelated to other events, while some may be part of a related or ordered series of events.
How do I choose?
It is very common for an application to use BOTH events and messages, the best choice should be based on a specific use case.
Messages should be used if the processing of communications need a guarantee that they occurred, while events should be used for broadcasts.
For each communication, ask yourself, does the sending component expect the communication to be processed in a particular way by the destination component?
- If the answer is YES, then choose to use messages.
- If the answer is NO, then choose to use events.