I have an integration app that polls records of different types from an internal database every few seconds and upserts them into Salesforce. I have two pollers that run independently from one another that create custom sObjects of type Event and type Person. Event has a foreign-key to Person in the internal database and that's reflected on their sObjects via a lookup, and a Person can have multiple Events associated with him. There's a workflow within the internal database system that creates a new Event and Person simultaneously, and the integration app pollers pick up both of these and upsert them into Salesforce in a non-deterministic order.
My goal is to set the Person lookup on the Event sObject, taking into account that the records may come in out of order (a Person may be inserted before an Event, or an Event may be inserted before a Person). To handle this, I set up two triggers—one on Event and one on Person—that look to ensure that the lookup will always be set. The Event trigger takes the external ID of the Person that lives on the Event and tries to find matching Persons to set the lookup. The Person trigger finds all Events that contain the external ID of that Person and whose Person lookup is null and tries to set the lookup on the Events.
Because the records are inserted very near to each other (often within a few milliseconds), sometimes neither trigger is able to locate the records it needs (verified by placing log statements and seeing that the queries return no results). Both triggers run after insert, but I'm assuming because their execution happens pre-commit, if the trigger execution overlaps, then there's a chance that both triggers can effectively be unaware that the records they expect exist?
- What can I do here? Is there a way to run all this logic post-commit?
- Do triggers execute concurrently? Is there anyway to run them sequentially?