Sub topic 13
Handling expired tokens, errors and retries
This chapter assumes you can already request a token, create a session, and send a message with the earlier examples. Here you wrap those calls so a short outage or an expired token does not end the conversation.
Why calls fail
Most failures fall into three groups. Each needs a different response.
| Status or symptom | Likely cause | What to do |
|---|---|---|
| 401 | The access token expired or was revoked | Request a new token, then retry once |
| 400, 403, 404 | Bad request body, missing permission, or an unknown or ended session | Fix the request. Do not retry. |
| 429, 500, 502, 503, 504 | Rate limiting or a temporary server problem | Wait, then retry with backoff |
| Timeout or dropped connection | Network trouble | Retry carefully (see below) |
Check the exact status codes and error bodies your org returns. Log the response body whenever a call fails, because it usually names the cause.
Refreshing an expired token
The client credentials flow gives you no refresh token. When the access token expires, you request a new one with the same client ID and secret. Cache the token in memory and fetch a new one only after a 401. Refresh at most once per request. If the second attempt also returns 401, the cause is the app configuration or the run-as user, so retrying again will not help.
A wrapper with retries
This helper sends every call through one function. It refreshes the token on a 401 and retries temporary failures with exponential backoff and jitter. Jitter is a small random delay that stops many clients from retrying at the same moment.
import os
import random
import time
import requests
MY_DOMAIN = os.environ["SF_MY_DOMAIN"]
RETRYABLE = {429, 500, 502, 503, 504}
_token = None
def get_access_token(force: bool = False) -> str:
global _token
if _token is None or force:
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,
)
response.raise_for_status()
_token = response.json()["access_token"]
return _token
def call_api(method, url, extra_headers=None, max_attempts=4, **kwargs):
refreshed = False
attempt = 0
while True:
headers = {
"Authorization": f"Bearer {get_access_token()}",
"Content-Type": "application/json",
**(extra_headers or {}),
}
try:
response = requests.request(
method, url, headers=headers, timeout=60, **kwargs
)
except (requests.ConnectionError, requests.Timeout):
response = None
if response is not None:
if response.status_code == 401 and not refreshed:
get_access_token(force=True)
refreshed = True
continue
if response.status_code not in RETRYABLE:
response.raise_for_status()
return response
attempt += 1
if attempt >= max_attempts:
if response is not None:
response.raise_for_status()
raise RuntimeError(f"{method} {url} failed after {max_attempts} attempts")
delay = 2 ** attempt + random.random()
if response is not None and "Retry-After" in response.headers:
try:
delay = max(delay, float(response.headers["Retry-After"]))
except ValueError:
pass
time.sleep(delay)Use call_api("POST", f"{API_BASE}/agents/{AGENT_ID}/sessions", json=body) in place of a bare requests.post. The same wrapper works for messages and for the session delete.
Retrying messages safely
Creating a session and reading data are safe to repeat. Sending a message is less safe. If a request times out, the agent may have received it and acted on it. A retry could then run an action twice, such as creating a case.
- Keep the same
sequenceIdwhen you resend a message, so the call is the same logical message and not a new turn. - For actions with side effects, check the outcome in Salesforce before you retry.
- Limit retries on message sends to two or three.
Cleanup when things fail
Keep the finally block that ends the session. If the session create call fails, there is no session to end. If a message call fails after all retries, still end the session. A 404 on the delete call usually means the session is already gone, so log it and move on.
Exercise
Your service gets a 401 on a message call, refreshes the token, and gets a 401 again. Should it keep refreshing and retrying? Why or why not?
Show answer
No. A second 401 right after a fresh token means the problem is not expiry. Likely causes are a missing OAuth scope, a wrong run-as user, or a token requested from the wrong domain. Retrying loops without fixing it, so raise the error and check the External Client App settings.