Sub topic 3
How a Trigger Ends Up Calling Itself
This chapter assumes you can write a basic Apex trigger on a standard object, read Trigger.new and Trigger.old, and use insert and update statements. It also assumes you know that Salesforce enforces governor limits. The goal is to understand the mechanisms that make a trigger run again inside its own transaction, so that the guards in later chapters make sense.
What recursion means for a trigger
A trigger is recursive when its own work causes the same trigger to run again before the current transaction finishes. The second run happens in the same transaction as the first, and it can cause a third run, and so on.
Salesforce does not let this continue forever. It stops the transaction with an error such as maximum trigger depth exceeded. When that happens, every change made in the transaction is rolled back, including the change the user originally asked for.
Recursion is rarely written on purpose. It usually appears because a trigger does a reasonable thing, such as updating a field, without noticing that the update itself is an event the trigger listens to.
The simplest case: DML on the same object
The most direct cause is a trigger that issues DML on the same object type it is fired from.
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
}Follow the sequence step by step:
- A user updates an Account.
- The
after updatetrigger runs and callsupdate toUpdate. - That
updateis an update of Account records, so theafter updatetrigger runs again. - The second run builds a new list and calls
updateagain. - This repeats until Salesforce reaches its depth limit and throws the error.
Nothing in the code checks whether the work was already done. The trigger writes 'Reviewed' every time, even when the value is already 'Reviewed'. The platform treats each update as a new event regardless.
Why the order of execution matters
Salesforce processes a save in a fixed sequence called the order of execution. In simplified form, it runs before triggers, validation rules, the database save, after triggers, and then workflow rules, flows, and other automation. Roll-up calculations and similar steps follow.
Two points in this sequence explain most recursion:
- DML statements inside a trigger start their own save, which runs through the same sequence for the records involved.
- Some automation that runs after the
aftertriggers can update the record again. When that happens, Salesforce runs thebeforeandaftertriggers a second time for that record.
The second point matters because the cause is then not in your trigger code. A trigger can run twice with no DML statement in it, because a workflow field update, a flow, or a process changed the record after the first pass.
Three common ways recursion appears
1. A trigger updates its own object
This is the example above. Any update, insert, upsert, or delete of the same object in a trigger on that object can re-fire it.
The insert case deserves a note. A trigger on after insert that inserts more records of the same type fires itself again with the new records. The after update case is more common because developers often want to stamp a field after the save.
2. Two objects update each other
Recursion does not need to stay within one object. Consider two triggers:
- An Account trigger updates related Contacts.
- A Contact trigger updates the parent Account.
Updating an Account updates its Contacts, which updates the Account, which updates its Contacts again. Each trigger looks harmless alone. Together they form a loop, and the depth is counted across both.
Loops like this are harder to spot because you must read two triggers, and sometimes a flow, to see the cycle.
3. Automation changes the record after the trigger
A workflow field update or a flow can change a record after your after trigger has finished. Salesforce then re-runs the triggers for that record, in the same transaction.
This is sometimes not an infinite loop. It is a second pass, and your trigger runs exactly twice. That is still a problem if the logic is not safe to run twice, for example if it creates a child record each time.
A guarded version still runs twice
A guard that stops infinite recursion does not necessarily make the logic run once. Suppose a trigger creates a Task on every after update, and a workflow field update touches the record afterward. Without a guard, the Task is created twice. With a limited guard it might still be created twice, depending on how the guard is written.
This is why the chapters that follow use several techniques, not one. Each technique answers a slightly different question:
| Question | Technique |
|---|---|
| Can I avoid DML entirely? | Change records in a `before` trigger |
| Did the field I care about change? | Compare `Trigger.new` with `Trigger.oldMap` |
| Have I already handled this record in this transaction? | A static `Set<Id>` |
| Should the whole handler run again? | A static Boolean flag, with caveats |
The way out, in brief
Three directions follow from the causes above. Later chapters cover each in detail.
Avoid the extra DML
In a before trigger, changes made to the records in Trigger.new are saved by the platform without a DML statement. No DML means no new save and nothing to re-fire.
trigger AccountTrigger on Account (before update) {
for (Account acc : Trigger.new) {
acc.Description = 'Reviewed';
}
}This version does the same job as the first example and cannot recurse through its own work.
Run only when something relevant changed
If the trigger needs after context, compare the new and old values and act only on records that changed in the way you care about.
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
List<Account> changed = new List<Account>();
for (Account acc : newList) {
Account oldAcc = oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
changed.add(acc);
}
}
// process only the records in 'changed'
}When the re-fired trigger finds that Rating did not change, changed is empty and the second pass does nothing.
Remember what was already done
A static variable keeps its value for the whole transaction, including re-fired triggers. A trigger can record that it has handled something and skip it on later passes. The next chapters show the Boolean flag and the Set<Id> forms, and explain why they behave differently when more than 200 records are involved.
Diagnosing a recursion error
When you see maximum trigger depth exceeded or a similar error, work through these checks:
- Read the debug log and look for the same trigger name repeating in the
CODE_UNIT_STARTEDlines. This confirms recursion and shows which objects are involved. - Look for DML in the trigger or in any class it calls. Include helper methods, because the DML may be several calls away.
- Check other triggers on related objects for updates that point back at the first object.
- Check for workflow field updates, flows, and processes on the object. These can cause a second pass without any Apex DML.
- Check whether the logic is safe to run more than once. If it is not, a guard is needed even when the pass count is only two.
Summary of the causes
| Cause | Where the loop comes from | First thing to check |
|---|---|---|
| Same-object DML | The trigger's own `update` or `insert` | DML statements in the trigger and its helper classes |
| Cross-object loop | Two triggers updating each other's objects | Triggers on all related objects |
| Post-trigger automation | Workflow field update or flow changing the record again | Declarative automation on the object |
Exercise
An after update trigger on Contact updates the parent Account, and an after update trigger on Account updates all of that Account's Contacts. A user edits one Contact. Explain how this can end in a depth error, and name one change that would stop the loop at its source.
Show answer
Editing the Contact fires the Contact trigger, which updates the Account. The Account update fires the Account trigger, which updates the Contacts. That Contact update fires the Contact trigger again, and the cycle repeats until Salesforce reaches the maximum trigger depth and rolls the transaction back. One fix is to compare old and new values in each trigger and act only when a field the logic depends on actually changed, so the second pass finds nothing to update. Another is to remove the DML by moving the change into a before trigger where possible, or to track processed record Ids in a static Set.
Exercise
A trigger on Opportunity creates one Task per record in its after update logic. There is no DML on Opportunity in the trigger, but Tasks are being created twice. What is a likely cause?
Show answer
A workflow field update, flow, or process on Opportunity changes the record after the first save. Salesforce then runs the triggers again for that record in the same transaction, so the Task logic runs a second time. The trigger is not calling itself, but it still runs twice. A changed-field check or a guard on processed record Ids would prevent the duplicate Task.