Apex CPU time limit exceeded.
Nested loops that pass in Sandbox burn through 10 seconds of CPU with production volumes.
The limit.
System.LimitException: Apex CPU time limit exceeded
Synchronous Apex gets 10,000ms of CPU. Async gets 60,000ms. O(n²) nested loops that look fine with 100 records explode at 50,000.
10s
Synchronous CPU limit
60s
Async CPU limit
6 hrs
Average downtime from this error
Bad vs good.
AccountProcessor.clsAnti-pattern
// ❌ BAD: Nested loops with O(n²) complexity
// Works fine with 100 records in Sandbox
// Burns through CPU time with 10,000+ records in Production
public void calculateCommission(List<Opportunity> opps) {
for (Opportunity opp1 : opps) {
for (Opportunity opp2 : opps) {
// O(n²) comparison - exponential CPU growth
if (opp1.AccountId == opp2.AccountId) {
Decimal commission = calculateComplexFormula(opp1, opp2);
opp1.Commission__c = commission;
}
}
}
update opps;
}
// With 10,000 opportunities = 100,000,000 iterations
// CPU timeout at 10 secondsAccountProcessor.clsFixed
// ✅ GOOD: Use Maps for O(n) complexity
// Linear time regardless of record count
public void calculateCommission(List<Opportunity> opps) {
// Group by AccountId using a Map
Map<Id, List<Opportunity>> oppsByAccount = new Map<Id, List<Opportunity>>();
for (Opportunity opp : opps) {
if (!oppsByAccount.containsKey(opp.AccountId)) {
oppsByAccount.put(opp.AccountId, new List<Opportunity>());
}
oppsByAccount.get(opp.AccountId).add(opp);
}
// Process each account's opportunities
for (List<Opportunity> accountOpps : oppsByAccount.values()) {
for (Integer i = 0; i < accountOpps.size(); i++) {
Decimal commission = calculateFormula(accountOpps[i]);
accountOpps[i].Commission__c = commission;
}
}
update opps;
}The fix.
Replace nested loops with Maps for O(n) lookups. Jataka profiles real CPU milliseconds in a Kamikaze Sandbox pod before the PR merges.
Catch this before production.
Book a pilot and watch Jataka block this exact anti-pattern on your next PR.