Batch chaining in Salesforce

Consider a scenario. A broadband provider runs a daily scheduled job to update Internet Usage Statements of their customers and emails those statements as a pdf to their customers whoever has selected “Mail me a copy” option on their portal.

This provider operates in 3 different countries India, China and the USA with more than 100 million users. India has 40; China has 35 and USA has 25 million users respectively. The already built program is failing a lot of times. The program is optimized to handle huge data. Still, it is failing with “Too many query locator rows” error and whenever it fails some users receive the statement, and some don’t, and they raise complaints.

Such issues arise due to huge data processing. The upper limit of batchable query locator to fetch data is 50 million, but as it is challenging the upper limit, an error occurs. Therefore it is necessary to reduce the volume of data retrieved by query locator using filters in the query, that’s where Batch chaining comes into the picture. Batch chaining is a process of combining multiple batch classes to form a chain. Batch classes when chained execute sequentially one after another.

For example:

In the above situation, we can create three different batch classes based on the country of the user and chain them together. Each batch class may complete processes for their specified country only; hence the load will be reduced and under limits.

Let’s see the code for the first class. This class can be a scheduled class.

public class IndiaUsageStatements{

    public void finish(Database.BatchableContext context){

        ChinaUsageStatements china = new ChinaUsageStatements();

        Database.executeBatch(china,200)

    }

}

 In the above code, the second class is called from the finish method to ensure continuous chaining. Similarly, a third class can be called from Second class in this manner:

public class ChinaUsageStatements{

    public void finish(Database.BatchableContext context){

        USAUsageStatementsusa = new USAUsageStatements();

        Database.executeBatch(usa,200)

    }

}

Simultaneously more classses can be called from the finish methods of the future class if required. Thus batch chaining is an efficient method of advanced salesforce data processing.

Note: The above example code only shows the finish method for easy understanding.

Happy batching !