Sub topic 10
Retrying with Queueable Apex
What this chapter assumes
This chapter assumes you have read the earlier chapters on timeouts, status handling, and error classification. You should be comfortable with Queueable, HttpRequest, and HttpResponse. You should also know which failures are worth repeating: a CalloutException from a timeout or connection failure, and HTTP 408, 429, and 5xx responses. Everything else, such as 400, 401, 403, and 404, is permanent and should not be retried.
This chapter covers how to run a retry. A Queueable job gives you a delay between attempts, a fresh set of governor limits for each attempt, and a clean place to stop.
Why retry in a separate transaction
You could loop inside one transaction: call, fail, call again. This is a poor design in Apex for three reasons.
- Apex has no sleep function. A loop would retry immediately, which hits a service that is probably already overloaded.
- All attempts share one transaction. The limit of 100 callouts and the cumulative callout time limit of 120 seconds apply to the whole transaction. Several 30-second timeouts can use up the 120 seconds quickly.
- The user waits for the whole loop if the code runs synchronously.
A Queueable job runs in its own transaction with its own limits. A job can enqueue a new job with a delay, and that gives you the wait between attempts. Each attempt is a separate job, so a failure in one cannot use up the budget of the next.
The retry job
This is the job from the chapter's code examples. It makes one attempt. It then either finishes or schedules the next attempt.
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);
}
}You start the sequence with the first attempt number:
System.enqueueJob(new RetryableCallout('{"orderId":"A-1001"}', 1));How the code works
Database.AllowsCalloutsis required. Without it, theHttp.sendcall throws aCalloutExceptionthat says callouts are not allowed from this context. Because the code catchesCalloutException, a missing marker would look like a transient failure and would be retried until the attempts ran out. Always check this interface first when every attempt fails.- The two exits that do not retry are a 2xx success and a permanent error. Both end with
return, so no new job is queued. - The
catchblock only logs. Control then falls through toretryLater(). The transient status codes reachretryLater()the same way, because theifstatements above skip theirreturn. - The attempt number travels with the job as a constructor argument. A Queueable has no memory between runs, so any state that survives to the next attempt must be passed through the constructor.
System.enqueueJob(job, delayMinutes)takes a delay in whole minutes. The allowed range is 0 to 10. The cap inMath.min(10, ...)keeps the value valid.
The delay schedule
The delay is 2^(attempt - 1) minutes, capped at 10. With MAX_ATTEMPTS = 4, the job waits as follows.
| Attempt that failed | Delay before next attempt | Total scheduled wait so far |
|---|---|---|
| 1 | 1 minute | 1 minute |
| 2 | 2 minutes | 3 minutes |
| 3 | 4 minutes | 7 minutes |
| 4 | none, retries exhausted | 7 minutes |
The totals count only the scheduled delay. Each attempt can also take up to its 30-second timeout, and the queue adds some time before a job starts. Treat the delay as a minimum, not an exact schedule.
The delay unit is a whole minute, so jitter is coarse. Jitter is a small random change to each delay, and it keeps many failed jobs from all retrying at the same moment. With minute granularity you can only add whole minutes. If many records can fail together, for example during a partner outage, consider adding a random 0 or 1 minute where the cap allows it. Do this only if the load on the partner matters.
The flow of one retry sequence
Keeping retries safe
A timeout does not tell you that the request failed. The partner may have processed the order and been too slow to reply. If your retry sends the same POST again, you could create the order twice.
The fix is an idempotency key. This is a unique value that you generate once per logical operation and send with every attempt. A service that supports it returns the first result for a repeated key instead of acting twice. The header name varies by API, and Idempotency-Key is common. Check your partner's documentation.
The key must be created before the first attempt and passed unchanged to each retry. If each attempt generated its own key, the protection would be useless.
public class IdempotentCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
private final String payload;
private final String idempotencyKey;
private final Integer attempt;
public IdempotentCallout(String payload) {
this(payload, Uuid.randomUUID().toString(), 1);
}
private IdempotentCallout(String payload, String idempotencyKey, Integer attempt) {
this.payload = payload;
this.idempotencyKey = idempotencyKey;
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.setHeader('Idempotency-Key', idempotencyKey);
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());
}
if (attempt >= MAX_ATTEMPTS) {
System.debug(LoggingLevel.ERROR, 'Retries exhausted for key ' + idempotencyKey);
return;
}
Integer delayMinutes = Math.min(10, (Integer) Math.pow(2, attempt - 1));
System.enqueueJob(new IdempotentCallout(payload, idempotencyKey, attempt + 1), delayMinutes);
}
}The public constructor creates the key and starts at attempt 1. The private constructor is used only by the job itself to carry the same key forward. Callers cannot pass an attempt number or key by mistake.
Some methods are naturally safe to repeat. GET, PUT, and DELETE are defined as idempotent in HTTP, and POST is not. Even so, a partner's PUT can have side effects. Do not assume that a method is safe without reading the API documentation.
Limits that affect chaining
- A Queueable that is already running can enqueue only one child job. A retry job that enqueues exactly one successor fits this rule. Code that tries to enqueue two jobs in one
executethrows aLimitException. - A synchronous transaction, such as a trigger or controller, can enqueue up to 50 jobs. Keep this in mind if you start one retry job for each record in a large batch.
- Developer Edition and trial orgs limit the chain depth to 5. Other orgs have no fixed depth limit. A
MAX_ATTEMPTSof 4 stays inside the lower limit. - Callouts cannot be made in a trigger's synchronous context after uncommitted DML work. Enqueue the job from the trigger instead. The job runs after the transaction commits, so the callout happens in a clean transaction.
Common errors
- The
retryLater()method is called with no attempt cap, or the cap is compared with the wrong variable. The chain then never ends and keeps using async capacity. - The code catches
Exceptioninstead ofCalloutException. A bug such as a null pointer is then treated as transient and retried. Bugs should surface, not repeat. - The job retries on every non-2xx status. A 400 or 404 will not improve with time, so these retries waste attempts and delay the real log entry.
- A new idempotency key is created inside
execute. Each retry then looks like a new request to the partner. - The code relies on
System.debugfor exhausted retries. Debug logs are not stored for later review. A later chapter covers recording exhausted jobs and replaying them, and a Transaction Finalizer (System.attachFinalizer) can catch a job that dies from an unhandled exception.
Exercises
Exercise
You change MAX_ATTEMPTS in RetryableCallout to 6. Using the same delay formula, what delay is used after each failed attempt, and how many minutes of scheduled waiting happen if every attempt fails?
Show answer
The delays follow min(10, 2^(attempt - 1)) for attempts 1 to 5: 1, 2, 4, 8, and 10 minutes (the 16 from attempt 5 is capped at 10). Attempt 6 stops without scheduling another job. The total scheduled wait is 1 + 2 + 4 + 8 + 10 = 25 minutes, not counting callout time or queue delay.
Exercise
A POST to a payment endpoint times out on attempt 1 and succeeds on attempt 2, yet the customer was charged twice. What went wrong, and what is the fix?
Show answer
The timeout did not mean the first request failed. The partner probably processed it but replied too slowly, so the retry repeated the charge. The fix is to generate an idempotency key once, before the first attempt, send it in a header on every attempt, and pass it unchanged to each retry job. The partner API must support the key and return the first result for a repeated one.