Apex Trigger Best Practices and Patterns

Triggers are often the first Apex code a team writes, and often the code that causes the most trouble a year later. A trigger that works fine when a user edits one record can fail when a data load updates 10,000. This guide covers the patterns that keep triggers safe as an org grows.

One trigger per object

Salesforce's documentation is clear on this: if more than one trigger is defined on an object for the same event, the order they run in isn't guaranteed. Two triggers on Opportunity can run in a different order from one transaction to the next, which leads to bugs that are very hard to reproduce.

Keep one trigger per object, and let it handle every event you need.

Keep the trigger thin

The trigger itself should do almost nothing. It hands the work to a handler class. This makes the logic testable, reusable and easy to read.

Apex  ·  OpportunityTrigger.trigger
trigger OpportunityTrigger on Opportunity (
    before insert, before update,
    after insert, after update
) {
    OpportunityTriggerHandler.run();
}
Apex  ·  OpportunityTriggerHandler.cls
public with sharing class OpportunityTriggerHandler {

    public static void run() {
        if (Trigger.isBefore) {
            if (Trigger.isInsert || Trigger.isUpdate) {
                setDefaults((List<Opportunity>) Trigger.new);
            }
        } else if (Trigger.isAfter) {
            if (Trigger.isInsert || Trigger.isUpdate) {
                updateLastWonDate(
                    (List<Opportunity>) Trigger.new,
                    (Map<Id, Opportunity>) Trigger.oldMap
                );
            }
        }
    }

    // Before trigger: change fields on the records being saved.
    // No DML needed, the values are saved with the record.
    private static void setDefaults(List<Opportunity> opps) {
        for (Opportunity opp : opps) {
            // Tidy up names typed or imported with extra spaces
            if (opp.Name != null) {
                opp.Name = opp.Name.normalizeSpace();
            }
        }
    }

    // After trigger: update related records.
    private static void updateLastWonDate(
        List<Opportunity> opps,
        Map<Id, Opportunity> oldMap
    ) {
        Set<Id> accountIds = new Set<Id>();

        for (Opportunity opp : opps) {
            Opportunity oldOpp = (oldMap == null) ? null : oldMap.get(opp.Id);
            Boolean justWon = opp.IsWon && (oldOpp == null || !oldOpp.IsWon);

            if (justWon && opp.AccountId != null) {
                accountIds.add(opp.AccountId);
            }
        }

        if (accountIds.isEmpty()) {
            return;
        }

        List<Account> accountsToUpdate = new List<Account>();
        for (Id accId : accountIds) {
            // Last_Won_Date__c is an example custom field
            accountsToUpdate.add(new Account(
                Id = accId,
                Last_Won_Date__c = Date.today()
            ));
        }

        update accountsToUpdate;
    }
}

Always write for bulk

The most common trigger mistake, in Salesforce's own words, is assuming the trigger runs for one record at a time. Code like Trigger.new[0] works when a user saves one record and silently ignores the rest when the API saves 200.

Follow these rules from the Apex Developer Guide:

  • Loop over every record in Trigger.new, never just the first.
  • No SOQL inside loops. Collect IDs into a Set<Id> and run one query with IN. A query per record hits the limit of 100 queries as soon as more than 100 records are in scope.
  • No DML inside loops. Add records to a list and run one DML statement on the list.

Here is the difference in practice:

Apex  ·  Wrong: a query for every record
for (Opportunity opp : Trigger.new) {
    Account acc = [SELECT Id, Industry FROM Account WHERE Id = :opp.AccountId];
    // ...
}
Apex  ·  Right: one query for all records
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
    if (opp.AccountId != null) {
        accountIds.add(opp.AccountId);
    }
}

Map<Id, Account> accounts = new Map<Id, Account>(
    [SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);

for (Opportunity opp : Trigger.new) {
    Account acc = accounts.get(opp.AccountId);
    // ...
}

Before or after?

Choosing the right event saves DML and avoids extra trigger runs.

Use a before trigger toUse an after trigger to
Set or fix field values on the record being savedCreate or update related records
Validate data and call addError()Use the record's Id on insert
Avoid an extra update statementWork with system fields set on save

In a before trigger, you change Trigger.new directly and the values are saved with the record. Running an update on the same records in an after trigger makes the trigger fire again, which is slower and opens the door to recursion.

Guard against recursion

Recursion happens when your trigger updates records that fire the same trigger again. Workflow field updates can also cause a second run. Salesforce documents that before and after update triggers run one more time after a workflow field update changes the record.

The Apex Developer Guide recommends static variables for this, defined in a class, not in the trigger. A static variable declared in a trigger doesn't keep its value between trigger contexts.

A simple Boolean flag works for small cases, but it has a problem. Triggers process records in chunks of 200. If a data load saves 1,000 records, a Boolean set during the first chunk can stop your logic from running for the other 800. Tracking the IDs you have already processed is safer:

Apex  ·  A recursion guard based on record IDs
public class TriggerGuard {
    private static Set<Id> processedIds = new Set<Id>();

    // Returns only records not handled yet in this transaction
    public static List<SObject> filterNew(List<SObject> records) {
        List<SObject> result = new List<SObject>();
        for (SObject rec : records) {
            if (rec.Id != null && !processedIds.contains(rec.Id)) {
                processedIds.add(rec.Id);
                result.add(rec);
            }
        }
        return result;
    }
}

Use it only for the parts of your logic that must run once per record, such as an after update that changes related data. Don't wrap the whole handler in it, or you may skip a legitimate second update.

⚠️ Static variables last only one transaction

A static variable keeps its value within a single transaction and resets afterwards. That's exactly what you want for a recursion guard. Don't use it to remember anything between separate saves.

Test with more than one record

A test that inserts one record proves almost nothing about a trigger. Insert at least 200 records in your tests so you cover a full chunk, and check the governor limits:

Apex  ·  A bulk trigger test
@IsTest
private class OpportunityTriggerHandlerTest {

    @IsTest
    static void setsLastWonDateInBulk() {
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        List<Opportunity> opps = new List<Opportunity>();
        for (Integer i = 0; i < 200; i++) {
            opps.add(new Opportunity(
                Name = 'Opp ' + i,
                AccountId = acc.Id,
                StageName = 'Prospecting',
                CloseDate = Date.today().addDays(30)
            ));
        }
        insert opps;

        for (Opportunity opp : opps) {
            opp.StageName = 'Closed Won';
        }

        Test.startTest();
        update opps;
        Test.stopTest();

        Account result = [SELECT Last_Won_Date__c FROM Account WHERE Id = :acc.Id];
        Assert.areEqual(Date.today(), result.Last_Won_Date__c);
    }
}

Consider Flow for simple cases

Not every automation needs a trigger. Simple field updates on the same record are often better as a before-save record-triggered flow, which admins can maintain. Keep Apex triggers for logic that needs complex queries, callouts through async jobs, or high-volume performance. Whatever you choose, document it, so the next person knows where the automation lives.

Checklist

  • One trigger per object
  • The trigger calls a handler and holds no logic
  • No SOQL or DML inside loops
  • Same-record field changes happen in before triggers
  • Recursion guards live in a class and track record IDs
  • Tests run with at least 200 records

Sources and further reading

Share this article

Help others discover this content

More Articles

  • All Posts
  • Marketing Cloud
  • Data Cloud
  • Sales Cloud
  • SFMC Next