Sub topic 9
Designing a retry policy
This chapter assumes you can write a basic Apex callout and that you know the difference between a thrown CalloutException and an HTTP error response. It also assumes you have seen the earlier chapters on classifying retryable errors and on idempotency. Here you will combine those ideas into one explicit policy: how many attempts, how long to wait, and how to avoid hammering a struggling service.
What a retry policy decides
A retry policy answers four questions every time a callout fails:
- Is this failure worth retrying at all?
- Have we used up our attempts?
- How long should we wait before the next attempt?
- What do we do when the attempts run out?
Questions 1 and 4 were covered in other chapters. This chapter focuses on 2 and 3, and on keeping all four answers in one place so you can change them without touching callout code.
A retry is a bet that the next attempt will succeed. The bet only pays off for transient failures such as a timeout, a 503 during a deploy, or a 429 from rate limiting. For a 400 or 404, every extra attempt is wasted work and wasted limits.
Attempt caps
Every retry loop needs a hard cap. Without one, a permanently broken endpoint consumes async Apex executions forever. Each retry in Apex is a new Queueable job, and those count against your org's daily asynchronous Apex limits.
Choose the cap by asking how long the problem is likely to last and how long the business can wait:
- A brief blip (a load balancer restart) clears in seconds. Two or three attempts are enough.
- A deployment or failover can take several minutes. Four or five attempts with growing delays cover it.
- An outage that lasts hours is not a retry problem. Record the failure and replay it later, as the chapter on exhausted retries describes.
Count attempts, not retries. In this chapter, attempt 1 is the original call, so MAX_ATTEMPTS = 4 means one original call and up to three retries. Pick one convention and use it everywhere, because off-by-one errors are the most common bug in retry code.
Backoff: waiting longer each time
Retrying immediately usually fails for the same reason the first call failed. Backoff means waiting between attempts, and exponential backoff doubles the wait each time. It gives a recovering service room to catch up, and it spreads your load out in time.
With a base delay of 1 minute and doubling, the ceilings look like this:
| Attempt that just failed | Formula (minutes) | Delay ceiling before next attempt |
|---|---|---|
| 1 | 2^0 | 1 |
| 2 | 2^1 | 2 |
| 3 | 2^2 | 4 |
| 4 | 2^3 | 8 |
| 5 | 2^4 | 16, capped at 10 |
Always include a cap on the delay. Without it, the delays grow past what is useful. In Apex there is also a hard platform limit: the delay you pass to System.enqueueJob(job, delayInMinutes) is a whole number of minutes from 0 to 10. A cap of 10 matches that limit.
Granularity is one minute
The Queueable delay is measured in whole minutes. You cannot ask for a 500-millisecond or 20-second wait. This changes how you design the policy:
- The smallest wait you can schedule is 1 minute (a delay of 0 enqueues the job immediately, which is rarely what you want for a retry).
- For retries that must happen within seconds, such as a user waiting on a screen, Queueable delays are the wrong tool. Retry inside the same transaction a small number of times, or show the user an error and let them try again.
Jitter: avoiding synchronized retries
Suppose 500 records fail at the same moment because the service went down. If each one retries after exactly 1 minute, then 2, then 4, the service gets 500 requests at once at every step. This is called a thundering herd, and it can knock a recovering service back down.
Jitter adds randomness to the delay so the retries spread out. The common approach, called full jitter, picks a random delay between the minimum and the exponential ceiling. With whole-minute granularity, the result for attempt 3 is a random value from 1 to 4 minutes.
Jitter matters most when many records can fail together, for example a batch job that makes a callout per record. For a rarely used integration with one record at a time, it costs nothing and does no harm, so include it by default.
Honoring Retry-After
Some services tell you how long to wait. A 429 or 503 response may carry a Retry-After header, usually a number of seconds (it can also be an HTTP date, which this chapter does not parse). If the server gives you a number, respect it, but still keep it within your cap. If the header is missing or unreadable, fall back to your own backoff.
Because Queueable delays are in whole minutes, convert seconds to minutes by rounding up. Rounding down would retry before the server said it was ready.
A policy class
Put the decisions in one small class with no callout code in it. It is easy to read, and you can unit test it without mocks.
public with sharing class RetryPolicy {
public static final Integer MAX_ATTEMPTS = 4;
public static final Integer MAX_DELAY_MINUTES = 10;
// Attempt 1 is the original call.
public static Boolean canRetry(Integer attempt) {
return attempt < MAX_ATTEMPTS;
}
public static Boolean isRetryable(Integer statusCode) {
return statusCode == 408
|| statusCode == 429
|| (statusCode >= 500 && statusCode <= 599);
}
// Full jitter: a random whole number of minutes from 1 up to the ceiling.
public static Integer backoffMinutes(Integer attempt) {
Integer ceiling = Math.min(
MAX_DELAY_MINUTES,
(Integer) Math.pow(2, attempt - 1)
);
return 1 + (Integer) Math.floor(Math.random() * ceiling);
}
// Use Retry-After when it is a plain number of seconds, otherwise back off.
public static Integer delayFor(HttpResponse res, Integer attempt) {
String header = (res == null) ? null : res.getHeader('Retry-After');
if (String.isNotBlank(header)) {
String trimmed = header.trim();
if (trimmed.isNumeric() && trimmed.length() <= 6) {
Integer seconds = Integer.valueOf(trimmed);
Integer minutes = (Integer) Math.ceil(seconds / 60.0);
return Math.min(MAX_DELAY_MINUTES, Math.max(1, minutes));
}
}
return backoffMinutes(attempt);
}
}Three details are worth noting:
delayForaccepts a null response. A timeout throws an exception, so there is no response, and the code falls through to the normal backoff.- The
length() <= 6check keepsInteger.valueOffrom overflowing on a huge header value. - The cap applies to the server's value too. A
Retry-After: 3600becomes 10 minutes here, and the next attempt may fail again. That is acceptable, because the attempt cap still ends the sequence.
Using the policy in a Queueable
Now the Queueable from the previous chapter shrinks to the callout and a call to the policy.
public class RetryableCallout implements Queueable, Database.AllowsCallouts {
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);
HttpResponse res = null;
try {
res = new Http().send(req);
Integer code = res.getStatusCode();
if (code >= 200 && code < 300) {
return;
}
if (!RetryPolicy.isRetryable(code)) {
System.debug(LoggingLevel.ERROR, 'Permanent failure: ' + code);
return;
}
} catch (System.CalloutException e) {
System.debug(LoggingLevel.WARN, 'Transient failure: ' + e.getMessage());
}
if (!RetryPolicy.canRetry(attempt)) {
System.debug(LoggingLevel.ERROR, 'Retries exhausted after ' + attempt + ' attempts');
return;
}
Integer delay = RetryPolicy.delayFor(res, attempt);
System.enqueueJob(new RetryableCallout(payload, attempt + 1), delay);
}
}Start the sequence with System.enqueueJob(new RetryableCallout(body, 1));. The res variable stays null when the callout throws, which is why delayFor checks for null.
Budgeting the whole sequence
Check the policy against two budgets before you ship it.
Time. With four attempts and the delays above, the worst case adds up to 1 + 2 + 4 = 7 minutes of waiting, plus up to four 30-second timeouts. If a downstream process needs the result within 5 minutes, this policy is too slow for it, and you must shrink the cap or the delays.
Limits. Each attempt is its own transaction with its own callout limits, so retrying does not use up the per-transaction callout count of the original request. But each attempt is an asynchronous execution, and those count toward your org's daily async limits. If 10,000 records can fail at once, the policy can create up to 30,000 extra jobs. Estimate the worst case, not the average.
Also remember that a Queueable can enqueue only one child job per execution. A retry chain satisfies this, because each attempt enqueues exactly one next attempt. If you fan out (for example, one job retrying 200 records separately), you need a different structure, such as batching the records into one payload.
Common mistakes
- Retrying non-idempotent requests blindly. If a POST timed out, the server may have processed it. Send an idempotency key that stays the same across attempts, so a repeat does not create a duplicate. Generate the key once, before the first attempt, and pass it through the Queueable constructor.
- Resetting the attempt counter. Pass
attempt + 1into the new job. Creating the next job with1loops forever. - Retrying in the same transaction with a loop. Apex has no sleep. A loop that retries immediately wastes your 120-second cumulative callout time and the per-transaction callout limit, and it gives the server no time to recover.
- Putting the policy values in several places. If the cap lives in the Queueable and the delays live in a trigger helper, they drift apart. Keep them in
RetryPolicy. - Treating the cap as a secret. Make it a constant, or read it from custom metadata, so operations staff can tune it without a deployment. Choose custom metadata only if you actually need to change it often.
Testing the policy
Because RetryPolicy has no callouts, its tests are short and need no mocks.
@IsTest
private class RetryPolicyTest {
@IsTest
static void backoffStaysWithinCeiling() {
for (Integer i = 0; i < 200; i++) {
Integer first = RetryPolicy.backoffMinutes(1);
Integer third = RetryPolicy.backoffMinutes(3);
Integer late = RetryPolicy.backoffMinutes(9);
Assert.areEqual(1, first, 'Attempt 1 ceiling is 1 minute');
Assert.isTrue(third >= 1 && third <= 4, 'Attempt 3 ceiling is 4 minutes');
Assert.isTrue(late >= 1 && late <= 10, 'Delay is capped at 10 minutes');
}
}
@IsTest
static void attemptCapStopsRetries() {
Assert.isTrue(RetryPolicy.canRetry(RetryPolicy.MAX_ATTEMPTS - 1));
Assert.isFalse(RetryPolicy.canRetry(RetryPolicy.MAX_ATTEMPTS));
}
@IsTest
static void onlyTransientStatusesAreRetryable() {
Assert.isTrue(RetryPolicy.isRetryable(503));
Assert.isTrue(RetryPolicy.isRetryable(429));
Assert.isFalse(RetryPolicy.isRetryable(400));
Assert.isFalse(RetryPolicy.isRetryable(404));
}
}The loop runs the random function 200 times per case. A single run could pass by luck even with a bug, and repetition makes a bounds error very likely to show up.
Choosing values: a short checklist
- Set the cap from the longest outage you want to ride out, not from a habit of "three tries".
- Keep the delay cap at or below 10 minutes, because the platform does not accept more in
enqueueJob. - Always add jitter when many records can fail together.
- Always honor
Retry-After, but cap it. - Always require an idempotency key for any request that creates or changes data.
- Always decide what happens after the last attempt before you write the first retry.
Exercise
Your policy has MAX_ATTEMPTS = 5 and uses full jitter with a 10-minute cap. What is the longest total time spent waiting between attempts, excluding callout time? What is the shortest? Why can't you retry within 15 seconds using System.enqueueJob?
Show answer
There are 4 waits, after attempts 1 to 4, with ceilings of 1, 2, 4, and 8 minutes. The longest total is 1 + 2 + 4 + 8 = 15 minutes. The shortest is 4 minutes, because each wait is at least 1 minute. System.enqueueJob accepts a delay only in whole minutes from 0 to 10, so 15 seconds cannot be expressed. A delay of 0 runs the job as soon as possible, which is not a controlled wait.