Concept 7 of 10Asynchronous Apex

Batch Apex

Chunked processing of large data sets: start, execute and finish, scope size, Database.Stateful, the flex queue, error handling and testing.

Your confidence:Not rated

Simple explanation

A batch class implements Database.Batchable<sObject> with three methods:

  • start returns the records to process: a Database.QueryLocator (up to 50 million rows) or an Iterable (subject to normal query limits).
  • execute runs once per chunk (scope). Default scope is 200, configurable up to 2,000. Each chunk is its own transaction with fresh async limits, so one failing chunk doesn't roll back the others.
  • finish runs once at the end: send a summary, log, or chain the next job.

Start it with Database.executeBatch(new MyBatch(), scopeSize).

Useful options

  • Database.Stateful keeps instance variables across chunks (counters, error lists). Use it sparingly: state is serialised between chunks.
  • Database.AllowsCallouts for callouts in execute.
  • Database.RaisesPlatformEvents publishes BatchApexErrorEvent when a chunk fails, so a subscriber can log or retry.

Concurrency: up to 5 batch jobs are queued or active at once; up to 100 more wait in the flex queue, which admins can reorder.

Real-world analogy

Batch Apex is moving house with a van that holds 200 boxes. start lists every box, execute is one van trip (if one trip crashes, the others still arrive), and finish is the final walkthrough. Stateful is the clipboard you carry between trips.

Worked example

Recalculate a health score on every active account each night, collecting failures and raising events for unexpected errors:

public with sharing class AccountHealthBatch
        implements Database.Batchable<SObject>, Database.Stateful, Database.RaisesPlatformEvents {

    private Integer processed = 0;
    private List<String> failures = new List<String>();

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
            SELECT Id, (SELECT Id, IsClosed, CreatedDate FROM Cases WHERE CreatedDate = LAST_N_DAYS:90)
            FROM Account
            WHERE Status__c = 'Active'
        ]);
    }

    public void execute(Database.BatchableContext bc, List<Account> scope) {
        List<Account> updates = new List<Account>();
        for (Account acc : scope) {
            updates.add(new Account(Id = acc.Id, Health_Score__c = HealthScoreCalculator.score(acc.Cases)));
        }
        List<Database.SaveResult> results = Database.update(updates, false);
        for (Integer i = 0; i < results.size(); i++) {
            if (results[i].isSuccess()) {
                processed++;
            } else {
                failures.add(updates[i].Id + ': ' + results[i].getErrors()[0].getMessage());
            }
        }
    }

    public void finish(Database.BatchableContext bc) {
        AsyncApexJob job = [SELECT Status, NumberOfErrors, JobItemsProcessed FROM AsyncApexJob WHERE Id = :bc.getJobId()];
        IntegrationLog.info('AccountHealthBatch', processed + ' updated, ' + failures.size() + ' record errors, '
            + job.NumberOfErrors + ' failed chunks');
    }
}

// Scheduled nightly with a scope of 500:
// Database.executeBatch(new AccountHealthBatch(), 500);

Diagram

Rendering diagram…

Key points

  • start β†’ execute per chunk β†’ finish. Each chunk is a separate transaction.
  • QueryLocator up to 50 million rows; scope 200 by default, up to 2,000.
  • Database.Stateful for counters and summaries; keep state small.
  • Database.RaisesPlatformEvents + BatchApexErrorEvent for robust error handling.
  • 5 active batch jobs; others wait in the flex queue (up to 100).
  • Choose scope size by work per record (callouts, complex logic β†’ smaller scope).

Limits and gotchas

  • Calling Database.executeBatch from a trigger can flood the flex queue during data loads. Guard it, or use a queueable coordinator.
  • Large scope + heavy logic hits CPU or heap limits; tune scope from real measurements.
  • Each execute with callouts is limited to the callout limits per transaction; use scope ≀ the number of callouts you can make.
  • Records can change between start and execute. Re-check critical conditions in execute.
  • In tests, only one execute runs, so test data should fit in one scope.

🎀 How to say this in an interview

Explain chunk-level transactions (partial failure), scope tuning, and how you'd monitor and recover (AsyncApexJob, BatchApexErrorEvent, idempotent re-runs). Mention cursors + queueable as an alternative when batch slots are the bottleneck.

Common follow-ups

A batch must process 30 million records nightly but takes too long. What do you look at?

Query selectivity in start (indexed filters), work per record and scope size, avoiding per-record DML or callouts, whether all records truly need processing (incremental by SystemModstamp), and whether the work can be parallelised with cursors and queueables or moved off-platform.

How do you rerun only the failed records?

Capture failed IDs (Stateful list or BatchApexErrorEvent subscriber) into a log object, then start the batch again with a query or iterable over those IDs. Make the processing idempotent so reruns are safe.