Skip to main content

Salesforce Batch Apex Guide: How to Process Large Data Volumes

In plain words: Batch processing in Salesforce (known as Batch Apex) is a way to handle massive amounts of data by breaking it down into smaller, manageable pieces. If you try to update 50,000 records at once in a standard script, Salesforce will crash and throw a Governor Limit error. Batch Apex safely processes those records in background chunks (like 200 at a time) until the whole job is done.

In enterprise Salesforce environments, dealing with large datasets is a daily reality. Whether you are running a nightly sync to update thousands of Accounts or purging old log files, standard synchronous Apex simply cannot handle the load. This is where Asynchronous Apex, specifically Batch Processing, steps in.

Let's explore how Batch Apex works, why it is critical for performance, and how you can implement it from scratch.

Why Do We Need Batch Apex?

Salesforce operates in a multi-tenant cloud, meaning everyone shares the same server resources. To prevent one bad piece of code from hogging the servers, Salesforce enforces strict Governor Limits (like a maximum of 10,000 DML operations or 100 SOQL queries per transaction).

360 Card: The Benefits of Batch Processing
  • Limit Evasion: Every chunk (batch) gets a fresh set of Governor Limits. Processing 200 records at a time means you'll never hit the 10,000 DML limit, even if you are updating millions of rows.
  • Asynchronous Execution: Batches run in the background. Your users don't have to stare at a loading screen while the system works.
  • Granular Error Handling: If one chunk of 200 records fails, the rest of the chunks will continue to process successfully.
  • Scheduling: You can schedule batches to run automatically during off-peak hours to minimize system slowdowns.

Step 1: Writing the Batch Class

To create a batch job, your Apex class must implement the Database.Batchable interface. This interface forces you to define three distinct methods: start, execute, and finish.

  • start: Runs once at the very beginning. This is where you write your SOQL query to gather all the records you want to process.
  • execute: Runs multiple times. Salesforce takes the massive list from your start method, chops it into chunks (default 200 records), and passes them into this method to be processed.
  • finish: Runs once at the very end. Use this to send a confirmation email or trigger a follow-up job.
public class AccountUpdateBatch implements Database.Batchable<sObject> {
    
    // 1. START: Collect the records
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Retrieve all records that need processing
        return Database.getQueryLocator('SELECT Id, Name FROM Account WHERE IsActive__c = true');
    }

    // 2. EXECUTE: Process the chunk
    public void execute(Database.BatchableContext context, List<Account> scope) {
        for (Account acc : scope) {
            // Apply your business logic
            acc.Description = 'Updated via Batch Apex';
        }
        
        // Update the database for this specific chunk
        update scope;
    }

    // 3. FINISH: Wrap up
    public void finish(Database.BatchableContext context) {
        System.debug('Batch Job Complete!');
        // Optional: Send an email alert to the admin here
    }
}
Developer Trap: Losing Your Variables (Statefulness)
By default, Batch Apex is stateless. This means if you create an integer variable to count total processed records, it resets back to zero every time a new chunk runs! If you need a variable to retain its value across all batches (like tracking the total number of failed records), you must add implements Database.Stateful to your class definition.

Step 2: Running and Scheduling the Batch

Once your class is written, you need to tell Salesforce to run it. You can launch it manually from the Developer Console, or schedule it via code.

Running It Immediately:
To run the job right now with the standard chunk size of 200, open the Execute Anonymous window and run:
Database.executeBatch(new AccountUpdateBatch());

Alternatively, you can schedule the batch to run automatically. You can do this through the Salesforce UI (Setup > Apex Classes > Schedule Apex) or programmatically via the System.scheduleBatch() method.

// Schedule the batch to run 15 minutes from now, processing in chunks of 100
String jobId = System.scheduleBatch(new AccountUpdateBatch(), 'Nightly Account Sync', 15, 100);

Step 3: Monitoring Your Batch Job

Because batch jobs run silently in the background, you need a way to check on them.

Simply log into Salesforce, go to Setup, and search for Apex Jobs. This dashboard will show you the real-time status of your batch (Queued, Processing, Completed, or Failed), along with the total number of batches processed and any errors that occurred.

Core Takeaway: Whenever a business requirement asks you to process more than a few thousand records at once, immediately default to using Batch Apex. It protects your org from crashing and ensures data is handled safely.

Conclusion

Batch processing is an essential pattern in the Salesforce ecosystem. By dividing massive datasets into smaller chunks, Batch Apex allows developers to safely navigate governor limits and perform heavy backend updates without interrupting the user experience. Keep your execute methods clean, remember Database.Stateful when you need to track totals, and you will master large data volumes in no time.