Sub topic 8
Checking Consumption with the Limits Class
This chapter assumes you can read Apex classes and triggers, and that you know basic SOQL and DML. You should also know that governor limits are per-transaction caps on resources such as queries, DML statements, CPU time and heap. The chapter shows how to measure how much of each limit a transaction has used, so you can find problems before the platform throws a limit exception.
What the Limits class does
Limits is a built-in Apex class in the System namespace. It reports the state of the current transaction's governor limits. Most resources have a pair of static methods:
Limits.getX()returns how much of resource X the transaction has used so far.Limits.getLimitX()returns the maximum allowed for resource X in the current context.
The numbers are for the whole transaction, not for one class or one trigger. If a flow, a trigger and a helper class all run in the same transaction, they all add to the same counters.
The getLimitX() values are not constants you should copy into your code. Some limits differ between synchronous and asynchronous execution. For example, the heap limit is larger in asynchronous Apex, and so is the CPU time limit. Reading the limit at run time gives you the value that applies to the code that is running.
The most useful methods
| Resource | Used so far | Maximum |
|---|---|---|
| SOQL queries | `Limits.getQueries()` | `Limits.getLimitQueries()` |
| Rows returned by SOQL | `Limits.getQueryRows()` | `Limits.getLimitQueryRows()` |
| DML statements | `Limits.getDmlStatements()` | `Limits.getLimitDmlStatements()` |
| Rows processed by DML | `Limits.getDmlRows()` | `Limits.getLimitDmlRows()` |
| CPU time (ms) | `Limits.getCpuTime()` | `Limits.getLimitCpuTime()` |
| Heap size (bytes) | `Limits.getHeapSize()` | `Limits.getLimitHeapSize()` |
| Future calls | `Limits.getFutureCalls()` | `Limits.getLimitFutureCalls()` |
| Queueable jobs | `Limits.getQueueableJobs()` | `Limits.getLimitQueueableJobs()` |
Check the Apex Developer Guide section on execution governors and limits for the current maximums. Salesforce changes these values between releases, and this chapter does not state them for that reason.
Printing a snapshot
The simplest use is to print the counters at the point you care about. Run this in Anonymous Apex or inside a method:
System.debug('SOQL queries: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML statements: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU time (ms): ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());
System.debug('Heap size (bytes): ' + Limits.getHeapSize() + ' of ' + Limits.getLimitHeapSize());Each line prints a pair such as SOQL queries: 3 of 100. Open the debug log and filter for USER_DEBUG to see them.
Measuring a single operation
Because the counters only go up during a transaction, you can find the cost of one piece of code by reading a counter before and after it and subtracting. This is the most practical way to use Limits.
Integer queriesBefore = Limits.getQueries();
Integer rowsBefore = Limits.getQueryRows();
List<Account> accounts = [SELECT Id, Industry FROM Account LIMIT 50];
Integer queriesUsed = Limits.getQueries() - queriesBefore;
Integer rowsUsed = Limits.getQueryRows() - rowsBefore;
System.debug('That block used ' + queriesUsed + ' queries and ' + rowsUsed + ' rows.');The same technique works for a method call. Suppose you suspect that a helper is expensive:
Integer queriesBefore = Limits.getQueries();
Integer dmlBefore = Limits.getDmlStatements();
AccountService.updateIndustries(accounts);
System.debug('updateIndustries cost '
+ (Limits.getQueries() - queriesBefore) + ' queries and '
+ (Limits.getDmlStatements() - dmlBefore) + ' DML statements.');If the cost grows with the number of records you pass in, the method is not bulkified. A bulk-safe method costs about the same for 1 record as for 200.
A diagram of the measurement pattern
Using the loop test to expose a bug
Here is the anti-pattern from the earlier chapters, with a counter added so the problem is visible. The trigger runs one query per Contact:
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;
}
System.debug('Queries used: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
}Insert one Contact and the log shows Queries used: 1. Insert 50 and it shows 50. Insert more than the query limit in one transaction and the trigger fails with a System.LimitException. The counter makes the linear growth visible long before the failure.
The bulkified version uses one query for any batch size:
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;
}
}
System.debug('Queries used: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
}The log now shows the same count whether you insert 1 Contact or 200.
Guarding against a limit at run time
Limits can also change what the code does. If an operation is optional, you can skip it, or hand it to asynchronous Apex, when the transaction is close to a cap.
public class AuditService {
public static void logIfRoom(List<Account> accounts) {
Integer dmlLeft = Limits.getLimitDmlStatements() - Limits.getDmlStatements();
Integer rowsLeft = Limits.getLimitDmlRows() - Limits.getDmlRows();
if (dmlLeft < 1 || rowsLeft < accounts.size()) {
System.debug(LoggingLevel.WARN, 'Skipping audit: not enough DML capacity left.');
return;
}
List<Task> tasks = new List<Task>();
for (Account a : accounts) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Audit'));
}
insert tasks;
}
}This check compares the remaining capacity with what the work needs. It checks both DML statements and DML rows, because either one can be the limit that you hit.
Use this sparingly. A guard like this is a safety net for optional work. It is not a substitute for bulkifying the code. If core business logic needs the capacity, skipping it silently hides a bug, so prefer a visible failure or a move to Queueable or Batch Apex.
Common mistakes
- Treating the counters as per-class. They are per-transaction. A trigger that uses 2 queries may run in a transaction that already used 98.
- Hard-coding limit values. Use
getLimitX()so the code follows both the current release and the execution context. - Measuring with too little data. A test that inserts one record shows a cost of 1 for both the loop and the bulk version. Measure with a full batch of 200 records.
- Leaving debug lines in production code. Debug statements consume CPU time and log space. Remove them, or keep them behind a
LoggingLevelthat you do not log in production. - Expecting
Limitsto refresh inside a transaction. Only a new transaction resets the counters, for example eachexecutecall of a Batch Apex job.Test.startTest()andTest.stopTest()give the code between them a fresh set of limits in a test. - Catching
LimitException. A limit exception cannot be caught withtry/catch. The transaction ends. Checking in advance withLimitsis the only way to react.
Using Limits in tests
Tests are a good place to assert on consumption, because they fail the build when someone adds a query inside a loop later. Wrap the code under test in Test.startTest() and Test.stopTest(), then compare the counters:
@IsTest
private class ContactBeforeLimitsTest {
@IsTest
static void queryCountDoesNotGrowWithBatchSize() {
Account acc = new Account(Name = 'Parent');
insert acc;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Bulk ' + i, AccountId = acc.Id));
}
Test.startTest();
insert contacts;
Integer queries = Limits.getQueries();
Test.stopTest();
System.assert(queries < 10,
'Expected a small, fixed number of queries but used ' + queries);
}
}Between startTest() and stopTest() the counters start from zero, so queries reflects only the insert and the trigger work it caused. The threshold of 10 is a deliberate loose bound. It is far below 200, so a per-record query would fail the test, but it leaves room for other triggers or automation on the object.
Choosing where to measure
| Situation | Approach |
|---|---|
| Exploring a slow or failing transaction | Print counters with `System.debug` and read the debug log |
| Finding which method is expensive | Read a counter before and after the call and subtract |
| Preventing regressions | Assert on counters in a bulk test |
| Optional work near a cap | Check remaining capacity, then skip or defer |
The debug log also ends with a CUMULATIVE_LIMIT_USAGE section that lists each limit by namespace. It is useful when you cannot edit the code, for example when the transaction includes managed package code.
Exercise
A helper method ContactService.enrich(List<Contact> contacts) is called from a trigger. You measure it with Limits.getQueries() before and after the call. With 1 Contact it uses 1 query. With 200 Contacts it uses 200 queries. What does this tell you, and what would you look for in the method?
Show answer
The query count grows with the number of records, so the method is not bulkified. It almost certainly runs a SOQL query inside a loop over the contacts. Collect the needed Ids into a Set before the loop, run one query that filters with IN :ids into a Map, and look up each record by Id inside the loop. After the change, the method should use the same number of queries for 1 and for 200 Contacts.
Exercise
Why does try { insert records; } catch (System.LimitException e) { ... } not protect you when the transaction is out of DML statements, and what should you do instead?
Show answer
A System.LimitException cannot be caught. When a governor limit is exceeded the transaction ends and rolls back, and the catch block never runs. Instead, check capacity before the work, for example by comparing Limits.getDmlStatements() with Limits.getLimitDmlStatements(), and either skip optional work or move the work to Queueable or Batch Apex.