Sub topic 8
Making repeated requests safe
This chapter assumes you can write a basic Apex callout and know the HTTP methods and status codes. It also assumes you know the difference between a thrown CalloutException and an error response, and which failures are worth retrying. Here you will learn why a retry can cause harm, and how to design requests so a repeat does no damage.
Why retries are dangerous
A retry is safe only if running the same request twice has the same effect as running it once. Many requests do not meet that standard.
Suppose your Queueable job sends POST /orders to an external system. The remote system receives the request and creates the order. Then the response is lost, or your callout reaches its timeout before the response arrives. Apex throws a CalloutException. Your retry logic classifies the failure as transient and sends the request again. The remote system now has two orders.
A timeout does not tell you that the request failed. It tells you that you did not get an answer. The server may have done nothing, may have finished the work, or may still be working.
Idempotent and non-idempotent operations
An operation is idempotent if repeating it leaves the system in the same state as running it once. The HTTP specification defines which methods are meant to behave this way.
| Method | Idempotent by definition | Notes |
|---|---|---|
| GET, HEAD | Yes | Read-only, so repeats are safe. |
| PUT | Yes | Replaces a resource with the same content each time. |
| DELETE | Yes | The second delete may return 404, but the end state is the same. |
| POST | No | Typically creates something or triggers an action. |
| PATCH | No | Safe only if the patch sets values and does not increment or append. |
These are rules for how servers should behave. They are not guarantees. A badly designed GET /reports/run can still send an email. Check the API documentation before you rely on a method's reputation.
The risky cases are the ones that matter most in integrations: creating records, charging payments, sending messages, and starting jobs. Those are usually POST requests.
Idempotency keys
An idempotency key is a unique string that the client generates for one logical operation. The client sends the same key on every attempt at that operation. The server stores the result of the first attempt under that key. When it sees the key again, it returns the stored result and does not repeat the work.
Many APIs, such as payment providers, accept the key in a header called Idempotency-Key. The header name and the behavior vary between APIs, so confirm both in the documentation. The server must support the feature. If it ignores the header, sending it does nothing.
Two rules decide whether the technique works:
- Generate the key once, before the first attempt. If each attempt makes a new key, the server sees each retry as a new operation.
- Carry the key to every retry. In a Queueable chain, that means passing it through the constructor.
Choosing a key
You have two main options.
Random key, generated at enqueue time. EncodingUtil.convertToHex(Crypto.generateAesKey(128)) returns 32 random hex characters. A random key identifies one attempt chain. It is simple and cannot collide with unrelated operations. The weakness is that the key lives only in your job's state. If a different transaction later starts the same logical operation, for example a trigger that fires twice for the same record, it produces a different key, and the server sees two operations.
Deterministic key, derived from the operation. Build the key from the record ID and a hash of the content, so the same logical operation always produces the same key. This also protects you from duplicate enqueues.
A deterministic key needs care. If the key is only the record ID, a legitimate second request with changed data would match the first key. The server would return the old result and ignore your new data. Include something that changes when the operation changes, such as a hash of the payload or a version number.
public static String buildKey(Id recordId, String payload) {
Blob digest = Crypto.generateDigest(
'SHA-256',
Blob.valueOf(String.valueOf(recordId) + ':' + payload)
);
return EncodingUtil.convertToHex(digest);
}The same record and payload always give the same key. Any change to the payload gives a different one.
Putting the key into the retry job
This version of the Queueable from the retry chapter generates the key once in start and passes it to each new attempt. It also separates request building from sending, which makes the header easy to test.
public class IdempotentCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
private final String payload;
private final Integer attempt;
private final String idempotencyKey;
public IdempotentCallout(String payload, Integer attempt, String idempotencyKey) {
this.payload = payload;
this.attempt = attempt;
this.idempotencyKey = idempotencyKey;
}
// Entry point: the key is created here, once.
public static Id start(Id recordId, String payload) {
String key = buildKey(recordId, payload);
return System.enqueueJob(new IdempotentCallout(payload, 1, key));
}
public static String buildKey(Id recordId, String payload) {
Blob digest = Crypto.generateDigest(
'SHA-256',
Blob.valueOf(String.valueOf(recordId) + ':' + payload)
);
return EncodingUtil.convertToHex(digest);
}
public static HttpRequest buildRequest(String payload, String key) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', key);
req.setBody(payload);
req.setTimeout(30000);
return req;
}
public void execute(QueueableContext ctx) {
try {
HttpResponse res = new Http().send(buildRequest(payload, idempotencyKey));
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 IdempotentCallout(payload, attempt + 1, idempotencyKey),
delayMinutes
);
}
}Every retry reuses idempotencyKey. The constructor receives it and retryLater passes it on, so all four possible attempts share one identity.
Responses specific to idempotency
APIs that support keys often add status codes of their own. Typical cases:
- The same key, a completed request. The server returns the original response, often with a header that marks it as a replay. Treat this as success.
- The same key while the first request is still running. Some APIs return 409 Conflict. This is usually worth retrying after a delay, but only when the documentation says so. Otherwise 409 is a permanent conflict, as the classification chapter described.
- The same key with a different payload. Many APIs return 400 or 422. This is a bug in your code, not a transient fault. Do not retry it. It is also the reason the key should change when the payload changes.
Read the error body (see the chapter on status codes) before you decide. The status code alone often cannot separate "still processing" from "key reused with different data".
When the server has no key support
If the API cannot accept an idempotency key, you can still reduce the risk:
- Check before you repeat. After an ambiguous failure, query the remote system for the record using a reference you control, such as your Salesforce record ID stored as an external reference. Retry the create only if the record is absent. This works for any API that can search by reference, but it adds a call and leaves a small gap in which two attempts can overlap.
- Use PUT with a client-chosen identifier. If the API lets you create a resource at
PUT /orders/{your-id}, repeating the request replaces the same resource and cannot create a second one. - Make the receiving side deduplicate. If you own the remote system, store the key and reject repeats.
- Do not retry at all. For a non-idempotent operation with no safe check, treat an ambiguous failure as permanent. Log it for a person to review. A duplicate charge is usually worse than a delayed one.
The same idea applies in the other direction. When an external system calls Salesforce and may repeat its request, use upsert with an external ID field. Repeating an upsert updates the same record and does not create a second one.
Duplicate jobs inside Salesforce
Retries are not the only source of repeated callouts. A trigger can fire more than once for one business event, and a user can click a button twice. Each time, your code might enqueue a new job.
A deterministic key helps here, because both jobs send the same key and the server collapses them. You can also stop the duplicate before it runs. Apex provides AsyncOptions with a duplicate signature, which makes System.enqueueJob refuse to queue a second job with the same signature while the first is still waiting. Use it for work that should run once, and keep the idempotency key as the second line of defense, because a signature does not cover a job that has already started.
Testing that the key survives
You can test the header without a mock, because buildRequest is a static method.
@IsTest
private class IdempotentCalloutTest {
@IsTest
static void requestCarriesIdempotencyKey() {
String key = IdempotentCallout.buildKey('001000000000001AAA', '{"qty":1}');
HttpRequest req = IdempotentCallout.buildRequest('{"qty":1}', key);
Assert.areEqual(key, req.getHeader('Idempotency-Key'));
}
@IsTest
static void sameOperationGivesSameKey() {
String first = IdempotentCallout.buildKey('001000000000001AAA', '{"qty":1}');
String second = IdempotentCallout.buildKey('001000000000001AAA', '{"qty":1}');
Assert.areEqual(first, second);
}
@IsTest
static void changedPayloadGivesNewKey() {
String first = IdempotentCallout.buildKey('001000000000001AAA', '{"qty":1}');
String second = IdempotentCallout.buildKey('001000000000001AAA', '{"qty":2}');
Assert.areNotEqual(first, second);
}
}These tests cover the rules that matter: the header is sent, equal operations share a key, and changed data gets a new key. Test the retry chain itself separately. Apex tests cannot run chained Queueable jobs to completion, so assert on retryLater behavior through smaller methods, as the testing chapter describes.
Common mistakes
- Generating the key inside
execute. Each retry runsexecuteagain and would produce a new key. Create the key before the first attempt. - Using only the record ID as the key. A later, different request for the same record gets the old response.
- Treating a timeout as a clean failure. Always assume the work may have happened.
- Assuming PATCH is safe. A patch that adds to a value or appends to a list is not idempotent.
- Skipping the server documentation. Header names, key lifetimes, and conflict codes all differ between APIs.
Exercise
A Queueable job sends POST /payments and gets a CalloutException from a read timeout. The developer's code builds a new random Idempotency-Key inside execute() on every attempt. What goes wrong, and what is the fix?
Show answer
Each retry uses a different key, so the server treats it as a new payment. If the first request actually succeeded before the timeout, the customer is charged twice. The fix is to generate the key once before the first attempt, for example in a static start method, and pass it through the constructor to every retry.
Exercise
You derive an idempotency key from the record ID only. A user edits the record and the system sends an updated request. Why can this fail, and how would you change the key?
Show answer
The server sees the same key as the earlier request and returns the stored result for the old data, so the update is never applied. Include something that changes with the operation, such as a SHA-256 hash of the payload or a version number, so a changed request gets a new key while an exact repeat keeps the same one.