Sub topic 2
The limits that matter most in a transaction
This chapter assumes you can read basic Apex, use List, Set and Map, write simple SOQL and DML, and know what a trigger and its before and after events are. It covers the per-transaction limits that cause most production failures, where their values come from, and how to recognize the code that breaks them.
What a transaction is
A transaction is one unit of work that Salesforce either commits completely or rolls back completely. Governor limits are counted per transaction. A transaction can start from several entry points:
- A user saves a record in the UI.
- An API call inserts or updates records.
- A trigger, a Visualforce or Aura controller method, or a test method runs.
- An asynchronous job runs one of its methods, such as one
executecall of a Batch Apex job.
Everything that runs inside that entry point shares one set of counters. If a trigger fires a flow, which fires another trigger, all of that work draws from the same budget. The counters are not reset between your code and any automation it triggers.
When a limit is exceeded, Salesforce throws a System.LimitException. This exception cannot be caught with try/catch. The transaction stops and all of its database changes are rolled back. That is why limits are a design concern and not something to handle with error handling.
try {
for (Integer i = 0; i < 101; i++) {
List<Account> accts = [SELECT Id FROM Account LIMIT 1];
}
} catch (Exception e) {
// Never runs for a LimitException. The transaction is already doomed.
System.debug('Caught: ' + e.getMessage());
}The limits to know first
Salesforce publishes many limits. A small group causes most real failures. The values below are the ones for synchronous Apex, and they are the figures most developers meet first.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Records returned by SOQL queries | 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 points about the table:
- The SOQL query count and DML statement count limits are about how many statements run, not how many records they touch. One query that returns 40,000 rows counts as one query and 40,000 rows.
- Asynchronous means Queueable, Batch,
@futureand Scheduled Apex. It gets larger query, CPU and heap allowances because no user is waiting on the result.
The values above are accurate at the time of writing, but Salesforce can change them between releases. Treat them as orientation, not as constants to hard-code. The authoritative source is the "Execution Governors and Limits" page in the Apex Developer Guide. You can also read live values from the Limits class, covered in a later chapter.
SOQL queries
Each SOQL statement you execute counts once, whether it is written inline in square brackets or run with Database.query. A for loop over a query, such as for (Account a : [SELECT Id FROM Account]), still counts as one query, although the platform fetches the rows in chunks of 200 behind the scenes.
The query count is the limit that bites first in trigger code. A loop that runs one query per record reaches 101 queries after 101 iterations.
Rows returned by queries
A transaction can retrieve at most 50,000 rows in total across all of its queries. This is a running total, not a per-query figure. Two queries that each return 30,000 rows exceed it. If a query would exceed the total, Salesforce throws System.LimitException: Too many query rows: 50001.
A related limit applies to sub-queries and relationship queries. For example, a parent query that includes a child sub-query counts the child rows too.
DML statements and DML rows
Each insert, update, delete, undelete, upsert or merge statement counts as one DML statement, as does each Database.insert style call. A single statement can process many records, and the number of records is limited separately to 10,000 per transaction.
This split is what makes bulkification work. A statement that handles 200 records in a list costs 1 of 150 statements. Doing the same work with 200 separate statements would fail.
CPU time
CPU time measures how long the Salesforce application servers spend running your Apex code, in milliseconds. Synchronous transactions get 10,000 ms. Some work is not counted: time waiting on the database for a query or DML is not Apex CPU time, and neither is time spent in callouts. Work done by declarative automation does count toward the transaction in some cases, which is why heavy Flow plus Apex combinations can reach the limit.
Typical causes of CPU limit failures:
- Nested loops over large lists, which grow with the product of the two sizes.
- Repeated string concatenation or JSON serialization in a loop.
- Many triggers, flows and validation rules all running on the same save.
A CPU failure shows as System.LimitException: Apex CPU time limit exceeded.
Heap size
Heap is the memory your transaction uses to hold variables, collections and query results. The synchronous limit is 6 MB. Large query results stored in lists, large Blob or String values, and maps built from big data sets all use heap. The error is System.LimitException: Apex heap size too large.
One common source is querying fields you do not need. Selecting long text fields for 50,000 rows can use the whole heap long before the row limit is reached.
How a trigger multiplies the cost
Triggers receive records in batches of up to 200 for a single save operation from the API or a data load. The trigger code runs once per batch, not once per record. This means a per-record query inside a for loop over Trigger.new costs up to 200 queries per batch, which is over the limit of 100.
Here is the anti-pattern from the topic plan.
trigger ContactBefore on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
c.Description = 'Industry: ' + a.Industry;
}
}This code passes when a user creates one Contact in the UI. It passes in a quick manual test. It fails when a data load inserts 200 Contacts, because the 101st iteration runs the 101st query. The failure appears only in bulk, which is why code like this reaches production.
The cost model is simple: take the number of SOQL or DML statements inside a loop and multiply by the loop count. If that product can exceed the limit, the code is unsafe.
flowchart TD
A[Data load of 200 Contacts] --> B[Trigger runs once with 200 records]
B --> C{Query inside loop?}
C -->|Yes| D[200 queries issued]
D --> E[Limit of 100 exceeded]
E --> F[LimitException and full rollback]
C -->|No| G[1 query issued]
G --> H[Transaction commits]The diagram above is a plain flowchart for orientation. The next block is the same idea in the platform's required diagram format.
The fix in outline
The bulkified version collects Ids first, runs one query, and then reads from a Map.
trigger ContactBefore on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}
}This uses one query for 1 record or 200. The row count stays bounded by the number of distinct parent Accounts. Later chapters walk through this pattern in detail. Here the point is the counting: the query count no longer depends on the batch size.
DML follows the same rule. Add records to a List in the loop and run one statement after it.
trigger AccountAfter on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}Common errors and edge cases
- Assuming the limit is per trigger. The counters are per transaction. Two triggers on the same object, plus a flow, plus a managed package all spend from the same budget. A trigger that uses 60 queries is safe alone and fails when another component uses 50.
- Counting records instead of statements. A DML statement on a list of 200 records is one statement. Developers sometimes split lists into smaller chunks "to be safe". That only uses up the statement limit faster.
- Forgetting the queries in called methods. A helper method with a query inside, called from a loop, has the same cost as an inline query. The loop does not need to be visible in the method itself.
- Testing with one record. A test that inserts one record cannot reveal a limit problem that appears at 200.
- Relying on
try/catch. As shown earlier,LimitExceptioncannot be caught. - Ignoring 50,000 rows. A query without a selective
WHEREclause on a growing object works in a sandbox and fails in production once the data grows. - Reading limits from memory. Limits differ between synchronous and asynchronous contexts and can change by release.
Two limits are also worth knowing by name, although they come up less often: 100 callouts per transaction, and 2,000 total pending operations of certain kinds. The Apex Developer Guide lists them all.
Putting numbers on a design
You can estimate risk before you run anything. Take this example: a trigger on Opportunity runs one query and one update per record in the batch, in a synchronous transaction.
- Queries: 1 per record, limit 100. Safe up to 100 records, unsafe at 101.
- DML statements: 1 per record, limit 150. Safe up to 150 records.
- The first limit reached is the query limit, at record 101.
After bulkifying, the same trigger uses 1 query and 1 DML statement regardless of batch size. The remaining risks are the row limits (50,000 queried, 10,000 changed), CPU time and heap, which depend on data volume and loop complexity and not on statement counts.
Exercise
A before-insert trigger on Contact receives 200 records. Inside a loop over Trigger.new it runs one SOQL query and one update statement per record, in a synchronous transaction. At which record does the transaction first fail, and which limit causes it? What would the counts be after bulkifying so that the trigger uses one query and one update on a List?
Show answer
It fails at record 101, when the 101st SOQL query runs, because the synchronous limit is 100 queries. The DML limit of 150 statements would have been the next to fail. After bulkifying, the trigger uses 1 query and 1 DML statement for any batch size up to 200, so neither statement limit is a concern. The row limits (50,000 queried, 10,000 in DML) still apply to the data volume.
Exercise
A developer wraps a loop that runs one query per record in try/catch (Exception e) to handle the case where the 100-query limit is hit. Why does this not work, and what should the developer do instead?
Show answer
A System.LimitException cannot be caught, so the catch block never runs, and the transaction is rolled back. The developer should move the query out of the loop by collecting the keys in a Set, running one query into a Map, and reading from the Map inside the loop.