Sub topic 3
Why Several Triggers on One Object Cause Trouble
This chapter assumes you can read basic Apex (classes, methods, collections), know what DML operations are, and have heard of governor limits. It covers one question: what goes wrong when an object has more than one trigger. The next chapter turns the answer into a rule.
The situation
Salesforce lets you create as many triggers on an object as you like. Nothing in the platform stops you from writing AccountTriggerA, AccountTriggerB and AccountTriggerC, all subscribed to before insert. The compiler accepts them, and each one runs.
This is how most orgs end up with the problem. A developer adds a trigger for a feature. Two years later another developer adds a second one, because they don't want to touch the first. A managed package adds a third. Each decision looks reasonable, and the result is an object whose behavior nobody can describe in full.
Problem 1: the execution order is not defined
When two triggers on the same object subscribe to the same event, Salesforce does not promise which one runs first. The Apex Developer Guide says the order of execution for multiple triggers on the same event is not guaranteed. In practice the order often looks stable, so code may pass tests for years and then change behavior after a deployment or a platform release.
This matters whenever one trigger depends on the other. Suppose two before insert triggers exist on Account.
trigger AccountDefaults on Account (before insert) {
for (Account acc : Trigger.new) {
if (acc.Industry == null) {
acc.Industry = 'Other';
}
}
}trigger AccountRouting on Account (before insert) {
for (Account acc : Trigger.new) {
if (acc.Industry == 'Other') {
acc.Rating = 'Cold';
}
}
}AccountRouting only works as intended if AccountDefaults ran first. If the order flips, accounts created without an industry get no rating, and no error is raised. The data is simply wrong. You will find this kind of bug only by noticing bad records.
The next diagram shows the two possible orders for these triggers.
Problem 2: governor limits are shared
All triggers on one save operation run in the same transaction, so they draw from the same governor limits. Salesforce enforces limits per transaction, not per trigger. For synchronous Apex, those limits include 100 SOQL queries and 150 DML statements.
With several independent triggers, no single author sees the whole budget. Each trigger looks cheap on its own. Trigger A runs one query, trigger B runs one query, and a package trigger runs a few more. Then a second object's triggers, a flow and a workflow-style update add their own. Add recursion (see below) and the total can reach the limit in a transaction that none of the authors tested.
A single handler for the object makes the cost visible in one place. You can ask, "How many queries does an Account update run in total?" and answer it by reading one class.
Problem 3: duplicated and conflicting work
Separate triggers often repeat the same query or the same loop, because each one is self-contained.
trigger AccountOwnerSync on Account (after update) {
Set<Id> ownerIds = new Set<Id>();
for (Account acc : Trigger.new) {
ownerIds.add(acc.OwnerId);
}
Map<Id, User> owners = new Map<Id, User>(
[SELECT Id, Email FROM User WHERE Id IN :ownerIds]
);
// use owners ...
}trigger AccountNotifier on Account (after update) {
Set<Id> ownerIds = new Set<Id>();
for (Account acc : Trigger.new) {
ownerIds.add(acc.OwnerId);
}
Map<Id, User> owners = new Map<Id, User>(
[SELECT Id, Email FROM User WHERE Id IN :ownerIds]
);
// use owners ...
}Both are bulk-safe, and both query the same data. The transaction pays for two queries where one would do. In one handler you can query once and pass the result to the methods that need it.
Conflicts are worse than duplication. Two triggers may write the same field with different rules. The one that runs last wins, and since the order is undefined, so does the outcome. The same applies to addError: one trigger can block a save for a reason another trigger's author never knew about.
Problem 4: the object's behavior has no single home
Consider what a new team member must do to answer "What happens when an Account is updated?" With several triggers, they have to do the following:
- Open the list of Apex triggers in Setup, or search the codebase for
on Account. - Filter out triggers that belong to installed packages and cannot be read.
- Read each trigger and note which events it handles.
- Guess at the run order.
With a single trigger and handler, the answer is in one file. This affects debugging, code review and onboarding more than it affects performance.
Version control also suffers. Two developers adding features each edit their own trigger, so merge conflicts are rare, but behavior conflicts go unnoticed. When both features must change the same method in one handler, the conflict is visible in the pull request. That is the better place to find it.
Problem 5: recursion is hard to control
A trigger that updates records can fire triggers again. For example, an after update trigger on Account that updates child Contacts fires Contact triggers, and a Contact trigger might update the parent Account. Salesforce allows trigger recursion up to a stack depth limit, and past that point the transaction fails.
With several triggers on the same object, each one needs its own protection against re-entry, or they share a flag by convention. Nothing enforces that. If one trigger guards itself and another doesn't, the unguarded one runs again on every pass. A later chapter in this tutorial builds a recursion guard in the handler. That works well because there is one entry point to guard.
Problem 6: testing and bypassing are all or nothing
Tests for an object with many triggers are rarely isolated. A test that wants to check one rule inserts an Account, and every trigger fires. Required fields from other features must be filled in, other triggers' side effects create extra records, and the test fails for reasons unrelated to the rule under test.
You also can't switch one trigger off from code. There is no Trigger.disable() for a specific trigger. Teams work around this with custom settings or custom metadata flags checked at the top of each trigger, and each trigger has to remember to check them. With a single handler, one switch can cover everything. The base handler chapter shows this.
A summary of the failure modes
| Problem | What goes wrong | Why several triggers make it worse |
|---|---|---|
| Undefined order | Dependent logic works until the order changes | Each trigger is independent, so no order is expressed |
| Shared limits | Transaction hits a limit no author predicted | Nobody sees the total cost |
| Duplication | Same query or loop repeated | Each trigger is self-contained |
| Conflicting writes | Last writer wins, unpredictably | No single place resolves the rules |
| Scattered logic | Hard to read, review and onboard | Behavior spread across many files |
| Recursion | Re-entry or stack depth errors | No shared guard |
| Testing and bypass | Tests are coupled, switches are partial | No single control point |
What this does not claim
Multiple triggers are not forbidden, and they don't always break. An object with two triggers that touch different fields, in different events, and never interact can work for years. The pattern in this tutorial is a defense against the cases where they do interact, and against the growth that makes interactions likely.
Also, merging triggers into one file does not fix poor logic. A single trigger with 400 lines of loops, queries and DML in the body has the same limit and clarity problems. That is why the plan has two steps: first one trigger per object, then a trigger body that contains no logic.
Packages add a limit to this advice. You can't edit triggers from a managed package, and their order relative to yours is also undefined. Keeping your own code in one trigger reduces the number of unknowns to the package triggers alone.
Finding the problem in your own org
You can check which objects have more than one trigger without opening each file. Query the ApexTrigger object with the Tooling API or in the Developer Console's query editor (tick "Use Tooling API").
SELECT TableEnumOrId, COUNT(Id)
FROM ApexTrigger
WHERE ManageableState = 'unmanaged'
GROUP BY TableEnumOrId
HAVING COUNT(Id) > 1Each row returned is an object with more than one unmanaged trigger. Standard objects appear by name, and custom objects appear by Id, so you may need to look the Id up. Start with the objects that have the most triggers, since they have the most chances for conflict.
Exercise
Two before update triggers on Opportunity both set StageName. One sets it to 'Qualified' when Amount is over 10000, and the other sets it to 'Prospecting' when the record has no Account. A record has an Amount of 50000 and no Account. Which stage does it end up with, and why is that a problem?
Show answer
It is not possible to say. Salesforce does not define the order of triggers on the same object and event. If the Amount trigger runs last, the stage is 'Qualified'. If the Account trigger runs last, it is 'Prospecting'. The result can change after a deployment or platform release without any code change, and neither trigger reports an error. Putting both rules in one handler method lets you write the order and the precedence explicitly.
Exercise
A transaction inserts 200 Accounts. Three separate after insert triggers each run one SOQL query that does not depend on a loop. How many queries do they use together, and what is the benefit of a single handler?
Show answer
Together they use three of the 100 SOQL queries allowed in the transaction, assuming no other code runs queries. A single handler can run a shared query once and pass the result to each method, which would use one query instead of three if they need the same data. It also gives one place to read the total cost.