Sub topic 2
Order of Execution and Why Triggers Can Run Twice
This chapter assumes you can write a basic Apex trigger, use Trigger.new and Trigger.old, and run DML statements such as update. It also assumes you know that governor limits apply to a whole transaction. Here you will learn the sequence Salesforce follows when it saves a record. That sequence explains why your trigger sometimes runs again when you did nothing to cause it.
One save is many steps
When a user edits an Account and clicks Save, Salesforce does more than write a row. It runs a fixed series of steps, called the order of execution. Your triggers are two of those steps. Other automation sits between and after them, and some of it can change the record again.
The simplified sequence for an update looks like this:
- Load the existing record and overlay the new field values.
- Run system validation and before-save record-triggered flows.
- Run
beforetriggers. - Run system validation again, then custom validation rules and duplicate rules.
- Save the record to the database without committing it.
- Run
aftertriggers. - Run assignment, auto-response, and workflow rules.
- If a workflow rule field update changed the record, run
before updateandafter updatetriggers once more. - Run after-save record-triggered flows and processes, escalation rules, and roll-up summary recalculation.
- Commit the transaction.
The exact placement of flows has shifted between Salesforce releases. Check the "Triggers and Order of Execution" page in the Apex Developer Guide for your org's release. The idea that matters here does not change. Several steps after your after trigger can write to the same record again.
Two ways a trigger runs again
A trigger can run more than once in a transaction for two different reasons. They behave differently, so learn to tell them apart.
Re-fire caused by automation
A workflow rule field update changes the record after your after trigger has finished. Salesforce then runs the before update and after update triggers once more. It does this once, not in a loop. Custom validation rules do not run again at that point.
After-save flows and processes that update the same record can also cause another trigger run. Which automation re-fires triggers depends on the tool and on the release. Treat any automation that writes back to the triggering record as a possible second run.
The practical effects are:
- Your trigger code runs twice for one user save.
- The second run sees the values the automation wrote.
- Any side effect in your trigger happens twice. This covers creating a child record, sending an email, and incrementing a counter.
Re-fire caused by your own DML
The other cause is your code. If an after update trigger runs update on the same object, Salesforce runs the whole order of execution for the records you update. That includes the trigger, and it runs inside the current trigger call.
This is true recursion. The new call can itself issue DML, which starts another call. Salesforce stops the chain at a stack depth of 16 and throws a System.DmlException that reads "maximum trigger depth exceeded." Each level also spends from the same governor limits. These are limits such as 150 DML statements and 100 SOQL queries (the synchronous limits). A runaway trigger can hit those limits before it reaches depth 16.
| Row | Automation re-fire | Your own DML |
|---|---|---|
| Cause | Workflow field update, flow, or process writes to the record | A trigger or class runs DML on records of the same object |
| How often | Once more for workflow field updates | Repeats until a guard stops it or depth 16 is reached |
| Where it runs | After the first trigger invocation has finished | Nested inside the current trigger invocation |
| Failure mode | Duplicate side effects | Depth error or governor limit error |
Both causes share one fact. Everything happens in one transaction, so static variables keep their values across all of the runs. The next chapters use that fact to build guards.
Seeing the second run
You can observe a re-fire yourself. First create a class that holds a counter. A static variable lives for the whole transaction, so it counts runs across re-fires.
public class RunCounter {
public static Integer beforeRuns = 0;
}Then add a trigger that increments the counter and logs each run.
trigger AccountAudit on Account (before update, after update) {
if (Trigger.isBefore) {
RunCounter.beforeRuns++;
}
System.debug(
LoggingLevel.INFO,
'Operation: ' + Trigger.operationType +
', before-run count so far: ' + RunCounter.beforeRuns
);
}Now create a workflow rule on Account with a field update, for example one that sets Description whenever Rating changes. Run this in Anonymous Apex, then read the debug log:
Account acc = new Account(Name = 'Order Demo');
insert acc;
acc.Rating = 'Hot';
update acc;You should see this pattern for the update:
BEFORE_UPDATEwith a count of 1AFTER_UPDATEBEFORE_UPDATEwith a count of 2AFTER_UPDATE
The second pair appears because the workflow field update changed the record. Nothing in your trigger asked for it.
Why this matters for your code
The order of execution has four consequences for trigger design.
- Triggers must be safe to run twice. Write them so a second run with the same data does no harm. A trigger that always inserts a Task for each updated Account will create two Tasks when a workflow field update is active.
- The second run may not look like an update you made. The record now carries values written by automation. A check such as "did the field change?" gives a different answer on each run.
- Adding automation can break old code. A trigger that worked for years can start duplicating work when an admin adds a workflow field update or an after-save flow. Your code did not change, but the order of execution now does more.
- Where you write matters. In a
beforetrigger you changeTrigger.newdirectly, and Salesforce saves those values as part of step 5. No extra DML is needed, so you cannot cause recursion that way. Anaftertrigger cannot editTrigger.new, so any change to the same records needs DML. That DML starts a new order of execution.
Here is the problem case. This trigger changes records in an after trigger with DML, so it re-fires itself:
trigger AccountTrigger on Account (after update) {
List<Account> toUpdate = new List<Account>();
for (Account acc : Trigger.new) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
update toUpdate; // fires this trigger again, with no guard
}The update starts a new order of execution for the same Accounts. The trigger runs again, builds the same list, and updates again, until Salesforce throws the depth error.
Common mistakes
- Assuming one save means one trigger run. Debug logs show how many times your trigger ran. Check them before you decide what a trigger does.
- Blaming only your code. If a trigger runs twice and you have no DML on the same object, look for workflow rules, flows, and processes on that object.
- Putting side effects in re-fired logic. Emails, callouts that queue work, and child record inserts happen once per run. Without guards, they happen twice.
- Assuming the depth limit protects you. The limit of 16 stops the loop only after your trigger has already done 16 levels of work and used up governor limits.
- Relying on old memory of the order. Flow changed where several steps happen. Read the current documentation for the release your org runs.
What comes next
You now have the model: one save passes through many steps, and both automation and your own DML can send a record back through the triggers. The next chapter looks closely at how a trigger ends up calling itself. Later chapters cover the fixes: using before triggers, checking for changed fields, and static variable guards.
Exercise
An Account has a workflow rule with a field update, and an after update trigger that creates one Task per updated Account. A user edits an Account once. How many Tasks do you expect, and why? What would change if the trigger instead ran update on the same Accounts with no guard?
Show answer
Expect two Tasks. The workflow field update changes the record after the first after update run, so Salesforce runs the before update and after update triggers once more, and the trigger creates a second Task. If the trigger ran an unguarded update on the same Accounts, it would re-fire itself repeatedly in a nested way until Salesforce throws "maximum trigger depth exceeded" at depth 16, or a governor limit is reached first.
Exercise
Why does changing acc.Description on records in Trigger.new inside a before update trigger not cause the trigger to run again, while the same change made with update in an after update trigger does?
Show answer
In a before trigger, Salesforce saves the modified Trigger.new values as part of the normal save step, so no DML statement is issued and no new order of execution starts. In an after trigger the records are read-only, so the change needs an update statement. That DML runs a new order of execution for the records, including their triggers.