design-patternsarchitecturepublish-subscribemessagingevent-driven

What is recommended when publishing multiple variations of a message?


I'm looking for a recommended approach for the following scenario.

I have an API endpoint through which one can add/remove their friends.

PATCH /api/me/friends HTTP/1.1
Content-Type: application/json

{
  "friends": ["GUID"]
}

After updating the DB, the system publishes the event FriendsUpdated, which contains the resulting collection of friends after applying the change. This is, if the current value is ["John", "Jane"] and then I add "James" and remove "Jane", the system will publish the following message:

{
  "Person": "...",
  "Friends": ["John", "James"]
}

The thing is that there is also the need of having another event that tells the actual changes that were performed, this is, which friends were added and which ones were removed. Something like this:

{
  "Person": "...",
  "Friends": {
    "Added": ["James"],
    "Removed": ["Jane"]
  }
}

What is the recommended approach to follow to accomplish the scenario described above?

All I can think of is to have the following logic:

This could be an acceptable solution, but I'm willing to know if there are better ways of doing this. Thanks!


Solution

  • I tried to perform my trade-off analysis from the following perspectives:

    I've also tried to name situations when you should either pick them or avoid them.

    Single event

    In this case the reported/emitted event contains all the information for all interested parties.

    From the producer-side that means the event emission logic is simple but the event's payload is bloated.

    From the consumer-side that means the transferred data might be larger than the useful/profitable data.

    Containing all the things that might be useful for anyone is generally considered as a good practice if you as a producer don't know upfront who and when will process your data.

    In a high volume and/or high velocity system this approach can have worse performance than multiple events.

    Multiple events

    In this case the reported/emitted events are focused and concise.

    From the producer-side that means the events emission logic could be more complex (like all successfully published or none), it also requires the management of multiple event schemas.

    From the consumer-side that means the event processing can be quicker and more straightforward. Also there is a possibility to subscribe to more events, process them independently (at different rate, on different resources).

    If the events are used for example for service-to-service communication then having multiple lighter, dedicated events are better.

    This approach can be problematic if you need to correlate the events.