Today, I want to discuss the ResponseCache policy.
The ResponseCache policy allows API publishers to add caching to any backend system. This simple capability is really powerful and can help you offload over-burdened backend systems, or more importantly improve response times for snappier front-end performance.
But it’s important to use this tool in the right way. The HTTP Spec says that caches in HTTP servers should be used to satisfy only GET or HEAD verbs. This means a system should never return a cached result for a POST or a PUT or a DELETE, for example. But out of the box, the ResponseCache in Apigee Edge allows you to cache anything.
What if you don’t want to return cached responses for POSTs or PUTs?
It’s a simple matter of configuration.
Let’s have a look at the policy. In the Administrative Portal for Apigee Edge, if you drag-and-drop a ResponseCache policy into an API Proxy, currently you get a configuration that looks like this:
<ResponseCache name="Response-Cache-1">
<DisplayName>Response Cache-1</DisplayName>
<Properties/>
<CacheKey>
<Prefix/>
<KeyFragment ref="request.uri" type="string"/>
</CacheKey>
<Scope>Exclusive</Scope>
<ExpirySettings>
<ExpiryDate/>
<TimeOfDay/>
<TimeoutInSec ref="">3600</TimeoutInSec>
</ExpirySettings>
<SkipCacheLookup/>
<SkipCachePopulation/>
</ResponseCache>
Notice that the SkipCacheLookup and SkipCachePopulate elements are present but empty. What this means is that the cache gets populated and served, for any request, with any verb.
To make sure the cache gets populated and served only for GET or HEAD, you can make a simple change to the configuration, like this:
<ResponseCache name="Response-Cache-1">
<DisplayName>Response Cache-1</DisplayName>
<Properties/>
<CacheKey>
<Prefix/>
<KeyFragment ref="request.uri" type="string"/>
</CacheKey>
<Scope>Exclusive</Scope>
<ExpirySettings>
<ExpiryDate/>
<TimeOfDay/>
<TimeoutInSec ref="">3600</TimeoutInSec>
</ExpirySettings>
<SkipCacheLookup>NOT (request.verb ~~ \"(GET|HEAD)\")</SkipCacheLookup>
<SkipCachePopulation>NOT (request.verb ~~ \"(GET|HEAD)\")</SkipCachePopulation>
</ResponseCache>
You can make other changes to this configuration, to set the cache key to include query parameters, or to respect the Accept headers. Read the doc to find out more.
And, here’s a video explaining and showing what I just wrote above.
