Newer Version Available
Decoupled Publishing and Subscription
Publisher and Subscriber Processes Not in the Same Transaction
Event publishing and subscription processes don’t run in the same transaction. As a result, a Salesforce record that an event publisher creates after publishing might not be committed to the database before the subscriber receives the event message. If the subscriber looks up the record, it might not be found because it hasn’t been committed yet. For example, consider this scenario.
- A Process Builder process publishes an event and creates a task record.
- A trigger on the Task object runs some logic, which delays the commit of the task record.
- A second Process Builder process, which is subscribed to the event, receives the event
and looks up the newly created task. The process returns the following error because the
trigger hasn’t finished executing, and the record is not yet
committed.
"MyProcess process is configured to start when a MyEvent platform event message occurs. A MyEvent message occurred, but the process didn't start because no records in your org match the values specified in the process's Object node."
The example uses Process Builder, but the scenario applies to other methods of publishing and subscribing, such as the API and triggers.
Conversely, if a subscriber creates a Salesforce record after receiving an event message, the new record might not be found immediately after publishing. The reason is that the event is not processed synchronously after publishing, or the event processing might take a long time if the logic is complex.
Event Publishing and Trigger Order of Execution
If an after insert trigger on a Salesforce object publishes an event, the event can be processed before the Salesforce record in the trigger is committed to the database. For example, consider this scenario.
- An after insert trigger on a custom object publishes an event message.
- A Process Builder process is subscribed to the event. Due to the trigger order of execution, the process is fired before the trigger finishes execution and before it commits the new custom object record.
- The process tries to look up the record to match the event and fails because the record is not found.
One possible solution is to create a scheduled action in your process that publishes a platform event 0 hours after the custom object created date. The scheduled action runs after the custom object is committed. Another option is to publish the event from a @queueable or @future Apex method, which ensures that the publish call is made only when the original transaction is committed. If the trigger’s transaction is rolled back, the @queueable and @future methods aren't executed and the event isn't published.