When should triggers be used?

I have a social mobile app, where users can like posts. Every time a like occurs, a cloud function creates a new Like object and then, a Like afterSave trigger fetches the post, increases its numberOfLikes, creates a Notification object and performs a fetch/update on the poster.

My question is, have I divided the amount of work between the cloud function and the trigger properly? Should the cloud function do all the work? Are triggers heavy for the system and so they should only be used on less frequent operations?

I believe the performance will be similar either way. In order to decide where to run this logic, Iā€™d actually analyze if you want to run this process every time a Like object is created (even when created by other parts of your code or dashboard, etc) or not.

1 Like

There are several aspects to consider:

  • Performance (can multiple updates be done in one DB command rather than split up in a cloud code function and a trigger?)
  • Resilience (if a multi-step process fails somewhere in the middle, does it lead to data inconsistency and can that case be handled in a complex combination of methods and trigger?)
  • Modularity (does an operation have to be done every time after an object update, so that it may be practical in a class hook?)
  • Readability (is the code readable in a complex sequence of triggers?)

Parse Server provides a rich toolbox and here is no right or wrong answer on which tools to use. There are many ways to achieve the same outcome. The tools you would use are usually the ones that fit well into the overall code structure so that the code stays readable and maintainable while also reducing code complexity to mitigate the likelihood of bugs.

You may want to consider going without triggers if the majority of operations on a class does not lead to anything being executed in the trigger. If a trigger is set in cloud code, the trigger code path will always add additional execution time, which may add up significantly for your use case especially when code is complex (e.g multiple triggers) and at scale.

1 Like