Sub topic 13
Building Threshold Alerts
This chapter assumes you can call the REST Limits resource, read the Sforce-Limit-Info header, and handle REQUEST_LIMIT_EXCEEDED errors, all covered in earlier chapters. Here you combine those signals into alerts that warn you before an integration stops working.
Why alerts need thresholds
The daily API request limit is a rolling 24-hour count. If you only learn about it from a REQUEST_LIMIT_EXCEEDED error, the integration is already failing. A threshold alert fires while there is still headroom, so someone can pause a job or raise the limit before calls are rejected.
A good alert answers three questions:
- What is measured? For example, percent of
DailyApiRequestsused. - When does it fire? One or more thresholds, such as 70%, 85% and 95%.
- Who acts, and how? A named owner and a channel, such as chat or email.
Choosing the signal
Each source you have already met fits a different job.
| Signal | Best for | Cost |
|---|---|---|
| Sforce-Limit-Info header | Free, per-call tracking inside the integration | None. It arrives on calls you already make |
| REST Limits resource | Scheduled checks and checks of other limits | One API call per check |
| Setup API usage notifications | Email warnings to admins at a set percentage | None, but limited to email |
| ApiTotalUsage event logs | Finding who caused the spike, after the alert | Needs Event Monitoring access |
Use the header for the integration you own. Use a scheduled Limits check for a view of the whole org, because other integrations also spend the same limit.
Setting tiered thresholds
Use more than one level, and give each level a different response.
| Used | Level | Typical response |
|---|---|---|
| 70% | Warning | Post to a team channel. No action required |
| 85% | High | Notify the owner. Review recent callers |
| 95% | Critical | Page on-call. Pause non-essential jobs |
Pick percentages from your own usage pattern. If a nightly sync normally uses 60% of the limit, a 70% alert fires every night and people will learn to ignore it.
A working checker
The script below reads the Limits resource, picks the highest threshold that has been crossed, and prints an alert. Replace send_alert with a call to your chat or email service.
import os
import requests
THRESHOLDS = [(95, "CRITICAL"), (85, "HIGH"), (70, "WARNING")]
def send_alert(level, message):
# Replace with a webhook, email, or paging call.
print(f"[{level}] {message}")
def check_daily_api_usage():
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
resp = requests.get(
f"{instance_url}/services/data/v60.0/limits",
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
resp.raise_for_status()
daily = resp.json()["DailyApiRequests"]
used = daily["Max"] - daily["Remaining"]
percent = 100 * used / daily["Max"]
for threshold, level in THRESHOLDS:
if percent >= threshold:
send_alert(
level,
f"Daily API usage at {percent:.1f}% ({used}/{daily['Max']})",
)
return level
return None
if __name__ == "__main__":
check_daily_api_usage()Run it on a schedule, for example every 10 minutes from cron or a scheduled cloud job. The check itself costs one API call per run, which is small compared with a 15,000 or larger daily limit.
Avoiding alert fatigue
An alert that fires every 10 minutes while usage stays above 85% is noise. Add these rules:
- Alert on a change of level. Store the last level sent and notify only when it rises, or when usage drops back below the lowest threshold.
- Add a cooldown. For example, repeat the same level no more than once every few hours.
- Include context in the message: percent used, remaining calls, and a link to the runbook or the Event Monitoring query for finding the caller.
- Alert on the rate too. A jump from 20% to 60% within an hour can be more urgent than a slow climb to 70%.
Remember that the limit is rolling, so usage falls as old calls age out of the 24-hour window. Do not assume the count resets at midnight.
The alert flow
Common mistakes
- Alerting only at 100%. By then calls are already failing.
- Using one threshold for every org. A sandbox and production have different limits and different tolerance.
- Letting the monitoring script hit the limit itself. Keep checks infrequent and handle errors from the check, so the alert system fails loudly instead of silently.
- Forgetting other limits. Concurrent request limits and per-transaction governor limits need their own monitoring, such as logging
Limitsvalues in Apex.
Exercise
Your nightly sync uses about 65% of the daily API limit every night. You set alerts at 60%, 80%, and 95%, and the team now ignores the 60% alert. What would you change, and what extra rule would stop repeated messages while usage stays high?
Show answer
Move the lowest threshold above the normal baseline, for example to 75% or 80%, so the alert fires only on unusual usage. Then add alert-on-change logic with a cooldown. Store the last level sent, notify only when the level rises, and repeat the same level no more than once every few hours.
Exercise
Why should an org-wide threshold alert link to Event Monitoring or Setup usage pages?
Show answer
The Limits resource shows how much of the limit is used, but not who used it. The ApiTotalUsage logs and Setup pages show users, connected apps, and clients, so the responder can find the cause.