Sub topic 14
Common pitfalls and anti-patterns
This chapter assumes you can write Apex triggers and classes, you know SOQL and DML, you know the governor limits at a high level, and you have used the four async tools covered earlier: @future, Queueable, Batch, and Scheduled Apex. It collects the mistakes that show up most often in code review and in production, grouped by where they come from.
Pitfalls that come from the trigger
Most async problems start in a trigger, because a trigger can run for 1 record or 200 records, and for several batches of 200 in one transaction.
Enqueueing or calling a future method inside a loop
A transaction can make at most 50 @future calls and 50 System.enqueueJob calls. A loop that makes one call per record fails on the 51st record.
// Anti-pattern: one async call per record
for (Account a : Trigger.new) {
PartnerSync.sendAccountNames(new Set<Id>{ a.Id }); // fails after 50 records
}Collect the Ids first and make one call:
// Better: one async call for the whole trigger batch
Set<Id> ids = new Map<Id, Account>(Trigger.new).keySet();
if (!ids.isEmpty()) {
PartnerSync.sendAccountNames(ids);
}The same rule applies to Queueable. Pass the whole list into one job and let execute do the work in bulk.
Starting jobs on every save without a guard
A trigger that enqueues a job on every update can flood the queue. Data loads and integrations can save thousands of records in minutes. Each save may enqueue a job, and each job may update records that fire the trigger again.
A static variable does not fix this. Statics last for one transaction, and the async job runs in a new transaction with fresh statics. Use data-based guards instead:
- Enqueue only when a relevant field actually changed, by comparing
Trigger.newwithTrigger.oldMap. - Use a status field such as
Sync_Status__c, and skip records that are alreadyQueuedorDone. - Check
System.isFuture(),System.isBatch(), andSystem.isQueueable()when the same code can run in several contexts.
Calling `Database.executeBatch` from a trigger
A batch started from a trigger competes for a small number of slots. At most 5 batch jobs can be queued or active at once. Extra jobs wait in the flex queue, which holds up to 100 jobs in the Holding status. When a bulk load fires the trigger repeatedly, the flex queue fills and executeBatch starts failing. Start a Queueable from the trigger instead. If the work really needs Batch Apex, have the Queueable or a scheduled job check capacity first.
Pitfalls that come from misunderstanding the contract
Passing the wrong thing to a future method
A future method accepts only primitives and collections of primitives. Passing an sObject is a compile error. Passing a serialized sObject compiles, but the data may be stale by the time the method runs. Pass Ids and re-query inside the method.
Future calls also have no guaranteed order and return no job Id. If call B depends on call A having finished, you need Queueable chaining.
Forgetting the callout marker
Callouts need an explicit opt-in in each tool:
| Tool | How to allow callouts |
|---|---|
| `@future` | `@future(callout=true)` |
| Queueable | Also implement `Database.AllowsCallouts` |
| Batch | Also implement `Database.AllowsCallouts` |
| Schedulable | Not allowed in `execute`. Start a Queueable or Batch that has the marker. |
A Queueable without the marker fails only at the moment of the callout, which is easy to miss if your tests mock the callout.
public class PartnerPushJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public PartnerPushJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(accts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 300) {
throw new CalloutException('Partner API returned ' + res.getStatusCode());
}
}
}Throwing on a bad status code matters. If you only log it, the job shows as Completed in Apex Jobs even though the work failed.
Assuming batch instance variables persist
Each execute call in a batch runs in its own transaction, and the framework may deserialize a fresh copy of your class for each one. Without Database.Stateful, a counter or list you update in execute is back to its starting value in finish.
Adding Database.Stateful fixes this, but it has a cost. The whole object is serialized between calls, so a stateful list that grows with every chunk can hit heap limits or slow the job. Keep state small: counts, a short list of failed Ids, or an error summary. Write large results to a custom object instead.
Misreading chain limits
A running Queueable can enqueue only one child job. Calling System.enqueueJob twice inside execute fails on the second call. In Developer Edition and trial orgs, the chain depth is also capped at 5. Design chains to be sequential, not branching. If you need fan-out, use Batch Apex.
Chains also have no natural end. A job that enqueues itself unconditionally runs until someone aborts it. The ChunkedUpdateJob pattern in the chaining chapter ends because remaining shrinks. Always make sure the next job receives strictly less work than the current one.
Pitfalls that come from capacity
Ignoring the shared daily cap
Async executions share one daily allocation per org, calculated as the greater of 250,000 or 200 times the number of user licenses, over 24 hours. Every future call, Queueable run, scheduled run, and each batch execute chunk counts. A batch with a scope size of 1 over 500,000 records uses 500,000 executions, which exceeds a 250,000 cap on its own. Keep the scope size large unless limits force it smaller.
Choosing scope size by habit
The default scope size is 200, and 200 is also the maximum for a QueryLocator batch. Scope size is a trade-off, not a tuning knob you set once:
- Lower it when each record triggers heavy work, such as a callout per record, complex triggers, or many SOQL queries. If
executehits a CPU or SOQL limit, only that chunk rolls back, but the job keeps trying later chunks. - Raise it (up to 200) when each record is cheap, to save executions and wall-clock time.
Overusing Scheduled Apex
The org allows 100 scheduled jobs. Developers sometimes call System.schedule from a trigger or a utility method to run "something in five minutes", and each call creates a new scheduled job. Scheduled Apex is for recurring, time-based work. For "run this soon, once", use Queueable.
Another common mistake is putting real work in the Schedulable.execute method. That method shares the limits of an async transaction, can't make callouts directly, and a failure leaves no per-record information. Keep it to a few lines that start a Batch or Queueable job, as NightlyStaleLeadJob does.
Scheduling a duplicate
Deploying a class that schedules itself in a setup script, or re-running the script, creates another job with the same behavior under a new name. Before scheduling, look for an existing job by name:
List<CronTrigger> existing = [
SELECT Id FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly stale lead cleanup'
];
if (existing.isEmpty()) {
System.schedule('Nightly stale lead cleanup', '0 0 2 * * ?', new NightlyStaleLeadJob());
}Pitfalls that come from failure handling
Swallowing exceptions
A try/catch that catches Exception and does nothing makes a failed job look successful. In Queueable and Batch, an uncaught exception marks the job Failed, which is the signal you want. Catch only what you can handle, and log or rethrow the rest.
Using a finalizer as a retry loop
A finalizer is the right place to log a failure or enqueue a follow-up. It is a bad place to retry forever. A finalizer that re-enqueues the same failing job on UNHANDLED_EXCEPTION creates an infinite retry loop, which then consumes the daily cap. Keep a retry counter in the job's constructor and stop after a small number of attempts.
public class RetryFinalizer implements Finalizer {
private Id accountId;
private Integer attempt;
public RetryFinalizer(Id accountId, Integer attempt) {
this.accountId = accountId;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION && attempt < 3) {
System.enqueueJob(new RetryableJob(accountId, attempt + 1));
}
}
}Here RetryableJob would be a Queueable class that calls System.attachFinalizer(new RetryFinalizer(accountId, attempt)) at the start of its execute method.
Pitfalls that come from tests
- Asserting before
Test.stopTest(). Async work has not run yet. Put assertions afterstopTest. - Expecting chains to run. Under test, chained Queueable jobs may not run as they do in production, and a chain that is allowed can fail with a stack depth error. Test each job's
executelogic on its own, and guard the chaining call if needed. - Expecting every batch chunk to run. In a test, a batch started between
startTestandstopTestruns a singleexecutecall. Keep the test data within one scope. - Not testing the failure path. Write at least one test where the job throws, and assert what your finalizer or
finishmethod did in response.
Quick review checklist
- Does each trigger make at most one async call per transaction?
- Is there a data-based guard against re-enqueueing?
- Do all callout-capable jobs carry
callout=trueorDatabase.AllowsCallouts? - Is batch state small, and does the class need
Database.Statefulat all? - Does every chain shrink its work and end?
- Is the scope size chosen on purpose?
- Can a failure be seen in Apex Jobs or a log?
Exercise
A trigger on Account runs System.enqueueJob(new PartnerPushJob(new Set<Id>{ a.Id })) for each record in Trigger.new. A data load of 200 accounts fails. What is the cause, and how do you fix it?
Show answer
One transaction can call System.enqueueJob at most 50 times, and the loop makes 200 calls. Collect the Ids into one set and enqueue a single job, System.enqueueJob(new PartnerPushJob(ids)), after checking the set is not empty. Add a guard so the job is only enqueued for records where a relevant field changed.
Exercise
A batch class increments a counter named failures in execute and prints it in finish. The log always shows 0, although some chunks failed. Name the cause and one risk of the fix.
Show answer
The class does not implement Database.Stateful, so instance variables are not kept between execute calls. Adding Database.Stateful fixes it. The risk is that the whole object is serialized between chunks, so keeping a large collection in it can slow the job or exceed heap limits. Store a count or a short list of Ids instead.