Trigger Recursion and Cascading
Trigger Recursion and Cascading are critical concepts in Salesforce development that every Platform Developer I candidate must understand. **Trigger Recursion** occurs when a trigger's execution causes the same trigger to fire again, creating a loop. For example, if an after-update trigger on the … Trigger Recursion and Cascading are critical concepts in Salesforce development that every Platform Developer I candidate must understand. **Trigger Recursion** occurs when a trigger's execution causes the same trigger to fire again, creating a loop. For example, if an after-update trigger on the Account object updates the same Account record, the trigger fires again, potentially creating an infinite loop. Salesforce enforces governor limits to prevent truly infinite recursion, but uncontrolled recursion can quickly exhaust DML statements, SOQL queries, and CPU time limits, causing runtime exceptions. To prevent recursion, developers commonly use a **static Boolean variable** in a helper class. The trigger checks this variable before executing its logic. Once the trigger runs the first time, the static variable is set to true, preventing subsequent executions. For example: public class TriggerHelper { public static Boolean hasRun = false; } In the trigger, you check: if(!TriggerHelper.hasRun) { TriggerHelper.hasRun = true; // execute logic } More sophisticated approaches use static Sets to track processed record IDs, allowing the trigger to skip only already-processed records rather than blocking all subsequent executions. **Trigger Cascading** happens when a trigger on one object causes a trigger on another object to fire. For instance, an after-insert trigger on Opportunity might update the parent Account, which then fires an after-update trigger on Account. This cascading chain can become complex and difficult to debug, especially when multiple objects and triggers are involved. Cascading is not inherently bad but must be carefully managed. Developers should document trigger execution order, maintain a single trigger per object pattern, and use handler classes to centralize logic. Understanding the **order of execution** in Salesforce — including validation rules, before triggers, after triggers, workflow rules, and process builders — is essential to predicting cascading behavior. Both recursion and cascading can lead to governor limit violations and unexpected side effects, making proper design patterns and thorough testing indispensable for robust Salesforce development.
Trigger Recursion and Cascading – Salesforce Platform Developer 1 Exam Guide
Trigger Recursion and Cascading
Why Is This Important?
Trigger recursion and cascading is one of the most critical topics on the Salesforce Platform Developer 1 exam. In real-world Salesforce development, poorly managed triggers can lead to infinite loops, governor limit violations, unexpected data modifications, and system crashes. Understanding how to identify, prevent, and control recursive and cascading trigger behavior is essential for writing robust, scalable Apex code. The exam frequently tests your ability to predict execution outcomes when triggers fire in chain reactions and to apply best practices to prevent runaway logic.
What Is Trigger Recursion?
Trigger recursion occurs when a trigger performs a DML operation that causes the same trigger to fire again. For example, an after update trigger on the Account object updates the same Account record, which causes the after update trigger to fire again. This cycle can repeat indefinitely until Salesforce governor limits (such as the maximum stack depth or DML statement limit) are hit, resulting in a runtime exception.
What Is Trigger Cascading?
Trigger cascading occurs when a trigger on one object performs a DML operation on a different object, which in turn has its own trigger that fires. That second trigger might perform DML on yet another object (or even back on the original object), creating a chain of trigger executions. For example:
1. An after insert trigger on Opportunity creates a Task.
2. An after insert trigger on Task updates the related Account.
3. An after update trigger on Account updates the original Opportunity.
4. This causes the Opportunity trigger to fire again.
This chain can grow complex and difficult to debug, especially in orgs with many triggers and automation tools working together.
How Does It Work? The Salesforce Order of Execution
To understand recursion and cascading, you need to understand Salesforce's Order of Execution when a record is saved:
1. System validation rules run.
2. before triggers execute.
3. System validation rules and custom validation rules run again.
4. The record is saved to the database (but not committed).
5. after triggers execute.
6. Assignment rules, auto-response rules, and workflow rules execute.
7. If workflow field updates exist, the record is updated again, and before and after triggers fire one more time.
8. Process Builder and Flows execute.
9. DML operations in the above steps may invoke additional triggers (cascading).
10. The transaction is committed.
Key points to remember:
- Workflow field updates cause triggers to re-fire, but only once (Salesforce prevents infinite re-firing from workflow field updates).
- Process Builder and Flow DML operations can cause trigger cascading.
- Each new DML operation in a trigger starts a new execution context within the same transaction, sharing governor limits.
How to Prevent Trigger Recursion
1. Static Boolean Variable (Most Common Pattern)
Create a helper class with a static Boolean variable that acts as a flag:
public class TriggerHelper {
public static Boolean isFirstRun = true;
}
In your trigger:
trigger AccountTrigger on Account (after update) {
if (TriggerHelper.isFirstRun) {
TriggerHelper.isFirstRun = false;
// Perform DML operations
}
}
This ensures the trigger logic runs only once per transaction. However, be aware that a simple Boolean flag prevents the trigger from running for any subsequent execution in the same transaction, which may not always be desired.
2. Static Set to Track Processed Record IDs
A more refined approach uses a static Set of IDs to track which records have already been processed:
public class TriggerHelper {
public static Set<Id> processedIds = new Set<Id>();
}
In your trigger handler:
for (Account acc : Trigger.new) {
if (!TriggerHelper.processedIds.contains(acc.Id)) {
TriggerHelper.processedIds.add(acc.Id);
// Process record
}
}
This is more granular and allows the trigger to process new records that enter the transaction later.
3. One Trigger Per Object Pattern
Best practice dictates having only one trigger per object with a handler class. This gives you centralized control over execution flow and makes it easier to manage recursion. Multiple triggers on the same object have no guaranteed execution order, making recursion and cascading harder to predict and debug.
4. Trigger Framework
Using a trigger framework (such as a base TriggerHandler class with methods like beforeInsert(), afterUpdate(), etc.) provides built-in recursion control, maximum loop count settings, and consistent patterns across the org.
Key Concepts for the Exam
- Static variables persist for the duration of a single transaction but are reset between transactions. They are the primary tool for controlling recursion.
- Governor limits are shared across all trigger executions within a transaction. Cascading triggers consume from the same pool of DML statements (150), SOQL queries (100), etc.
- Workflow field updates cause triggers to re-execute once. This is a well-known source of unexpected recursion.
- before triggers that modify Trigger.new records do NOT cause re-execution because no additional DML is performed. Only explicit DML statements or workflow field updates cause re-firing.
- after triggers are where recursion most commonly occurs because you must use DML to modify records (you cannot modify Trigger.new in after triggers).
- Records modified in before triggers via Trigger.new do not require DML and therefore do not cause recursion on the same object.
Common Exam Scenarios
Scenario 1: A developer writes an after update trigger on Contact that updates the parent Account. The Account has an after update trigger that updates all child Contacts. What happens?
Answer: Without recursion prevention, this creates an infinite loop until governor limits are exceeded. The correct solution is to implement a static variable to stop the recursion.
Scenario 2: A before insert trigger on Case sets a field value on the Case record using Trigger.new. Does this cause recursion?
Answer: No. Modifying Trigger.new in a before trigger does not require a DML statement, so the trigger does not re-fire.
Scenario 3: A workflow rule with a field update fires after an after update trigger on Opportunity. Will the trigger fire again?
Answer: Yes. Workflow field updates cause the before and after update triggers to fire one additional time.
Scenario 4: An after insert trigger on Account creates a related Contact. The Contact after insert trigger creates a Task. Can this cause issues?
Answer: This is cascading. While not infinite (different objects, different events), it consumes shared governor limits. If any of these triggers circle back to insert or update an Account, recursion begins.
Exam Tips: Answering Questions on Trigger Recursion and Cascading
1. Look for DML in after triggers: When a question describes an after trigger performing DML on the same object, immediately think recursion. The answer will almost always involve using a static variable to prevent it.
2. Trace the execution path: For cascading questions, mentally (or on scratch paper) trace the chain: Object A trigger → DML on Object B → Object B trigger → DML on Object C → and so on. Check if the chain ever circles back to the original object and trigger event.
3. before triggers modifying Trigger.new do NOT recurse: This is a favorite trick in exam questions. If a before trigger sets a field on the record in Trigger.new, no additional DML is needed, so no recursion occurs.
4. Remember the workflow re-fire rule: Workflow field updates cause triggers to fire again, but only once. The exam may test whether you know this secondary execution happens.
5. Static variables reset between transactions: If a question asks about separate API calls or user actions, each one is a new transaction with reset static variables. Recursion guards using static variables only work within a single transaction.
6. Governor limits are cumulative: In cascading scenarios, the exam may ask what error occurs. The answer is typically a governor limit exception (e.g., too many DML statements, too many SOQL queries, or maximum trigger depth exceeded).
7. One trigger per object is best practice: If an exam question asks how to ensure predictable trigger behavior, the answer involves the one-trigger-per-object pattern with a handler class.
8. Understand the difference between recursion and cascading: Recursion is the same trigger firing repeatedly. Cascading is a chain of different triggers firing sequentially. Both can cause issues, but they require slightly different mental models to analyze.
9. Static Boolean vs. Static Set: A static Boolean (isFirstRun) is a simpler but blunter instrument. A static Set of processed IDs is more precise. The exam generally focuses on the static Boolean approach but may present scenarios where the Set approach is more appropriate.
10. Eliminate wrong answers: If an answer option suggests using @future methods or queueable jobs solely to prevent recursion, it is likely incorrect. While asynchronous processing runs in a separate transaction, it is not the standard or recommended pattern for recursion prevention and introduces its own complexities.
By thoroughly understanding the mechanics of trigger execution, recognizing recursive and cascading patterns, and applying the static variable prevention technique, you will be well-prepared to answer these questions confidently on the Platform Developer 1 exam.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!