Salesforce Preventing Infinite Loops in bi-directional Sync with a running user on Platform Event Trigger
- asimalicodes
- Jan 14, 2024
- 2 min read
Setting a running user for a trigger subscribed to your platform event means modification made to records due to logic in the trigger will have the last modified user field with the value of the running user of the platform event trigger. I recommend using an api only user that is specified for the integration - doing so will enable you to identify and track changes easily as your org grows.
To prevent an infinite loop perform a check in the code or automation process where the callout to the external system occurs to check whether the last modified by field on the record was the running user specified on the platform event trigger. If the record was last modified by the running user then it is obvious that there is no new update that needs to be propagated to the external system.

PlatformEventSubscriberConfigs
To specify a running user for a platform event trigger create a file inside the folder PlatformEventSubscriberConfigs (create this folder if it doesn’t exist) with a name of the following format:
yourplatformeventtriggername.platformEventSubscriberConfig-meta.xml.
This file contains some key fields relevant for our discussion:
user - enter your desired running users username here
platformEventConsumer - enter the name of the platform event trigger here
<?xml version="1.0" encoding="UTF-8"?>
<PlatformEventSubscriberConfig xmlns="http://soap.sforce.com/2006/04/metadata">
...
<platformEventConsumer>yourplatformeventtriggername</platformEventConsumer>
<user>yourusersusername</user>
....
</PlatformEventSubscriberConfig>Deploy this file to your org.
Example of preventing infinite loop
In one of my projects I synced accounts in Salesforce with the equivalent object in an ERP system. I had code execute in a trigger that would run on AccountChangeEvent making a callout to the external system if a user in Salesforce created/updated/deleted an account record. To prevent an infinite loop, I verify that the user who updated the record is not the integration user (ie the trigger did not fire because of an incoming update from the ERP system):
trigger AccountChangeEventTrigger on AccountChangeEvent(after insert) {
if( erpintegrationuserid == header.getCommitUser()){
System.debug('#####Last Modified By Integration User Exiting Now To Prevent Infinite Loop :)####');
}
}


Comments