Sub topic 12
Monitoring Future Jobs in Setup
This chapter assumes you can write and call a @future method, and that you know the governor limits covered in earlier chapters. It covers how to see what your future methods did after the calling transaction ended. You can use the Apex Jobs page, the AsyncApexJob object, debug logs, and the daily async limit counter.
Why monitoring needs its own step
A future method runs in a separate transaction after your code returns. The user who clicked Save never sees an exception from it. A future method that fails produces no error on the page and no rollback of the original save.
Monitoring answers three questions:
- Did the job run?
- Did it succeed?
- If it failed, why?
The @future call also returns void, so your code gets no job ID back. You find the job afterward by class name, method name, and time.
The Apex Jobs page
Future methods appear on the same page as Batch and Queueable jobs.
- Open Setup.
- Enter "Apex Jobs" in Quick Find.
- Select Apex Jobs (under Environments, then Jobs, in Lightning Experience).
Each future invocation is one row. The columns that matter most:
| Column | What it tells you |
|---|---|
| Submitted Date | When the calling code queued the job |
| Job Type | `Future Method` for `@future` jobs |
| Status | Queued, Processing, Completed, or Failed |
| Status Detail | The exception message when a job fails |
| Apex Class | The class that contains the future method |
| Method Name | The future method that was invoked |
| Submitted By | The user whose transaction queued the job |
| Start Time, Completion Time, Elapsed Time | When it ran and how long it took |
Use the Job Type filter (or sort by it) to hide Batch and Queueable rows when you only care about future methods.
What the statuses mean
The status field follows a short lifecycle.
A job is queued only when the calling transaction commits. If the caller rolls back, the queued future call is discarded and you will never see a row for it. When a row is missing, check whether the calling transaction failed.
A job can stay in Queued for a while on a busy org. This is normal. Salesforce gives no guarantee about when a future method starts or in what order it runs, as described in the earlier chapter on execution behavior.
Reading a failure
For a failed job, open the Status Detail text. It holds the unhandled exception, such as:
System.QueryException: List has no rows for assignment to SObjectThat message is the first thing to read, but it does not tell you which record or input caused the failure. Because the calling code is gone, you often need the future method's arguments to reproduce the problem. Section "Logging inside the method" below covers this.
A failed future method does not retry. The platform runs it once, and a failure is final. If you need a retry, you must write it, for example by catching the error and calling a Queueable job.
Querying AsyncApexJob
The Apex Jobs page is a view of the AsyncApexJob object. You can query it in the Developer Console, in the VS Code query editor, or in Apex. Querying works well when you want to search, count, or build your own report.
List<AsyncApexJob> jobs = [
SELECT Id, ApexClass.Name, MethodName, Status, ExtendedStatus,
NumberOfErrors, CreatedDate, CompletedDate, CreatedBy.Name
FROM AsyncApexJob
WHERE JobType = 'Future'
ORDER BY CreatedDate DESC
LIMIT 20
];
for (AsyncApexJob j : jobs) {
System.debug(
j.ApexClass.Name + '.' + j.MethodName + ' ' + j.Status +
' at ' + j.CreatedDate + ' ' + (j.ExtendedStatus == null ? '' : j.ExtendedStatus)
);
}Run this as anonymous Apex and read the output in the debug log. Key fields:
JobTypeis'Future'for future methods. Other values include'BatchApex'and'Queueable'.Statusholds the lifecycle value.ExtendedStatusholds the error text for failed jobs. It matches the Status Detail column.MethodNameandApexClass.Nameidentify the code that ran.NumberOfErrorsis a count of failures.
Salesforce keeps AsyncApexJob records for a limited time after completion (about seven days). If you need a long history, copy the failures somewhere permanent. Do not depend on this object as an audit trail.
Finding failures only
To find just the failed jobs from the last day:
Datetime since = Datetime.now().addDays(-1);
List<AsyncApexJob> failed = [
SELECT ApexClass.Name, MethodName, ExtendedStatus, CreatedDate, CreatedBy.Name
FROM AsyncApexJob
WHERE JobType = 'Future'
AND Status = 'Failed'
AND CreatedDate >= :since
ORDER BY CreatedDate DESC
];
System.debug('Failed future jobs in the last 24 hours: ' + failed.size());A scheduled Apex class or a report on a custom log object can run this query and send an alert. That is more reliable than waiting for someone to open Setup.
Debug logs for future methods
The Apex Jobs page tells you that a job failed. A debug log tells you what happened inside it.
Each future method runs in its own transaction, so it produces its own debug log. That log is separate from the log of the transaction that queued it. To capture it:
- Open Setup and go to Debug Logs.
- Add a trace flag for the user that runs the job. That is the value in Submitted By.
- Reproduce the action that queues the future method.
- Open the new log and look for the future method's entry point.
Two details trip people up:
- The trace flag must exist before the job runs. Logs are not created after the fact.
- The user in the trace flag is the user whose transaction queued the job, not a system user.
When you search the log list, look for a second log entry that appears shortly after the one from the user's action. The Operation column and the log contents help you tell them apart.
Logging inside the method
The most useful monitoring comes from the method itself. Catch the exception, record the inputs, then rethrow so the job still shows as Failed.
public class AccountRatingService {
@future
public static void updateRatings(Set<Id> accountIds) {
try {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
} catch (Exception e) {
System.debug(LoggingLevel.ERROR,
'updateRatings failed for ' + accountIds.size() + ' ids: ' + e.getMessage());
throw e;
}
}
}The throw e; is deliberate. If you swallow the exception, the job finishes as Completed and the Apex Jobs page reports success while the work did not happen. Rethrowing keeps the Failed status honest.
In production, System.debug is only useful when a trace flag is active. For permanent records, insert a row into a custom log object, or publish a platform event. A log insert inside the catch block runs in the same transaction that failed. If an unhandled exception ends that transaction, the insert rolls back with it. Publishing a platform event configured to publish immediately avoids that problem.
Watching the daily limit
Monitoring is also about capacity. Future methods share a daily asynchronous Apex limit with Batch, Queueable, and scheduled Apex. Salesforce counts the executions over a rolling 24 hours, and the limit depends on your org's licenses (the greater of 250,000 or 200 times the number of user licenses).
You can read the per-transaction counters in Apex:
System.debug('Future calls used: ' + Limits.getFutureCalls()
+ ' of ' + Limits.getLimitFutureCalls());The per-transaction ceiling is 50 future calls. For the org-wide daily count, call the REST Limits resource (/services/data/vXX.X/limits) and read DailyAsyncApexExecutions. It reports the maximum and the remaining count. A trigger that makes one future call per record can use up the daily budget quickly, and the Apex Jobs page will show a long list of near-identical rows. A high volume of rows from one class and method is a sign that you should batch the IDs into fewer calls.
A quick triage routine
When a user says "the field never updated":
- Open Apex Jobs and sort by Submitted Date. Find a row for the right class and method near the time of the action.
- No row: the caller either never reached the
@futurecall, or its transaction rolled back. Check the guard conditions and the caller's debug log. - Status Queued: the job has not started. Wait, then check again.
- Status Failed: read Status Detail, then reproduce with a trace flag.
- Status Completed but data is wrong: the logic is at fault, not the platform. Check how the method re-queries its records, and whether another process overwrote the result.
Common mistakes
- Expecting a job ID from the call. Future methods return
void, so you must query by class and method. - Swallowing exceptions in a
catchblock, which makes failed work look Completed. - Setting a trace flag after the job has already run.
- Treating
AsyncApexJobas permanent storage. - Testing for
AsyncApexJobrows in unit tests. The test framework runs future methods atTest.stopTest(), and you should assert on the data they changed instead.
Exercise
A user reports that an account's Rating did not change after saving. The Apex Jobs page shows no row for AccountRatingService.updateRatings near that time. Name two likely causes and what you would check first.
Show answer
Either the calling code never reached the @future call (for example a guard such as System.isFuture() or System.isBatch() skipped it), or the calling transaction rolled back, which discards queued future calls. Check the caller's debug log for the save: look for an exception or rollback, and confirm the guard conditions allowed the call.
Exercise
Write a SOQL query that returns failed future method jobs, with the class name, method name, and error text, newest first.
Show answer
SELECT ApexClass.Name, MethodName, ExtendedStatus, CreatedDate FROM AsyncApexJob WHERE JobType = 'Future' AND Status = 'Failed' ORDER BY CreatedDate DESC