Apex Batch Processing: Handling Large Data Volumes

When you need to update half a million records, a normal Apex transaction won't get far. It runs into limits on query rows, DML rows and CPU time long before the job is done. Batch Apex solves this by splitting the work into small chunks. Each chunk runs in its own transaction, with its own fresh set of governor limits. This guide shows how to build a batch class you can trust in production.

How Batch Apex works

A batch class implements Database.Batchable and has three methods:

MethodWhen it runsWhat it does
startOnce, at the beginningReturns the records to process, usually as a Database.QueryLocator
executeOnce per chunkProcesses one chunk of records
finishOnce, at the endSends a summary, logs results or starts a follow-up job

By default each chunk has 200 records. When start returns a QueryLocator, you can set the chunk size up to 2,000, and the query can return up to 50 million records.

A complete batch class

This example marks Accounts as inactive when they have had no activity for two years. It uses partial-success DML, keeps running totals across chunks, and reports what happened when it finishes.

Apex  ·  InactiveAccountBatch.cls
public with sharing class InactiveAccountBatch
        implements Database.Batchable<SObject>, Database.Stateful, Database.RaisesPlatformEvents {

    // Instance variables keep their values between chunks because of Database.Stateful
    private Integer processed = 0;
    private Integer failed = 0;
    private List<String> errorSamples = new List<String>();

    public Database.QueryLocator start(Database.BatchableContext bc) {
        Date cutoff = Date.today().addYears(-2);
        return Database.getQueryLocator([
            SELECT Id, Name, Is_Active__c
            FROM Account
            WHERE Is_Active__c = true
                AND (LastActivityDate < :cutoff OR LastActivityDate = null)
        ]);
    }

    public void execute(Database.BatchableContext bc, List<Account> scope) {
        for (Account acc : scope) {
            acc.Is_Active__c = false; // Is_Active__c is an example custom field
        }

        // allOrNone = false: one bad record doesn't roll back the whole chunk
        Database.SaveResult[] results = Database.update(scope, false);

        for (Integer i = 0; i < results.size(); i++) {
            if (results[i].isSuccess()) {
                processed++;
            } else {
                failed++;
                if (errorSamples.size() < 20) {
                    errorSamples.add(scope[i].Id + ': ' + results[i].getErrors()[0].getMessage());
                }
            }
        }
    }

    public void finish(Database.BatchableContext bc) {
        AsyncApexJob job = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()
        ];

        String summary = 'Inactive account batch ' + job.Status
            + ' | updated: ' + processed
            + ' | failed: ' + failed
            + ' | chunks: ' + job.JobItemsProcessed + '/' + job.TotalJobItems;

        System.debug(LoggingLevel.INFO, summary);
        if (!errorSamples.isEmpty()) {
            System.debug(LoggingLevel.WARN, String.join(errorSamples, '\n'));
        }
        // In a real org, save the summary to a log object or send it to the team.
    }
}

What each piece is doing

  • Database.Stateful keeps instance variables, like processed and failed, between chunks. Without it, every chunk starts with fresh values. Static variables reset between chunks either way.
  • Database.update(scope, false) saves the records that are fine and reports the rest. With the default all-or-none behaviour, one bad record would fail the whole chunk.
  • errorSamples is capped at 20. A stateful batch carries its variables through every chunk, so don't let a list grow without limit. Heap size for async Apex is 25 MB.
  • Database.RaisesPlatformEvents makes the platform publish an error event if an unhandled exception happens. More on that below.

💡 Only use Database.Stateful when you need it

Stateful batches have to save and restore their state for every chunk. If you don't need running totals or a list of errors, leave it out.

Run the job

Apex  ·  Start the batch
// Default chunk size of 200
Id jobId = Database.executeBatch(new InactiveAccountBatch());

// Smaller chunks for heavy logic, for example records that fire complex triggers
Id smallJobId = Database.executeBatch(new InactiveAccountBatch(), 50);

Choose the chunk size based on the work each record causes. If the update fires triggers, flows and roll-ups, smaller chunks of 50 to 100 avoid CPU timeouts. If the work is light, the default 200 is fine.

Catch unexpected errors with BatchApexErrorEvent

Partial-success DML handles record-level errors. But what if the code itself throws an exception, or hits a governor limit? When a batch class implements Database.RaisesPlatformEvents, Salesforce publishes a BatchApexErrorEvent for unhandled exceptions in start, execute or finish.

The event tells you:

  • AsyncApexJobId: which job failed
  • Phase: START, EXECUTE or FINISH
  • ExceptionType and Message: what went wrong
  • JobScope: the IDs of the records in the failed chunk
  • StackTrace: where it happened

You can subscribe with a trigger and save the details somewhere useful:

Apex  ·  BatchApexErrorEventTrigger.trigger
trigger BatchApexErrorEventTrigger on BatchApexErrorEvent (after insert) {
    List<Batch_Error_Log__c> logs = new List<Batch_Error_Log__c>();

    for (BatchApexErrorEvent evt : Trigger.new) {
        // Batch_Error_Log__c and its fields are an example custom object
        logs.add(new Batch_Error_Log__c(
            Job_Id__c = evt.AsyncApexJobId,
            Phase__c = evt.Phase,
            Exception_Type__c = evt.ExceptionType,
            Message__c = evt.Message,
            Record_Ids__c = evt.JobScope
        ));
    }

    insert logs;
}

Now a failed chunk leaves a record your admin can find, with the exact record IDs to retry.

Schedule the batch

To run the job every night, wrap it in a Schedulable class. It's a good idea to check that the previous run has finished first, so two copies never run at the same time.

Apex  ·  InactiveAccountScheduler.cls
public with sharing class InactiveAccountScheduler implements Schedulable {

    public void execute(SchedulableContext sc) {
        Integer running = [
            SELECT COUNT()
            FROM AsyncApexJob
            WHERE JobType = 'BatchApex'
                AND ApexClass.Name = 'InactiveAccountBatch'
                AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
        ];

        if (running == 0) {
            Database.executeBatch(new InactiveAccountBatch(), 200);
        }
    }
}
Apex  ·  Schedule it for 2 AM every day
System.schedule(
    'Inactive Account Cleanup - Nightly',
    '0 0 2 * * ?',
    new InactiveAccountScheduler()
);

Limits worth knowing

These come from the Apex Developer Guide:

LimitValue
Records a QueryLocator can return50 million
Default chunk size200
Maximum chunk size with a QueryLocator2,000
Batch jobs queued or active at the same time5
Jobs waiting in the Apex flex queue100
Async Apex executions per 24 hours (batch, future, Queueable, scheduled)250,000, or 200 × user licenses if that is higher
Callouts per start, execute or finish100 (needs Database.AllowsCallouts)
SOQL queries per async transaction200
Heap size per async transaction25 MB
CPU time per async transaction60,000 ms

The 24-hour limit counts each execute call, and it's shared with all other async Apex in the org. A job of 1 million records at 200 per chunk uses 5,000 executions. That's fine on its own, but worth knowing if many jobs run every night.

Test the batch

Batch jobs started between Test.startTest() and Test.stopTest() run when stopTest() is called, so you can assert the results right after. In a test, the batch can only run one chunk, so keep the test data under your chunk size.

Apex  ·  InactiveAccountBatchTest.cls
@IsTest
private class InactiveAccountBatchTest {

    @IsTest
    static void marksOldAccountsInactive() {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < 50; i++) {
            accounts.add(new Account(Name = 'Old Account ' + i, Is_Active__c = true));
        }
        insert accounts;

        Test.startTest();
        Database.executeBatch(new InactiveAccountBatch(), 200);
        Test.stopTest();

        Integer stillActive = [SELECT COUNT() FROM Account WHERE Is_Active__c = true];
        Assert.areEqual(0, stillActive, 'All accounts without activity should be inactive');
    }
}

New test accounts have no activity, so LastActivityDate is null and they all match the query.

Checklist

  • start returns a QueryLocator with only the fields you need
  • Chunk size fits the work each record causes
  • DML uses Database.update(records, false) and handles failures
  • Database.Stateful is used only for running totals, and lists are capped
  • Database.RaisesPlatformEvents plus a trigger catches unexpected errors
  • The scheduler checks that the last run has finished
  • Tests run the batch inside Test.startTest() and Test.stopTest()

Sources and further reading

Share this article

Help others discover this content

More Articles

  • All Posts
  • Marketing Cloud
  • Data Cloud
  • Sales Cloud
  • SFMC Next