Sub topic 8
Passing Ids and re-querying in async code
This chapter assumes you can write an Apex trigger, know what Trigger.new and Trigger.newMap hold, and have seen a basic Queueable class. It covers what to hand to the asynchronous job and why.
Pass Ids, not records
When a trigger enqueues a job, the job does not run immediately. It runs later in its own transaction, so the data you passed in may have changed by then. Another trigger, a flow, or a user may have edited the record. A record passed from Trigger.new is a snapshot of how it looked when the trigger fired.
The safer pattern has two steps:
- The trigger passes only the record Ids.
- The async code queries the records again and works with current values.
Why re-query
- Fresh values. The query returns what is committed now, not what the trigger saw.
- More fields.
Trigger.newonly contains fields on the record. A query can also read formula fields, parent fields such asOwner.Name, and fields set by other automation. - Deleted records. If a record was deleted before the job ran, the query simply returns fewer rows. Passing a stale sObject would send data for a record that no longer exists.
- Fresh limits. The query runs in the async transaction, so it uses that transaction's own SOQL limits, not the trigger's.
Future methods require it
A @future method must be static, return void, and accept only primitives or collections of primitives. You cannot pass an Account, but you can pass a Set<Id>.
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];
if (accounts.isEmpty()) {
return;
}
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 isEmpty() guard handles the case where every record was deleted before the job ran.
Queueable classes allow more, but Ids are still better
A Queueable can store sObjects in member variables, so the language does not force you to pass Ids. The same staleness problem applies, though. Store a Set<Id> in the constructor and query inside execute:
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
// build the request from accounts and send it
}
}Ids are also small. A job that carries thousands of full records makes the serialized job larger and slower to queue.
Common mistakes
- Using a before trigger. In
before insert, records have no Ids yet. Enqueue from anaftertrigger. - Passing
Trigger.newto a future method. This fails to compile, because sObject lists are not allowed as parameters. - Querying inside a loop. Use one query with
IN :accountIdsfor the whole batch. - Assuming the data matches the trigger event. Fields may differ from what the trigger saw. If the job needs a specific old value, pass that value explicitly in a primitive-friendly structure, such as a
Map<Id, String>.
Exercise
A Queueable job receives a List<Account> taken from Trigger.new and sends it to an external service. Between the trigger and the job, a flow changes the account's Name. What does the service receive, and how do you fix it?
Show answer
The service receives the old Name, because the list is a snapshot from when the job was enqueued. Pass a Set<Id> to the constructor and query the accounts at the start of execute, so the job sends the committed Name.