GET Request Caching

Caching is one of the fundamental principles of REST APIs. Being cache-able is actually one of the six architectural constraints of REST APIs. APIs that use the GET method are usually cache-able by default unless specified otherwise. POST requests are usually not cache-able unless specified otherwise.

Restful integrations with Salesforce follow the same design guidelines. In this post we will specifically examine the behavior of the client and server for a system where Salesforce is set to be the client and consumes REST APIs provided by a different server.

POST requests are not cache-able by default. And most Salesforce use cases should fall under the same criteria because POST methods are usually utilized for sending updated data to the API server.

GET requests are cache-able by default. Browsers and most modern client applications cache the responses of GET requests automatically. To change the behavior this automatic caching, Cache-Control headers must be set accordingly. A reference to the allowed values can be found here.

Caching of HTTP Get requests

When Salesforce calls requests data using the GET method using Apex, Salesforce will automatically use cached responses from the GET endpoint until the default cached response has expired. This can be extremely hard for Salesforce administrators and developers to debug because looking through the debug logs will make it seem that an API request was made and a response was received from the server. However, that is absolutely not the case because in reality Salesforce debug logs are displaying the results of the cached API call.

This behavior can be verified by examining the logs on the API server. For example, test by invoking the GET request from the Developer Console five times in quick succession. With no customization to the cache-control headers for the GET API, the API server should only have received the request once. Salesforce logs will show successful response all five times, while the API server will only show one successful API request.

Real world Salesforce use cases can demand different behavior. Sometimes users may request retrieval of fresh data from their back-end system or a different third-party application. To allow this functionality, developers must set the Cache-Control headers for the response to let Salesforce expire the API response as frequently as desired.

Comments