Sub topic 13
Choosing the right tool: a decision framework
You now know how each of the four asynchronous Apex tools works. This chapter turns that knowledge into a repeatable way to pick one. It assumes you can write Apex triggers and classes, run SOQL and DML, and have met the earlier chapters on @future, Queueable, Batch, and Scheduled Apex.
Start with the requirement, not the tool
Developers often pick the tool they know best. A better habit is to describe the requirement first and let it rule tools out. Ask these questions in order:
- Does the work need to happen at a specific time or on a recurring schedule?
- How many records does it touch, and could that number grow?
- Does it need state that is not a primitive, such as a list of sObjects or a custom class?
- Does it make callouts?
- Does the caller need to know which job was started, to monitor it or chain it?
- Must steps run in a strict order?
Each answer removes some options. The sections below show how.
Compare the tools side by side
| Question | `@future` | Queueable | Batch | Scheduled |
|---|---|---|---|---|
| Parameter types | Primitives and collections of primitives only | Any serializable state in member variables | Any state, and `Database.Stateful` keeps it between calls | Any, but the class is usually small |
| Returns a job Id | No | Yes, from `System.enqueueJob` | Yes, from `Database.executeBatch` | Yes, from `System.schedule` |
| Typical data size | Small | Small to medium | Up to 50 million records with a QueryLocator | Not a processing tool |
| Chaining | Cannot call another future method | One child job from a running job | One batch from `finish` | Can start batch or Queueable jobs |
| Callouts | `callout=true` | `Database.AllowsCallouts` | `Database.AllowsCallouts` | Not directly in `execute`. Delegate instead. |
| Runs at a chosen time | No | No | No | Yes, by cron expression |
| Failure hook | None | Finalizer | `finish` method | None |
Read the table by row. If you need a job Id, @future is out. If you need to process a million records, only Batch fits comfortably. If you need a clock, Scheduled Apex must be involved.
The decision process
The flowchart below puts the questions in a practical order.
Rule 1: a schedule means Scheduled Apex
Only Scheduled Apex starts work at a given time. Keep the execute method of the scheduled class short. Its job is to start other work, not to do it. For large volumes, start a batch. For small ones, enqueue a Queueable. This keeps the scheduled class easy to test and lets you reuse the batch or Queueable from other entry points, such as a button or a trigger.
Rule 2: large volume means Batch
Batch Apex splits a query result into chunks. Each execute call is its own transaction with fresh governor limits. A failure in one chunk does not roll back chunks that already finished. Use Batch when any of these is true:
- The record count is large or unbounded, for example "all leads untouched for a year".
- A single transaction would hit limits such as 10,000 DML rows or the CPU limit.
- You want partial progress to survive an error.
A Queueable that processes one big list is still one transaction, so it has the same limits as the code that enqueued it, except for the larger async limits on heap, CPU, and SOQL queries. Chunking by hand with chained Queueables works, but you then maintain the chunking logic that Batch gives you for free.
Rule 3: moderate work with state or sequencing means Queueable
Queueable is the general-purpose choice. It accepts non-primitive state, returns a job Id, allows callouts with Database.AllowsCallouts, supports finalizers, and can chain a child job. Choose it when:
- You have a list of sObjects to pass along, not just Ids.
- Step two must run only after step one finishes.
- You want a finalizer to log failures or retry.
- You want to monitor the job through its Id.
Rule 4: future methods are the narrow case
A @future method is static, returns void, and takes only primitives or collections of primitives. It returns no Id, so you cannot monitor or abort it individually. You cannot call one from another future method or from a batch job. New code rarely needs it. Valid reasons to keep it are a small, self-contained callout, or mixed DML work where you must move a setup-object update such as a User change into a separate transaction, and existing code already uses it.
Because @future is limited in every way Queueable is not, Queueable is the safer default whenever both would work.
Edge cases that change the answer
Choosing by the calling context
Where the code starts matters. A trigger on a bulk load may fire hundreds of times in a transaction. Limits on the number of async calls per transaction, such as 50 @future calls and 50 System.enqueueJob calls, apply to the synchronous transaction. Enqueue once per transaction with a collection, not once per record.
Code already running inside a batch execute or a future method has stricter rules. A batch can enqueue limited follow-up work, and a future method cannot call another future method. When a shared helper might run in different contexts, check the context at runtime.
public class AsyncRouter {
public static void process(List<Account> accts) {
Boolean queueSlotFree =
Limits.getQueueableJobs() < Limits.getLimitQueueableJobs();
if (System.isBatch() || System.isFuture() || !queueSlotFree) {
// Already async, or no slot left: do the work inline.
new AccountReviewJob(accts).execute(null);
} else {
System.enqueueJob(new AccountReviewJob(accts));
}
}
}This reuses AccountReviewJob from the Queueable chapter. Calling execute(null) works because that class never reads the context. If your class does use QueueableContext, pass real logic through a plain method instead.
Choosing by org-wide limits
Every async tool shares the org's daily async execution allowance. The Batch tool also has queue limits, such as five batch jobs running at once. Extra jobs wait in the flex queue, up to 100 held jobs. A design that starts many small batches wastes these slots. If a nightly job would start dozens of tiny batches, combine them into one batch with a larger query.
Choosing by failure behavior
Decide how failures should look before you pick:
- A batch chunk that throws loses only that chunk. The
finishmethod still runs, so you can report counts. - A Queueable that throws stops its own work. Attach a finalizer if you need to log or retry.
- A future method that throws leaves little trace except the debug log and the Apex Jobs page. You cannot attach a handler.
If the business cares about knowing a failure happened, that favors Queueable with a finalizer or Batch with a finish report.
Choosing by testability
All four tools run in tests only after Test.stopTest(). Queueable and future jobs run once at that point. A batch job in a test runs a single execute call, so keep test data to one scope. A Queueable that chains a child cannot chain inside a test, so the child is not enqueued from the test context. Design for this by moving the logic into a plain method you can test directly.
A worked example
Requirement: every night, find leads with no activity for a year, mark them stale, and email a count to an admin.
- Time-based, so Scheduled Apex is required.
- Lead volume may be hundreds of thousands, so Batch does the work.
- The count must survive across chunks, so the batch implements
Database.Stateful. - The email goes out in
finish.
This is the design the earlier chapters built: NightlyStaleLeadJob calls Database.executeBatch(new StaleLeadBatch(), 200). The scheduler stays small, and the batch can also be started by hand from the Developer Console when you need to rerun it.
Now a different requirement: when an Opportunity closes, send its data to a partner API, then update a status field after the response arrives.
- No schedule, small volume.
- A callout is needed, and the status update depends on the response.
- The request payload may include a list of sObjects.
- You want to monitor the job.
A Queueable implementing Database.AllowsCallouts with a finalizer for failures fits. A @future(callout=true) method could send the request, but it cannot pass sObjects and gives you no Id.
Common wrong turns
- Using Batch for a handful of records. The overhead of the three-method structure and the flex queue gives you nothing.
- Using a Queueable chain to walk a very large data set. Each link is a separate job and you lose Batch's query handling.
- Putting heavy work directly in the scheduled class's
executemethod. You then cannot reuse it or run it on demand. - Reaching for
@futurebecause a tutorial showed it first.
Exercise
A requirement says: "Every Sunday at 06:00, recalculate a rollup field on all Accounts, which currently number about 800,000." Which tool or combination do you choose, and why not a single Queueable?
Show answer
Use Scheduled Apex to start a Batch job. The weekly time requires a Schedulable class with a cron expression such as '0 0 6 ? * SUN'. The volume requires Batch, because each execute call gets fresh governor limits and the QueryLocator can cover 800,000 rows. A single Queueable would run all the work in one transaction and hit DML, CPU, or heap limits. Chaining Queueables would force you to write your own chunking and would use more of the async allowance.
Exercise
Why is Queueable usually preferred over @future for a new callout that needs a list of Account records as input?
Show answer
A future method accepts only primitives and collections of primitives, so you would pass Ids and query the records again. A Queueable can hold the list of Accounts in a member variable, returns a job Id for monitoring, and supports finalizers. All three are things a future method cannot do.