Avoid child queries in long running batches.

Recently I was working on a production incident and have found issues with child queries in batch apex where the following stats holds right:

Query: On contact 
Total records: ~0.4 million
Child query filters: Two string and one record type check

Issues:
  • CPU timeout error
  • Batch will not start.

Solution: Removed child query completely and written logic inside execute method. Please follow code snippet given below:

global void execute(Database.BatchableContext bc, Contact[] conScopeLst) {
Set<id> conIds = new Set<id>();
for (Contact c : conScopeLst) conIds.add(c.Id);
Map<Id, list<Contact_Child__c>> conChildMap = new Map<Id, list<Contact_Child__c>>();
for(Contact_Child__c cc : [SELECT Id, contact__c FROM Contact_Child__c WHERE filter1__c = 'filter1' AND filter2__c = 'filter2' AND contact__c =:conIds ]){
list<Contact_Child__c> tempLst = new list<Contact_Child__c>();
if(conChildMap.containsKey(cc.contact__c))tempLst = conChildMap.get(cc.contact__c);
tempLst.add(cc);
conChildMap.put(cc.contact__c, tempLst);
}
//rest of the logic:
//usage of map
//list<Contact_Child__c> list = conChildMap.get(----pass contact record id------);
}






Comments