Sub topic 11
When retries run out
What this chapter assumes
You should already have the bounded RetryableCallout Queueable from the previous chapter. It retries transient failures with a doubling delay and stops after four attempts. You should also know basic DML, SOQL, and custom objects. This chapter covers what happens after the last attempt fails.
In the earlier version, exhaustion ends with a System.debug call. Debug logs are short-lived and only exist if someone enabled tracing before the failure. A failed order sync then disappears with no record that it ever happened. The goal here is to save every permanently failed callout, so someone can review it and replay it.
Three ways a callout ends without success
A callout job can give up for three different reasons, and each needs its own hook.
| Ending | Where it is detected | How to record it |
|---|---|---|
| Non-retryable response (400, 401, 404, 422) | In `execute`, after the status check | Log immediately, do not retry |
| Retries exhausted (timeout or retryable status on the last attempt) | In `execute`, in the retry method | Log with the last error |
| Unhandled exception (a limit exception, a null pointer, a failed enqueue) | Outside your code paths | A transaction finalizer |
The first two are normal control flow, so you can handle them with ordinary code. The third is the dangerous one. An unhandled exception ends the job before your logging line runs, and try/catch cannot catch limit exceptions at all. A finalizer is the tool for that case.
A record for failed callouts
Store failures in a custom object. This chapter assumes an object named Failed_Callout__c with these fields.
| Field | Type | Purpose |
|---|---|---|
| `Endpoint__c` | Text(255) | Named credential path that was called |
| `Payload__c` | Long Text Area | The request body, needed to replay |
| `Status_Code__c` | Number(3,0) | Last HTTP status, empty for timeouts |
| `Error_Message__c` | Long Text Area | Last error text or response body |
| `Attempts__c` | Number(2,0) | How many attempts were made |
| `Status__c` | Picklist | New, Replayed, Resolved |
The logger below is one small class that every exit point calls.
public with sharing class FailedCalloutLogger {
public static void log(String endpoint, String payload,
Integer statusCode, String message, Integer attempts) {
Failed_Callout__c rec = new Failed_Callout__c(
Endpoint__c = endpoint,
Payload__c = payload,
Status_Code__c = statusCode,
Error_Message__c = message == null ? null : message.abbreviate(32000),
Attempts__c = attempts,
Status__c = 'New'
);
Database.SaveResult sr = Database.insert(rec, false);
if (!sr.isSuccess()) {
System.debug(LoggingLevel.ERROR,
'Could not store failed callout: ' + sr.getErrors()[0].getMessage());
}
}
}Database.insert(rec, false) returns a result instead of throwing. A failure in the failure handler should not hide the original problem. Truncating the message matters because an error body from a remote service can be larger than the field.
Logging at each exit point
Here is the full job. It reuses the retry rules from the earlier chapters and now calls the logger when it stops. It also attaches a finalizer first, so the unhandled-exception case is covered.
public class RetryableCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
private static final String ENDPOINT = 'callout:Orders_API/orders';
private final String payload;
private final Integer attempt;
public RetryableCallout(String payload, Integer attempt) {
this.payload = payload;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
System.attach(new CalloutFinalizer(ENDPOINT, payload, attempt));
HttpRequest req = new HttpRequest();
req.setEndpoint(ENDPOINT);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(payload);
req.setTimeout(30000);
Integer code = null;
String reason = null;
try {
HttpResponse res = new Http().send(req);
code = res.getStatusCode();
if (code >= 200 && code < 300) {
return;
}
reason = 'HTTP ' + code + ': ' + res.getBody();
Boolean retryable = code == 408 || code == 429
|| (code >= 500 && code <= 599);
if (!retryable) {
FailedCalloutLogger.log(ENDPOINT, payload, code, reason, attempt);
return;
}
} catch (System.CalloutException e) {
reason = 'CalloutException: ' + e.getMessage();
}
if (attempt >= MAX_ATTEMPTS) {
FailedCalloutLogger.log(ENDPOINT, payload, code, reason, attempt);
return;
}
Integer delayMinutes = Math.min(10, (Integer) Math.pow(2, attempt - 1));
System.enqueueJob(new RetryableCallout(payload, attempt + 1), delayMinutes);
}
}The job logs only after the last attempt, not after every failure. If it logged every attempt, one flaky order would create four records and reviewers could not tell which one still needs attention.
Catching unhandled exceptions with a finalizer
A transaction finalizer is a class that implements Finalizer. You attach it from inside a Queueable with System.attach. The platform runs it after the job ends, whether the job succeeded or failed. That includes failures that try/catch cannot intercept, such as an uncatchable limit exception.
public class CalloutFinalizer implements Finalizer {
private final String endpoint;
private final String payload;
private final Integer attempt;
public CalloutFinalizer(String endpoint, String payload, Integer attempt) {
this.endpoint = endpoint;
this.payload = payload;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
Exception ex = ctx.getException();
FailedCalloutLogger.log(endpoint, payload, null,
'Unhandled exception: ' + (ex == null ? 'unknown' : ex.getMessage()),
attempt);
}
}
}The finalizer does nothing when the result is SUCCESS. The handled exit paths already log, so only UNHANDLED_EXCEPTION needs a record here. If the finalizer logged on every run, a normal success would look like a failure.
Replaying failed callouts
A stored record is useful only if someone can act on it. Replay means taking a record in the New state and sending its payload again. Replay is a human decision, because the cause matters.
- A timeout or 503 is usually safe to replay once the remote system is healthy again.
- A 400 or 422 will fail again unchanged. Fix the data or the mapping first.
- A 401 points to a credential problem. Fix the named credential, then replay.
public with sharing class FailedCalloutReplay {
public static Integer replay(Integer maxRecords) {
Integer cap = Math.min(maxRecords, 50);
List<Failed_Callout__c> rows = [
SELECT Id, Payload__c
FROM Failed_Callout__c
WHERE Status__c = 'New'
ORDER BY CreatedDate
LIMIT :cap
];
for (Failed_Callout__c rec : rows) {
System.enqueueJob(new RetryableCallout(rec.Payload__c, 1));
rec.Status__c = 'Replayed';
}
update rows;
return rows.size();
}
}The cap of 50 matches the limit on System.enqueueJob calls in one synchronous transaction. The replay restarts at attempt 1, so the job gets a full set of retries again. If the replay fails too, the job writes a new New record, and the old one stays Replayed as history.
Replay only works safely if the earlier chapter's idempotency rule holds. The first attempt may have reached the remote system before the timeout fired, so the payload should contain the same idempotency key every time. Generate the key before the first enqueue and store it in the payload. Then a replay of an order that actually succeeded is rejected or ignored by the remote API, and it creates no duplicate.
Edge cases and decisions
- Sensitive data.
Payload__cholds a copy of the request body. If it contains personal or financial data, limit access with field-level security, or store a record reference instead of the full body and rebuild the payload on replay. - Sharing.
with sharingmeans the logger and replay respect the running user's access. A Queueable running for a user without create access onFailed_Callout__ccannot write the record. Grant the permission through a permission set, or move logging into a class that runs in system mode if your security review accepts it. - Alerting. A record nobody looks at is the same as no record. Add a list view or report of
Newrecords, and consider a scheduled job that emails a count when it is above zero. - Volume. A long outage can create thousands of records. Add a cleanup job that deletes
Resolvedrecords after a retention period. - Double logging. If the job enqueues a retry and then throws, the finalizer logs a failure while the child job may still succeed. Keep the enqueue as the last statement of
execute, as the code above does.
Putting it together
Exhaustion handling has three parts. The job records its own deliberate exits, a finalizer records the accidental ones, and a replay method turns stored records back into jobs. With these in place, a callout that still fails after every retry leaves a record with its payload, its last error, and its attempt count.
Exercise
A Queueable callout job hits a 422 response on its first attempt. The code returns without retrying, and nothing is logged. A finalizer is attached that logs only on UNHANDLED_EXCEPTION. What goes wrong, and what is the fix?
Show answer
The job ended normally, so the finalizer sees a SUCCESS result and logs nothing. The failure is lost, and nobody knows the order was never sent. The fix is to call FailedCalloutLogger.log in the non-retryable branch before returning, as the RetryableCallout class above does. A non-retryable status is a handled exit, so the job's own code must record it.
Exercise
A support user selects 200 failed records and your replay method tries to replay them all from one button click. What happens, and how do you handle it?
Show answer
A synchronous transaction can call System.enqueueJob at most 50 times, so the 51st call throws a limit exception and the update never runs. Cap each run at 50, as the replay method does with Math.min(maxRecords, 50), and have the user run it again for the next batch. For larger volumes, use Batch Apex or a Queueable that replays a slice and chains itself.