Sub topic 8
Passing Ids and re-querying in async code
This chapter covers what to pass from a trigger into asynchronous Apex, and why record Ids are almost always the right choice. It assumes you can write an Apex trigger, know what Trigger.new and Trigger.newMap contain, and know the difference between a primitive and an sObject. It also assumes you have seen @future and Queueable classes at least once.
The problem: async code runs later
An asynchronous job does not run inside the trigger transaction. It is placed on a queue and runs after the transaction commits, sometimes seconds later and sometimes minutes later under load. During that gap, the data can change in several ways:
- A user edits the record.
- A workflow, flow, or another trigger updates the record.
- An integration changes the record.
- A different async job processes the same record first.
Whatever you copied out of the trigger is a snapshot of the record at the moment the trigger ran. If you carry that snapshot into the async job, you will send old values to the external service. This is the stale data problem.
The second problem is that the snapshot may be incomplete. Fields that a trigger did not touch or select are not available on the object, and reading one throws a System.SObjectException ("SObject row was retrieved via SOQL without querying the requested field"). Fields calculated by the platform during the save, such as formula fields and system fields like LastModifiedDate, can also be missing or wrong in Trigger.new for before triggers.
Rules for each async mechanism
The two mechanisms have different restrictions on what you can pass.
| Mechanism | What you can pass | Notes |
|---|---|---|
| `@future` method | Primitives, and collections of primitives | sObjects and custom Apex types are not allowed as parameters |
| Queueable class | Any serializable member variable, including sObjects and custom types | Allowed, but the data is still a snapshot |
| Batch Apex | Constructor arguments, or a query locator | The query runs when the job starts, so it reads current data |
A future method refuses sObjects for exactly the reason above. The platform cannot guarantee that the object you pass will still match the database when the method runs. A Queueable lets you store sObjects in member variables, so the language will not stop you from making the mistake. That is why the habit matters more there.
The pattern: pass Ids, query fresh
The pattern has three steps:
- In the trigger, collect the Ids of the records that need work.
- Pass the
Set<Id>to the async code. - In the async code, run a SOQL query filtered by those Ids and select exactly the fields you need.
The trigger from this tutorial follows it:
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}Trigger.newMap is available in after insert triggers, and keySet() returns a Set<Id>. The trigger holds no field values at all. The job then re-queries:
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new AccountSyncFinalizer());
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}
}
}The query WHERE Id IN :accountIds runs when execute runs, not when the trigger ran. It returns whatever the database holds at that moment. It also selects only Id and Name, so the payload contains no accidental fields.
The same rule applies to a future method. Its signature forces the pattern, because only primitives and collections of primitives are accepted:
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());
}
}A future method must be static and return void. Set<Id> is accepted because Id is a primitive type.
What the timeline looks like
The diagram shows where the snapshot goes stale and where the fresh query happens.
If the job had carried the original Account objects, the payload would hold the name from the insert. Because it carries Ids, the payload holds the name after the edit.
Edge cases
Records deleted before the job runs
The query returns only records that still exist. If a record was deleted, it is missing from the result, and your code should not assume the result size equals the Id set size. Loop over the query result, not over the Id set.
If you need to include deleted records, add ALL ROWS to the query. Be deliberate about this. Most integrations should skip deleted records or send a separate delete message.
Records that no longer qualify
Sometimes the trigger enqueues work because of a condition, such as a status changing to Approved. By the time the job runs, the condition may be false again. Add the condition to the query's WHERE clause, so the job acts on the current truth:
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Id IN :accountIds AND Rating = 'Hot'
];Sharing and field-level security
Async code runs in system context by default. A class declared with sharing still enforces record sharing for the user who enqueued the job, but field-level security is not enforced unless you ask for it. If the payload leaves the org, decide explicitly whether to use WITH USER_MODE or WITH SECURITY_ENFORCED, and test the outcome.
Extra queries cost limits
Re-querying costs one SOQL query per job. This is cheap compared with the cost of sending wrong data. The query count belongs to the async transaction, which has its own limits (100 synchronous SOQL queries in the future and Queueable context is the same as the synchronous limit of 100, and 200 for Batch Apex execute is also 200). Check the current limits in the Salesforce documentation, because they differ by release and context.
Passing the Ids of a large set
A single trigger transaction can contain up to 200 records per chunk, so a Set<Id> is small. A data load with many chunks fires the trigger many times, each enqueuing its own job. That is a bulkification concern and is covered in the next chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unsupported parameter type` when saving a future method | The parameter is an sObject or a custom class | Change the parameter to `Set<Id>` or `List<Id>` and re-query |
| `SObject row was retrieved via SOQL without querying the requested field` | The job reads a field that its own query did not select | Add the field to the `SELECT` list |
| The external system shows old values | The Queueable stored sObjects from `Trigger.new` | Store Ids and query in `execute` |
| The job sends fewer records than expected | Records were deleted or no longer match the `WHERE` filter | Expect the result to be smaller than the Id set, and handle an empty list |
| `List has no rows for assignment to SObject` | The job used `[SELECT ...][0]` or a single-row assignment | Assign to a `List` and check `isEmpty()` |
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
if (accounts.isEmpty()) {
return;
}Summary of the habit
- The trigger decides which records need work and passes their Ids.
- The async code decides what the data looks like by querying it.
- The query selects only the fields the payload needs.
- The code handles a result smaller than the Id set.
Exercise
A teammate writes a Queueable whose constructor takes a List<Account> (passed as Trigger.new) and builds the callout payload directly from it in execute. Name two problems with this and describe the fix.
Show answer
First, the accounts are a snapshot from the trigger, so if a user or automation changes a record before the job runs, the payload contains stale values. Second, fields not present on the trigger records throw an SObjectException when read, and values that the platform calculates during the save may be missing. The fix is to pass a Set<Id> from the trigger (for example Trigger.newMap.keySet()), store it in the Queueable, and run SELECT Id, Name FROM Account WHERE Id IN :accountIds inside execute. The query should also handle an empty result.
Exercise
A future method declared as @future(callout=true) public static void sync(List<Account> accounts) fails to save. Why, and how would you rewrite the signature and first line of the body?
Show answer
Future methods accept only primitives and collections of primitives as parameters, so List<Account> is rejected. Change the signature to public static void sync(Set<Id> accountIds) and start the body with List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];.