Handling multiple crud operations with one message

Hello everyone,

I’m trying to figure out a way to receive an array of objects in my controller and then sending them in a NServiceBus message. The idea is to process all of those entities (perform validations, saving them) in the proper handler and then retrieving a summary of the whole transaction (not sure if it should be only one transaction) with its validation results and the status of every entity.

What should be the best way to achieve this?

Hi Saul,

Your question does raise a few questions from my part to figure out exactly what you’re trying to achieve:

  • Is your goal some kind of bulk update process?
  • Does the failed validation of one entity affect the rest of the set?
  • Should the entities all be saved within the same transaction? And why?
  • Why do you require the summary?

Assuming that your goal is:

  • To update a set of entities, validate them before saving
  • Each entity can succeed or fail independent of the others in the array

This would be my suggestion:

If you can split the processing of the entities on a per entity level, I would pursue that. The reasoning behind that, is that batch-updating an unknown amount of entities within the execution of one handler might get you into trouble as you might get long-running handlers that continuously timeout depending on the load.

If you need to correlate all these operations together, you can use a saga in order to achieve that but still handle each entity being updated as a single unit of work. This is referred to as the scatter-gather pattern.

The message starting the saga could contain the instructions to update all the entities. The handler for that starting message could just defer the validation and saving operations to other messages within that saga, splitting the operations in smaller units of work. In this scenario, the saga would keep track of the validation results and status of every entity. By the time the saga completes, you will have a complete summary of the changes that were persisted in your system.

When using this approach there is concurrency to take into account, about which you can find more information here.

If my assumption is off and the scenario that you’re trying to solve is different, let me know.

I hope that helps,

Kind regards,

Laila

1 Like

Hi Laila, yes this worked!

Thanks for pointing to the scatter-gather pattern this was what I needed.