Sub topic 14
Monitoring Async Jobs
This chapter assumes you have built the trigger, Queueable and Finalizer from the earlier chapters. It also assumes you can run SOQL in Anonymous Apex and know where Setup is. Once the callout runs outside the trigger, it fails somewhere the user can't see. Monitoring lets you find those failures.
Why async work needs monitoring
When the trigger calls System.enqueueJob, the user's save finishes immediately. The callout runs later, in its own transaction. If the callout fails, nobody sees an error on the record page. The failure appears only in job records, debug logs and anything your own code writes.
You need to answer three questions:
- Did the job run?
- Did it finish, fail or get aborted?
- If it failed, why?
The AsyncApexJob object
Salesforce records every async Apex execution as a row in AsyncApexJob. You can query it with SOQL. These fields matter most for callout jobs:
| Field | What it tells you |
|---|---|
| `Id` | The job Id. `System.enqueueJob` returns this value. |
| `JobType` | `Future`, `Queueable`, `BatchApex`, `BatchApexWorker`, `ScheduledApex` and others. |
| `Status` | `Queued`, `Preparing`, `Processing`, `Holding`, `Completed`, `Failed` or `Aborted`. |
| `ApexClass.Name` | The class that ran. For future methods this is the class that holds the method. |
| `MethodName` | The method name. It is set for future jobs. |
| `NumberOfErrors` | For batch jobs, the number of failed batches. |
| `JobItemsProcessed`, `TotalJobItems` | Progress for batch jobs. |
| `ExtendedStatus` | The error message when a job fails. |
| `CreatedDate`, `CompletedDate` | Timing. |
A future method returns void, so you never receive its job Id. You can still find it by querying JobType = 'Future' and filtering on MethodName.
Job lifecycle
A Queueable moves through a short set of states. Batch jobs add Preparing and can also wait in Holding if the Apex Flex Queue is in use.
Completed, Failed and Aborted are final states. A job in one of them never runs again.
Capturing the job Id when you enqueue
The trigger from earlier chapters ignores the return value of System.enqueueJob. Keeping it lets you correlate a record with its job. This example uses Anonymous Apex so you can try it directly:
Set<Id> ids = new Map<Id, Account>([SELECT Id FROM Account LIMIT 5]).keySet();
Id jobId = System.enqueueJob(new AccountSyncJob(ids));
System.debug('Enqueued job: ' + jobId);
AsyncApexJob job = [
SELECT Id, Status, JobType, ExtendedStatus, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug(job.Status + ' / ' + job.JobType);The status you print right after enqueueing is usually Queued. The job cannot start until the current transaction ends. Run the second query again a few seconds later to see Completed.
If you need the Id elsewhere, store it on a custom field or in a log record. Do this only if you have a real use for it, because it adds a DML statement to the trigger transaction.
Querying job history
For day-to-day checks, query by status and date. This query lists failures and aborts from the last day:
List<AsyncApexJob> problems = [
SELECT Id, JobType, Status, ApexClass.Name, MethodName,
ExtendedStatus, NumberOfErrors, CreatedDate, CompletedDate
FROM AsyncApexJob
WHERE Status IN ('Failed', 'Aborted')
AND CreatedDate = LAST_N_DAYS:1
ORDER BY CreatedDate DESC
LIMIT 100
];
for (AsyncApexJob j : problems) {
System.debug(j.ApexClass.Name + '.' + j.MethodName + ' ' + j.Status + ': ' + j.ExtendedStatus);
}To check the callout backlog, count the jobs that have not started:
Integer waiting = [
SELECT COUNT() FROM AsyncApexJob
WHERE ApexClass.Name = 'AccountSyncJob' AND Status IN ('Queued', 'Holding')
];
System.debug('Waiting jobs: ' + waiting);A backlog that keeps growing means your triggers enqueue work faster than the org runs it. That is a signal to batch more records per job, as covered in the bulk-safe chapter.
Monitoring in Setup
You can also watch jobs without code:
- Open Setup and search for Apex Jobs.
- Filter by status, or sort by submitted date.
- Read the Status Details column for the error message of a failed job.
The Apex Jobs page shows the same rows as AsyncApexJob. Batch jobs also show a progress count. The Apex Flex Queue page lists batch jobs in Holding and lets you reorder them. Queueable and future jobs never enter the Flex Queue.
For a deeper look, use debug logs. Add a trace flag for the user the job runs as, which is the user who enqueued it. The log for the async transaction then shows each callout, its timing and any exception.
Limits that affect monitoring
Know these numbers when you read job data. They are the current documented values, but check the Apex Developer Guide for your release.
- A single transaction can enqueue up to 50 Queueable jobs. A Queueable running in the async context can enqueue only 1 child job.
- A single transaction can call up to 50 future methods.
- The org-wide cap is 250,000 async Apex executions per 24 hours, or the number of user licenses multiplied by 200, whichever is greater. Batch Apex counts per batch, not per job.
- Up to 5 batch jobs run at the same time. The Flex Queue holds up to 100 more.
You can check your position inside a transaction:
System.debug(Limits.getQueueableJobs() + ' of ' + Limits.getLimitQueueableJobs() + ' Queueable jobs used');
System.debug(Limits.getFutureCalls() + ' of ' + Limits.getLimitFutureCalls() + ' future calls used');If a trigger exceeds the cap, the platform throws a LimitException in the trigger transaction. That exception rolls back the user's save. This is the only async failure that surfaces to the user.
Linking Finalizers to jobs
A Finalizer receives a FinalizerContext that carries the Id of the job it was attached to. Logging that Id lets you join your own log lines to the AsyncApexJob row:
public class AccountSyncFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
Id jobId = ctx.getAsyncApexJobId();
ParentJobResult result = ctx.getResult();
if (result == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
'Job ' + jobId + ' failed: ' + ctx.getException().getMessage());
} else {
System.debug('Job ' + jobId + ' finished with ' + result);
}
}
}In production, replace System.debug with a write to a custom log object or a Platform Event. Debug logs expire and are not searchable across users.
What the status does not tell you
A Completed status means the Apex code finished without an unhandled exception. It does not mean the external system accepted your data. Look at the earlier AccountSyncJob code. When the server answers with HTTP 500, Http.send returns normally. The job completes, and your code only writes a debug line.
The table shows which problems change the job status:
| Situation | Job status | How you find it |
|---|---|---|
| Unhandled `CalloutException`, such as a timeout | `Failed` | `AsyncApexJob.ExtendedStatus`, Finalizer |
| HTTP 4xx or 5xx response, not handled | `Completed` | Only your own logging |
| HTTP 4xx or 5xx, code throws a custom exception | `Failed` | `ExtendedStatus`, Finalizer |
| Job cancelled with `System.abortJob` | `Aborted` | `AsyncApexJob` |
To make HTTP errors visible to monitoring, throw an exception when the status code is outside the 2xx range. The job then ends as Failed, and the Finalizer runs with UNHANDLED_EXCEPTION. Whether this is right depends on your retry plan. Exceptions give you a clear failure signal, and an explicit error log lets the job finish cleanly.
Aborting a job
You can cancel a job that has not finished:
System.abortJob(jobId);Aborting a Queued job removes it from the queue. Aborting a running job stops it at a safe point. It does not undo callouts that already left Salesforce.
Common mistakes
- Querying
AsyncApexJobfor a future method by Id. You do not get an Id, so filter byJobTypeandMethodName. - Reading
Statusin the same transaction that enqueued the job. The job has not started yet, so you will seeQueued. - Treating
NumberOfErrorsas a measure for Queueable jobs. It is meaningful for batch jobs. - Assuming old rows stay forever. Salesforce removes completed job records after a limited period, so store your own log entries if you need long history.
Exercise
Your Queueable sends accounts to an external API. The API returns HTTP 503, but Setup > Apex Jobs shows the job as Completed. Why, and what two changes would make this failure visible in the job record and in your Finalizer?
Show answer
Http.send returns the 503 response normally, so no exception is thrown and the job ends as Completed. To make the failure visible, check the status code and throw an exception when it is outside 200-299, for example throw new CalloutException('Sync failed: ' + res.getStatusCode());. The job then ends as Failed with the message in ExtendedStatus. Attach a Finalizer with System.attachFinalizer that checks for ParentJobResult.UNHANDLED_EXCEPTION and logs ctx.getAsyncApexJobId() with the exception message.
Exercise
Write a SOQL query that returns the Id, status and error message of all failed Queueable jobs for the class AccountSyncJob created in the last 7 days.
Show answer
SELECT Id, Status, ExtendedStatus FROM AsyncApexJob WHERE JobType = 'Queueable' AND ApexClass.Name = 'AccountSyncJob' AND Status = 'Failed' AND CreatedDate = LASTNDAYS:7