Using Platform Events for Apex Automations

4:17 PM

 Platform Events are meant for integration with other platforms outside of Salesforce. However, you could also define apex triggers on platform events, this helps in certain situations like below

  • If you want to execute the apex as another user (with elevated access) other than the running/current user, even though apex triggers run as system user the running user is still the user who initiated the transaction
  • Since platform events run asynchronously, these run on a separate thread and help as an alternative when you run into governor limits on an object apex trigger

Sample Use Case: Opportunity trigger is running into CPU timeout exception, you are moving automation's that run after Opportunity stage moves to Closed Won into a asynchronous operation to avoid CPU timeout.

STEP 1: Create a platform Event:

 

Step 2: Create a custom field

Create a custom field on the platform event to store the Opportunity ID 

 

Step 3: Create the apex trigger

Step 4: Call the platform event trigger by simply creating a record from the Opportunity trigger or a flow


Note: The platform event object needs to be granted access to the profiles that will be creating the event record, FLS is not applicable

0 comments