Sub topic 8
Tracking usage with the Sforce-Limit-Info header
This chapter assumes you can make authenticated HTTP requests to the Salesforce REST API, you know what the daily API request limit is, and you have read the chapter on the REST Limits resource. You should also be comfortable reading short Python scripts.
What the header is
Every response from the Salesforce REST API and SOAP API carries an HTTP header named Sforce-Limit-Info. It reports how many API requests your org has used in the current 24-hour rolling window and what the maximum is. A typical value looks like this:
Sforce-Limit-Info: api-usage=25/15000The first number is the usage so far. The second number is the daily maximum for the org. In this example, 25 of 15,000 requests have been used.
The header costs nothing extra. You do not make a separate call to get it. It arrives with the data you already asked for, so a client can keep a running count of usage as a side effect of normal work.
Header versus the Limits resource
The REST Limits resource and the header report the same underlying counter for daily API requests, but they suit different jobs.
| Aspect | `/limits` resource | `Sforce-Limit-Info` header |
|---|---|---|
| Extra request needed | Yes, and that request is itself a call | No, it rides on every response |
| Scope of data | Many limits, such as storage, email, and Bulk API | Daily API requests only |
| Best use | Periodic health checks and dashboards | Continuous tracking inside an integration |
| Freshness | At the moment of the call | At the moment of the response |
Use the header when your integration already makes many calls and you want to react quickly. Use the Limits resource when you need limits other than daily API requests.
Format and parsing
The value is a list of name=value pairs. Today the common pair is api-usage=used/max. Some responses can carry more than one pair, separated by commas, and a pair may include per-application details. Write a parser that looks for the pair you want and ignores the rest. Do not split the whole string on = and assume one result.
import re
USAGE_PATTERN = re.compile(r"api-usage=(\d+)/(\d+)")
def parse_limit_info(header_value):
"""Return (used, maximum) from a Sforce-Limit-Info value, or None."""
if not header_value:
return None
match = USAGE_PATTERN.search(header_value)
if not match:
return None
return int(match.group(1)), int(match.group(2))
print(parse_limit_info("api-usage=25/15000"))
print(parse_limit_info("api-usage=25/15000, per-app-api-usage=5/1000"))
print(parse_limit_info(""))The function returns (25, 15000) for the first two inputs and None for the empty string. Returning None instead of raising an error matters, because some responses omit the header. A monitoring feature should never break the call it observes.
Tracking usage on every call
The next step is to wrap your HTTP client so each response updates a shared record. This example uses a requests.Session with a response hook. A hook is a function the library calls after every response.
import os
import requests
USAGE = {"used": None, "max": None}
def parse_limit_info(header_value):
import re
match = re.search(r"api-usage=(\d+)/(\d+)", header_value or "")
return (int(match.group(1)), int(match.group(2))) if match else None
def record_usage(response, *args, **kwargs):
parsed = parse_limit_info(response.headers.get("Sforce-Limit-Info"))
if parsed:
USAGE["used"], USAGE["max"] = parsed
return response
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['ACCESS_TOKEN']}"
session.hooks["response"].append(record_usage)
instance_url = os.environ["INSTANCE_URL"]
query = "SELECT Id, Name FROM Account LIMIT 5"
resp = session.get(
f"{instance_url}/services/data/v60.0/query",
params={"q": query},
timeout=30,
)
resp.raise_for_status()
if USAGE["max"]:
percent = 100 * USAGE["used"] / USAGE["max"]
print(f"Used {USAGE['used']} of {USAGE['max']} ({percent:.1f}%)")Every call made through session now refreshes USAGE. Your own code can read it at any time, for example before it starts a large batch of work.
The diagram below shows the flow.
Acting on the reading
A number is only useful if something responds to it. Three common responses are:
- Log it. Write the used and maximum values with each request ID or job name. Later you can see which job caused a jump.
- Throttle. If usage passes a set share of the maximum, add a delay between calls or defer non-urgent work.
- Alert. Send a message to a person or a monitoring system when usage crosses a threshold. The chapter on threshold alerts covers designing these.
Here is a small guard that combines the second and third:
import time
def check_budget(used, maximum, warn=0.80, stop=0.95):
"""Return 'ok', 'warn', or 'stop' based on the share of the limit used."""
share = used / maximum
if share >= stop:
return "stop"
if share >= warn:
return "warn"
return "ok"
def run_job(items, process, used_max):
for item in items:
status = check_budget(*used_max())
if status == "stop":
print("Stopping: daily API budget nearly exhausted")
return
if status == "warn":
time.sleep(1) # slow the pace while usage is high
process(item)Here used_max is a function that returns the latest (used, maximum) pair, such as one that reads the USAGE dictionary from the previous example. The stop threshold leaves a margin. That margin protects other integrations and users in the same org, which draw from the same pool.
Edge cases and gotchas
- The count is for the whole org. The header shows org-wide usage, not usage by your integration. A rising number may come from another app, a user, or a scheduled job. Use Event Monitoring to find the source.
- The value can lag or jump. Your client sees the counter as of each response. Other clients are adding to it at the same time, so two responses a moment apart may differ by more than your own calls.
- Not every call counts the same way. Some requests, such as certain authentication calls, do not increase the daily total. Do not try to predict the counter from your own call count. Read it.
- The header may be absent. Error responses from a gateway, redirects, or calls to some endpoints can lack the header. Handle
Noneand keep the last good reading. - The window is rolling. The usage figure covers the past 24 hours, not a calendar day. Usage falls as old calls age out, not at midnight.
- Compare against the right maximum. Read the maximum from the header instead of hard-coding 15,000. The maximum depends on edition, licenses, and add-ons, and it can change.
- Browser clients may not see it. In browser code, cross-origin rules can hide response headers unless the server exposes them. A server-side proxy is a safer place to collect the value.
Reading the header from the command line
For a quick check without writing code, ask curl to print response headers. The -D - option writes headers to standard output, and -o /dev/null discards the body.
curl -s -D - -o /dev/null \
-H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/query?q=SELECT+Id+FROM+Account+LIMIT+1" \
| grep -i '^sforce-limit-info'This is a handy way to confirm the header is present for a new integration user or a new endpoint. Note that this check is itself an API call and adds one to the count.
Choosing between sources
Pick the tool by the question you are asking.
| Question | Best source |
|---|---|
| How close is this integration to the limit right now? | `Sforce-Limit-Info` header |
| How much of storage, email, or Bulk API capacity is left? | REST Limits resource |
| Who or what is using the calls? | Event Monitoring `ApiTotalUsage` logs |
| Should an admin be warned by email? | Setup API usage notifications |
The header works best as the always-on, low-cost signal inside your own client. The other sources fill in the details that the header cannot give you.
Exercise
Your integration reads Sforce-Limit-Info and sees "api-usage=12000/15000". You stop all calls at 80 percent. Should the integration stop, and why might you also want to look at Event Monitoring?
Show answer
Yes. 12000 / 15000 is 80 percent, so the guard at 80 percent triggers. The header shows org-wide usage, not just your integration's share, so Event Monitoring ApiTotalUsage logs help you find which users, connected apps, or clients made the calls.
Exercise
A response arrives without a Sforce-Limit-Info header. What should a well-written parser do, and why?
Show answer
Return None (or skip the update) and keep the last known reading. Raising an error would let a monitoring feature break the real API call, and some responses legitimately lack the header.