Sub topic 13
Handling expired tokens, errors and retries
This chapter assumes you can already request an access token, create a session, send a message and end the session. It covers what happens when those calls fail, and how to retry safely without sending duplicate messages or leaking sessions.
Why a working integration still fails
Every call in the Agent API conversation goes over the network and carries a bearer token. Any of these can go wrong in production:
- The access token expires partway through a long-running job.
- The API throttles you because you sent too many requests.
- A temporary server problem returns a 5xx status.
- A session ends or is no longer found.
- A timeout leaves you unsure whether the agent received your message.
Each failure needs its own response. Retrying everything the same way causes duplicate messages or hides real configuration errors.
Sorting errors by what to do next
Read the HTTP status code first, then the response body. The body often names the cause.
| Status | Typical meaning | Action |
|---|---|---|
| 400 | Malformed body, bad field value, or invalid `sequenceId` | Fix the request. Do not retry. |
| 401 | Access token expired, revoked or missing | Request a new token, then retry once. |
| 403 | The token is valid but lacks permission, for example a missing scope or an agent the run-as user cannot access | Fix the configuration. Do not retry. |
| 404 | Agent ID or session ID not found, or the session already ended | Check the ID. If the session is gone, create a new one. |
| 429 | Too many requests | Wait, then retry with backoff. |
| 500, 502, 503, 504 | Temporary server or gateway problem | Retry with backoff, a limited number of times. |
The general rule is that 4xx errors (except 401 and 429) mean your request is wrong, so repeating it gives the same result. 5xx errors and 429 are about timing, so waiting can help.
Expired tokens
The client credentials flow does not return a refresh token. When the access token expires, you do not refresh it. You repeat the original token request from the first chapters of this tutorial and get a new token.
There are two ways to notice expiry:
- React to a 401 response, get a new token and retry.
- Track the token's age yourself and renew it before it expires.
Reacting to 401 is simpler and works even if the token is revoked early. Tracking age saves one failed call per expiry. A reasonable choice is to react to 401, because it covers both cases without guessing the token lifetime. The lifetime is set by your org's session settings and may differ from what you expect.
Retry after a 401 only once. If a freshly issued token also gets a 401, the problem is configuration, not expiry. Check the External Client App, its scopes, and the run-as user.
Also handle failures in the token request itself. A 400 from the token endpoint usually means a wrong client ID or secret, or a flow that is not enabled for the app. These do not fix themselves, so fail loudly and include the response body in the log message. Never log the client secret or the token.
Backoff and retries
When you retry a throttled or failing call, wait longer after each attempt and add a small random delay (jitter). Without jitter, many clients that failed together retry together and fail together again.
- Use exponential backoff: roughly 1 second, 2 seconds, 4 seconds.
- Add random jitter to each wait.
- If the response has a
Retry-Afterheader with a number of seconds, wait at least that long. - Set a maximum number of attempts. Three or four is typical.
Retrying message sends safely
Retrying a GET is harmless. Retrying a message POST is not always harmless. If a request times out, the agent may have received your message and may even have acted on it, for example by updating a record. Sending it again can repeat that action.
Choose by failure type:
- Got a 429 or 503 response: the server answered, so retrying is usually safe.
- Connection error before any bytes were sent: retrying is safe.
- Read timeout after the request was sent: you do not know the outcome. Do not retry blindly. Consider ending the session and starting over, or let a person decide for actions with side effects.
Each message has a sequenceId that increases through the conversation. Do not assume that resending the same sequenceId is treated as a duplicate. Verify that behavior in your own org before relying on it.
A client with token renewal and retries
This example wraps the calls from earlier chapters in one function. It keeps the token in memory, renews it on a 401, backs off on 429 and 5xx, and only retries network failures when you say it is safe.
import os
import random
import time
import requests
MY_DOMAIN = os.environ["SF_MY_DOMAIN"]
RETRYABLE_STATUS = {429, 500, 502, 503, 504}
def fetch_token() -> str:
response = requests.post(
f"{MY_DOMAIN}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
)
if not response.ok:
# The body names the cause, such as an invalid client. It holds no secrets.
raise RuntimeError(f"Token request failed: {response.status_code} {response.text}")
return response.json()["access_token"]
class TokenCache:
def __init__(self) -> None:
self._token = None
def get(self, force_refresh: bool = False) -> str:
if self._token is None or force_refresh:
self._token = fetch_token()
return self._token
def wait_time(response, attempt: int) -> float:
retry_after = response.headers.get("Retry-After") if response is not None else None
if retry_after and retry_after.isdigit():
return float(retry_after)
return (2 ** (attempt - 1)) + random.uniform(0, 0.5)
def call_api(method, url, tokens, max_attempts=4, retry_network=False,
extra_headers=None, timeout=60, **kwargs):
refreshed = False
for attempt in range(1, max_attempts + 1):
headers = {
"Authorization": f"Bearer {tokens.get()}",
"Content-Type": "application/json",
**(extra_headers or {}),
}
try:
response = requests.request(
method, url, headers=headers, timeout=timeout, **kwargs
)
except (requests.ConnectionError, requests.Timeout):
if not retry_network or attempt == max_attempts:
raise
time.sleep(wait_time(None, attempt))
continue
if response.status_code == 401 and not refreshed:
tokens.get(force_refresh=True)
refreshed = True
continue
if response.status_code in RETRYABLE_STATUS and attempt < max_attempts:
time.sleep(wait_time(response, attempt))
continue
response.raise_for_status()
return response
raise RuntimeError("Retries exhausted")To use it, replace the direct requests.post calls in your conversation code. For the message call, leave retry_network at False:
tokens = TokenCache()
reply = call_api(
"POST",
f"https://api.salesforce.com/einstein/ai-agent/v1/sessions/{session_id}/messages",
tokens,
json={"message": {"sequenceId": 1, "type": "Text", "text": "Hello"}},
)For session creation, a network retry is reasonable because no conversation exists yet. Pass retry_network=True there.
Session problems
A 404 on /sessions/{session_id}/messages usually means the session ended or expired. Sessions do not live forever. The earlier conversation context is gone, so a new session starts with no memory of the old one. If the user must continue, replay the key facts in the first message of the new session or pass them as context variables.
Keep the finally block that ends the session. When ending a session after an error, a failure in the end call should not hide the original error. Log it and move on.
Logging for diagnosis
Log enough to trace a failure without exposing data:
- The HTTP method, URL path, status code and attempt number.
- Your own
externalSessionKeyand thesessionId. - The response body for 4xx errors.
- Never the token, the client secret or full user messages if they may hold personal data.
Common mistakes
- Retrying a 400 or 403 in a loop. It cannot succeed.
- Looping on 401 without a limit, which can lock the client out or flood the token endpoint.
- Requesting a new token for every call instead of reusing the cached one.
- Retrying without any delay, which makes throttling worse.
- Treating a timeout as proof that the message was not delivered.
Exercise
Your job sends a message and the call fails with a read timeout. A colleague proposes wrapping the call in a loop that retries up to five times. What is the risk, and what would you do instead?
Show answer
The agent may have received and acted on the first message before the timeout, so each retry can repeat side effects such as creating duplicate records. Instead, do not retry blindly. Log the session ID, end the session, and either start a new session or let a person check the result, unless the agent's actions are safe to repeat.
Exercise
A request returns 401. You request a new token and retry, and the second call also returns 401. What should you do next, and why not request more tokens?
Show answer
Stop and treat it as a configuration problem. A freshly issued token that is still rejected points to the External Client App, its scopes, or the run-as user rather than expiry. Repeating token requests will not fix that and may add load to the token endpoint.