Send Docs Feedback

Response Cache policy

  About | Samples | Element reference | Flow variables | Error codes  

What

Caches data from a backend resource, reducing the number of requests to the resource. As apps make requests to the same URI, you can use this policy to return cached responses instead of forwarding those requests to the backend server. The ResponseCache policy can improve your API's performance through reduced latency and network traffic.

You'll likely find ResponseCache most useful when backend data used by your API is updated only periodically. For example, imagine you have an API that exposes weather report data refreshed only every ten minutes. By using ResponseCache to return cached responses between refreshes, you can decrease the number of requests reaching the backend. This also reduces the number of network hops.

Where

The ResponseCache policy type is unique in that it must be attached to both the request and response Flow in an API proxy. See the samples for specific attachment guidance in different situations.

ProxyEndpoint TargetEndpoint
    PreFlow Flow PostFlow PreFlow Flow PostFlow    
Request              
              Response
    PostFlow Flow PreFlow PostFlow Flow PreFlow    

Samples

This sample shows how to have cached responses kept for 10 minutes.

Imagine that you have an API at the following URL:

http://{org_name}-test.apigee.net/weather/forecastrss?w=23424778

You're using the query parameter w as a cache key. Apigee Edge checks the value of the query parameter w whenever a request is received. If a valid (that is, non-expired) response is present in the cache, then the cached response message is returned to the requesting client.

Now imagine that you have a ResponseCache policy configured as follows.

<ResponseCache name="ResponseCache">
    <CacheKey>
        <KeyFragment ref="request.queryparam.w" />
    </CacheKey>
    <ExpirySettings>
        <TimeoutInSec>600</TimeoutInSec>
    </ExpirySettings>
</ResponseCache>

The first time the API proxy receives a request message for the following URL, the response is cached. On the second request within 10 minutes, a cache lookup occurs -- the cached response is returned to the app with no request forwarded to the backend service.

http://{org_name}-test.apigee.net/weather/forecastrss?w=23424778

HTTP headers and query parameters are automatically populated as variables when a request is received. Any HTTP header is available as request.header.{header_name}, for example request.header.user-agent. Any query parameter is available as request.queryparam.{queryparam_name}, for example request.queryparam.action.

The following example shows how to have the cache lookup skipped and have the cache refreshed.

The optional SkipCacheLookup condition (if configured) is evaluated in the request path. If the condition evaluates to true, then the cache look up is skipped and the cache is refreshed.

A common use of conditional cache refresh is a condition that defines a specific HTTP header that causes the condition to evaluate to true. A scripted client application could be configured to periodically submit a request with the appropriate HTTP header, explicitly causing the response cache to refresh.

For example, imagine a call to an API at the following URL:

'http://{org_name}-test.apigee.net/weather/forecastrss?w=23424778' -H "bypass-cache:true"

Now imagine the following ResponseCache policy configured on that proxy. Note that the bypass-cache condition is set to true.

<ResponseCache name="ResponseCache">
    <CacheKey>
        <KeyFragment ref="request.queryparam.w" />
    </CacheKey>
    <!-- Explicitly refresh the cached response -->
    <SkipCacheLookup>request.header.bypass-cache = "true"</SkipCacheLookup>
    <ExpirySettings>
        <TimeoutInSec>600</TimeoutInSec>
    </ExpirySettings>
</ResponseCache>

For more information about conditions, see Create dynamic API flows using conditions.

Element reference

The element reference describes the elements and attributes of the policy.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ResponseCache async="false" continueOnError="false" enabled="true" name="Response-Cache-1">
    <DisplayName>Response Cache 1</DisplayName>
    <FaultRules/>
    <Properties/>
    <CacheKey>
        <Prefix/>
        <KeyFragment ref="request.uri" type="string"/>
    </CacheKey>
    <Scope>Exclusive</Scope>
    <ExpirySettings>
        <ExpiryDate/>
        <TimeOfDay/>
        <TimeoutInSec ref="">300</TimeoutInSec>
    </ExpirySettings>
    <CacheLookupTimeoutInSeconds/>
    <ExcludeErrorResponse/>
    <SkipCacheLookup/>
    <SkipCachePopulation/>
    <UseAcceptHeader/>
    <UseResponseCacheHeaders/>
</ResponseCache>

<ResponseCache> attributes

<ResponseCache async="false" continueOnError="false" enabled="true" name="Response-Cache-1">
Field Name Description Default Presence
async

Set to true to specify that the policy should be run in a thread pool different than the pool servicing the request/response flow. Default is false.

This setting is only used for for internal optimization. 

false Optional
continueOnError

Most policies are expected to return an error when a failure occurs. By setting this attribute to true, Flow execution continues on failure.

false Optional
enabled Determines whether a policy is enforced or not. If set to false, a policy is 'turned off', and not enforced (even though the policy remains attached to a Flow). true Optional
name

The internal name of the policy. This name is referenced in Step elements to attach the policy to a Flow.

Note: Characters you can use in the name are restricted to: A-Z0-9._\-$ %. The Management UI enforces additional restrictions, such as automatically removing characters that are not alphanumeric.

N/A Required

<CacheKey> element

Configures a unique pointer to a piece of data stored in the cache.

You can further augment the cache key configured here by using values from response headers. For more information, see Configuring a cache key.
<CacheKey>
    <Prefix>string</Prefix>
    <KeyFragment ref="variable_name" />
    <KeyFragment>literal_string</KeyFragment>
</CacheKey>

Default:

N/A

Presence:

Required

Type:

N/A

<CacheKey> constructs the name of each piece of data stored in the cache. The key is often set using a value from entity headers or query params. In those cases, you would have the element's ref attribute specify a variable containing the 

At runtime, <KeyFragment> values are prepended with either the <Scope> element value or <Prefix> value. For example, the following results in a cache key of UserToken__apiAccessToken__<value_of_client_id>:

<CacheKey>
    <Prefix>UserToken</Prefix>
    <KeyFragment>apiAccessToken</KeyFragment>
    <KeyFragment ref="request.queryparam.client_id" />
</CacheKey>

You use the <CacheKey> element in conjunction with <Prefix> and <Scope>. For more information, see Working with cache keys.

<CacheLookupTimeoutInSeconds> element

Specifies the number of seconds after which an unsuccessful cache lookup will be considered a cache miss. If this occurs, flow resumes along the cache-miss path.

<CacheLookupTimeoutInSeconds>30</CacheLookupTimeoutInSeconds>

Default:

30

Presence:

Optional

Type:

Integer

<CacheResource> element

Specifies the cache where messages should be stored. Omit this element to use the included shared cache.

<CacheResource>cache_to_use</CacheResource>

Default:

N/A

Presence:

Optional

Type:

String

For more about configuring caches, see Manage environment caches.

<ExcludeErrorResponse> element

Set to true to not cache target responses that are HTTP error status codes; only responses with status codes from 200 to 205 will be cached. Set this to false to cache responses with any status code.

<ExcludeErrorResponse>false</ExcludeErrorResponse>

Default:

true

Presence:

Optional

Type:

Boolean

<ExpirySettings>/<ExpiryDate> element

Specifies the date on which a cache entry should expire. Use the form mm-dd-yyyy. When present, this element's sibling, <TimeoutInSec>, overrides <ExpiryDate>.

<ExpirySettings>
    <ExpiryDate ref="{date_variable}">expiration_date</ExpiryDate>
</ExpirySettings>

Default:

N/A

Presence:

Optional

Type:

String

Attributes

<ExpiryDate ref="" />
Attribute Description Default Presence Type
ref

The variable from which to get the value. Should not be used if this element contains a literal value.

N/A Optional String

<ExpirySettings> element

Specifies when a cache entry should expire. When present, <TimeoutInSec> overrides both <TimeOfDay> and <ExpiryDate>.

<ExpirySettings>
  <TimeOfDay ref="time_variable">expiration_time</TimeOfDay>
  <TimeoutInSec ref="duration_variable">seconds_until_expiration</TimeoutInSec>
  <ExpiryDate ref="date_variable">expiration_date</ExpiryDate>
</ExpirySettings>

Default:

N/A

Presence:

Required

Type:

N/A

<Scope> element

Enumeration used to construct a prefix for a cache key when a <Prefix> element is not provided in the <CacheKey> element.

<Scope>scope_enumeration</Scope>

Default:

"Exclusive"

Presence:

Optional

Type:

String

The <Scope> setting determines a cache key that is prepended according to the <Scope> value. For example, a cache key would take the following form when scope is set to Exclusive : orgName__envName__apiProxyName__deployedRevisionNumber__proxy|TargetName__ [ serializedCacheKey ].

If a <Prefix> element is present in <CacheKey>, it supercedes a <Scope> element value. Valid values include the enumerations below.

You use the <Scope> element in conjunction with <CacheKey> and <Prefix>. For more information, see Working with cache keys.

Acceptable values

Scope Value Description
Global

Cache key is shared across all API proxies deployed in the environment. Cache key is prepended in the form  orgName __ envName __.

If you define a <CacheKey> entry with the <KeyFragment> apiAccessToken and a <Global> scope, each entry is stored as orgName__envName__apiAccessToken, followed by the serialized value of the access token. For an API proxy deployed in an environment called 'test' in an organization called 'apifactory', access tokens would be stored under the following cache key: apifactory__test__apiAccessToken.

Application

API proxy name is used as the prefix.

Cache key is prepended in the form orgName__envName__apiProxyName.

Proxy

ProxyEndpoint configuration is used as the prefix.

Cache key is prepended in the form orgName__envName__apiProxyName__deployedRevisionNumber__proxyEndpointName .

Target

TargetEndpoint configuration is used as the prefix.

Cache key prepended in the form orgName__envName__apiProxyName__deployedRevisionNumber__targetEndpointName .

Exclusive

Default. This is the most specific, and therefore presents minimal risk of namespace collisions within a given cache.

Prefix is one of two forms:

  • If the policy is attached to the ProxyEndpoint flow, prefix is of the form ApiProxyName_ProxyEndpointName.
  • If the policy is attached at TargetEndpoint, prefix is of the form ApiProxyName_TargetName.

Cache key prepended in the form orgName__envName__apiProxyName__deployedRevisionNumber__proxyNameITargetName

For example, the full string might look like this:

apifactory__test__weatherapi__16__default__apiAccessToken
.

<SkipCacheLookup> element

Defines an expression that, if it evaluates to true at runtime, specifies that cache lookup should be skipped and the cache should be refreshed.

<SkipCacheLookup>variable_condition_expression</SkipCacheLookup>

Default:

N/A

Presence:

Optional

Type:

String

From the following example, if the bypass-cache variable is set to true in an incoming header, cache lookup is skipped and the cache is refreshed.

<SkipCacheLookup>request.header.bypass-cache = "true"</SkipCacheLookup>

<SkipCachePopulation> element

Defines an expression that, if it evaluates to true at runtime, specifies that a write to the cache should be skipped.

<SkipCachePopulation>variable_condition_expression</SkipCachePopulation>

Default:

N/A

Presence:

Optional

Type:

String

For example, the following would skip the cache write if the response status code was 400 or higher:

<SkipCachePopulation>response.status.code >= 400</SkipCachePopulation>

<ExpirySettings>/<TimeOfDay> element

The time of day at which a cache entry should expire. Use the form hh:mm:ss . When present, this element's sibling, <TimeoutInSec>, overrides <TimeOfDay>.

<ExpirySettings>
    <TimeOfDay ref="time_variable">expiration_time</TimeOfDay>
</ExpirySettings>

Default:

 

Presence:

Optional

Type:

String

Attributes

Attribute Description Default Presence Type
ref Variable with the expiration time value. N/A Optional String
 

<ExpirySettings>/<TimeoutInSec> element

The number of seconds after which a cache entry should expire. When present, this element overrides its siblings, <TimeOfDay> and <ExpiryDate>.

<ExpirySettings>
    <TimeoutInSec ref="duration_variable">seconds_until_expiration</TimeoutInSec>
</ExpirySettings>

Default:

N/A

Presence:

Optional

Type:

Integer

Attributes

Attribute Description Default Presence Type
ref Variable with the timeout value.
N/A
Optional String

<UseAcceptHeader> element

Set to true to have a reponse cache entry's cache key appended with values from response Accept headers.

Edge uses the Accept, Accept-Encoding, Accept-Language and Accept-Charset request headers when calculating the cache key. This approach prevents a client from getting a media type they did not ask for.

For example, consider if two requests come in from the same URL, where the first request accepts gzip and the second does not. The first request will be cached, and the cached entry will (probably) be a gzipped response. The second request will read the cached value and may then return a gzipped entry to a client that is not capable of reading gzip.

See Configuring a cache key for more.

<UseAcceptHeader>false</UseAcceptHeader>

Default:

false

Presence:

Optional

Type:

Boolean

<UseResponseCacheHeaders> element

Set to true to have HTTP response headers considered when setting the "time to live" (TTL) of the response in the cache. When this is true, Edge considers the values of the following response headers, comparing the values with those set by <ExpirySettings> when setting time to live:

  • Cache-Control s-maxage
  • Cache-Control max-age
  • Expires

See Setting cache entry expiration for more details.

<UseResponseCacheHeaders>false</UseResponseCacheHeaders>

Default:

false

Presence:

Optional

Type:

Boolean

Usage notes

Through configuration in the ResponseCache policy, you can have Edge include HTTP response headers in setting cache entry expiration and cache keys. This section describes you can use the policy with headers to manage cache expiration and cache keys.

For more about how Edge handles response headers with the ResponseCache policy, see Support for HTTP response headers.

For other best practice suggestions related to the ResponseCache policy, see Best practices for API proxy design and development.

Setting cache entry expiration

As with the Populate Cache policy, you can set a response cache entry's expiration (its time to live) using the <ExpirySettings> element. In the ResponseCache policy, you can also have Edge consider response headers when they're present.

To use response headers, you set the <UseResponseCacheHeaders> element value to true. That setting causes Edge to consider the response headers, compare them with the value set by <ExpirySettings>, then use the lowest value between the two. When considering the response headers, Edge chooses the value available as described in the following:

For example, imagine a response is cached with the following values:

  • No Cache-Control s-maxage value
  • A Cache-Control max-age value of 300
  • An Expires date in three days
  • An <ExpirySettings> TimeOutInSec value of 600.

In this case, the Cache-Control max-age value would be used for the TTL because it is lower than the <ExpirySettings> value and because there is no Cache-Control s-maxage value (which takes precedence over max-age).

Configuring a cache key

As with general purpose cache policies such as the Populate Cache policy, with ResponseCache you use <CacheKey> and <Scope> elements to configure cache key creation for cache entries. With ResponseCache you can also make cache keys more meaningful by having response Accept headers appended to key values.

For general information about configuring cache keys, see Working with cache keys. For information about using Accept headers, see <UseAcceptHeader>.

Flow variables

The following predefined Flow variables are populated when a ResponseCache policy is executed. For more information about Flow variables, see Variables reference.

Variables Type Permission Description
responsecache.{policy_name}.cachename String Read-Only Returns the cache used in the policy
responsecache.{policy_name}.cachekey String Read-Only Returns the key used
responsecache.{policy_name}.cachehit Boolean Read-Only True if the policy execution is successful
responsecache.{policy_name}.invalidentry Boolean Read-Only True if the cache entry in not valid

Error codes

Error Code Message
CacheNotFound Cache {0}, not found in organization : {1}
InvalidCacheResourceReference Invalid cache resource reference {0} in Step definition {1}. Context {2}
EntryCannotBeCached Entry {0} can not be cached. Only serializable entries are cached.
CannotDeleteStepDefinition Step definition {0} should be detached before deletion
ResponseCacheStepAttachmentNotAllowedReq Response cache step definition {0} can not be attached more than once in the request path
ResponseCacheStepAttachmentNotAllowedResp Response cache step definition {0} can not be attached more than once in the response path
InvalidTimeout CacheLookupTimeoutInSeconds{0} value should be greater than zero

Schema

Each policy type is defined by an XML schema (.xsd). For reference, policy schemas are available on GitHub.

Help or comments?

  • If something's not working: Ask the Apigee Community or see Apigee Support.
  • If something's wrong with the docs: Click Send Docs Feedback on this page.
    (Incorrect? Unclear? Broken link? Typo?)