Sub topic 6
Measuring usage with the Apex Limits class
This chapter assumes you can read basic Apex, know what a transaction is (one unit of execution, such as a trigger run or a single execute call), and have seen governor limits in the earlier chapter. Here you will measure how much of those limits your code has used while it runs.
What the Limits class does
Governor limits cap what one Apex transaction can consume. The Limits class is a built-in set of static methods that report two things:
- Used so far: methods named
getX(), such asLimits.getQueries(). - Ceiling: methods named
getLimitX(), such asLimits.getLimitQueries().
The Limits class measures the current transaction only. It does not show your daily API request count. For that, use the REST Limits resource covered in a later chapter.
Common methods
| Resource | Used | Ceiling |
|---|---|---|
| SOQL queries | `Limits.getQueries()` | `Limits.getLimitQueries()` |
| DML statements | `Limits.getDmlStatements()` | `Limits.getLimitDmlStatements()` |
| CPU time (ms) | `Limits.getCpuTime()` | `Limits.getLimitCpuTime()` |
| Heap size (bytes) | `Limits.getHeapSize()` | `Limits.getLimitHeapSize()` |
The ceilings depend on context. For example, synchronous and asynchronous transactions get different heap and SOQL ceilings. Always read the ceiling from getLimitX() instead of hard-coding a number.
Printing a usage snapshot
This snippet prints four limits at the point where it runs.
System.debug('SOQL queries: ' + Limits.getQueries() + '/' + Limits.getLimitQueries());
System.debug('DML statements: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements());
System.debug('CPU time (ms): ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
System.debug('Heap size (bytes): ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());Run it in Anonymous Apex with the Developer Console open, then filter the log for USER_DEBUG. At the start of a fresh transaction, the used values are near zero.
Measuring a block of code
A single snapshot says little. Take one before and one after a piece of code, and subtract. The difference is the cost of that code.
Integer queriesBefore = Limits.getQueries();
Integer cpuBefore = Limits.getCpuTime();
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 200];
for (Account a : accounts) {
a.Description = 'Reviewed ' + a.Name;
}
Integer queriesUsed = Limits.getQueries() - queriesBefore;
Integer cpuUsed = Limits.getCpuTime() - cpuBefore;
System.debug('Block used ' + queriesUsed + ' queries and ' + cpuUsed + ' ms CPU');This block should report one query. CPU time varies between runs, so compare several runs instead of trusting one number.
Acting on usage at runtime
You can also use the values to change behavior. A common pattern is to stop early, or defer work, when a limit is close.
public with sharing class LimitGuard {
public static Boolean queriesLow() {
Integer remaining = Limits.getLimitQueries() - Limits.getQueries();
return remaining < 5;
}
}Code that calls LimitGuard.queriesLow() can then hand the rest of its work to a Queueable job instead of failing with a limit exception.
Common errors
- Reading limits in the wrong place. Values are per transaction. A value read in a test method does not reflect production behavior.
- Hard-coding ceilings. A fixed
100breaks when the code runs asynchronously or the platform changes the limit. - Leaving debug statements in hot paths.
System.debugitself costs CPU time, and it costs more inside loops. Log summaries after the loop. - Expecting the Limits class to catch everything. Some limits are not exposed there. Uncatchable
System.LimitExceptionerrors still end the transaction if you cross a ceiling.
Exercise
A trigger runs 40 SOQL queries before your code starts. You want your code to defer work to a Queueable job when fewer than 10 queries remain. Which expression gives the remaining count, and why not compare against 100?
Show answer
Use Limits.getLimitQueries() - Limits.getQueries() and check whether it is below 10. Comparing against a fixed 100 is wrong because the ceiling depends on the execution context, for example synchronous versus asynchronous, so getLimitQueries() is the reliable source.