Sub topic 3
Future methods: simple, fire-and-forget work
This chapter assumes you can write basic Apex classes, run SOQL and DML, read a trigger, and write a simple unit test. It also assumes you know the governor limits exist, even if you don't remember the numbers.
A future method is the oldest and smallest asynchronous tool in Apex. You mark a static method with @future. When you call it, Salesforce does not run the body. It queues a request and returns control to your code. The body runs later, in its own transaction, when the platform has capacity.
When a future method fits
Use a future method when three things are true:
- The work can happen after the current transaction commits.
- The caller does not need a result back.
- The inputs are simple values such as Ids or strings.
Two classic cases are callouts that must not run inside a trigger's transaction, and DML on setup objects mixed with DML on regular objects.
Callouts after DML
A trigger cannot make a callout once the transaction has uncommitted DML. Moving the callout into a future method avoids that, because the callout runs in a fresh transaction after the commit.
Mixed DML
Salesforce does not allow DML on a setup object (such as User or PermissionSetAssignment) and a non-setup object (such as Account) in one transaction. Putting one of the two operations in a future method splits them into separate transactions.
The anatomy of a future method
public class PartnerSync {
@future(callout=true)
public static void sendAccountNames(Set<Id> accountIds) {
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);
System.debug(res.getStatusCode());
}
}Each part of this example follows from a rule:
- The method is
static. There is no object instance to keep between the call and the run. - The method returns
void. Nobody is waiting for a value, so there is nothing to return. - The parameter is a
Set<Id>. Future parameters must be primitives, or arrays and collections of primitives. callout=trueis required for HTTP callouts. Without it, the callout throws an exception at run time.- The method queries the accounts itself. It does not receive them.
The endpoint uses a Named Credential (callout:Partner_API), so the URL and credentials stay out of the code.
Why parameters must be primitives
Salesforce serializes the arguments when you call the method, stores the request, and deserializes it later. That limit keeps the stored request small and simple. It also means you cannot pass an Account record or a custom class instance.
Passing Ids has a useful side effect. The method re-queries the records, so it sees their current values instead of a snapshot from the moment of the call. The record may have changed between the call and the run, and that is usually what you want.
If you need to pass structured data, you can serialize it to a JSON string and deserialize it inside the method. If you find yourself doing this often, use Queueable Apex, covered in the next chapter.
Calling a future method from a trigger
The most common mistake is calling the method once per record. A trigger can handle up to 200 records at a time, and one Apex invocation can make at most 50 future calls. Always collect the Ids and call the method once.
trigger AccountSync on Account (after insert, after update) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
if (!System.isFuture() && !System.isBatch()) {
PartnerSync.sendAccountNames(ids);
}
}The guard matters. A future method cannot call another future method, and a batch job cannot call one either. If an update made inside a future or batch context fires this trigger, an unguarded call throws an exception. System.isFuture() and System.isBatch() let you skip the call in those contexts.
The guard has a cost. When the trigger runs inside a future or batch job, the sync silently does not happen. If that matters for your requirement, a Queueable job is the better choice.
What happens to a future call
Notice that the request is queued, not run, when you call the method. If the original transaction rolls back, the queued request is discarded and the method never runs.
Limits and restrictions
The restrictions that matter in practice:
| Restriction | What it means for you |
|---|---|
| Static and `void` | You cannot return data or hold state. |
| Primitive parameters only | Pass Ids or JSON strings, then re-query or deserialize. |
| 50 future calls per Apex invocation | Bulkify. One call per trigger run, not per record. |
| Org-wide daily cap | The cap is 250,000 async executions per 24 hours, or the number of user licenses times 200, whichever is greater. Future methods share this cap with other async tools. |
| No chaining | A future method cannot call another future method. |
| No guaranteed order | Two future calls may run in either order, or at the same time. |
| No job Id returned | You cannot easily track or abort a single call. |
The limits inside the future transaction are higher than in synchronous code. For example, heap is 12 MB instead of 6 MB, and CPU time is 60 seconds instead of 10. That makes future methods useful for work that is too heavy for the synchronous transaction.
The numbers above are the documented limits at the time of writing. Check the current Apex Developer Guide before relying on an exact figure.
Failure modes
Running out of order
Because order is not guaranteed, do not queue "step 1" and "step 2" as two future calls. If step 2 depends on step 1, use a chained Queueable job.
Row locks
Two future methods updating the same records at the same time can fail with UNABLE_TO_LOCK_ROW. This happens when a trigger fires several times in quick succession, queueing overlapping calls. Keep the work in each call small, and avoid touching the same records from several calls.
Silent failure
If a future method throws an unhandled exception, the caller never finds out. The failure appears only in the debug log and in the Apex Jobs page. Catch exceptions inside the method and record them somewhere visible, such as a custom log object.
public class SafeSync {
@future(callout=true)
public static void send(Set<Id> accountIds) {
try {
PartnerSync.sendAccountNames(accountIds);
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + e.getMessage());
}
}
}This wrapper calls the first example as a plain static method, so it runs inside the wrapper's future transaction. That is a legal way to reuse the code, since only calling a future method from a future context throws.
Stale input
A future call that runs minutes later sees the data as it is then. If you need the exact values from the moment of the call, a future method is the wrong choice. Serialize those values into the argument instead.
Testing a future method
A future method runs only when the test calls Test.stopTest(). Queue the call between Test.startTest() and Test.stopTest(), then assert afterwards. Callouts are not allowed in tests, so you also need a mock. A minimal mock looks like this:
@IsTest
global class PartnerMock implements HttpCalloutMock {
global HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}In the test method, call Test.setMock(HttpCalloutMock.class, new PartnerMock()); before Test.startTest(). Test.stopTest() then runs the queued future call against the mock.
Summary of the decision
Choose a future method for a short, one-step job with simple inputs, where you do not care about the result. Move to Queueable Apex when you need object parameters, a job Id, chaining, or failure handling.
Exercise
A trigger on Contact calls a future method once for each record in Trigger.new. A data load inserts 200 contacts in one batch. What goes wrong, and how do you fix it?
Show answer
One Apex invocation can make at most 50 future calls, so the 51st call throws a limit exception and the load fails. Collect the Contact (or Account) Ids into a Set<Id> inside the trigger loop and call the future method once after the loop. The method then queries the records it needs by Id.
Exercise
Why can a future method not accept a List<Account> as a parameter, and what are two ways to work around that?
Show answer
Future parameters must be primitives or collections of primitives, because the arguments are serialized and stored until the method runs. You can pass the Ids and re-query inside the method, or pass a JSON string made with JSON.serialize and deserialize it in the method. A Queueable class avoids the limit, because it can hold sObjects in member variables.