Sub topic 6
Designing for Bulk: Why It Matters
This chapter assumes you know the Salesforce data model, can build a simple record-triggered flow, and understand loops and collections. It also assumes you have read the previous chapter on governor limits. Here you will see why automation must handle many records at once, and how to write Apex and Flow that does.
What "bulk" means
Salesforce rarely processes one record at a time. A data load, an API call, a list view mass update, or a Batch Apex job can all save up to 200 records in a single operation. Salesforce then runs your automation once for that whole group, inside one transaction.
Governor limits are counted per transaction, not per record. If your logic spends one SOQL query per record, 200 records need 200 queries. The synchronous limit is 100 queries, so the transaction fails. Automation that works when you test with one record can break the first time someone imports a file.
A bulk-safe design uses a fixed number of queries and DML statements, no matter how many records arrive.
The anti-pattern: work inside the loop
The usual mistake is a query or DML statement inside a for loop.
for (Contact c : Trigger.new) {
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
a.Description = 'Has contacts';
update a;
}With 200 contacts, this runs 200 queries and 200 updates. It hits the 100 query limit first and throws a System.LimitException. That exception cannot be caught, and the whole transaction rolls back.
The bulk-safe pattern
Use three steps: collect, query once, act once.
- Collect the IDs you need into a
Set. - Run one query that filters with
IN :ids. - Change the records in memory, then run one DML statement on the list.
trigger ContactTrigger on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<Account> toUpdate = new List<Account>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
toUpdate.add(new Account(
Id = (Id) ar.get('acctId'),
Contact_Count__c = (Integer) ar.get('total')
));
}
update toUpdate;
}This trigger assumes a custom number field Contact_Count__c exists on Account. It uses one aggregate query and one update, whether 1 or 200 contacts arrive. The null check matters because contacts without an account would otherwise put null into the set.
Bulk safety in Flow
Record-triggered flows are bulkified by the platform. When 200 records fire a flow, Salesforce runs the flow interviews together and groups matching operations, such as Create Records or Update Records elements. You still need to avoid the same mistake by hand.
- Do not put Get Records, Create Records, Update Records, or Delete Records elements inside a Loop element.
- Inside a loop, only change variables or add items to a collection. After the loop, run one DML element on the whole collection.
- Use Get Records once, outside the loop, and read its results from the collection.
Flow Builder warns you when it finds a data element inside a loop. Treat that warning as an error to fix.
Bulk safety in invocable methods
When a flow calls Apex, the method receives a list of requests, one per interview. Your method must handle the whole list in one call. The signature List<Request> is the reason. A method that takes a single value cannot be invoked in bulk. Run one query for all requests and one update for all results, as the invocable example later in this tutorial does.
Test with 200 records
Bulk bugs only appear with volume, so test for volume. Insert 200 records in one DML statement and check the result.
@IsTest
private class ContactTriggerTest {
@IsTest
static void countsContactsInBulk() {
Account a = new Account(Name = 'Acme');
insert a;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Contact ' + i, AccountId = a.Id));
}
insert contacts;
a = [SELECT Contact_Count__c FROM Account WHERE Id = :a.Id];
Assert.areEqual(200, a.Contact_Count__c);
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Too many SOQL queries: 101" | Query inside a loop | Query once with `IN :ids` |
| "Too many DML statements: 151" | DML inside a loop | Add records to a list, run DML once |
| Flow works for one record, fails on import | Data element inside a Loop | Move it outside, use a collection |
| Trigger fails on records with no parent | Unchecked `null` ID in the set | Skip `null` before adding |
Exercise
A flow loops over a collection of 150 opportunities and runs an Update Records element for each one inside the loop. Why is this a problem, and how do you fix it?
Show answer
Each pass through the loop runs a separate DML statement, so 150 passes exceed the limit of 150 DML statements once other automation also uses DML, and it wastes the transaction budget even below the limit. Inside the loop, set the new field values on each record and add the record to a collection variable. After the loop ends, run one Update Records element on that collection.