How many times a Batch’s execute method is called?

Manjot Singh
Salesforce-Lightning
2 min readSep 5, 2019

Above question is silly right? We already know how many times a execute method will be called. If we are processing 10,000 records and batch size is 100 then number of times a batch’s execute method will be called is 10000/100 = 100 times. Yup, you are right.

Lets do another example we are getting 15,000 records from query locator and batch size is 75. Then how many times execute method is called 15000/75 = 200 times. Right? 🤔

Second answer is wrong. Number of times execute method will be called is 300. How i came up this number? 😎

This number comes from chunking on Salesforce side which is called as retrieveChunkSize. Retrievechunksize and scopeSize that we give in database.execute method determine the number of execute method calls. So what are different retrieveChunkSize. There are 3:- 100, 400 and 2000.

Which retrieveChunkSize will be used depends upon batch size. Like if batch size is

  1. 1 to 100 then retreiveChunkSize = 100
  2. 101 to 400 then retreiveChunkSize = 400
  3. 401 to 2000 then retreiveChunkSize = 2000

Lets take our second example and try to solve puzzle why execute method will be called 300 times. Our batch size is 75 it comes in between first chunk size so retreiveChunkSize will be 100. As our retreiveChunkSize is 100 total retreive chunks will be 15000/ 100 = 150.

Now we have 150 retreive chunks of size 100 each. But our batch size is 75. So what will happen is first we will get a retreive chunk of 100 records. After that as batch size is 75 we will get a execute method with 75 records. Second execute method will be called with 100–75 = 25 records. Then we will move to second retreive chunk of 100 records.

For each retreivechunk of 100 records, we will get execute method with 75 records and then 25 records. Each chunk will need 2 execute method for execution. That makes total number 150 * 2 = 300.

Similarly if we had batch size of 40. Then execute method will be called with chunks of 40,40 and 20.

Retreivechunks only work for if start method returns a query locator(Not an iteratables) for a SOQL query that doesn’t contain inner or subqueries in it.

Refrence:- https://help.salesforce.com/articleView?id=000313357&language=en_US&type=1&mode=1

Thanks to Yogesh for helping me understand RetreiveChunks Yogeshwar Tailor | LinkedIn

If you learned something new…. Clap 👏 🙂

--

--