Saturday, May 15, 2021

How to control number of batches in batch apex using scope size?

As we know default scope size is 200 i.e If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200 records.

When  an apex job is executed by setting some value for scope size it is not necessary that the number of record processed in one batch iteration will be same as that of scope size specified.

Records from the query locator are retrieved in chunks of given chunk size called retrieveChunkSize .

Chunks size available are 100,200,400.

Selection of chunk size depends on the scope size specified.


If 1 <= scopeSize <= 100, then retrieveChunkSize = 100

If 101 <= scopeSize <= 400, then retrieveChunkSize = 400
If 401 <= scopeSize <= 2000, then retrieveChunkSize = 2000


So Let say if we 285 records to be proceeds and we specify the scope size as 80 than the retrieveChunkSize  will be 100.

In this case the total number of batches will note be 4 i.e (285/80) but in this case it would be 3 retrieve chunks and 6 execute chunks so the total number of batches will be 6.

1. Retrieve chunk 1: retrieve first 100 records
Execute chunk 1: pass first 80 records to execute() method
Execute chunk 2: pass remaining 20 records from this retrieve chunk to execute() method

2. Retrieve chunk 2: retrieve next 100 records

Execute chunk 3: pass first 80 records to execute() method
Execute chunk 4: pass remaining 20 records from this retrieve chunk to execute() method

3. Retrieve chunk 3: retrieve next 85 records

Execute chunk 5: pass first 80 records to execute() method
Execute chunk 6: pass remaining 5 records from this retrieve chunk to execute() method

No comments:

Post a Comment