Batch Apex Best Practices

By in
778
Batch Apex Best Practices

Batch is the best tool to run asynchronous processes in the background. Since Batch Apex takes a heavy toll on processing, querying, and DMLs, it’s important to make sure they are optimized and ensure that the best practices are followed.

Img Source: Apex Hours

 

Best Practices

Some of the common best practices of the batch apex are as follows.

  1. To make sure that the execution of batch jobs is faster, you need to minimize the time of Web service callout and tune queries that are used in the batch Apex code.
  2. The more time the batch job takes to execute, the more likely other queued jobs are delayed when many jobs are in the queue.
  3. You should only use Batch Apex if you know that you have more than one batch of records. If the records to run are not more than one batch, you are probably better off using Queueable Apex
  4. Optimize any SOQL query to gather the records to execute as quickly as possible.
  5. Try to minimize the number of asynchronous requests created to minimize the chance of delays.
  6. You need to take extreme precautions if you plan to invoke a batch job from a trigger. You should be able to guarantee that the trigger won’t add more batch jobs than the limit.
  7. It’s very important to note that when developing integrations using Batch Apex, you must include Database.AllowsCallouts to the class definition:

public class WhiteGloveUtility implements Database.Batchable<sObject>,

   Database.AllowsCallouts{

}

 

There’s a very common error that you may encounter, “You have uncommitted work pending. Please commit or rollback before calling out.”

This happens if you’re trying to make an external service callout after completing your DML. To resolve this issue, you have to first make a callout and then make a DML.

 

Conclusion

In this way, you must use best practices while developing batch apex classes. This is to ensure that the code is running in an optimized way.

 

If you want to learn more about Batch Apex, check out my related blog below!

 

Additional Resources

Cover Photo by Jeffrey F Lin on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *