batch apex

best practices and examples

general information

Batch APEX is a great tool to help cleanse data and implement tasks that need to happen on a schedule. Unfortunately, as with everything else in Salesforce, batch jobs have some pretty crippling limitations; the biggest being the inability to have more than 100 jobs schedule at any given moment and no more than 100 jobs running in the queue. These two limits have huge implications if not managed properly. I developed a tool to help admins and developers circumnavigate these errors to increase productivity, break the limits, and put in measures to ensure all jobs are run regardless of the system status. Check out the Batch Master Salesforce app for more information on how what it does. 

There are several aspects of the batch architecture that can cause both critical failures and incredible efficiencies. Designing the query start method is one of the most important parts to making sure your batch class is going to run in the most efficient way possible. Picking to base the query on the wrong object or adding unnecessary sub-queries can lead to poor performing batch jobs and unnecessary or duplicate computing work. 

The architecture of the execute method, while important is not mission critical. It should be built with care, but the efficiency and querying limits are most likely not going to be hit in these methods. The most important concept to remember in the execute method is that queries that can be run once across all jobs in the batch should be placed in the constructor to reduce the overall number of queries. This is one way to help improve efficiency in the execute method. 

The finish object is a tremendous tool to use. It is a great place to analyze and provide a digest on the results of the job. Creating a list of users (admins and developers) to send the results of the job to is incredibly valuable to monitor the performance of a batch job. One of the cool features of a batch job is the ability to split the queried results into smaller chunks (scope size) for parallel processing and increasing efficiency. Understanding this key feature is important when building out the finish method. Developers can store the results of each sub-job and transfer those results into the finish method to be emailed, chatter posted, or POSTed via an API (possibly to Slack). 

Check out the resources on the for examples on how to build a batch class.


Suggestions on commenting in the batch job class follow the same principles as those laid out in the triggers page. Ensuring there are proper comments, descriptions, and creation/business value information about the job all help create strong documentation.