Sub topic 11
When retries run out
This chapter assumes you can write a Queueable job that makes a callout and re-enqueues itself with a delay, as in the previous chapter. It covers what to do after the last attempt fails.
Why exhaustion needs a plan
A bounded retry policy always ends. After the final attempt, the earlier RetryableCallout only wrote a System.debug line. Debug logs are not retained long and nobody reads them in production, so the failed request is lost.
A permanently failed callout is business data that did not reach another system. Treat it like any other record: store it, make it visible, and allow it to be replayed.
The flow after exhaustion looks like this:
Record the failure
Create a custom object, here called Callout_Failure__c. These fields are enough to diagnose and replay a request:
| Field | Type | Purpose |
|---|---|---|
| `Endpoint__c` | Text | Which integration failed |
| `Payload__c` | Long Text Area | The request body to replay |
| `Last_Status_Code__c` | Number | HTTP status, empty for a timeout |
| `Last_Error__c` | Long Text Area | Exception message or response body |
| `Attempts__c` | Number | How many tries were made |
| `Status__c` | Picklist | `New`, `Replayed`, `Abandoned` |
Be careful with Payload__c. If the body contains personal or sensitive data, restrict access to the object with permissions, or store a reference to the source record instead of the body.
Replace the System.debug call in retryLater with a method that saves the failure. Keep the last status code and message in the job so the record can say why it failed.
public class RetryableCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
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) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(payload);
req.setTimeout(30000);
Integer code = null;
String error;
try {
HttpResponse res = new Http().send(req);
code = res.getStatusCode();
if (code >= 200 && code < 300) {
return;
}
error = res.getBody();
if (!(code == 408 || code == 429 || (code >= 500 && code <= 599))) {
recordFailure(code, error); // permanent: do not retry
return;
}
} catch (System.CalloutException e) {
error = e.getMessage();
}
retryLater(code, error);
}
private void retryLater(Integer code, String error) {
if (attempt >= MAX_ATTEMPTS) {
recordFailure(code, error);
return;
}
Integer delayMinutes = Math.min(10, (Integer) Math.pow(2, attempt - 1));
System.enqueueJob(new RetryableCallout(payload, attempt + 1), delayMinutes);
}
private void recordFailure(Integer code, String error) {
insert new Callout_Failure__c(
Endpoint__c = 'Orders_API/orders',
Payload__c = payload,
Last_Status_Code__c = code,
Last_Error__c = error == null ? null : error.abbreviate(30000),
Attempts__c = attempt,
Status__c = 'New'
);
}
}Both exhaustion and a permanent failure such as a 400 end in recordFailure. A 400 will not succeed on repeat, so retrying it would waste attempts.
The abbreviate call keeps the text within a field limit you choose. Match the number to your field length, because an insert fails if the value is too long.
Catching crashes with a finalizer
recordFailure runs only when the code reaches it. If the job hits an unhandled exception or a governor limit, the insert never happens. A transaction finalizer runs after the job ends, whether it succeeded or failed, and can record the failure.
public class FailureFinalizer implements Finalizer {
private final String payload;
private final Integer attempt;
public FailureFinalizer(String payload, Integer attempt) {
this.payload = payload;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
insert new Callout_Failure__c(
Endpoint__c = 'Orders_API/orders',
Payload__c = payload,
Last_Error__c = String.valueOf(ctx.getException()),
Attempts__c = attempt,
Status__c = 'New'
);
}
}
}Attach it at the top of execute with System.attachFinalizer(new FailureFinalizer(payload, attempt));. A finalizer is attached once per job, and the job does not retry automatically when it crashes. So the finalizer's job is to record the loss, not to retry.
Replaying failures
Replay means creating a fresh job from a stored record. Start the attempt count over at 1 so the new job gets the full retry budget.
public with sharing class FailureReplayer {
public static void replay(List<Id> failureIds) {
List<Callout_Failure__c> failures = [
SELECT Id, Payload__c
FROM Callout_Failure__c
WHERE Id IN :failureIds AND Status__c = 'New'
];
for (Callout_Failure__c f : failures) {
System.enqueueJob(new RetryableCallout(f.Payload__c, 1));
f.Status__c = 'Replayed';
}
update failures;
}
}Replay is only safe if the request is idempotent. The first attempt may have reached the server even though your side timed out. Send the same idempotency key in the stored payload or header so the server recognizes a duplicate.
Also remember the limit on System.enqueueJob calls per transaction. Replay in batches, or chain the work.
Make failures visible
A record nobody reads is a silent loss. Pick at least one way to surface them:
- A list view or report on
Status__c = 'New'. - A scheduled job that emails a count when new failures exist.
- A platform event or custom notification for failures on critical integrations.
Exercise
A callout returns HTTP 400 on its first attempt. Should the job retry, and what should happen to the request?
Show answer
No. A 400 is a permanent client error and a retry would send the same bad request. The job should call recordFailure at once, saving the payload, status code, and response body in a CalloutFailure_c record so someone can fix the data and replay it.
Exercise
Why does replay need an idempotency key even though the original request was recorded as failed?
Show answer
A timeout means your code did not get a response. The server may still have processed the request. Replaying without an idempotency key could create a duplicate order. With the key, the server can detect the repeat and return the original result.