Sub topic 4
Governor limits that bulkification protects
This chapter explains the per-transaction limits that make bulkification necessary. It assumes you can read basic Apex, know SOQL and DML syntax, and know that triggers fire on insert, update, delete, and undelete. Later chapters show how to fix code that breaks these limits. This one covers what the limits are, how they are counted, and how triggers break them.
Why limits exist
Salesforce runs many customers' code on shared infrastructure. Governor limits cap how much of that infrastructure one piece of Apex can use. They keep one org's runaway loop from slowing down other orgs.
For trigger authors, the main fact is that limits are counted per transaction, not per trigger and not per record. Your code is judged by how many resources the whole transaction uses.
The limits that matter for triggers
These are the limits that triggers hit most often. The values are for synchronous Apex. Asynchronous Apex has higher values for some limits.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Records retrieved by SOQL | 50,000 | 50,000 |
| DML statements issued | 150 | 150 |
| Records processed by DML | 10,000 | 10,000 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
Two other limits come up in trigger work: callouts (100 per transaction) and Queueable jobs (50 per synchronous transaction). Check the current Apex Developer Guide for exact values, because Salesforce can change them.
Notice that two limits count statements and two count records. A single insert accounts; with 200 records uses one DML statement and 200 DML rows. A for loop that calls insert 200 times uses 200 DML statements, which is more than the limit of 150.
What counts as one transaction
A transaction is one unit of work that commits or rolls back together. A save from the UI is one transaction. An API call is one transaction per batch of records the client sends. A trigger invocation is not a transaction. It runs inside one.
Triggers can run more than once inside a single transaction, and all those runs share one set of limits. There are two common ways this happens:
- Chunking. If one DML statement touches more than 200 records, Salesforce calls your trigger once per chunk of up to 200. A
insertof 600 records runs the trigger three times in the same transaction. - Cascades. A trigger on one object can perform DML on another object. That fires the second object's triggers, workflow field updates, flows, and so on, all inside the same transaction.
This is why a trigger that "works fine" for 5 records can fail in production. The limit is not about your trigger alone. It is about everything the transaction does.
Seeing the limit break
Here is the anti-pattern from the plan. It runs one query per record.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one SOQL query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
if (a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}The arithmetic is simple. The loop issues one query per contact. With 100 contacts, it issues exactly 100 queries, which is the limit. The 101st contact pushes the transaction over, and Salesforce throws:
System.LimitException: Too many SOQL queries: 101The trigger has a second problem. If a contact has no AccountId, the query returns no rows, and assigning an empty result to a single Account variable throws a QueryException. A bulkified version, shown in a later chapter, avoids both problems.
You can reproduce the failure from the Developer Console's anonymous Apex window. Run this against a sandbox or scratch org that has the trigger deployed. It needs one existing account, so it creates one first.
Account acct = new Account(Name = 'Limit Demo', Industry = 'Banking');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 101; i++) {
contacts.add(new Contact(LastName = 'Demo ' + i, AccountId = acct.Id));
}
insert contacts; // fails: Too many SOQL queries: 101If you reduce the loop to 100 iterations, the insert succeeds with no queries to spare. Any other query in the transaction, from another trigger or a flow, would push it over.
Limits are not catchable
A LimitException cannot be caught with try/catch. When it is thrown, the whole transaction rolls back and all your changes are lost. This has two consequences:
- You cannot write code that "recovers" after exceeding a limit. You can only check usage before you reach it (see the chapter on the
Limitsclass). - The failure is all-or-nothing. If record 101 triggers the exception, records 1 through 100 are rolled back too.
Why 200 records is the number to design for
Triggers receive records in lists of up to 200. That is the largest chunk a single trigger run sees, and it is the size that API loads, Data Loader, and Bulk API jobs commonly produce. If your code uses one SOQL query and one DML statement per trigger run, it uses a small, fixed number of statements however many records arrive. If it uses one per record, its usage grows with the batch size.
This gives you a design rule. Count how many limited operations your code uses as a function of the number of records n:
| Pattern | SOQL queries used | Outcome at n = 200 |
|---|---|---|
| Query inside the loop | n | 200, fails at 101 |
| One query before the loop | 1 | 1, safe |
| Query inside a nested loop | n × m | Fails very early |
Your goal is a statement count that stays constant as n grows. Bulkification is the practice of reaching it.
CPU time and heap are limits too
Query and DML counts are the most common failures, but the other limits matter in triggers:
- CPU time. Nested loops over large collections burn CPU even when they issue no queries. A loop that scans a 5,000-item list for every one of 200 records does one million comparisons. Looking up a value in a
Mapinstead of scanning aListremoves that cost. - Heap size. Querying many fields on many records and keeping them all in memory can reach 6 MB. Select only the fields you need and avoid storing the same data in several collections.
- Rows retrieved. A query with a loose
WHEREclause can return more than 50,000 rows and fail even though it is a single query. Filter withIN :idsrather than querying a whole object.
Common errors
- Testing with one record. A trigger tested with a single record never shows a per-record query problem. Always test with 200.
- Forgetting other automation. Your trigger may use 3 queries, but a flow and two other triggers on the same transaction may use 97. Budget for what is already in the transaction.
- Assuming each trigger run has fresh limits. Chunks and cascades share counters, as the diagram shows.
- Reading a limit as per object. Limits are per transaction, not per sObject type.
Exercise
A Data Loader job inserts 1,000 Contacts through the SOAP API with a batch size of 200. The Contact trigger runs one SOQL query per record. In how many of the five batches does the trigger fail, and why?
Show answer
All five batches fail. Each batch of 200 is a separate transaction with its own limits, and each one needs 200 queries, which is more than the limit of 100 for synchronous Apex. The failure happens at the 101st record of each batch. The error is a LimitException ("Too many SOQL queries: 101"), and each batch rolls back because the exception cannot be caught.
Exercise
A trigger makes no SOQL queries and no DML calls. It still fails on large batches with a CPU time error. Name one likely cause and one fix.
Show answer
A likely cause is a nested loop that compares every record in Trigger.new against every item in a List, which costs n × m operations. The fix is to load the comparison data into a Map keyed by the lookup value and use map.get(key) inside the loop, which makes each lookup a constant-time operation.