Apex – When Do Before Save Record Triggered Flows Run Compared to Before Insert Triggers?

apexorder-of-executionrecordtriggeredflowtriggervisual-workflow

I have come across an interesting situation. I have an apex trigger running before insert and before update on the account object. I am performing some complex logic in this trigger that updates the value on a given account field.

I also have a before save record triggered flow (Fast Field Updates – I'm pretty sure this means before save) that references the value in the field that the apex trigger added / modified.

However, my process is not working as I would expect, and I have suspicion that at the point in which the flow is accessing the given field, the apex trigger has not set it yet. So, upon researching, I discovered that before save flows run 'Immediately prior to' before save apex triggers (see the following documentation):

Order of the save operation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm

Save Operation Diagram: https://architect.salesforce.com/1/asset/immutable/s/e6cf2ac/assets/images/Salesforce-Order-Of-Execution-Diagram.png

Before Save Flows: https://help.salesforce.com/s/articleView?id=sf.flow_concepts_trigger_record.htm&type=5

I did not anticipate this behavior, and I am wondering how I can get around this? Is there any way to make the apex trigger run first? My problem is that the flow is a rather extensive flow and I was reaching some governor limits (specifically the CPU time) when running as an after save flow. It performs much better as a before save flow; my original problem was that when I had an after save flow, I called a custom apex action to do the logic that I am NOW doing in the before save apex trigger. However, a before save flow does not accept custom apex actions, so it was necessary for me to add that custom logic to an apex trigger. Unfortunately, I am just now finding out about this order-of-operations, and it is causing my flow to perform incorrectly.

Ideally, the flow would remain a before save flow but run AFTER the apex trigger. Is there any way to customize when an apex trigger and / or flow runs in relation to each other?

Best Answer

Unfortunately there's not much you can do. You can't change the order of execution, so you're going to have to re-design your flow/trigger logic.

The flow/trigger design cannot be done in isolation with each other, as the order they run is very important.

We've had to go through this process multiple times for our customers as we've migrated from process builders to before triggered flows.

Related Topic