Sub topic 11
Handling REQUEST_LIMIT_EXCEEDED and Retries
This chapter assumes you can send authenticated REST requests to Salesforce, read JSON responses, and follow short Python and Apex examples. You should also know the difference between the daily API request limit and concurrent request limits from earlier chapters.
What the error looks like
When an org goes over a request limit, Salesforce rejects the call and returns an error body. The REST API returns HTTP status 403 with a JSON array:
[
{
"message": "TotalRequests Limit exceeded.",
"errorCode": "REQUEST_LIMIT_EXCEEDED"
}
]The errorCode is REQUEST_LIMIT_EXCEEDED for several different limits. The message text tells you which limit you hit. Always log both fields.
| Message text | Limit that was hit | Does waiting help? |
|---|---|---|
| `TotalRequests Limit exceeded.` | Daily API request limit (24-hour rolling window) | Only after enough older requests age out of the window. This can take hours. |
| `ConcurrentPerOrgLongTxn Limit exceeded.` | Concurrent long-running requests (those over 20 seconds) | Yes. Retry after a short delay, once running requests finish. |
| `ConcurrentPerOrgApiRequests` style messages | Concurrent request cap for the org | Yes. Retry after a short delay. |
Message wording can differ by API and release. Treat the table as a guide and match on the text you actually see in your logs.
Two kinds of failure, two responses
The most important decision in your handler is whether the failure is short-lived or long-lived.
- A concurrency error clears in seconds. Other requests are using the slots, and they will finish. Retrying with backoff is correct.
- A daily limit error does not clear in seconds. Retrying every few seconds wastes effort, and each rejected attempt can still add load. The right response is to stop sending non-essential calls, alert someone, and resume later.
Exponential backoff with jitter
Exponential backoff doubles the wait after each failed attempt: 1 second, 2, 4, 8, and so on. Jitter adds a random amount to each wait. Without jitter, many clients that failed at the same moment retry at the same moment and collide again. This is sometimes called a thundering herd.
A common formula is "full jitter": wait a random time between 0 and min(cap, base * 2^attempt).
The following Python example retries only errors that are safe to retry. It stops at once on a daily limit error.
import os
import random
import time
import requests
INSTANCE_URL = os.environ["INSTANCE_URL"]
TOKEN = os.environ["ACCESS_TOKEN"]
class DailyLimitExceeded(Exception):
"""Raised when the 24-hour API request limit is used up."""
def error_details(resp):
"""Return (errorCode, message) from a Salesforce error body."""
try:
first = resp.json()[0]
return first.get("errorCode", ""), first.get("message", "")
except (ValueError, KeyError, IndexError, TypeError):
return "", resp.text[:200]
def get_with_retry(path, max_attempts=5, base=1.0, cap=30.0):
url = f"{INSTANCE_URL}{path}"
headers = {"Authorization": f"Bearer {TOKEN}"}
for attempt in range(max_attempts):
resp = requests.get(url, headers=headers, timeout=30)
if resp.status_code < 400:
return resp
code, message = error_details(resp)
if code == "REQUEST_LIMIT_EXCEEDED":
if "TotalRequests" in message:
raise DailyLimitExceeded(message)
# Concurrency limit: back off and try again.
delay = random.uniform(0, min(cap, base * 2 ** attempt))
print(f"Attempt {attempt + 1} hit a limit ({message}). "
f"Sleeping {delay:.1f}s")
time.sleep(delay)
continue
# Any other error is not a limit problem. Do not retry blindly.
resp.raise_for_status()
raise RuntimeError(f"Gave up after {max_attempts} attempts on {path}")
if __name__ == "__main__":
r = get_with_retry("/services/data/v60.0/limits")
print(r.json()["DailyApiRequests"])Note what the code does not do. It does not retry 4xx errors such as INVALID_FIELD or MALFORMED_QUERY. Those fail the same way every time, and retrying them only burns API calls.
Retry safety: idempotency
A retry is safe only if running the request twice has the same effect as running it once.
GETrequests, including SOQL queries, are safe to retry.PATCHandDELETEon a specific record are generally safe, because repeating them leaves the record in the same state.POSTthat creates a record is not safe. If the first call succeeded but the response was lost, a retry creates a duplicate.
For inserts, use an upsert on an external ID field. An upsert sends PATCH /services/data/v60.0/sobjects/Account/Ext_Id__c/ABC-123. Running it twice yields one record, so you can retry it freely. Rate-limit errors are returned before the work is done, so the main duplicate risk comes from timeouts and dropped connections, where you cannot tell whether the call completed.
Honor Retry-After when it is present
Some responses include a Retry-After header. If one is present, use it in place of your computed delay. Do not assume it always appears. Salesforce does not guarantee the header on REQUEST_LIMIT_EXCEEDED responses, so your code needs the backoff formula as the fallback.
def delay_from(resp, attempt, base=1.0, cap=30.0):
retry_after = resp.headers.get("Retry-After")
if retry_after and retry_after.isdigit():
return min(cap, float(retry_after))
return random.uniform(0, min(cap, base * 2 ** attempt))Checking headroom before you send
Retries react to failure. You can also avoid failure by checking usage first. Earlier chapters showed the Sforce-Limit-Info header, which returns a value like api-usage=14980/15000 on each response. Read it after every call and slow down as you approach the limit.
def usage_fraction(resp):
header = resp.headers.get("Sforce-Limit-Info", "")
if "api-usage=" not in header:
return None
used, maximum = header.split("api-usage=")[1].split("/")[:2]
return int(used) / int(maximum)
def should_throttle(resp, soft_limit=0.9):
fraction = usage_fraction(resp)
return fraction is not None and fraction >= soft_limitA reasonable policy has three tiers:
- Below 80 percent: run normally.
- Between 80 and 95 percent: defer low-priority work, such as nightly reports and full re-syncs.
- Above 95 percent: run only critical calls and alert the owner.
The exact numbers depend on how much margin your org needs. Pick values from your own traffic patterns.
Limit errors inside Apex
Apex governor limits behave differently. Exceeding one throws a System.LimitException, such as "Too many SOQL queries: 101". You cannot catch this exception. The transaction stops and rolls back. Retrying inside the same transaction does nothing, because the counters do not reset.
What you can do is check before you cross the line, using the Limits class from the earlier chapter:
public with sharing class SafeProcessor {
public static void processAccounts(List<Id> accountIds) {
for (Id accountId : accountIds) {
// Stop before the 100 SOQL query ceiling (200 in async) is reached.
if (Limits.getQueries() >= Limits.getLimitQueries() - 5) {
System.debug(LoggingLevel.WARN,
'Near SOQL limit. Deferring remaining records.');
System.enqueueJob(new RetryRemaining(accountIds, accountId));
return;
}
List<Contact> contacts =
[SELECT Id FROM Contact WHERE AccountId = :accountId];
// ... work with contacts ...
}
}
public class RetryRemaining implements Queueable {
private List<Id> allIds;
private Id startId;
public RetryRemaining(List<Id> allIds, Id startId) {
this.allIds = allIds;
this.startId = startId;
}
public void execute(QueueableContext ctx) {
List<Id> remaining = new List<Id>();
Boolean started = false;
for (Id i : allIds) {
if (i == startId) { started = true; }
if (started) { remaining.add(i); }
}
SafeProcessor.processAccounts(remaining);
}
}
}The queued job runs in a new transaction with fresh counters. This pattern defers work. The real fix for a loop that runs a query per record is to move the query outside the loop. That is a bulkification change, covered under reducing consumption.
Handling the daily limit in practice
When TotalRequests is exceeded, the org's API calls fail until older calls fall out of the rolling 24-hour window. A sound handler does the following.
- Stop the integration's non-essential traffic at once. Use a circuit breaker, a flag that makes your client skip calls for a set period instead of sending them to fail.
- Persist the work that could not be sent, in a queue or table, so nothing is lost.
- Alert a human with the integration name, the time, and the last known usage.
- Resume gradually. Test with one cheap call, such as the Limits resource, before releasing the backlog.
A minimal circuit breaker looks like this:
import time
class CircuitBreaker:
def __init__(self, cooldown_seconds=900):
self.cooldown = cooldown_seconds
self.open_until = 0.0
def trip(self):
self.open_until = time.time() + self.cooldown
def allow(self):
return time.time() >= self.open_untilCall trip() when you catch DailyLimitExceeded, and check allow() before each request. The 15-minute cooldown is a starting point. Tune it to how quickly usage recovers in your org.
Common mistakes
- Retrying immediately in a tight loop. This makes concurrency errors worse and can burn the daily limit. Always wait.
- Retrying without a cap. Set a maximum number of attempts and a maximum delay.
- Treating every 403 as a limit error. A 403 can also mean a permission problem. Check
errorCodebefore deciding. - Ignoring the message text.
REQUEST_LIMIT_EXCEEDEDalone cannot tell you whether to wait seconds or hours. - Retrying non-idempotent writes. This creates duplicates.
- Many workers retrying in lockstep. Add jitter so they spread out.
Exercise
Your integration receives a 403 with errorCode REQUESTLIMITEXCEEDED and the message "TotalRequests Limit exceeded." A teammate proposes retrying every 5 seconds for up to 10 attempts. Explain why this is the wrong response, and describe what the handler should do instead.
Show answer
The message shows the daily 24-hour API request limit is used up, not a short-lived concurrency limit. Slots do not free up in seconds, so 10 retries over 50 seconds will almost certainly all fail and add more rejected traffic. The handler should raise a distinct daily-limit error instead of retrying. It should trip a circuit breaker to stop non-essential calls, save the unsent work in a queue, alert the owner with the last known usage, and resume later by probing with a single cheap call such as the Limits resource. Backoff with jitter is only for concurrency-type messages.
Exercise
A sync job retries a failed POST that creates Account records after a network timeout. Afterward you find duplicate accounts. What caused this, and how do you make the retry safe?
Show answer
A timeout does not tell the client whether Salesforce finished the insert. If the first call succeeded and only the response was lost, the retry creates a second record. Make the operation idempotent by using an upsert on an external ID field (PATCH to /sobjects/Account/ExtId_c/<value>), so repeating the call updates the same record. Alternatively, query by a unique key before retrying.