What role do asynchronous Apex and batch jobs play in handling heavy background processing for support operations?
Answer
Basics: Synchronous transactions limit CPU to 10,000 ms, heap to 6 MB and 100 SOQL queries. Jobs such as nightly reassignments, SLA recalculations, case archiving or sync with external systems exceed that, so they run in the background.
How it works: Choose by need:
- Batch Apex (
Database.Batchable): millions of records; QueryLocator up to 50 million; scope 1-2000 (default 200); each scope is its own transaction; up to 5 batches running, 100 in Flex Queue (Holding). - Queueable: chained or complex jobs, accepts objects; up to 50 enqueued per synchronous transaction; one child per running queueable; chains unlimited in production (5 in Developer Edition).
- Schedulable: runs at cron times; up to 100 scheduled jobs.
- @future: simple fire-and-forget, max 50 per transaction, primitive parameters only.
- Platform Events and scheduled or async-path Flows for declarative cases.
Advanced / deep dive: Use Database.Stateful to carry counters across scopes (costs heap). Add Database.AllowsCallouts for callouts in batch. Use partial-success DML (Database.update(records, false)) and log SaveResult errors to a custom object, since one bad record should not fail a scope. Keep job queries selective. Monitor in Apex Jobs and Flex Queue; chain from finish() for sequencing. Beware row locks when multiple batches update the same parent records. Avoid hard-coded queue Ids; query by DeveloperName.
Code / config example:
global class EscalateStaleCasesBatch implements Database.Batchable<SObject> {
global Database.QueryLocator {
Database.getQueryLocator([SELECT Id, OwnerId FROM Case
AND LastModifiedDate < LAST_N_DAYS:]);
}
global {
[SELECT Id FROM Group WHERE Type= AND DeveloperName= LIMIT ].Id;
(Case c : scope) c.OwnerId = q;
Database.update(scope, );
}
global {}
}