Sub topic 14
Common pitfalls and anti-patterns
This chapter assumes you know basic Apex, SOQL and DML, governor limits, triggers, and how to write unit tests. It collects the mistakes that show up most often with future, Queueable, Batch, and Scheduled Apex, and shows how to avoid each one.
Pitfall 1: Starting async work from async work
Async tools have their own rules about what can start what. A future method cannot call another future method, and it cannot be called from a Batch or another future context. A Queueable job started from a running Queueable can enqueue only one child. Calling System.enqueueJob in a loop inside a chained job fails on the second call.
The usual cause is a trigger that enqueues a job, where that job's own DML fires the same trigger again.
public class GuardedEnqueue {
public static void enqueueIfAllowed(List<Account> accts) {
if (System.isFuture() || System.isBatch()) {
return; // already async: do the work inline or skip
}
if (Limits.getQueueableJobs() < Limits.getLimitQueueableJobs()) {
System.enqueueJob(new AccountReviewJob(accts));
}
}
}Check the context before you enqueue. Also use a static flag to stop a trigger from re-enqueueing work it caused itself.
Pitfall 2: Enqueueing one job per record
Each call to System.enqueueJob or a future method counts against a per-transaction limit. A trigger that fires for 200 records and enqueues a job for each one hits that limit fast.
// Anti-pattern: one job per record
for (Account a : Trigger.new) {
System.enqueueJob(new AccountReviewJob(new List<Account>{ a }));
}
// Better: one job for the whole list
System.enqueueJob(new AccountReviewJob(Trigger.new));Pass the whole collection to one job. This is the same bulkification rule you already use for SOQL and DML.
Pitfall 3: Using Batch Apex for small jobs
Batch Apex is built for large volumes. Each batch job enters the flex queue and waits for a free slot, so a small job can sit for minutes. If you have a few hundred records, a Queueable job starts sooner and does the same work. Org-wide caps also apply: the org can hold only a limited number of jobs in the flex queue, and only five batch jobs run at the same time.
Pitfall 4: Assuming batch instance variables persist
Every execute call is a separate transaction, and by default the class is rebuilt between calls. A counter that is not marked Database.Stateful resets each time. Stateful batches also serialize their state after every call, so storing a large list there slows the job and can fail it. Keep state small, such as counts or a short list of Ids.
Pitfall 5: Ignoring failures
A failed future method gives you no way to react. A failed Queueable job can still be handled, because you can attach a finalizer and log the error or retry. Without one, the exception shows only in the Apex Jobs page. If the work matters, use a Queueable with a finalizer. Keep retries bounded so a permanent error does not loop forever.
Pitfall 6: Putting heavy logic in the Schedulable class
A scheduled class should be short. It should start a batch or a Queueable job and return. Heavy work inside execute runs under the scheduler's limits and is harder to test. Also remember that an org can hold only 100 scheduled jobs. Schedule one job per task, not one job per record.
Pitfall 7: Trusting test results without stopTest
Async code does not run in a test until Test.stopTest(). An assertion placed before that line checks the data before the job ran, so it fails or passes for the wrong reason. Put the assertions after stopTest.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Async from async | Limit exception on enqueue | Check `System.isFuture()` and `System.isBatch()` |
| Job per record | Too many queueable jobs | Pass the whole collection |
| Batch for tiny jobs | Long wait to start | Use Queueable |
| Lost batch state | Counter always zero | Implement `Database.Stateful` |
| No failure handling | Silent failures | Attach a finalizer |
| Heavy scheduler | Hard to test, limits hit | Delegate to batch or Queueable |
Exercise
A trigger on Account enqueues a Queueable job for every record in Trigger.new, and bulk loads of 200 records fail with a limit error. What two changes fix it?
Show answer
Enqueue a single job that takes the whole list of records, and add a guard (such as a static flag or a System.isFuture() and System.isBatch() check) so async code does not enqueue more work from a context where it is not allowed.
Exercise
A Batch class counts the records it updates in a private Integer, but finish always reports 0. What is missing?
Show answer
The class must implement Database.Stateful. Without it, instance variables are reset between execute calls.