Live demos are back. See Testim Mobile in action on Feb 21 | Save your spot

A Beginner’s Guide to Batch Apex in Salesforce

Apex is a development platform created by Salesforce that allows you to use Salesforce's powerful functionality and build your own custom…

Testim
By Testim,

Apex is a development platform created by Salesforce that allows you to use Salesforce’s powerful functionality and build your own custom cloud-based software applications.

Salesforce allows multiple users to use their development platform simultaneously. The Apex engine enforces runtime and data limitation measures called governor limits to avoid performance issues and optimize processing. With governor limits, Salesforce guides its users to write code based on programming best practices, limits the number of operations a user can make simultaneously, etc.

The goal is to minimize situations where users take up more shared resources than necessary.

This problem often occurs for larger companies with advanced needs and is limited in the number of records they can manipulate or their operations in general.

To overcome this hurdle, Salesforce has introduced the Batch Apex feature.

In this article, you’ll understand what Batch Apex is and why it’s useful. Also, you’ll see the specific Batch Apex code syntax and some of its best practices for optimal performance.

What Is Batch Apex?

Batch Apex allows you to deal with many individual instances or records as they’re commonly known, which otherwise can surpass the typical system limitations. Batch Apex, as the name implies, processes records asynchronously in batches. As a result, they run following the platform’s limits. More specifically, Batch Apex breaks your recordset into smaller groups of records that are easier to process and manage.

Batch Apex is ideal for situations where you have a high volume of records that you need to process daily or regularly.

Batch Apex Advantages

Consider a case where you use Batch Apex and run a large number of records. At first, your records are grouped into batches of a maximum of 200 records each, which is the upper limit. Afterward, the processing of each batch, which is considered a distinct Apex transaction, is added to the Apex task queue and waits to be executed. The way Batch Apex functions offers several advantages:

  • First of all, you won’t have to worry about your transactions exceeding the governor limit because it resets each time a batch is executed.
  • Batch Apex will not process new batches unless the current batch is completed.
  • With Batch Apex classes, you’ll be able to run tasks asynchronously and process a significant number of records frequently, according to a predefined schedule that suits you.
  • Lastly, Batch Apex allows you to break down your task into smaller, much more manageable chunks.

Batch Apex Syntax

To get started with Batch Apex, you have to create and then invoke an Apex class that implements the Database.Batchable interface. This interface has three methods.

Start Method

The start method gathers the records that need to go to the execute method of the Database.Batchable interface for processing.

When a Batch Apex task begins, it automatically invokes the start method once, and there are two options it can return; either the Database.QueryLocator object or an iterable object that stores the records sent to the execute method.

In cases where a Salesforce Object Query Language (SOQL) query is enough to determine the object scope of the task, then you can use the QueryLocator option. You can avoid the governor limit of how many records you can retrieve from SOQL queries when using the QueryLocator object.

However, if you’re planning to perform a more sophisticated action, then the iterable is the preferable choice. You can even create your own custom iterable for your advanced needs. One thing to keep in mind is that, unlike the QueryLocator, the governor limit of how many records you can retrieve from SOQL queries remains in this case.

Execute Method

Execute is the method that will have all the logic you will perform for each batch. So if you’re updating those records or archiving them, the logic will go here. The execute method will perform every time a batch runs. If, for example, you have 10 batches, the execute method will be called 10 times, once for each batch. Batches can have up to 200 records.

The execute method has two parameters. The first is a reference to the Database.BatchableContext object and the second is a list of the records returned by the start method.

Finish Method

The third method you need to implement is the finish method. If you want to perform an action after processing all the batches, like sending a status report or email to the administrator, you need to specify it here. The finish method is executed once and only after all the batches are successful. It takes a reference to the Database.BatchableContext object as a parameter.

Below you can see some boilerplate Batch Apex code:

code syntax

Batch Apex Invoking

You can invoke a Batch Apex class using the Database.executeBatch method.

batch apex invoking

In this case, the default number of records will pass to the execute method for processing, which is 200.

Another option is to limit the batch size by adding a scope parameter. This will determine precisely the number of records you need to pass to the execute method.

scope parameter

Batch Apex State

As mentioned above, the processing of each Apex batch is a discrete transaction. That means that every time the execute method runs, it creates a new copy of the object, and all static and instance variables initiate.

Using Database.Stateful will help you keep the same state during all transactions. Keeping the same state can be beneficial in cases where you need to calculate records. You have to use it carefully, though, as it can affect the performance of your batch; for example, it can lead to a longer batch execution time.

Batch Apex Testing

You can test Batch Apex by inserting some sample records in a test class. Then, you can invoke it and verify whether or not the records were modified as planned. Batch Apex allows you to test the execute method only once. Therefore, you need to determine how many records will pass to the execute method by using the executeBatch method and specifically the scope parameter.

Apex has two test methods, startTest and stopTest, where you’ll place your test logic and executeBatch method.

batch apex testing

Batch Apex Best Practices

There are several best practices that you can implement to make sure that Batch Apex is performing optimally:

  • Use normal Apex instead of Batch Apex when you have a small number of records that you need to run.
  • Organize your SOQL queries properly to maximize the efficient processing of your batches.
  • Salesforce uses queues to manage asynchronous tasks. If you pile up your queue with a significant number of requests that are waiting to run, it’s possible you’ll face delays. Reducing asynchronous requests will help you prevent slow execution times.

Final Thoughts

Salesforce’s Batch Apex is a suitable solution for organizations that have large numbers of records and are struggling with the governor limit. Whenever there’s a need to process millions of records at once, it’s the only solution developers have. It’s gaining popularity as every major project in Salesforce is currently using it.

You can learn more about Batch Apex and find code examples in Apex’s developer guide. Also, Salesforce has a free online learning platform where you can learn how to use Batch Apex in detail.

Are you using Salesforce? Testim for Salesforce is a powerful AI-powered testing tool that will help you automate and simplify your Salesforce applications testing efforts.

Learn more about how Salesforce tests Salesforce and see how Testim can help.