My Approach to Prevent Trigger Recursion (Without Losing My Mind)
If you've been a Salesforce developer for long enough, you've probably met the silent killer of many orgs, trigger recursion.
You update a record β it fires another trigger β that update fires again β and before you know it, you've got a full-blown infinite loop. π
In my early projects, I used quick fixes like static booleans or flags:
if (runOnce) return;
runOnce = true;
It worked⦠until it didn't. Debugging became painful, especially when multiple triggers or integrations were involved.
Then I found a cleaner pattern, a centralized recursion manager, reusable across all triggers:
public class TriggerContext {
private static Set<String> executed = new Set<String>();
public static Boolean isFirstRun(String key) {
return executed.add(key);
}
}
Now, inside any trigger, I just use:
if (!TriggerContext.isFirstRun('Account_BeforeUpdate')) return;
- β No global flags
- β No spaghetti logic
- β Simple, readable, and scalable
When I combine this with Custom Metadata / Custom Settings for trigger control (to enable or disable specific logic dynamically), I get complete control over automation.
π The best part: Admins and developers can work safely in parallel β no accidental recursion, no broken data integrity, and definitely no overnight or weekend debugging sessions.
If your org is struggling with unpredictable trigger behavior, give this pattern a shot. You can thank me later. π