Sub topic 4
Passing record IDs and re-querying data
This chapter assumes you can write Apex classes with static methods and collections, run SOQL queries and DML, and have already declared a basic @future method. It covers why future methods take IDs instead of records, how to re-query safely, and the mistakes that follow from skipping that step.
The rule: primitives and collections of primitives only
A future method can accept only primitive data types, arrays of primitives, or collections of primitives. It cannot accept sObjects or user-defined objects. The compiler rejects a signature such as List<Account> or a custom wrapper class.
| Parameter type | Allowed in a future method |
|---|---|
| `Id`, `String`, `Integer`, `Decimal`, `Boolean`, `Date`, `Datetime` | Yes |
| `Set<Id>`, `List<String>`, `Map<Id, String>` | Yes |
| `Account`, `List<Contact>`, `Map<Id, Account>` | No |
| A custom Apex class instance | No |
The method must also be static and return void.
There is a reason for this rule. A future method does not run when you call it. The platform serializes the arguments, stores them in a queue, and runs the method later in its own transaction. Primitives serialize without ambiguity. An sObject would be a snapshot of field values at the moment of the call, and that snapshot might be old by the time the method runs.
Why the snapshot problem matters
Time passes between the call and the execution. The delay is usually short, but it has no guaranteed upper bound. During that gap:
- A user can edit the record.
- A workflow, flow, or another trigger can change field values.
- A different future method or batch job can update the same record.
- The record can be deleted.
If you could pass an Account object, your code would work on field values from the past and could overwrite newer changes with them. Passing only the ID forces the method to fetch the current record, so it works with what the database holds when it runs.
The standard pattern
The pattern has four steps: take a collection of IDs, query the records, apply the logic, and perform DML only on records that need a change.
public class AccountRatingService {
@future
public static void applyRatings(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id, Rating, AnnualRevenue
FROM Account
WHERE Id IN :accountIds
];
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
Boolean unrated = a.Rating == null;
Boolean large = a.AnnualRevenue != null && a.AnnualRevenue > 1000000;
if (unrated && large) {
a.Rating = 'Hot';
toUpdate.add(a);
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}Several details in this example are deliberate.
- Re-querying returns current values. The
Rating == nullcheck runs against the data as it is now. If someone already set a rating, the method leaves it alone. - The method does not assume every ID still exists. If a record was deleted, the query returns fewer rows than
accountIdshas entries. The loop simply never sees the missing record. A method that assumed a one-to-one match would fail. - It updates only what changed. Updating unchanged records wastes DML rows and can fire triggers and automation again for no reason.
- It guards the empty case. Calling
updateon an empty list is legal, but the explicit check makes the intent clear.
You can try it from Anonymous Apex:
Account a = new Account(Name = 'Big Co', AnnualRevenue = 5000000);
insert a;
AccountRatingService.applyRatings(new Set<Id>{ a.Id });The future method runs after the anonymous block finishes. Query the account a few seconds later to see the rating.
Passing extra values along with the IDs
Sometimes the method needs a value that is not stored on the record, such as a reason code, a target status, or a user-chosen option. Pass it as a separate primitive parameter.
public class CaseStatusService {
@future
public static void closeCases(Set<Id> caseIds, String closeReason) {
List<Case> cases = [
SELECT Id, Status, Description
FROM Case
WHERE Id IN :caseIds AND IsClosed = false
];
for (Case c : cases) {
c.Status = 'Closed';
c.Description = (c.Description == null ? '' : c.Description + '\n')
+ 'Closed automatically: ' + closeReason;
}
update cases;
}
}The IsClosed = false filter in the query is a second form of re-checking. A case that was closed between the call and the execution is skipped, so the method does not append a duplicate note.
If each ID needs its own value, a Map<Id, String> is allowed:
public class OwnerNoteService {
@future
public static void addNotes(Map<Id, String> noteByAccountId) {
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :noteByAccountId.keySet()
];
for (Account a : accounts) {
a.Description = noteByAccountId.get(a.Id);
}
update accounts;
}
}Passing structured data as JSON
Occasionally you need to pass something that is not on a record yet and does not fit a simple collection, for example a list of values computed in the caller. A common workaround is to serialize the data to a String with JSON.serialize and parse it with JSON.deserialize in the future method.
public class PendingChangeService {
public class Change {
public Id accountId;
public String newPhone;
}
@future
public static void applyChanges(String changesJson) {
List<Change> changes = (List<Change>) JSON.deserialize(
changesJson, List<Change>.class
);
Map<Id, String> phoneById = new Map<Id, String>();
for (Change c : changes) {
phoneById.put(c.accountId, c.newPhone);
}
List<Account> accounts = [
SELECT Id, Phone FROM Account WHERE Id IN :phoneById.keySet()
];
for (Account a : accounts) {
a.Phone = phoneById.get(a.Id);
}
update accounts;
}
}Use this sparingly. Serializing whole sObjects to JSON brings the stale-data problem back, just hidden inside a string. A reasonable rule is to put only the new values you want to apply into the JSON, never the full record, and to re-query before you write. If you find yourself passing complex objects often, that is a signal to consider Queueable Apex, which accepts non-primitive member variables. The last chapter of this tutorial compares the options.
Common errors
- Declaring an sObject or list of sObjects as a parameter. This fails at compile time. Change the parameter to
Set<Id>orList<Id>. - Omitting
staticor returning a value. Future methods must be static and returnvoid. You cannot get a result back from the call. - Querying inside a loop in the caller, then passing IDs one at a time. Each call counts against the per-transaction limit on future calls. Collect IDs first and make one call.
- Assuming the query returns every ID you passed. Deleted, merged, or sharing-restricted records may be missing. Loop over the query results, not over the original ID set.
- Skipping re-validation of business conditions. Re-query the fields you depend on and check them again. The condition that was true at call time may no longer hold.
- Reading fields you did not select. Accessing a field that was not in the
SELECTlist throws aSObjectExceptionat run time. Select every field the logic reads. - Expecting the caller to see the result. After your trigger or class calls a future method, the in-memory records in the caller do not reflect what the future method will do. Reading those records again right away shows the old data, because the future method has not run.
Checking your understanding
Exercise
A teammate writes @future public static void sync(List<Contact> contacts) and gets a compile error. Rewrite the signature so it compiles, and explain what the method body must now do before it can read Email from each contact.
Show answer
Change the parameter to Set<Id> contactIds (or List<Id>). Inside the method, query the records with SELECT Id, Email FROM Contact WHERE Id IN :contactIds and loop over the query result. Future methods cannot take sObjects because the method runs later in a separate transaction, and a passed object would hold stale field values. Re-querying returns current data, and the loop over the query result also copes with any contacts that were deleted before the method ran.
Exercise
Your future method receives 10 account IDs, but its query returns only 8 rows. Name two likely causes and say how the method should behave.
Show answer
Two of the records were probably deleted or merged after the call and before the method ran. A second possible cause is that the running user in the future context cannot see them because of sharing or an added filter such as a status condition. The method should loop over the 8 returned records and not assume all 10 exist. It may log the missing IDs if that matters, but it should not throw an error just because the counts differ.