Platform Event Design when Subscribers are Apex TriggersAny Platform Event Library or Best Practices out there?Unable to cover try catch for UserPackageLicense test classDocumentation Incorrect? Is it possible to cover/deploy triggers on Platform Events?Testmethod verification that @future published Platform EventCharset for Platform Event not UTF-8?Platform Event Subscription is in Suspended StatusApex Platform Events Subscriber not always triggeredPlatform Event throws RetryableException and then SFDC stops the trigger from consuming events for hoursView Platform Event External SubscribersError handling when publishing platform eventsPlatform Events from flow are processed one by one or in bulk?Platform event subscribers on Visualforce page not being called always when platform event is published

Why did the "Orks" never develop better firearms than Firelances and Handcannons?

Using Sed to add counter to keyword

Platform Event Design when Subscribers are Apex Triggers

Isn't "Dave's protocol" good if only the database, and not the code, is leaked?

Does taking on an assistant professor position prevent me from doing post-docs later?

Did Snape really give Umbridge a fake Veritaserum potion that Harry later pretended to drink?

Why did C++11 make std::string::data() add a null terminating character?

What is meaning of 4 letter abbreviations in Roman names like Titus Flavius T. f. T. n. Sabinus?

Speeding up thousands of string parses

Do I need to be legally qualified to install a Hive smart thermostat?

How to figure out layers of the atmosphere?

Was Wolfgang Unzicker the last Amateur GM?

How can power levels matter in a magic system that emphasizes control?

Why did moving the mouse cursor cause Windows 95 to run more quickly?

How to improve the size of cells in this table?

Is there an easy way to index by a binary vector / mask?

Why would a propellor have blades of different lengths?

Does the Defensive Duelist feat stack with the Warforged integrated protection?

What is meant by perfect, imperfect consonance and dissonance?

Should I cheat if the majority does it?

Is there a typical layout to blocking installed for backing in new construction framing?

Two queries on triangles, the sides of which have rational lengths

How can solar sailed ships be protected from space debris?

how to convert Timestring to seconds



Platform Event Design when Subscribers are Apex Triggers


Any Platform Event Library or Best Practices out there?Unable to cover try catch for UserPackageLicense test classDocumentation Incorrect? Is it possible to cover/deploy triggers on Platform Events?Testmethod verification that @future published Platform EventCharset for Platform Event not UTF-8?Platform Event Subscription is in Suspended StatusApex Platform Events Subscriber not always triggeredPlatform Event throws RetryableException and then SFDC stops the trigger from consuming events for hoursView Platform Event External SubscribersError handling when publishing platform eventsPlatform Events from flow are processed one by one or in bulk?Platform event subscribers on Visualforce page not being called always when platform event is published






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















This is a general design question on how to structure trigger files for platform events. Say I publish a platform event "lead created"
and I want to do several distinct things within the same Salesforce org that published the event. I know the way that Salesforce "subscribes" to this event is via a trigger on the pEvt. I'm thinking the design should be multiple trigger files (one for each "subscriber") when processing the event via apex instead of the "one trigger per object" rule with custom objects. The thinking is that each trigger file is actually a distinct subscriber to the event and so should be separated out appropriately. This also means logic would be written within the trigger, which should be fine since the only phase that is supported is 'after insert'. Most trigger frameworks take care of working with the different phases which doesn't apply to pEvts.



I'd like to know if this design makes sense and if anyone else has implemented a platform event design where the "subscribers" are actually within the same Salesforce org that published the event.










share|improve this question




























    4















    This is a general design question on how to structure trigger files for platform events. Say I publish a platform event "lead created"
    and I want to do several distinct things within the same Salesforce org that published the event. I know the way that Salesforce "subscribes" to this event is via a trigger on the pEvt. I'm thinking the design should be multiple trigger files (one for each "subscriber") when processing the event via apex instead of the "one trigger per object" rule with custom objects. The thinking is that each trigger file is actually a distinct subscriber to the event and so should be separated out appropriately. This also means logic would be written within the trigger, which should be fine since the only phase that is supported is 'after insert'. Most trigger frameworks take care of working with the different phases which doesn't apply to pEvts.



    I'd like to know if this design makes sense and if anyone else has implemented a platform event design where the "subscribers" are actually within the same Salesforce org that published the event.










    share|improve this question
























      4












      4








      4








      This is a general design question on how to structure trigger files for platform events. Say I publish a platform event "lead created"
      and I want to do several distinct things within the same Salesforce org that published the event. I know the way that Salesforce "subscribes" to this event is via a trigger on the pEvt. I'm thinking the design should be multiple trigger files (one for each "subscriber") when processing the event via apex instead of the "one trigger per object" rule with custom objects. The thinking is that each trigger file is actually a distinct subscriber to the event and so should be separated out appropriately. This also means logic would be written within the trigger, which should be fine since the only phase that is supported is 'after insert'. Most trigger frameworks take care of working with the different phases which doesn't apply to pEvts.



      I'd like to know if this design makes sense and if anyone else has implemented a platform event design where the "subscribers" are actually within the same Salesforce org that published the event.










      share|improve this question














      This is a general design question on how to structure trigger files for platform events. Say I publish a platform event "lead created"
      and I want to do several distinct things within the same Salesforce org that published the event. I know the way that Salesforce "subscribes" to this event is via a trigger on the pEvt. I'm thinking the design should be multiple trigger files (one for each "subscriber") when processing the event via apex instead of the "one trigger per object" rule with custom objects. The thinking is that each trigger file is actually a distinct subscriber to the event and so should be separated out appropriately. This also means logic would be written within the trigger, which should be fine since the only phase that is supported is 'after insert'. Most trigger frameworks take care of working with the different phases which doesn't apply to pEvts.



      I'd like to know if this design makes sense and if anyone else has implemented a platform event design where the "subscribers" are actually within the same Salesforce org that published the event.







      platform-event design-patterns






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 9 hours ago









      willardwillard

      6645 silver badges17 bronze badges




      6645 silver badges17 bronze badges




















          3 Answers
          3






          active

          oldest

          votes


















          3














          This is interesting, I quickly wrote 2 triggers on a platform event. And when I fired them I could see 2 debug logs, saying both triggers were own transaction.



          Both being own transaction means, they get own set of limits. Also as both are the async process you genuinely don't care about the order of execution.



          I have made architecture where we split our process via events and subscribe via triggers, but never tried something like having 2 triggers on 1 event.



          I believe you can do this when you wanna make a couple of complicated processes independent of each other. Having multiple subscribers to same event do makes sense in my opinion.






          share|improve this answer


















          • 2





            if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

            – willard
            6 hours ago


















          2














          This is all rather subjective. However, some comments from my perspective:




          1. For testability, without the need to actually insert data into the database (for traditional triggers) or actually publishing events on the event bus (for platform events), IMHO you should always put all the trigger code into a separately testable Apex class, simply calling that code as a one-liner trigger. This has multiple benefits, and these are my top 2:



            1.a. This makes your tests run faster (no need to insert into the DB through either mechanism)



            1.b. You can use a "factory method with dependency injection" approach (see this previous answer for a description of that pattern) to allow mocking out trigger behaviour in "integration type unit tests"



          2. It makes logical sense to me, in terms of design best practice, to split out the subscribers - after all, order of execution is very unlikely to be relevant between the subscribers as you have implied. You do, however, want to check to see if there are any limits that might get in the way of this approach.



          3. We have implemented an Apex-based subscriber for our own Platform Event in our managed package. The reason we did this was two-fold:



            3.a. The Platform Events are processed in a separate and asynchronous manner, regardless of what happens in the initiating session



            3.b. The trigger is executed as a different user (the Automated Process user) than the contextual user where the event was published.



          4. We used the "factory method with dependency injection" approach, and unit tests for our event subscriber code that don't actually rely on the publishing of events.






          share|improve this answer






























            1














            In addition to the other answers:



            Once you go the multiple triggers per xxx__e approach you need to consider race conditions and record locking in your design. There is no guarantee of which trigger will execute "first" and furthermore, Trigger t might get X records per transaction and Trigger u might get Y (X notequal Y) records per transaction. Both triggers can execute concurrently.



            It may also complicate any error retry use cases where the xxx__e event on Trigger t passes whereas Trigger u fails.






            share|improve this answer

























              Your Answer








              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "459"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f267928%2fplatform-event-design-when-subscribers-are-apex-triggers%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              This is interesting, I quickly wrote 2 triggers on a platform event. And when I fired them I could see 2 debug logs, saying both triggers were own transaction.



              Both being own transaction means, they get own set of limits. Also as both are the async process you genuinely don't care about the order of execution.



              I have made architecture where we split our process via events and subscribe via triggers, but never tried something like having 2 triggers on 1 event.



              I believe you can do this when you wanna make a couple of complicated processes independent of each other. Having multiple subscribers to same event do makes sense in my opinion.






              share|improve this answer


















              • 2





                if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

                – willard
                6 hours ago















              3














              This is interesting, I quickly wrote 2 triggers on a platform event. And when I fired them I could see 2 debug logs, saying both triggers were own transaction.



              Both being own transaction means, they get own set of limits. Also as both are the async process you genuinely don't care about the order of execution.



              I have made architecture where we split our process via events and subscribe via triggers, but never tried something like having 2 triggers on 1 event.



              I believe you can do this when you wanna make a couple of complicated processes independent of each other. Having multiple subscribers to same event do makes sense in my opinion.






              share|improve this answer


















              • 2





                if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

                – willard
                6 hours ago













              3












              3








              3







              This is interesting, I quickly wrote 2 triggers on a platform event. And when I fired them I could see 2 debug logs, saying both triggers were own transaction.



              Both being own transaction means, they get own set of limits. Also as both are the async process you genuinely don't care about the order of execution.



              I have made architecture where we split our process via events and subscribe via triggers, but never tried something like having 2 triggers on 1 event.



              I believe you can do this when you wanna make a couple of complicated processes independent of each other. Having multiple subscribers to same event do makes sense in my opinion.






              share|improve this answer













              This is interesting, I quickly wrote 2 triggers on a platform event. And when I fired them I could see 2 debug logs, saying both triggers were own transaction.



              Both being own transaction means, they get own set of limits. Also as both are the async process you genuinely don't care about the order of execution.



              I have made architecture where we split our process via events and subscribe via triggers, but never tried something like having 2 triggers on 1 event.



              I believe you can do this when you wanna make a couple of complicated processes independent of each other. Having multiple subscribers to same event do makes sense in my opinion.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 8 hours ago









              Pranay JaiswalPranay Jaiswal

              21.5k5 gold badges33 silver badges69 bronze badges




              21.5k5 gold badges33 silver badges69 bronze badges







              • 2





                if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

                – willard
                6 hours ago












              • 2





                if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

                – willard
                6 hours ago







              2




              2





              if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

              – willard
              6 hours ago





              if each trigger is its own execution context, that makes a great case to have each "subscriber" separated out into its own trigger.

              – willard
              6 hours ago













              2














              This is all rather subjective. However, some comments from my perspective:




              1. For testability, without the need to actually insert data into the database (for traditional triggers) or actually publishing events on the event bus (for platform events), IMHO you should always put all the trigger code into a separately testable Apex class, simply calling that code as a one-liner trigger. This has multiple benefits, and these are my top 2:



                1.a. This makes your tests run faster (no need to insert into the DB through either mechanism)



                1.b. You can use a "factory method with dependency injection" approach (see this previous answer for a description of that pattern) to allow mocking out trigger behaviour in "integration type unit tests"



              2. It makes logical sense to me, in terms of design best practice, to split out the subscribers - after all, order of execution is very unlikely to be relevant between the subscribers as you have implied. You do, however, want to check to see if there are any limits that might get in the way of this approach.



              3. We have implemented an Apex-based subscriber for our own Platform Event in our managed package. The reason we did this was two-fold:



                3.a. The Platform Events are processed in a separate and asynchronous manner, regardless of what happens in the initiating session



                3.b. The trigger is executed as a different user (the Automated Process user) than the contextual user where the event was published.



              4. We used the "factory method with dependency injection" approach, and unit tests for our event subscriber code that don't actually rely on the publishing of events.






              share|improve this answer



























                2














                This is all rather subjective. However, some comments from my perspective:




                1. For testability, without the need to actually insert data into the database (for traditional triggers) or actually publishing events on the event bus (for platform events), IMHO you should always put all the trigger code into a separately testable Apex class, simply calling that code as a one-liner trigger. This has multiple benefits, and these are my top 2:



                  1.a. This makes your tests run faster (no need to insert into the DB through either mechanism)



                  1.b. You can use a "factory method with dependency injection" approach (see this previous answer for a description of that pattern) to allow mocking out trigger behaviour in "integration type unit tests"



                2. It makes logical sense to me, in terms of design best practice, to split out the subscribers - after all, order of execution is very unlikely to be relevant between the subscribers as you have implied. You do, however, want to check to see if there are any limits that might get in the way of this approach.



                3. We have implemented an Apex-based subscriber for our own Platform Event in our managed package. The reason we did this was two-fold:



                  3.a. The Platform Events are processed in a separate and asynchronous manner, regardless of what happens in the initiating session



                  3.b. The trigger is executed as a different user (the Automated Process user) than the contextual user where the event was published.



                4. We used the "factory method with dependency injection" approach, and unit tests for our event subscriber code that don't actually rely on the publishing of events.






                share|improve this answer

























                  2












                  2








                  2







                  This is all rather subjective. However, some comments from my perspective:




                  1. For testability, without the need to actually insert data into the database (for traditional triggers) or actually publishing events on the event bus (for platform events), IMHO you should always put all the trigger code into a separately testable Apex class, simply calling that code as a one-liner trigger. This has multiple benefits, and these are my top 2:



                    1.a. This makes your tests run faster (no need to insert into the DB through either mechanism)



                    1.b. You can use a "factory method with dependency injection" approach (see this previous answer for a description of that pattern) to allow mocking out trigger behaviour in "integration type unit tests"



                  2. It makes logical sense to me, in terms of design best practice, to split out the subscribers - after all, order of execution is very unlikely to be relevant between the subscribers as you have implied. You do, however, want to check to see if there are any limits that might get in the way of this approach.



                  3. We have implemented an Apex-based subscriber for our own Platform Event in our managed package. The reason we did this was two-fold:



                    3.a. The Platform Events are processed in a separate and asynchronous manner, regardless of what happens in the initiating session



                    3.b. The trigger is executed as a different user (the Automated Process user) than the contextual user where the event was published.



                  4. We used the "factory method with dependency injection" approach, and unit tests for our event subscriber code that don't actually rely on the publishing of events.






                  share|improve this answer













                  This is all rather subjective. However, some comments from my perspective:




                  1. For testability, without the need to actually insert data into the database (for traditional triggers) or actually publishing events on the event bus (for platform events), IMHO you should always put all the trigger code into a separately testable Apex class, simply calling that code as a one-liner trigger. This has multiple benefits, and these are my top 2:



                    1.a. This makes your tests run faster (no need to insert into the DB through either mechanism)



                    1.b. You can use a "factory method with dependency injection" approach (see this previous answer for a description of that pattern) to allow mocking out trigger behaviour in "integration type unit tests"



                  2. It makes logical sense to me, in terms of design best practice, to split out the subscribers - after all, order of execution is very unlikely to be relevant between the subscribers as you have implied. You do, however, want to check to see if there are any limits that might get in the way of this approach.



                  3. We have implemented an Apex-based subscriber for our own Platform Event in our managed package. The reason we did this was two-fold:



                    3.a. The Platform Events are processed in a separate and asynchronous manner, regardless of what happens in the initiating session



                    3.b. The trigger is executed as a different user (the Automated Process user) than the contextual user where the event was published.



                  4. We used the "factory method with dependency injection" approach, and unit tests for our event subscriber code that don't actually rely on the publishing of events.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  Phil WPhil W

                  1,9261 gold badge3 silver badges11 bronze badges




                  1,9261 gold badge3 silver badges11 bronze badges





















                      1














                      In addition to the other answers:



                      Once you go the multiple triggers per xxx__e approach you need to consider race conditions and record locking in your design. There is no guarantee of which trigger will execute "first" and furthermore, Trigger t might get X records per transaction and Trigger u might get Y (X notequal Y) records per transaction. Both triggers can execute concurrently.



                      It may also complicate any error retry use cases where the xxx__e event on Trigger t passes whereas Trigger u fails.






                      share|improve this answer



























                        1














                        In addition to the other answers:



                        Once you go the multiple triggers per xxx__e approach you need to consider race conditions and record locking in your design. There is no guarantee of which trigger will execute "first" and furthermore, Trigger t might get X records per transaction and Trigger u might get Y (X notequal Y) records per transaction. Both triggers can execute concurrently.



                        It may also complicate any error retry use cases where the xxx__e event on Trigger t passes whereas Trigger u fails.






                        share|improve this answer

























                          1












                          1








                          1







                          In addition to the other answers:



                          Once you go the multiple triggers per xxx__e approach you need to consider race conditions and record locking in your design. There is no guarantee of which trigger will execute "first" and furthermore, Trigger t might get X records per transaction and Trigger u might get Y (X notequal Y) records per transaction. Both triggers can execute concurrently.



                          It may also complicate any error retry use cases where the xxx__e event on Trigger t passes whereas Trigger u fails.






                          share|improve this answer













                          In addition to the other answers:



                          Once you go the multiple triggers per xxx__e approach you need to consider race conditions and record locking in your design. There is no guarantee of which trigger will execute "first" and furthermore, Trigger t might get X records per transaction and Trigger u might get Y (X notequal Y) records per transaction. Both triggers can execute concurrently.



                          It may also complicate any error retry use cases where the xxx__e event on Trigger t passes whereas Trigger u fails.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 4 hours ago









                          cropredycropredy

                          37.8k4 gold badges45 silver badges132 bronze badges




                          37.8k4 gold badges45 silver badges132 bronze badges



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Salesforce Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f267928%2fplatform-event-design-when-subscribers-are-apex-triggers%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                              Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                              François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480