Sub topic 6
Designing for bulk: why it matters
This chapter assumes you know the Salesforce data model, can find your way around Setup, have built a simple record-triggered flow, and understand loops and collections. It covers why record-triggered automation must handle many records at once, how to write Apex that does, and how Flow handles the same problem.
Why bulk is the normal case
A record-triggered automation does not run once per user click. It runs once per transaction, and a transaction can carry many records. Many things create that situation:
- A data load through Data Loader or Data Import Wizard. Batches go up to 200 records per chunk.
- An API call that inserts or updates a list of records.
- A Batch Apex job, which hands records to your code in scopes of up to 200.
- A flow or Apex class that updates a list, which fires the triggers and flows on that object.
- A list view mass action or a mass edit.
An Apex trigger receives all records in a chunk through Trigger.new, with up to 200 records per invocation. If your code assumes one record, it works in a manual test and fails the first time someone loads data.
A design is bulk-safe when its resource use does not grow in step with the number of records. Queries and DML statements should be counted per transaction, not per record.
The limits that make bulk matter
Governor limits are per transaction and are shared by Flow and Apex, which the previous chapter covered. Two limits matter most here. The values are for synchronous transactions.
| Limit | Synchronous value |
|---|---|
| SOQL queries issued | 100 |
| DML statements issued | 150 |
| Records returned by SOQL | 50,000 |
| Records processed by DML | 10,000 |
Suppose a trigger runs one query for each record. With 200 records that is 200 queries, and the 101st throws System.LimitException: Too many SOQL queries: 101. The whole transaction rolls back, including records that were fine. The same arithmetic applies to DML inside a loop and the 150-statement limit.
The anti-pattern: query or DML inside a loop
This trigger looks reasonable and passes a one-record test. It is not bulk-safe.
trigger ContactTriggerBad on Contact (after insert) {
for (Contact c : Trigger.new) {
// One query per contact
Account a = [SELECT Id, Contact_Count__c FROM Account WHERE Id = :c.AccountId];
a.Contact_Count__c = (a.Contact_Count__c == null ? 0 : a.Contact_Count__c) + 1;
// One DML statement per contact
update a;
}
}It also fails when AccountId is null, because the query returns no rows and assigning the result throws a QueryException. Two defects, and both come from thinking about one record at a time.
The bulk-safe pattern: collect, query once, act once
Bulk-safe Apex follows three steps.
- Loop over
Trigger.newand collect the IDs or keys you need into aSet. - Run one query outside the loop, filtering with
IN :set. - Build a list or map of changes and run one DML statement on it.
Here is the trigger from this tutorial's code example, which follows that pattern.
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;
}The example assumes a custom number field Contact_Count__c exists on Account. Whether the batch holds 1 contact or 200, the trigger uses one aggregate query and one update. The null check on AccountId keeps contacts without an account out of the set.
Three details matter:
- A
Setremoves duplicates. If 200 contacts belong to 3 accounts, the query filters on 3 IDs. - The aggregate query recounts from the database instead of adding one to a stored value. This avoids drift when records are deleted or when two transactions overlap.
update toUpdateon an empty list is allowed and does not count as a DML statement against the limit in a way that causes an error. It is still cleaner to guard it withif (!toUpdate.isEmpty())when the intent matters to a reader.
Accounts with no remaining contacts return no aggregate row, so their count is not reset by this code. That matters for delete and undelete triggers, which this example does not cover. If you extend the trigger to those events, set counts to zero for IDs that are missing from the results.
Using maps for lookups
When you need data from related records inside a loop, query into a Map first and read from it.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account parent = accountsById.get(c.AccountId);
if (parent != null && parent.Industry == 'Banking') {
// Work with the parent here, with no query in the loop
}
}Constructing a Map<Id, SObject> from a query result keys each record by its Id. A map lookup does not touch the database, so it costs no limit.
Other limits that bulk exposes
Query and DML counts get the attention, but a bulk load can hit others.
- CPU time. Synchronous transactions get 10,000 ms. Nested loops over 200 records each cost 40,000 iterations. Replace the inner loop with a map lookup.
- Heap size. Synchronous transactions get 6 MB. Querying wide records you do not need wastes heap. Select only the fields you use.
- Row limits. A query inside a trigger that scans a large table can reach the 50,000-row cap. Add selective filters.
- Callouts. You cannot make a callout from a trigger synchronously, and each transaction allows 100. Use asynchronous Apex such as Queueable for per-record callouts, and send them in batches.
Bulk in Flow
Flow is also built for bulk, but it will not stop you from breaking it. A record-triggered flow runs once per transaction chunk. The runtime processes the batch of records together as long as the flow's elements are bulkified, and many of them are. Get Records, Create Records, Update Records and Delete Records each run as one operation across the interview batch.
The usual mistake is placing a data element inside a Loop element. The loop runs for each item in a collection, and a Get Records or Update Records inside it runs once for each pass.
| Pattern in the flow | Result with 200 records |
|---|---|
| Get Records inside a Loop | Up to 200 queries |
| Update Records inside a Loop | Up to 200 DML statements |
| Loop that assigns values to items, then one Update Records after the loop | One DML statement |
| Get Records before the Loop, then reading results inside it | One query |
The fix mirrors Apex. Query before the loop, change records inside the loop with an Assignment element, add each changed record to a collection variable, and write the collection with one Update Records element after the loop.
Flow has two features that help with this. A record-triggered flow that changes the triggering record in a before-save flow needs no DML at all, because the changes apply to the record before it is saved. That is the cheapest option. And in an after-save flow, the $Record variable holds the single record for each interview, but the platform bundles interviews so that data elements outside loops still run once per batch. You do not have to loop over $Record yourself.
Treat a Get Records inside a loop as a defect during review, the same way you would treat a SOQL query inside a for loop.
Bulk-safe invocable methods
When a flow calls Apex, bulk safety carries over. The platform passes the invocable method a List with one entry for each flow interview in the batch, so the signature takes a list. The previous chapter's example, ApplyDiscountAction, collects discounts into a map, runs one query with IN :percentById.keySet(), and finishes with one update. An invocable method that takes a single parameter instead of a list is not allowed, which the compiler enforces.
Prove it with a bulk test
Bulk safety is a claim you test. Insert 200 records in one operation, since that is the size of a trigger chunk, and check the outcome.
@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);
}
}If the trigger ran a query per contact, this test would fail with a limit exception before reaching the assertion. The test also uses one insert on a list, which is how you must set up bulk data in your own tests. Production deployment requires at least 75% overall Apex code coverage, but coverage only proves lines ran. A single-record test can reach 100% coverage on the bad trigger above.
Test flows the same way. In a sandbox, load 200 records with Data Loader, or use a scripted insert in Anonymous Apex, and watch the debug log for limit usage.
List<Contact> batch = new List<Contact>();
Account a = [SELECT Id FROM Account LIMIT 1];
for (Integer i = 0; i < 200; i++) {
batch.add(new Contact(LastName = 'Bulk ' + i, AccountId = a.Id));
}
insert batch;
System.debug('SOQL used: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());Limits.getQueries() and Limits.getLimitQueries() report what the current transaction has used and what it may use. They help you check the cost of a change.
Common mistakes
- Testing only with one record.
- Putting a query, DML statement, or Get Records element inside a loop.
- Assuming
Trigger.newhas one entry, as inTrigger.new[0]. - Forgetting null checks on lookup fields before building query sets.
- Treating a passing test with 75% coverage as proof of bulk safety.
- Adding a new automation without counting the queries and DML statements already used by others on the same object. Limits are shared, so a design that is safe alone can fail in combination.
Exercise
A record-triggered flow on Opportunity has a Loop over a collection of related Contacts. Inside the loop, an Update Records element updates each contact. A data load of 200 opportunities, each with 1 contact, causes a DML limit error. What is the cause, and how should the flow be restructured?
Show answer
Update Records inside the loop runs one DML statement per contact. With 200 contacts that is 200 statements, which exceeds the limit of 150. Restructure the flow so the loop uses an Assignment element to change each contact and add it to a collection variable, then place a single Update Records element after the loop that saves the whole collection.
Exercise
Why can a trigger that runs a SOQL query inside a for loop over Trigger.new reach 100% code coverage and still be unsafe, and what test would expose the problem?
Show answer
Coverage counts executed lines, and a test that inserts one record executes every line while running only one query. The problem appears only when the batch is large. A test that inserts 200 records in a single DML operation causes 200 queries and throws a "Too many SOQL queries: 101" limit exception, which fails the test.