Recursion in Apex: Avoiding Trigger Loops and Embracing Proper Use

Recursion in Apex has a bit of a reputation. Many Salesforce developers first hear the term when a trigger unexpectedly calls itself over and over, leading to the dreaded “Maximum trigger depth exceeded” error. It’s easy to assume recursion = bad, especially if you don’t come from a computer science background. In reality, recursion is a fundamental programming concept, a powerful tool when used intentionally, but a source of tricky bugs when it happens unintentionally. This post will simplify recursion in the context of Apex, exploring both the pitfalls of unintended recursive triggers and the value of deliberate recursion for solving certain problems. We’ll look at code examples of each, discuss how recursion interacts with Salesforce governor limits and performance, and cover best practices (like static flags and trigger patterns) to prevent unwanted loops. By the end, you’ll know when to fear recursion, when to embrace it, and how to keep your triggers from going rogue.

Continue reading