Sub topic 6
Calling out with a future method
This chapter assumes you can write Apex classes and triggers, know the basics of governor limits, and have seen an HTTP callout with HttpRequest, Http and HttpResponse. It covers the @future(callout=true) annotation: how to use it from a trigger, what it restricts, and where it fails.
What a future method does
A future method is a static method that Salesforce runs later, in its own transaction, once system resources are free. The trigger's transaction commits first. The callout then runs in a separate transaction with no uncommitted work pending, so the callout restriction no longer applies.
Two things make this work:
@futurequeues the call instead of running it.callout=truetells the platform that the future method is allowed to make callouts. Without it, the callout throws aCalloutException.
The basic pattern
The trigger collects Ids and calls the future method once. The future method re-queries the records and makes the callout.
trigger AccountSyncTrigger on Account (after insert) {
AccountCalloutService.syncAccounts(Trigger.newMap.keySet());
}public class AccountCalloutService {
@future(callout=true)
public static void syncAccounts(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
System.debug('Status: ' + res.getStatusCode());
}
}The endpoint callout:Billing_API/accounts uses a Named Credential called Billing_API. The platform supplies the base URL and the authentication, so no secrets appear in the code.
The trigger makes one call to the future method for the whole batch. It does not loop over records and call the method once per account.
Restrictions you must follow
The platform enforces these rules when you save the class or when the method is called.
| Rule | Detail |
|---|---|
| Static and void | The method must be `static` and return `void`. You cannot get a result back. |
| Primitive parameters | Parameters must be primitives, arrays of primitives, or collections of primitives. sObjects and custom class instances are not allowed. |
| No ordering guarantee | Future methods run in the order resources allow, not in the order you called them. |
| No chaining | A future method cannot call another future method. |
| Not from batch or future | You cannot call a future method from a Batch Apex job or from another future method. |
| Limit per transaction | At most 50 future calls per Apex transaction. |
| Daily limit | The org has a 24-hour cap on async executions, shared with other async types (the greater of 250,000 or a per-license number). |
Check the current numbers in the Apex Developer Guide for your release. Limits change, and the daily cap depends on your licenses.
The primitive-parameter rule exists because the arguments are stored and used later. An sObject passed in could be out of date by the time the method runs, and the platform cannot guarantee that it is still valid.
Why you pass Ids and re-query
By the time the future method runs, the records may have changed. A user may have edited the account, a workflow may have updated it, or another trigger may have written to it. If you passed field values at queue time, you would send old data.
Passing Ids and re-querying gives you the current committed state:
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];The Ids may also point to records that were deleted in the meantime. The query then returns fewer rows than you expected. Your code should handle an empty list instead of assuming it matches the input.
if (accounts.isEmpty()) {
return;
}If you do need to pass field values, serialize them to a String with JSON.serialize, which is a primitive. Do this only when you need the values as they were at queue time, for example for an audit record.
Common errors
Callout without `callout=true`
@future
public static void syncAccounts(Set<Id> accountIds) {
// Throws System.CalloutException when the callout runs:
// "Callout from triggers are currently not supported" is not the message here;
// the future method itself is not allowed to call out.
}If you leave out callout=true, the method runs but the callout fails. Always add it to any future method that calls an external service.
Calling a future method from a future method
@future(callout=true)
public static void first(Set<Id> ids) {
second(ids); // System.AsyncException: Future method cannot be called from a future or batch method
}When you need a second step, use Queueable Apex, which allows chaining. The next chapter covers it.
Exceeding 50 calls
A trigger that calls a future method inside a for loop will fail once a transaction inserts or updates more than 50 records. The error is a limit exception, and it rolls back the whole transaction, including the user's data change. Call the method once per trigger invocation with a collection of Ids.
Re-entry from the response
If the future method updates the same records and a trigger on them calls the future method again, you get a loop. Each pass queues another one, and the org spends its async quota. Guard the trigger with a condition that checks a field you control, or with a static flag. A static flag does not carry over to the future method's separate transaction, so a field-based check is the safer option. The chapter on avoiding re-entry covers this in depth.
Calling a future method from a trigger safely
Two more details matter in practice.
First, you cannot call a future method from a context that is already async in a way the platform forbids. A trigger fired by a Batch Apex job that updates records cannot call a future method. If your triggers must work under batch updates, check System.isBatch() and System.isFuture() before you queue the call:
trigger AccountSyncTrigger on Account (after insert) {
if (!System.isFuture() && !System.isBatch()) {
AccountCalloutService.syncAccounts(Trigger.newMap.keySet());
}
}This avoids the exception, but it also means that records changed by a batch job are not synced. If that matters, use Queueable Apex, which can be enqueued from a batch execute method (with a limit of one enqueue there).
Second, future methods are not guaranteed to run quickly. Usually they start within seconds. Under load, they can wait much longer. Do not build a process that depends on the callout finishing within a set time.
Error handling in a future method
A future method cannot return a value or throw an exception to the caller. The caller has already finished. You have to record failures yourself.
The minimum is to check the status code:
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}A debug log is not durable, so for production, write failures to a custom object or publish a platform event. Also wrap send in a try/catch for CalloutException, which the platform throws for timeouts and connection failures. An unhandled exception in a future method is not retried. The work is lost, and you cannot attach a Finalizer as you can with Queueable Apex.
try {
HttpResponse res = new Http().send(req);
// check res.getStatusCode()
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
}Testing a future method
Tests cannot make real callouts, so you supply a mock with Test.setMock. Future methods queued in a test run only when Test.stopTest() is called, so the callout and its assertions go after that line.
@IsTest
private class AccountCalloutServiceTest {
private class MockOk implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void futureMethodRunsAfterStopTest() {
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Integer queued = [SELECT COUNT() FROM Account WHERE Name = 'Acme'];
System.assertEquals(1, queued, 'The insert should have committed');
}
}Test.startTest() also gives the code under test a fresh set of governor limits, and Test.stopTest() forces all queued async work to finish. Assertions on the result of the callout belong after stopTest().
When a future method is a good fit
A future method suits a small, fire-and-forget callout where you do not need chaining, a result, or complex input. It has the least code of the three async options. Once you need any of the following, move to Queueable Apex:
- Passing sObjects or custom types as input.
- Chaining a second job after the first.
- Attaching a Finalizer to handle failures.
- Getting a job Id back to monitor the work.
Exercise
A trigger on Contact calls ContactService.sync(c.Id) inside a for (Contact c : Trigger.new) loop. sync is a @future(callout=true) method. A data loader job inserts 200 contacts. What happens, and how do you fix it?
Show answer
The transaction fails with a limit exception because it queues more than 50 future calls, and the whole insert rolls back. Change the method to accept a Set<Id> and call it once from the trigger with Trigger.newMap.keySet(). Inside the method, query the contacts by Id and send them in one bulk request.
Exercise
Why can a future method not take a List<Account> as a parameter, and what should you pass instead?
Show answer
Future method parameters must be primitives or collections of primitives, because the arguments are stored and used later in a different transaction. Pass a Set<Id> (or List<Id>), then re-query the accounts inside the method so that you work with the current committed data.