How can developers implement custom rate limiting and throttling inside Apex REST web service endpoints?
Answer
Basics: Platform API limits (daily API requests, concurrent long-running requests) protect the org globally, but one noisy client can still exhaust them. Rate limiting means counting each caller's requests in a time window and rejecting extras with 429 Too Many Requests and a Retry-After header.
How it works:
- Identify the caller (running user, connected app, or an API key header).
- Build a window key (for example callerId plus the current minute).
- Increment a counter in Platform Cache (Org cache with a TTL equal to the window).
- If the count exceeds the threshold, set RestContext.response.statusCode = 429 and add Retry-After; otherwise continue.
Advanced / deep dive: Platform Cache is fast but its read-modify-write is not atomic, so under concurrency counts are approximate (allow some overshoot), and cache can be evicted, so fail open. Platform Cache requires allocated capacity; Enterprise Edition has none by default and Unlimited/Performance include a small amount (verify). A custom object counter is durable but costs DML and causes row-lock contention on hot rows. Each Apex REST request is its own transaction, so you cannot batch counters. Fixed windows allow bursts at boundaries; token-bucket or sliding window gives smoother control but needs more state. Real enforcement belongs at an API gateway (MuleSoft API Manager rate-limit policies, Azure/Kong), which also protects Salesforce from load. Salesforce itself returns 403 REQUEST_LIMIT_EXCEEDED for platform limits, not 429, so clients must handle both.
Code / config example:
@RestResource(urlMapping='/orders/v1/*')
global with sharing class OrderApi {
;
global {
RestContext.response;
+ UserInfo.getUserId() + String.valueOf(Datetime.now().getTime() / );
Cache. Cache.Org.getPartition();
(Integer) part.get(key);
count = (count == ) ? : count + ;
part.put(key, count, );
(count > LIMIT_PER_MIN) {
res.statusCode = ; res.addHeader(, );
res.responseBody = Blob.valueOf();
;
}
}
}