Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Asynchronous Apex

Apex Future Methods and Asynchronous Basics

Learn asynchronous Apex and @future methods: when to go async, the rules and limits, callouts from triggers, and a runnable Java stand-in of a background job queue.

Most Apex runs synchronously: the user clicks Save, your trigger runs, and the page waits until it finishes. That is fine for small work, but some tasks should not hold up the user or must run in a separate transaction: calling an external web service, processing thousands of records, or mixing setup and non-setup DML. Asynchronous Apex lets you hand work to the platform to run later in its own transaction with its own, usually larger, governor limits. This lesson introduces the options and covers the oldest and simplest one, the @future method.

Asynchronous Apex needs an org. Apex listings here are read-only with no output claims; the runnable examples are Java stand-ins that model a background queue.

The four async tools

Tool Best for
@future method One small piece of work, fire and forget
Queueable Apex Work with complex parameters, chaining, monitoring
Batch Apex Processing very large data sets in chunks
Scheduled Apex Running something at a set time

Why go async? Limits. A synchronous transaction allows 100 SOQL queries and 10 seconds of CPU; async transactions get 200 queries, 60 seconds of CPU and more heap. And callouts from a trigger must be async, because a trigger cannot wait on an external service.

Writing a future method

A future method is static, returns void, and is annotated @future. To allow HTTP callouts, add (callout=true).

APEX
public with sharing class AccountSync {

    @future(callout=true)
    public static void pushToErp(Set<Id> accountIds) {
        List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
        for (Account a : accounts) {
            HttpRequest req = new HttpRequest();
            req.setEndpoint('callout:Erp/accounts');
            req.setMethod('POST');
            req.setBody(JSON.serialize(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name }));
            new Http().send(req);
        }
    }
}

callout:Erp is a Named Credential, which keeps the URL and secrets out of code (see REST callouts). Call the method from a trigger or another class like any static method:

APEX
AccountSync.pushToErp(new Set<Id>{ acct.Id });

The platform queues it and returns immediately. It runs when resources allow, which is usually seconds later but is not guaranteed.

The rules

  1. Parameters must be primitives, arrays of primitives, or collections of primitives. You cannot pass an sObject or a custom class. Pass Ids and re-query inside the method, which also gives you fresh data.
  2. The method must be static and return void.
  3. You cannot chain: a future method cannot call another future method (and calling one from a batch or future context fails).
  4. A transaction may enqueue at most 50 future calls; never call it in a loop for each record.
  5. There is no job Id returned, so you cannot monitor or cancel it from code. Queueable fixes this.
  6. Order is not guaranteed between two future calls.

Calling one per record is the classic bug:

APEX
// Bad: 200 records in a trigger means 200 future calls, which exceeds the limit of 50
for (Account a : Trigger.new) {
    AccountSync.pushToErp(new Set<Id>{ a.Id });
}

Collect the Ids and call once:

APEX
Set<Id> ids = new Map<Id, Account>(Trigger.new).keySet();
AccountSync.pushToErp(ids);

Mixed DML and setup objects

Changing a "setup" object (such as User or PermissionSetAssignment) and a regular object (such as Account) in the same transaction throws a mixed DML error. Moving one of the changes to a future method puts it in a separate transaction, which is the traditional workaround.

Testing a future method

Wrap the call in Test.startTest() and Test.stopTest(); stopTest makes the future method run before the next line, so you can assert on its effects. Callouts still need a mock (Test.setMock).

APEX
@isTest
static void futureUpdatesRating() {
    Account a = new Account(Name = 'Async Co');
    insert a;
    Test.startTest();
    AccountSync.markHot(new Set<Id>{ a.Id });
    Test.stopTest();
    Assert.areEqual('Hot', [SELECT Rating FROM Account WHERE Id = :a.Id].Rating);
}

Try the idea: a background queue (Java stand-in)

Java Stand-in: fire-and-forget work on a queue (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop at the end breaks the 50-call rule on purpose; the real platform throws a System.LimitException you cannot catch.

Try the idea: pass Ids, not objects (Java stand-in)

Java Stand-in: re-query fresh data inside the job (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Passing Ids means the job always sees the latest data, even if the record changed after it was queued.

When not to use @future

If you need to pass an sObject, chain a second step, get a job Id, or process thousands of rows, use Queueable or Batch Apex instead. Many teams treat @future as legacy for new code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which parameter type is allowed in a @future method?

    Future methods accept only primitives, arrays of primitives and collections of primitives, such as Set<Id>.
  2. 2. Why must callouts from a trigger run asynchronously?

    Callouts after uncommitted work in the same transaction are not allowed; the future method runs in its own transaction with callout=true.
  3. 3. How many future calls can one transaction make?

    The limit is 50 future method calls per Apex invocation, so batch the work instead of calling per record.
  4. 4. What does a future method return to its caller?

    Future methods must return void, so there is nothing to monitor; Queueable returns a job Id.

Summary

  • Async Apex runs work later in its own transaction with larger limits.
  • @future methods are static, void, take only primitives, and max 50 per transaction.
  • Pass Ids and re-query; add callout=true for HTTP.
  • Prefer Queueable for new work that needs objects, chaining or a job Id.

Next: Queueable Apex