Batch apex: Are individual transactions (execute methods) run in serial

batch

I have spent few hours today to understand this as this was not clear from documentation. Also, the test seems to say that my understanding is wrong. So, wanted to verify with the community.

So, Questions is:
Lets say you have 1000 records, and a batch to process these records. Default batch size is 200. So, this means there will be 5 time execute method will be invoked. But, will they be invoked one after other or in parallel.

I tested it with 16 contact records, & executed batch with size 1. Serial is a custom field to order:

Batch class:

public class DemoBatch implements Database.Batchable<sObject>, Database.stateful {
public String a='';
public Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator([select id, firstName,serial__c from contact order by serial__c]);
}
public void execute(Database.BatchableContext BC, List<Contact> scope){
    System.debug('***scope'+scope[0].serial__c);
    if(scope[0].serial__c==6){
        for(Integer i = 0; i < 10000000;i++){
            
        }
    
        if(scope[0].serial__c==4){
            System.debug('***long');
            for(Integer i = 0; i < 10000000;i++){
                
            }
        }
    }
    a = a + scope[0].serial__c;
}
public void finish(Database.BatchableContext BC){
    System.debug('***a:Finish:'+a);
}

}

Though, I have intentially added delays here, the end result is always ordered. So, are individual executions are serial ??

Best Answer

execute methods run sequentially, but their order is not guarantee.
Documentation (emphasis mine):

Batches of records tend to execute in the order in which they’re received from the start method. However, the order in which batches of records execute depends on various factors. The order of execution isn’t guaranteed.

I.E. You run the batch with a scope size of 5 records and the start method fetchs 20 contacts ordered by serial__c (1, 2, ..., 20).
There will be 4 chunks and they will be handled sequentially, but the order of execution isn’t guaranteed, so it could be:

  1. [1, 2, 3, 4, 5]
  2. [16, 17, 18, 19, 20]
  3. [11, 12, 13, 14, 15]
  4. [6, 7, 8, 9, 10]
Related Topic