Sub topic 2
Apex Governor Limits in a Transaction
Assume you know basic Apex and can make REST API requests. Salesforce runs Apex in a multitenant environment, so one transaction cannot consume unlimited shared resources. A governor limit is a maximum resource allowance for one Apex transaction. Limits help prevent one transaction from affecting other organizations.
A transaction is one complete unit of Apex execution, such as a trigger run, synchronous request, or batch execution. Common limits include SOQL queries, DML statements, CPU time, and heap memory. Exceeding a limit stops the transaction and rolls back its database changes.
Measuring Usage with the Apex Limits Class
The Limits class reports the resources used by the current transaction and its ceiling. Each resource has a pair of methods: one returns consumption, and the other returns the maximum.
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());Use these values while troubleshooting or before an expensive operation. They do not report your organization’s daily API request usage.
Reading Usage from the REST Limits Resource
The REST Limits resource reports organization-level limits, including the daily API request allowance. Max is the maximum, and Remaining is the unused amount.
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/limits"
# Example value:
# "DailyApiRequests": {"Max": 15000, "Remaining": 14980}The daily value uses a rolling 24-hour window. It is separate from Apex transaction limits.
Tracking Usage with the Response Header
REST API responses can include Sforce-Limit-Info. For API usage, its value has the form api-usage=current/max.
Sforce-Limit-Info: api-usage=25/15000Record this header from every response if you need continuous monitoring. The REST resource gives a broader limits snapshot, while the header lets an integration observe usage as it makes requests.
Exercise
Which API should you use to measure SOQL queries consumed by the current Apex transaction?
Show answer
Use the Apex Limits class, especially Limits.getQueries() and Limits.getLimitQueries().