Trigger Recursion
By the end of this lesson, you'll be able to:
- Explain how a trigger can accidentally cause itself to fire again
- Use a static Boolean flag to prevent runaway recursion
- Recognize the symptoms of an unguarded recursive trigger
Prerequisites: "Avoiding Logic in Triggers"
How a trigger can trigger itself
trigger AccountTrigger on Account (after update) {
for (Account acc : Trigger.new) {
acc.Description = 'Last updated: ' + System.now();
}
update Trigger.new; // this update fires AccountTrigger again!
}
update Trigger.new inside an after update trigger on Account performs a fresh update on Account records — which fires AccountTrigger again, which updates again, which fires again... This is Module 9's recursion concept, but happening accidentally through the trigger/DML relationship rather than a method deliberately calling itself.
Guarding with a static flag
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public void afterUpdate(List<Account> updatedAccounts) {
if (hasRun) {
return;
}
hasRun = true;
for (Account acc : updatedAccounts) {
acc.Description = 'Last updated: ' + System.now();
}
update updatedAccounts;
}
}
This is Module 10's static fields — one shared value per class, not per object — put to direct use: hasRun persists across the recursive re-entry within the same transaction, so the second (recursive) call sees hasRun == true and exits immediately via the guard clause, instead of updating and re-triggering again.
Recognizing the symptoms
An unguarded recursive trigger typically shows up as a governor limit error — often "Too many DML statements" or "Apex CPU time limit exceeded" — from what looks like a single, simple update. If a trigger's error message mentions far more DML operations than the actual number of records being saved, unguarded recursion (rather than the SOQL/DML-in-a-loop problems from Module 7) is a strong suspect worth checking first.
Exercise
Add a static recursion guard to this handler method so it only runs its logic once per transaction.
Show hint
private static Boolean hasRun = false; then check and set it at the top of the method.
Trigger Recursion Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A trigger that performs DML on its own object can accidentally trigger itself again — trigger recursion — and needs a guard to stop it from running out of control.