Sub topic 6
Measuring usage with the Apex Limits class
This chapter assumes you can read basic Apex, know what a trigger and a transaction are, and have seen the governor limits introduced in the previous chapter. Here you learn how to measure consumption from inside a running transaction, so you can log it, branch on it, and catch problems before the platform throws an uncatchable exception.
What the Limits class is
The Limits class is a built-in Apex class in the System namespace. It reports how much of each per-transaction governor limit the current execution context has used so far. Every limit has two methods:
Limits.getX()returns the amount consumed so far.Limits.getLimitX()returns the ceiling for the current context.
For example, Limits.getQueries() is the number of SOQL queries issued so far, and Limits.getLimitQueries() is the maximum allowed. The limit methods return the ceiling for the context you are running in, not a fixed number. A synchronous transaction allows 100 SOQL queries, while an asynchronous one (Queueable, Batch, @future) allows 200. Heap size and CPU time also differ between synchronous and asynchronous contexts. Always read the ceiling from getLimitX() instead of hardcoding it.
The class measures one transaction only. It does not tell you how many REST API requests your org has used in 24 hours. That is the job of the REST Limits resource, covered in a later chapter.
Commonly used methods
| Resource | Used so far | Ceiling |
|---|---|---|
| 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()` |
| Callouts | `Limits.getCallouts()` | `Limits.getLimitCallouts()` |
| Queueable jobs enqueued | `Limits.getQueueableJobs()` | `Limits.getLimitQueueableJobs()` |
| Future calls | `Limits.getFutureCalls()` | `Limits.getLimitFutureCalls()` |
Other methods exist for SOSL queries, email invocations, and more. The Apex Reference Guide lists them all under the Limits class.
A first measurement
This snippet prints four of the most common counters. Run it in Anonymous Apex from the Developer Console, then open the debug log and filter for USER_DEBUG.
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());A fresh Anonymous Apex run starts with counters near zero. The output looks like SOQL queries: 0/100.
To see the counters move, put a query between two readings:
Integer before = Limits.getQueries();
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 10];
Integer after = Limits.getQueries();
System.debug('Queries used by this statement: ' + (after - before));
System.debug('Rows returned so far: ' + Limits.getQueryRows());Taking a reading before and after a block of code is the standard way to attribute cost to that block. The difference is what the block consumed.
What counts and what does not
Intermediate developers often misread these counters in a few predictable ways.
- A query counts once, however many rows it returns.
getQueries()goes up by one for each SOQL statement. Rows are tracked separately bygetQueryRows(). - A SOQL for loop is still one query per batch of records, not per record. The query is counted, but Apex retrieves records in chunks internally, so the loop does not multiply the query count. Rows still count toward
getQueryRows(). - Aggregate queries count rows differently. A
COUNT()query returns one row but may count against the row limit by the number of records it scanned in some forms. Test withgetQueryRows()instead of assuming. - Callouts count at the moment you make them, not when the response returns.
getCpuTime()includes only Apex CPU time. Time spent waiting on the database or on a callout does not count toward it.getHeapSize()is an approximation. It is useful for trend and threshold checks but should not be treated as an exact byte count.
Using the counters to make decisions
Reading counters is most valuable when your code reacts to them. The pattern is to check headroom before doing something expensive, then take a safer path when headroom is low.
public with sharing class SafeProcessor {
private static final Decimal CPU_SAFETY_RATIO = 0.80;
public static Boolean hasCpuHeadroom() {
Decimal used = Limits.getCpuTime();
Decimal max = Limits.getLimitCpuTime();
return used < max * CPU_SAFETY_RATIO;
}
public static Boolean hasQueryHeadroom(Integer needed) {
return (Limits.getLimitQueries() - Limits.getQueries()) >= needed;
}
public static void process(List<Id> accountIds) {
if (!hasQueryHeadroom(1) || !hasCpuHeadroom()) {
// Not enough room left in this transaction. Hand the work to a new one.
System.enqueueJob(new ProcessAccountsJob(accountIds));
return;
}
List<Account> accounts = [
SELECT Id, Name FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
a.Description = 'Processed ' + System.now().format();
}
update accounts;
}
public class ProcessAccountsJob implements Queueable {
private List<Id> ids;
public ProcessAccountsJob(List<Id> ids) {
this.ids = ids;
}
public void execute(QueueableContext ctx) {
SafeProcessor.process(ids);
}
}
}When the transaction is short on headroom, process moves the work into a Queueable job. That job starts a new transaction with fresh counters and the higher asynchronous ceilings.
There is a risk in this example. If the Queueable job also finds itself short of headroom, it will enqueue another job, and so on. In production, add a retry counter or a different fallback so a permanently overloaded state cannot create an endless chain.
Choosing a safety margin
The 80 percent threshold above is an arbitrary choice. Pick a margin based on how much a single unit of work costs. If one loop iteration can use 50 ms of CPU, a check at 80 percent of a 10,000 ms ceiling leaves 2,000 ms, which is plenty. If a single step can consume 3,000 ms, the same margin is too thin. Check headroom before each expensive step, and size the margin to the worst-case cost of that step.
Limits are exceptions you cannot catch
When a governor limit is exceeded, Apex throws a System.LimitException. You cannot catch it. A try/catch block does not stop the transaction from being aborted and rolled back.
try {
for (Integer i = 0; i < 200; i++) {
List<Account> a = [SELECT Id FROM Account LIMIT 1];
}
} catch (Exception e) {
// This block never runs for the limit failure.
System.debug('Caught: ' + e.getMessage());
}The loop above fails at the 101st query in a synchronous context. The catch block is skipped, and the whole transaction is rolled back. This is why the Limits class matters. You can only avoid the exception by checking before you cross the line.
Logging usage for later analysis
Debug logs are fine while developing, but they are short-lived and capped in size. For ongoing visibility, record snapshots at the end of important transactions and keep them somewhere you can query.
public with sharing class LimitSnapshot {
public static String describe(String label) {
return label
+ ' | queries=' + Limits.getQueries() + '/' + Limits.getLimitQueries()
+ ' | queryRows=' + Limits.getQueryRows() + '/' + Limits.getLimitQueryRows()
+ ' | dml=' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements()
+ ' | dmlRows=' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows()
+ ' | cpuMs=' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime()
+ ' | heap=' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize();
}
}Call System.debug(LimitSnapshot.describe('after-update')) at key points. For a persistent record, write the string to a custom object or publish it as a Platform Event. Keep in mind that a DML statement that writes a log record is itself counted. A rolled-back transaction also rolls back any log rows you inserted in it, whereas a published Platform Event with the "Publish Immediately" behavior is not rolled back.
Testing limit behavior
Apex tests are the place to prove your code stays within limits. The Test.startTest() and Test.stopTest() methods give the code under test a fresh set of governor limits, separate from the setup work in the test. This makes the counters you read inside that window reflect only your code.
@IsTest
private class SafeProcessorTest {
@IsTest
static void usesAtMostOneQuery() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
insert accounts;
List<Id> ids = new List<Id>(new Map<Id, Account>(accounts).keySet());
Test.startTest();
SafeProcessor.process(ids);
Integer queries = Limits.getQueries();
Test.stopTest();
System.assert(queries <= 1, 'Expected at most 1 query but saw ' + queries);
}
}Asserting on Limits values turns a performance regression into a failing test. A bulk test with 200 records is the usual choice, because 200 is the batch size a trigger receives from a bulk API load.
Common mistakes
- Hardcoding ceilings. Use
getLimitX()so the code stays correct across synchronous and asynchronous contexts and across platform changes. - Measuring once at the end. A single final reading tells you the total but not which step caused it. Take readings before and after suspect blocks.
- Forgetting that triggers share the transaction. Your class may look cheap alone and still fail when called from a trigger that also runs flows and other triggers.
- Reading
Limitsin a test outsidestartTest/stopTest. The counters then include test setup, which skews the result. - Confusing this class with org-level limits.
Limitsnever reports daily API requests.
Exercise
A trigger handler runs a SOQL query inside a for loop over 150 records, wrapped in a try/catch for Exception. The transaction fails with a limit error and the catch block never runs. Explain why, and name two ways the Limits class and your design can prevent this.
Show answer
Governor limit violations throw a System.LimitException that Apex cannot catch, so the transaction aborts and rolls back regardless of the try/catch. The loop issues one query per record, which crosses the 100-query synchronous ceiling. Prevention: (1) move the query outside the loop, query once with an IN clause on a collected set of Ids, and map the results; (2) before any query that cannot be avoided, compare Limits.getQueries() to Limits.getLimitQueries() and hand the work to a Queueable job when headroom is too low.
Exercise
Why should a test read Limits.getQueries() between Test.startTest() and Test.stopTest() rather than before startTest()?
Show answer
Test.startTest() resets the governor limit counters so that the code under test gets a fresh set of limits. Readings taken inside that window reflect only the code under test. Readings taken before startTest() include the queries and DML from the test's own setup, which inflates the numbers.