Sub topic 13
Building Threshold Alerts
This chapter assumes you have read the earlier chapters. You should know the daily API request limit, the REST Limits resource, and the Sforce-Limit-Info header. You should also be able to read short Python and make HTTP requests. Here you combine those sources into alerts that warn you before an integration stops working.
Why alerts need a design
Reading usage once tells you where you stand. An alert tells you when to act. Without alerts, most teams learn about a limit when REQUEST_LIMIT_EXCEEDED errors start to appear. By then the integration is already failing.
A good alert has four parts:
- A signal: a number you can measure, such as the percent of the daily limit used.
- A threshold: the value at which someone should be told.
- A destination: where the message goes, such as email, chat, or a pager.
- An action: what the person who receives it should do.
If you cannot name the action, the alert will be ignored. Design the action first, then the threshold.
Choosing signals
You have three sources of usage data. They differ in cost and freshness.
| Source | Cost in API calls | Freshness | Best use |
|---|---|---|---|
| REST Limits resource | One call per check | Current at the time of the call | Scheduled polling of many limits |
| `Sforce-Limit-Info` header | None, it rides on calls you already make | Current at the time of each response | Real-time tracking inside an integration |
| Setup notifications | None | Evaluated by Salesforce | Basic email warnings for admins |
The Limits resource counts as an API request itself. Polling it every few seconds wastes the limit you are trying to protect. Polling every 5 to 15 minutes is usually enough for a daily limit.
The header costs nothing. Every integration that already calls Salesforce can record it after each response. This gives you a continuous reading without extra calls.
Setup notifications need no code. They are a good baseline, but they only email people. They cannot post to chat or open a ticket.
The limit is a rolling 24-hour window, so the usage number can fall as old requests age out. Do not assume it only goes up during the day.
Choosing thresholds
A single threshold is rarely enough. Use tiers, each with a different urgency.
| Level | Example threshold | Meaning | Action |
|---|---|---|---|
| Info | 50% used | Usage is on a normal path or higher | Post to a channel, no one is paged |
| Warning | 75% used | Trend may reach the limit | Check which client is the heaviest |
| Critical | 90% used | Limit is likely to be hit soon | Pause non-essential jobs, page on-call |
These numbers are starting points. Tune them to your org. An org with a steady load can use tighter bands. An org with large nightly jobs should expect usage to jump.
Consider the rate, not only the level
A level threshold ignores time. At 3 p.m., 60% used is probably fine. At 9 a.m., 60% used means you will run out before lunch.
Compare two readings to estimate the burn rate:
- Read the usage now.
- Read the usage a fixed interval ago.
- Divide the difference by the interval to get requests per minute.
- Divide the remaining requests by that rate to get minutes until exhaustion.
Alert when the projected time to exhaustion is shorter than the time you need to respond. Because the window rolls, this projection is approximate. Treat it as a warning signal, not a prediction.
Avoid alert noise
Two habits reduce noise:
- Hysteresis: once an alert fires, do not fire again until usage has dropped well below the threshold, for example 5 points lower. Otherwise a value that hovers around 75% sends a message on every check.
- De-duplication: send one message per level crossing, not one per check.
Both require the checker to remember its last state. The example below stores it in a small file.
A diagram of the flow
A working checker
This script polls the Limits resource, picks a level, and sends a message only when the level changes upward. It posts to a webhook URL that you supply, which works with many chat tools. It stores the last level in a file.
import json
import os
import pathlib
import requests
INSTANCE_URL = os.environ["INSTANCE_URL"]
TOKEN = os.environ["ACCESS_TOKEN"]
WEBHOOK_URL = os.environ["ALERT_WEBHOOK_URL"]
STATE_FILE = pathlib.Path("limit_alert_state.json")
# (name, percent used), highest first
LEVELS = [("critical", 90), ("warning", 75), ("info", 50)]
HYSTERESIS = 5 # points below a threshold before the level clears
def get_percent_used():
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"]
return 100 * used / daily["Max"], used, daily["Max"]
def load_level():
if STATE_FILE.exists():
return json.loads(STATE_FILE.read_text()).get("level")
return None
def save_level(level):
STATE_FILE.write_text(json.dumps({"level": level}))
def threshold_of(level):
return dict(LEVELS).get(level, 0)
def classify(percent, previous):
"""Return the current level, applying hysteresis to the previous one."""
for name, limit in LEVELS:
if percent >= limit:
return name
# Below every threshold: keep the previous level until usage
# has dropped HYSTERESIS points under it.
if previous and percent >= threshold_of(previous) - HYSTERESIS:
return previous
return None
def notify(text):
requests.post(WEBHOOK_URL, json={"text": text}, timeout=30).raise_for_status()
def main():
percent, used, maximum = get_percent_used()
previous = load_level()
current = classify(percent, previous)
order = {None: 0, "info": 1, "warning": 2, "critical": 3}
if order[current] > order[previous]:
notify(
f"[{current.upper()}] Salesforce daily API usage at "
f"{percent:.1f}% ({used}/{maximum})"
)
save_level(current)
if __name__ == "__main__":
main()Run it from a scheduler such as cron every 10 minutes. The logic works like this:
classifyreturns the highest level whose threshold is met.- If usage falls below every threshold, the previous level is kept until usage drops 5 points under that level's threshold. This is the hysteresis.
mainnotifies only when the level rises. A drop to a lower level saves the new state but sends nothing, so a later rise alerts again.
Tracking usage from the header
If your integration already calls Salesforce, read the header on each response and avoid the extra poll. Wrap your calls in a small function:
import re
def parse_limit_info(response):
"""Return (used, maximum) from Sforce-Limit-Info, or None if absent."""
header = response.headers.get("Sforce-Limit-Info", "")
match = re.search(r"api-usage=(\d+)/(\d+)", header)
if not match:
return None
return int(match.group(1)), int(match.group(2))Call it after every response and feed the result to the same level logic. The header reflects the state at the time of that response. If many processes share one org, each sees the org-wide figure, so only one of them needs to alert. Pick one owner for the alert, or you will get duplicates.
Alerting on other limits
The daily request limit is the most common alert, but the Limits resource returns many other values. Each is a Max and Remaining pair, so the same code works. Examples include the limits on data storage, file storage, and the daily number of bulk or batch jobs. Names vary by org and API version, so list the keys once and choose the ones that matter to you.
Apex governor limits are different. They reset on every transaction, so a rolling alert does not apply. Instead, log a warning from inside the code when a transaction approaches its ceiling:
Integer used = Limits.getQueries();
Integer max = Limits.getLimitQueries();
if (used > max * 0.8) {
System.debug(LoggingLevel.WARN, 'SOQL queries at ' + used + '/' + max);
}Use this in code paths that have a history of near-misses. It tells you which transaction is heavy before it throws a limit exception.
Common errors in alert design
- Polling too often. Each Limits call costs one request. A checker running every 10 seconds uses 8,640 requests a day. Check how that compares to your limit.
- Alerting only on level. A fast burn from a runaway job can pass 90% within minutes. Add a rate-based rule for this case.
- Sending to a channel no one reads. Route critical alerts to a person or an on-call system.
- Alerting from every process. Without one owner, you get a message per integration for the same event.
- Using a token that expires. The checker needs a valid access token. Use a refresh flow or a dedicated integration user, and alert on authentication failures too. A silent checker looks the same as a healthy org.
- No test. Lower a threshold temporarily and confirm the message arrives.
Responding to an alert
An alert is only useful with a short runbook. For a critical daily API alert, a typical sequence is:
- Open the API usage view in Setup to confirm the number.
- Use the
ApiTotalUsageevent log files to find the heaviest user, connected app, or client. - Pause or throttle non-essential jobs from that client.
- Apply the consumption reductions from the earlier chapter: batch requests, use bulk operations, cache, or move to event-driven designs.
- Review the thresholds afterward. Adjust them if the alert came too late or too often.
Exercise
Your checker polls the Limits resource every 20 seconds and posts a message whenever usage is at or above 75%. Name two problems with this design and a fix for each.
Show answer
First, polling every 20 seconds makes 4,320 Limits calls a day, which consumes the limit you are monitoring. Poll every 5 to 15 minutes, or read the Sforce-Limit-Info header from calls you already make. Second, the checker posts on every run while usage stays above 75%, which floods the channel. Store the last alert level and send a message only when the level rises, and add hysteresis so a value hovering around 75% does not repeat.
Exercise
At 9 a.m. your org has used 40% of its daily limit and an hour ago it had used 25%. Why might a 75% level alert be too late, and what would you add?
Show answer
The usage rose 15 points in one hour. At that rate the remaining 60% lasts about four more hours, so the limit could be reached around 1 p.m. The 75% alert would fire about two hours from now, leaving only about two hours to respond. Add a burn-rate rule that estimates time to exhaustion from two readings and alerts when it falls below your response time.