# How can developers implement custom rate limiting and throttling inside Apex REST web service endpoints?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Rate Limiting, Apex REST Throttling

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Identify the caller (running user, connected app, or an API key header).
2. Build a window key (for example callerId plus the current minute).
3. Increment a counter in Platform Cache (Org cache with a TTL equal to the window).
4. 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:**
```apex
@RestResource(urlMapping='/orders/v1/*')
global with sharing class OrderApi {
    private static final Integer LIMIT_PER_MIN = 60;
    @HttpPost
    global static void create() {
        RestResponse res = RestContext.response;
        String key = 'rl' + UserInfo.getUserId() + String.valueOf(Datetime.now().getTime() / 60000);
        Cache.OrgPartition part = Cache.Org.getPartition('local.RateLimit');
        Integer count = (Integer) part.get(key);
        count = (count == null) ? 1 : count + 1;
        part.put(key, count, 120);              // TTL seconds
        if (count > LIMIT_PER_MIN) {
            res.statusCode = 429; res.addHeader('Retry-After', '60');
            res.responseBody = Blob.valueOf('{"error":"rate_limited"}');
            return;
        }
        // ... process request
    }
}
```

**Hidden gotchas & must-remember points:**
- Platform Cache counters are not atomic, so limits are approximate.
- Platform Cache needs allocated capacity or put calls fail; handle exceptions and fail open.
- Salesforce's own limit error is 403 REQUEST_LIMIT_EXCEEDED, not 429.
- Concurrent long-running API request limits apply separately.
- Per-user keys misbehave when many clients share one integration user; use a client identifier.
- Gateway enforcement is stronger than in-org code.

**Best practice:** Put coarse limits at a gateway and use in-org counters only as a backstop, always with Retry-After.

---
Source: ForceChallenges · last updated 2026-11-02
