Sub topic 8
Writing Handler Methods That Handle 200 Records
This chapter covers how to write handler methods that stay inside governor limits when a trigger receives a full batch of records. It assumes you know basic Apex syntax (classes, methods, collections), what DML operations are, and that Salesforce enforces governor limits per transaction. It also assumes you have seen a logic-less trigger that delegates to a handler class and dispatches on Trigger.operationType.
Why 200 is the number to design for
Salesforce calls a trigger with up to 200 records at a time. A single insert of 201 records runs the trigger twice in the same transaction, once with 200 records and once with 1. A Data Loader job, an API call, a batch Apex job, or a flow can all deliver full chunks.
The trigger body may therefore run many times in one transaction, and each run shares the same governor limits. The main limits that matter here are:
| Limit (synchronous transaction) | Value |
|---|---|
| SOQL queries issued | 100 |
| DML statements issued | 150 |
| Records processed by DML | 10,000 |
| Total CPU time | 10,000 ms |
If a handler runs one query per record, a chunk of 200 records fails on the 101st query with a System.LimitException. That error cannot be caught, and it rolls back the whole transaction. A handler that works in a one-record manual test can still fail in production.
The rule: collections in, collections out
A bulk-safe method follows one shape:
- Loop over the records and collect what you need (Ids, keys, new records to create).
- Run one SOQL query outside the loop, using the collected values with
IN :. - Loop again, using a
Mapfor lookups instead of searching a list. - Run one DML statement outside the loop on a collection.
The anti-pattern: SOQL and DML inside a loop
The following afterInsert method looks reasonable and passes a single-record test.
// Do not do this.
private void afterInsert(List<Account> newAccounts) {
for (Account acc : newAccounts) {
Task t = new Task(WhatId = acc.Id, Subject = 'Welcome call');
insert t; // one DML statement per record
}
}With 200 accounts it issues 200 DML statements. The limit is 150, so the 151st insert throws a System.LimitException. The same failure happens with a [SELECT ...] inside the loop, where the limit is 100 queries.
The bulk-safe version
Build a list inside the loop and run a single insert after it.
private void afterInsert(List<Account> newAccounts) {
List<Task> followUps = new List<Task>();
for (Account acc : newAccounts) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps; // one DML statement for the whole batch
}For 200 accounts this uses one DML statement. Adding records to a List costs no DML. Only the insert counts.
Before and after contexts handle records differently
The context you are in changes what you can do with the records.
- In a
beforecontext, the records inTrigger.neware not yet saved. You change them by assigning to their fields. Do not callupdateon them. The platform saves your changes for you. - In an
aftercontext,Trigger.newis read-only. Trying to assign to a field throws an error. To change the triggering records in anaftertrigger, you must query or create separate record instances and run DML on them. Trigger.newhas no Ids inbefore insert. Ids exist fromafter insertonward.
The beforeUpdate method below shows an assignment with no DML, and it reads the previous values from Trigger.oldMap.
private void beforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
for (Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Renamed from ' + oldMap.get(acc.Id).Name;
}
}
}This method does not query and does not run DML, so it uses none of the limits above regardless of batch size.
Querying related data once
When the logic needs data from another object, gather the keys first. This example, which assumes a custom Region_Code__c field on Account, sets the owner of new accounts based on a lookup object. It needs one query for the whole batch.
public with sharing class AccountOwnerAssigner {
public static void assignOwners(List<Account> newAccounts) {
// 1. Collect keys
Set<String> regionCodes = new Set<String>();
for (Account acc : newAccounts) {
if (acc.Region_Code__c != null) {
regionCodes.add(acc.Region_Code__c);
}
}
if (regionCodes.isEmpty()) {
return; // skip the query when there is nothing to look up
}
// 2. One query outside the loop
Map<String, Id> ownerByRegion = new Map<String, Id>();
for (Region_Owner__c ro : [
SELECT Region_Code__c, Owner__c
FROM Region_Owner__c
WHERE Region_Code__c IN :regionCodes
]) {
ownerByRegion.put(ro.Region_Code__c, ro.Owner__c);
}
// 3. Loop and use the Map
for (Account acc : newAccounts) {
Id ownerId = ownerByRegion.get(acc.Region_Code__c);
if (ownerId != null) {
acc.OwnerId = ownerId;
}
}
}
}The class is called from beforeInsert, so no DML is needed. The early return avoids spending a query when no record has a region code.
Updating related records in an after context
When the change goes to different records, collect them in a Map keyed by Id. A map prevents duplicate entries, and DML fails with a "duplicate id in list" error if the same Id appears twice in an update list.
public with sharing class ContactSync {
public static void copyPhoneToContacts(List<Account> newAccounts, Map<Id, Account> oldMap) {
Map<Id, Account> changed = new Map<Id, Account>();
for (Account acc : newAccounts) {
if (acc.Phone != oldMap.get(acc.Id).Phone) {
changed.put(acc.Id, acc);
}
}
if (changed.isEmpty()) {
return;
}
List<Contact> toUpdate = new List<Contact>();
for (Contact c : [
SELECT Id, AccountId, Phone
FROM Contact
WHERE AccountId IN :changed.keySet()
]) {
c.Phone = changed.get(c.AccountId).Phone;
toUpdate.add(c);
}
update toUpdate;
}
}Each contact appears once in the query result, so the list has no duplicates. The method runs one query and at most one DML statement for the whole batch.
Other limits that bulk code can still hit
Moving statements out of loops fixes the per-record cost. It does not remove every limit.
- Records per DML. One
updateof 10,000 or more records exceeds the row limit. If one account has many contacts, a chunk of 200 accounts could match thousands of contacts. - Query rows. A single transaction can retrieve 50,000 rows in total across all queries.
- CPU time. Nested loops over two large lists cost
n × moperations. Use aMapfor lookups to keep each pass linear. - Shared limits. The limits are shared by all triggers, flows, and code in the transaction. A handler that uses 90 queries leaves little room for anything else.
Common mistakes
- Writing and testing with one record, so loop-based DML or SOQL is never exercised.
- Calling
updateonTrigger.newrecords in abeforecontext. This is unnecessary, and it can cause the trigger to fire again. - Putting the same Id in a list more than once before DML.
- Querying inside a helper method that is called from a loop. The loop is hidden in the caller, but the cost is the same.
- Assuming
Trigger.newis ordered or has a fixed size. Treat it as an unordered batch of any size from 1 to 200.
Checking your work
A method is bulk-safe if you can answer yes to each question:
- Is every
[SELECT ...]outside any loop, including loops in calling methods? - Is every
insert,update,delete, andundeleteoutside any loop? - Do lookups use a
MaporSetinstead of a nested loop? - Are the list or map keys unique before DML?
- Does the method return early when there is nothing to do?
The next step is a test that proves the answers. Insert 200 records in one DML statement and the platform runs the handler with a full batch.
Exercise
A handler's afterUpdate method contains this loop. What happens when 200 accounts are updated in one DML statement, and how do you fix it? for (Account acc : newAccounts) { List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :acc.Id]; for (Contact c : contacts) { c.Description = 'Account updated'; } update contacts; }
Show answer
The loop runs one query and one DML statement per account. The 101st query throws an uncatchable System.LimitException (the query limit is 100), and the whole transaction rolls back. To fix it, collect the account Ids into a Set, run one query with WHERE AccountId IN :accountIds outside the loop, set the Description on each returned contact, add each contact to a List, and run one update on that list after the loop.
Exercise
Why should a before update method assign to fields on Trigger.new records instead of calling update on them?
Show answer
In a before context the platform saves the records after the trigger finishes, so field assignments are persisted with no DML. Calling update on those records is unnecessary, spends DML statements, and can cause the trigger to run again.