Sub topic 15
Measuring Limit Usage with the Limits Class
Prerequisites and goal
This chapter assumes you can write a bulkified trigger with a handler class, and that you know the main per-transaction governor limits. It also assumes you have run Apex tests and read a debug log. Here you will learn to measure how much of each limit a transaction uses. That lets you confirm a bulkified trigger is efficient, and you can find the step that is consuming a limit before it throws an exception.
What the Limits class does
System.Limits is a built-in class with two kinds of static methods:
getX()returns how much of a resource the current transaction has used so far.getLimitX()returns the maximum allowed for the current execution context.
The pairing matters because limits differ by context. A synchronous transaction allows 100 SOQL queries and 6 MB of heap. An asynchronous one, such as Queueable Apex, allows 200 queries and 12 MB of heap. Calling getLimitQueries() returns the correct ceiling for wherever your code is running, so you should not hard-code these numbers.
| Resource | Used so far | Maximum | Synchronous limit |
|---|---|---|---|
| SOQL queries | `Limits.getQueries()` | `Limits.getLimitQueries()` | 100 |
| Rows returned by SOQL | `Limits.getQueryRows()` | `Limits.getLimitQueryRows()` | 50,000 |
| DML statements | `Limits.getDmlStatements()` | `Limits.getLimitDmlStatements()` | 150 |
| Rows processed by DML | `Limits.getDmlRows()` | `Limits.getLimitDmlRows()` | 10,000 |
| Apex CPU time (ms) | `Limits.getCpuTime()` | `Limits.getLimitCpuTime()` | 10,000 |
| Heap size (bytes) | `Limits.getHeapSize()` | `Limits.getLimitHeapSize()` | 6,000,000 |
| Queueable jobs enqueued | `Limits.getQueueableJobs()` | `Limits.getLimitQueueableJobs()` | 50 |
The counters are cumulative for the whole transaction, not per trigger. If a before trigger, an after trigger, a flow, and a validation rule all run, they all draw from the same budget. Each counter reports the transaction's total at that moment, and not only your code's share.
Logging usage at a point in time
A small helper keeps measurements consistent. It prints every counter you care about with its ceiling.
public with sharing class LimitsLogger {
public static void log(String label) {
System.debug(LoggingLevel.INFO,
label
+ ' | SOQL ' + Limits.getQueries() + '/' + Limits.getLimitQueries()
+ ' | Rows ' + Limits.getQueryRows() + '/' + Limits.getLimitQueryRows()
+ ' | DML ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements()
+ ' | DML rows ' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows()
+ ' | CPU ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime()
+ ' | Heap ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize()
);
}
}Call it before and after the section you want to measure. The difference between the two lines is the cost of that section. You can run the next snippet in Anonymous Apex to see the difference between a per-record query and one bulk query.
List<Account> accounts = [SELECT Id FROM Account LIMIT 20];
Set<Id> ids = new Map<Id, Account>(accounts).keySet();
LimitsLogger.log('start');
for (Id accountId : ids) {
Account a = [SELECT Id, Industry FROM Account WHERE Id = :accountId];
}
LimitsLogger.log('after per-record queries');
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :ids]
);
LimitsLogger.log('after one bulk query');The first log line shows one query used for setup. The second grows by one query per account. The third grows by exactly one more. Open the execution log and filter on USER_DEBUG to read the lines. If your org has fewer than 20 accounts, the loop simply runs fewer times.
Where to take measurements
The following diagram shows the loop for measuring a trigger.
There are three practical places to measure.
- Debug logs. Every log ends with a
CUMULATIVE_LIMIT_USAGEsection that lists usage per namespace. It requires no code changes and is the quickest way to see a whole transaction. - Temporary
System.debugcalls. Use the helper above to narrow down which method consumes the most. - Test assertions. These turn a performance expectation into a check that fails when someone adds a query inside a loop.
Asserting limit budgets in tests
A test that inserts 200 records already fails if you exceed a hard limit. A budget assertion is stricter. It also fails when a change uses more queries than you intended, long before the limit is at risk.
Test.startTest() resets the governor counters, and Test.stopTest() restores the earlier values. So you read the counters inside the startTest and stopTest block, after the operation. Reading them after stopTest() returns the setup numbers.
This test measures the trigger from the earlier handler chapter.
@IsTest
private class OpportunityTriggerLimitsTest {
@IsTest
static void staysWithinBudgetFor200Records() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Budget ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
Test.startTest();
update opps;
Integer queriesUsed = Limits.getQueries();
Integer dmlUsed = Limits.getDmlStatements();
Integer dmlRowsUsed = Limits.getDmlRows();
Test.stopTest();
System.assert(queriesUsed <= 5,
'Expected at most 5 queries, used ' + queriesUsed);
System.assert(dmlUsed <= 5,
'Expected at most 5 DML statements, used ' + dmlUsed);
System.assertEquals(400, dmlRowsUsed,
'200 opportunity updates plus 200 task inserts');
}
}Choose a budget with some headroom, such as 5 where you expect 1 or 2. Other automation in the org, like flows or managed packages, may add a query or two. A budget that is too tight produces false failures. A budget that is too loose will not catch a regression.
The exact DML row count of 400 works here because the update touches 200 opportunities and the trigger inserts 200 tasks. If your org adds more automation on these objects, relax that assertion to a range.
Using limits to make runtime decisions
You can also use the counters in production code. A common use is checking remaining headroom before an optional step, for example deciding whether to run extra work inline or hand it to Queueable Apex.
public with sharing class HeadroomCheck {
public static Boolean hasQueryHeadroom(Integer needed) {
return (Limits.getLimitQueries() - Limits.getQueries()) >= needed;
}
}Use this sparingly.
- It does not replace bulkification. A trigger that skips work because it ran out of queries leaves data silently incomplete, which is worse than an error that rolls back the transaction.
- It suits work that is safe to defer, such as enrichment or notifications, and the deferred path must still run later.
System.LimitExceptioncannot be caught. Once a limit is exceeded, nocatchblock runs, so a check beforehand is the only guard.
Common pitfalls
- Reading after
stopTest(). The counters have returned to their pre-startTestvalues, so your measurement is wrong. - Assuming one trigger run per transaction. A single DML on 201 records fires the trigger twice, in chunks of 200 and 1, and both runs share the same counters. Measure with a realistic batch size.
- Confusing
getCpuTime()with wall-clock time. It counts Apex CPU time only. Time spent waiting on the database does not count, and the value varies between runs. Treat CPU assertions as loose guardrails. - Logging too much in production.
System.debugcalls themselves cost CPU. Remove the logging calls you added for diagnosis, or gate them behind a log level. - Forgetting that limits are per transaction. Totals from
getQueries()include queries made by other code in the same transaction, so a high number may not originate in your trigger. Use the debug log to find the source.
Exercise
A test calls Test.startTest(), runs update opps, calls Test.stopTest(), and then reads Limits.getQueries() to assert a query budget. The assertion passes even when the trigger contains a SOQL query inside a loop. Why, and how do you fix it?
Show answer
Test.stopTest() restores the counters to their values from before startTest(), so the value read afterward reflects only the setup code, not the update. Read Limits.getQueries() inside the startTest/stopTest block, right after the update statement, and store it in a variable to assert on after stopTest().
Exercise
A handler checks Limits.getQueries() < Limits.getLimitQueries() before running a required validation query, and skips the query otherwise. Why is this a poor use of the Limits class, and what should it do instead?
Show answer
Skipping a required step leaves records saved without the validation, so data quality fails silently. The handler should be bulkified so it uses a fixed small number of queries. Only optional or deferrable work should be gated on remaining headroom, and that work should be moved to Queueable Apex rather than dropped.