Sub topic 5
Your asynchronous options
This chapter assumes you can write and bulkify Apex triggers, know the main governor limits, and understand the earlier chapters. Those chapters explain why a trigger cannot call out directly and how to write an HTTP callout. Here you survey the asynchronous tools Apex offers and learn what each can and cannot do in a callout scenario.
What "asynchronous" buys you
Asynchronous Apex runs in a separate transaction, after the transaction that started it commits. That separation fixes the trigger problem. The database work in the trigger is finished and committed before the callout starts, so no uncommitted work is pending and the callout is allowed.
Asynchronous Apex also gets its own set of governor limits. Many are higher than the synchronous ones, such as heap size and CPU time. The callout limits stay the same: 100 callouts per transaction and 120 seconds of cumulative callout time.
The trade-off is timing. You cannot know exactly when the job will run, and you cannot return its result to the user who saved the record. The user's save completes first. The callout happens later, on its own schedule.
The four main tools
Apex has four asynchronous mechanisms that matter here.
Future methods
A future method is a static method marked @future. To call out, it must be marked @future(callout=true). It is the oldest and simplest tool.
- It must be
staticand returnvoid. - Its parameters must be primitives or collections of primitives. You cannot pass an sObject or a custom object.
- You get no job Id back, so you cannot track or cancel the job from code.
- You cannot chain future methods. A future method cannot call another future method, and a batch job cannot call one either.
- One transaction can make at most 50 future calls.
- Execution order is not guaranteed.
Queueable Apex
A Queueable is a class that implements Queueable. To call out, it must also implement Database.AllowsCallouts. You start it with System.enqueueJob, which returns a job Id.
- The constructor can take any serializable type, including sObjects and your own classes.
- The Id lets you query
AsyncApexJobto monitor the job. - A running Queueable can enqueue one child job, which lets you chain work.
- One synchronous transaction, such as a trigger, can enqueue up to 50 Queueable jobs.
- You can attach a Finalizer to run cleanup or retry logic even when the job fails with an unhandled exception.
Batch Apex
A batch class implements Database.Batchable<sObject>. To call out, it must also implement Database.AllowsCallouts. You start it with Database.executeBatch. The platform splits a large record set into chunks, and each chunk runs as its own transaction.
- Each
executecall has its own limits, including its own 100-callout allowance. - A batch job is built for large volumes, up to millions of records through a
QueryLocator. - Up to five batch jobs can be queued or active at once. More wait in the flex queue, which holds up to 100 jobs.
- Chunks are slower to start than a Queueable. A batch job is heavy for a handful of records.
Schedulable Apex
A Schedulable class implements Schedulable and runs at set times. It cannot make a callout itself. Its execute method must start a Queueable or batch job that does the callout. Use it for recurring work, not for reacting to a record change. A trigger fires on a change, so Schedulable rarely fits there.
Platform Events and Change Data Capture are also asynchronous, but they are a different design: subscribers process published messages. They are out of scope for this chapter.
How the options relate
The diagram shows the decision a trigger faces after a record change.
Comparing them side by side
| Feature | Future | Queueable | Batch |
|---|---|---|---|
| Callout marker | `@future(callout=true)` | `Database.AllowsCallouts` | `Database.AllowsCallouts` |
| Parameter types | Primitives and collections of primitives | Any serializable type | Set by the start method and constructor |
| Returns a job Id | No | Yes | Yes |
| Can be chained | No | Yes, one child from an async job | Yes, from `finish` |
| Limit per trigger transaction | 50 | 50 | 5 queued or active in total |
| Best for | Small, simple, one-off callouts | Most trigger callouts | Very large record sets |
| Failure hook | None | Finalizer | `finish` method |
For most trigger callouts, Queueable is the strongest default. It accepts richer data, gives you a Job Id, and supports Finalizers. Future methods still appear in existing code, and they work for simple cases.
What a trigger is allowed to start
The 50-job limit applies per synchronous transaction, but the rule changes once you are already inside asynchronous code. A running Queueable can enqueue only one more job. Calling System.enqueueJob twice from execute throws a LimitException.
You can check headroom at runtime with the Limits class. In an async context the limit value drops to 1, so the same check works in both places.
public class AsyncGuard {
public static Boolean canEnqueue() {
return Limits.getQueueableJobs() < Limits.getLimitQueueableJobs();
}
public static String context() {
if (System.isFuture()) {
return 'future';
}
if (System.isBatch()) {
return 'batch';
}
if (System.isQueueable()) {
return 'queueable';
}
return 'synchronous';
}
}Context awareness matters because a trigger can run in any of these contexts. A batch job that updates accounts fires your AccountSyncTrigger inside the batch transaction. A future method cannot be called from there, but a Queueable can be enqueued, within the one-job limit. A guard like canEnqueue lets you skip or defer work instead of crashing a data load.
The shape of a trigger callout
Whichever tool you choose, the trigger should do very little. It collects record Ids and hands them off, as in this example from the plan.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}This trigger starts one job for the whole batch of inserted accounts, not one job per account. Starting one per record is the most common mistake. A data load of 200 accounts would try to start 200 jobs and hit the 50-job limit. Later chapters cover the details of passing Ids, bulkification and avoiding loops.
Org-wide limits
Asynchronous work also counts against a daily org-wide cap. The platform allows the larger of 250,000 asynchronous executions or 200 times the number of user licenses, per 24 hours. Future calls, Queueable jobs, batch execute chunks and scheduled runs all draw from this pool. The pool is shared by the whole org, so one noisy trigger on a busy object can starve other automation. Because of this, enqueue the minimum number of jobs for each transaction.
Async work also queues behind other work. Under heavy load, a job may wait seconds or minutes. Do not design a user flow that needs the callout result immediately after the save.
Common errors
- "Future method cannot be called from a future or batch method." You tried to start a future call from async code. Use a Queueable instead, and check
System.isFuture()orSystem.isBatch()first. - "Too many queueable jobs added to the queue: 2." A Queueable enqueued more than one child. Chain a single job, or let one job process everything.
- "Too many queueable jobs added to the queue: 51." A trigger enqueued once per record. Collect the Ids and enqueue one job.
- "You have uncommitted work pending." This still appears if you start a callout in the same transaction as a DML statement. Move the callout into the async class.
- A callout fails in a Queueable. Check that the class implements
Database.AllowsCallouts. Without it, the callout is rejected even in an async context.
Exercise
A trigger on Account runs after update. It must send each changed account to an external system. A data load updates 200 accounts at a time. A developer proposes looping over Trigger.new and calling System.enqueueJob once per account. Explain what will fail and describe the fix.
Show answer
A synchronous transaction can enqueue at most 50 Queueable jobs, so the 51st call throws a LimitException and the whole load rolls back. The fix is to call System.enqueueJob once, outside the loop, passing the whole set of Ids (for example Trigger.newMap.keySet()). The job re-queries the accounts and sends them in one bulk request, or in a few requests if the payload is large. For very large volumes beyond one job's limits, switch to Batch Apex.
Exercise
Name the marker you must add to a Queueable class and to a Batch class so each can make a callout. Then say which of future, Queueable and Batch gives you no job Id to monitor.
Show answer
Both the Queueable class and the Batch class must implement Database.AllowsCallouts. A future method (marked @future(callout=true)) gives you no job Id. System.enqueueJob and Database.executeBatch both return one.