Sub topic 10
Retrying with Queueable Apex
This chapter assumes you can write a basic callout, know the difference between transient and permanent HTTP failures, and have used Queueable Apex at least once. Earlier chapters covered classifying errors and choosing a retry policy. Here you put that policy into code.
Why retry in a Queueable
A synchronous retry loop does not work well in Apex. There is no way to sleep between attempts, and every attempt counts against the callout limits of the same transaction. A retry that waits a minute or more has to happen in a new transaction.
A Queueable job provides that new transaction. Three features matter:
- It runs asynchronously, so the original request is not blocked.
- It can make callouts if it implements
Database.AllowsCallouts. System.enqueueJob(job, delayMinutes)schedules it to start after a delay of 0 to 10 minutes.
A job can enqueue one child job from its own execute method. Each retry is therefore a fresh job with its own limits and a delay you choose.
The retry flow
The job
The job carries two pieces of state: the payload to send and the attempt number. Both are private final fields set in the constructor, so a retry is just a new instance with attempt + 1.
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);
try {
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
if (code >= 200 && code < 300) {
return;
}
if (!(code == 408 || code == 429 || (code >= 500 && code <= 599))) {
System.debug(LoggingLevel.ERROR, 'Permanent failure: ' + code);
return;
}
} catch (System.CalloutException e) {
System.debug(LoggingLevel.WARN, 'Transient failure: ' + e.getMessage());
}
retryLater();
}
private void retryLater() {
if (attempt >= MAX_ATTEMPTS) {
System.debug(LoggingLevel.ERROR, 'Retries exhausted after ' + attempt + ' attempts');
return;
}
Integer delayMinutes = Math.min(10, (Integer) Math.pow(2, attempt - 1));
System.enqueueJob(new RetryableCallout(payload, attempt + 1), delayMinutes);
}
}Start the first attempt from any context that is allowed to enqueue jobs:
System.enqueueJob(new RetryableCallout('{"orderId":"A-1001"}', 1));How the code works
The execute method separates three outcomes. A 2xx response returns quietly. A status that is not retryable, such as 400 or 404, is logged and not retried, because repeating it gives the same answer. A CalloutException or a retryable status falls through to retryLater().
The delay is 2^(attempt - 1) minutes, capped at 10. With MAX_ATTEMPTS = 4, the retries wait 1, 2, and 4 minutes. The cap matters because enqueueJob rejects delays above 10 minutes.
Common errors
- Forgetting
Database.AllowsCallouts. The job runs but fails with an uncommitted-work or callout-not-allowed error at the firstsend. - Retrying a non-idempotent request. If the first attempt timed out after the server processed it, the retry creates a duplicate. Send an idempotency key in a header so the server can recognize the repeat. The same payload and key must be reused on every attempt.
- Expecting jitter from the delay. The delay unit is whole minutes, so you cannot add sub-minute randomness. Jitter helps mostly when many jobs retry at once, and here you can only vary the number of minutes.
- Unbounded chains. A job that always re-enqueues itself runs forever. The attempt counter is what stops it.
- Chaining in tests. A test can run the first job, but a chained job does not run in the same test. Test
executefor the attempt you care about, and assert the failure behavior directly.
What this version leaves out
Logging with System.debug disappears when the log expires. A production version should write exhausted failures to a custom object so someone can review and replay them. The next chapter covers that.
Exercise
A job makes a POST that creates an order. The request times out, and the job re-enqueues itself. Later you find two orders for one request. What went wrong, and what is the fix?
Show answer
The first attempt probably reached the server and created the order, but the response was lost. The retry then created a second order because the request was not idempotent. Generate an idempotency key once, store it in the job alongside the payload, and send it in a header on every attempt so the server can ignore the repeat.