Flying Blind Without the Limits Class
“Never checked Limits.getQueries() in my code. Hit governor limits in production with zero warning.”
What Happened
I had a complex Apex class making multiple SOQL queries across helper methods. In development it worked fine. In production, with process builders and other triggers stacking up in the same transaction, it blew past 100 SOQL queries. I had no idea how close I was to the limit because I never instrumented my code with Limits class checks. Adding debug logs with Limits.getQueries() would have shown me I was at 87 queries before my code even started.
The Wrong Way
public class OpportunityService {
public static void processOpps(List<Id> oppIds) {
// Just query and hope for the best
List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE Id IN :oppIds];
updateRelatedContacts(opps);
createFollowUpTasks(opps);
syncToExternalSystem(opps);
// No idea how many queries we've used.
// Other triggers in the transaction
// already used 80. We start at 80, not 0.
}
}The Right Way
public class OpportunityService {
public static void processOpps(List<Id> oppIds) {
System.debug('SOQL used before entry: '
+ Limits.getQueries() + '/'
+ Limits.getLimitQueries());
System.debug('DML used before entry: '
+ Limits.getDmlStatements() + '/'
+ Limits.getLimitDmlStatements());
if (Limits.getQueries() > 80) {
// We're already at 80 of 100.
// Queue this work asynchronously instead.
System.enqueueJob(
new OppProcessQueueable(oppIds));
return;
}
List<Opportunity> opps = [SELECT Id FROM Opportunity
WHERE Id IN :oppIds];
updateRelatedContacts(opps);
// ... rest of logic
}
}The Lesson
Use Limits.getQueries(), Limits.getDmlStatements(), and Limits.getHeapSize() liberally. Your code doesn't run in isolation — other automations share the same transaction limits.
Enjoyed this? Get more like it.
Glen's Musings — AI, investing, and building things. Occasional. Free.
More Apex Mistakes
SOQL Query Inside a For Loop (The Classic)
Wrote a SOQL query inside a for loop. 200 records came in. 200 queries fired. Governor said no.
Read morePainfulTest Class That Only Tests One Record
Wrote a test class that inserted 1 record. Got 100% coverage. Deployed. Trigger failed on bulk operations.
Read moreAnnoyingMixed DML: Setup and Non-Setup Objects in the Same Transaction
Inserted a User and an Account in the same transaction. Salesforce said absolutely not.
Read more