Was this helpful?

Apigee Edge exposes a Cache resource that can be used by API proxies to persist data across transactions.

There are three main reasons for using a Cache:

  • To reduce latency: The request is satisfied from the cache (which is closer to the client) instead of the origin server, so the cache gets the representation and displays it in a shorter time. This makes the server more responsive.
  • To reduce network traffic: Representations are reused, so the impact of processing duplicate or redundant requests is reduced. Cache reduces the amount of bandwidth you use, which decreases bandwidth requirements overall.
  • To persist data across transactions: Session data can be stored for reuse across HTTP transactions.

For guidance on which type of cache or persistence to use in different situations, see Persistence.

The sample policies in this reference are based on the Outbound OAuth sample proxy in on Github (see Samples reference). This sample uses the Cache policy to store an OAuth access token for re-use across multiple outbound calls.

The ResponseCache policy uses a dedicated cache that is different and isolated from the Cache resources you configure using the APIs and policies described here. For more information on response caching, see Reduce latency using ResponseCache.

Cache resources

You can create multiple Cache resources in each environment. For data segregation, the scope of a Cache is limited to an environment in which the Cache is created. (For example, API proxies running in a 'test' environment cannot access data in a Cache running in 'prod'.) Once the Cache is created, it can be populated with any serializable data by using Cache policies.

After creating a Cache, configure it only when you need to customize the Cache settings to optimize performance. Create a Cache using the Management UI or by using the API calls documented below.

If you have questions about your Cache resource configuration, contact Apigee Support.

Manage Caches using the API Platform API

Create a Cache

Use the Apigee Edge management API to create a Cache resource. Caches are created per environment. For data segregation, a Cache created in 'test', for example, cannot be accessed by API proxies deployed in 'prod'.

For example:

$ curl -H "Content-type:text/xml" -X POST -d \
'<Cache name="test-cache">
  <Description>A Cache resource for the test environment.</Description>
  <MaxElementsInMemory>100</MaxElementsInMemory>
  <ExpirySettings>
	<TimeoutInSec>300</TimeoutInSec>
  </ExpirySettings>
  <Compression>
	<MinimumSizeInKB>1024</MinimumSizeInKB>
  </Compression>
</Cache>' \
https://api.enterprise.apigee.com/v1/o/{org_name}/environments/test/caches \
-u myname:mypass

Configure a Cache resource

You can configure a Cache resource using the following elements.

Field Name Description
Description Description of the Cache resource.
MaxElementsInMemory Maximum number of Cache entries allowed in memory. Upon reaching the maximum limit, entries are discarded using Least Recently Used (LRU) algorithm.
ExpirySettings TimeoutInSec Duration (in seconds, ss) to live for each Cache entry.
TimeOfDay A specific time of day formatted as hh:mm:ss when all Cache entries will expire.
ExpiryDate A specific date formatted as mm-dd-yyyy when all Cache entries will expire.
Compression MinimumSizeInKB Optional. If specified, all entries larger than the size specified are compressed when stored to disk.

Update a Cache

To modify the Cache resource created above, issue a complete payload POST request to the same URI as above, except include the name of the Cache resource as a URI parameter

$ curl -H "content-type:text/xml" -X POST -d \
'<Cache name="test-cache">
	<Description>Updating the Cache.</Description>
	<MaxElementsInMemory>100</MaxElementsInMemory>
	<Persistent>false</Persistent>
	<ExpirySettings>
	  <TimeoutInSec>300</TimeoutInSec>
	</ExpirySettings>
        <Compression>
	  <MinimumSizeInKB>1024</MinimumSizeInKB>
	</Compression>
</Cache>' \
https://api.enterprise.apigee.com/v1/o/{org_name}/environments/test/caches/{cache_name} \
-u myname:mypass

Delete a Cache

To delete the Cache resource created above, use the DELETE verb:

$ curl -X DELETE \ 
https://api.enterprise.apigee.com/v1/o/{org_name}/environments/test/caches/{cache_name} \
-u myname:mypass

View Cache configuration

$ curl https://api.enterprise.apigee.com/v1/o/{org_name}/environments/test/caches/{cache_name} \
-u myname:mypass

Access the Cache at runtime

One reason why you may need to use the Cache resource is when you have OAuth access tokens that are used for outbound calls from Apigee Edge to protected backend services. Without a Cache in which to store the OAuth access token, the application would have to get a new access token for each request, which would not be efficient.

In the following example, an OAuth access token is written to the Cache using a PopulateCache policy. The OAuth token is retrieved for subsequent requests by a LookupCache policy. Once the access token expires, JavaScript is used to retrieve a new access token, which is in turn cached by the PopulateCache policy.

PopulateCache

The PopulateCache policy type enables you to write data to the Cache. In this example application an OAuth access token is written to the Cache.

The PopulateCache policy below writes the value of the source to the Cache resource named mycache. The source in this case is a custom variable named twitter-translate.apiAccessToken.

(Variables can be populated by policies or by code. The source variable in this example is populated by the following JavaScript call: context.setVariable('twitter-translate.apiAccessToken', getAccessToken());)

The policy also defines a CacheKey, which consists of one or more KeyFragments. The CacheKey is used as a reference by the LookupCache policy to retrieve the value of the access token. (See Working with CacheKeys.)

<PopulateCache name="token-cache">
    <CacheResource>mycache</CacheResource>
    <Source>twitter-translate.apiAccessToken</Source>
    <Scope>Exclusive</Scope>
    <CacheKey>
        <KeyFragment>apiAccessToken</KeyFragment>
    </CacheKey>
    <ExpirySettings>
        <TimeoutInSec>600</TimeoutInSec>
    </ExpirySettings>
</PopulateCache>

Configure the PopulateCache policy

Configure the PopulateCache policy using the following elements.

Field Name Description
CacheResource Specifies the Cache resource to be used.
Source Writes specified information from the source to the Cache.
Scope

Used to create a namespace for data in the Cache. Scope defines the default prefix for the CacheKey created by this policy. Scope is used to construct the CacheKey Prefix, when an explicit Prefix element is not defined for a CacheKey. If Prefix is provided, then Prefix overrides Scope.

Supported settings are Global, Application, Proxy, Target, Exclusive.

See Working with CacheKeys.

CacheKey Prefix
Used to create a namespace for data in the Cache. CacheKey is used by LookupCache policy to reference Cached data. The structure of a CacheKey is {Scope/Prefix}__{KeyFragment}__{KeyFragment}__{KeyFragment} . . .

You can define as many KeyFragments as needed to prevent namespace collisions in your cached data.

If defined, the value of Prefix used as the prefix value of the CacheKey for entries written to the Cache. Prefix overrides Scope elements.
KeyFragment
A KeyFragment can either contain a key (a static name that you provide) or a value (a dynamic entry set by referencing a variable).
 
KeyFragment elements are prepended with Prefix and concatenated to define the CacheKey. For example, where Prefix is set to UserToken), and 2 KeyFragments are defined as follows:
<CacheKey>
  <Prefix>UserToken</Prefix>
  <KeyFragment>apiAccessToken</KeyFragment>
  <KeyFragment>{request.queryparam.client_id}</KeyFragment>
</CacheKey>

The result is a CacheKey of UserToken__apiAccessToken__{value_of_client_id}.

See Working with CacheKeys.

ExpirySettings TimeoutInSeconds Duration (in seconds) to live for the cached entry.
TimeOfDay A specific time (hh:mm:ss) of day.
ExpiryDate Specify the date (mm-dd-yyyy).

LookupCache

Once values are populated in the Cache, a corresponding LookupCache policy can be configured to retrieve cached data at runtime. The following LookupCache policy reads from the Cache resource named test-cache and writes the value to the variable twitter-translate.apiAccessToken.

<LookupCache name="token-cache">
    <CacheResource>mycache</CacheResource>
    <AssignTo>twitter-translate.apiAccessToken</AssignTo>
    <Scope>Exclusive</Scope>
    <CacheKey>
        <KeyFragment>apiAccessToken</KeyFragment>
    </CacheKey>
</LookupCache>

Configure the LookupCache policy

Configure the LookupCache policy using the following elements.

Field Name Description
CacheResource Specifies the Cache resource to be used.
AssignTo Specifies the variable where the Cache entry is assigned after it has been retrieved from the Cache. Note that the variable must have write permissions.
Scope

Used to construct the Prefix for a CacheKey, when a Prefix is not provided in CacheKey. If a Prefix element is present in CacheKey, it supersedes any defined Scope.

Supported settings are Global, Application, Proxy, Target, Exclusive.

See Working with CacheKeys.

CacheKey Prefix
Used to create a namespace for matching requests to the cached responses.
 
If defined, the value of Prefix used as the prefix value of the CacheKey for entries written to the Cache. Any Prefix element that is defined overrides Scope settings.
 
 
KeyFragment
KeyFragment can either contain a key (a static name that you provide) or a value (a dynamic entry set by referencing a variable).
 
KeyFragment elements are prepended with Prefix and concatenated to define the CacheKey. For example, where Prefix is set to UserToken), and 2 KeyFragments are defined as follows:
<CacheKey>
  <Prefix>UserToken</Prefix>
  <KeyFragment>apiAccessToken</KeyFragment>
  <KeyFragment>request.queryparam.client_id</KeyFragment>
</CacheKey>

The result is a CacheKey of UserToken__apiAccessToken__{value_of_client_id}.

See Working with CacheKeys.

InvalidateCache

The Cache resource can be invalidated explicitly by specifying an HTTP header. When a request that contains the specified HTTP header is received, the Cache is flushed.

<InvalidateCache name="InvalidateMyCache">
    <CacheResource>test-cache</CacheResource>
    <Scope>Exclusive</Scope>
    <CacheKey>
         <Prefix>apiAccessToken</Prefix>
        <KeyFragment ref="request.header.invalidate_cache" />
    </CacheKey>
    <PurgeChildEntries>true</PurgeChildEntries>
</InvalidateCache>

Configure the InvalidateCache policy

Configure the InvalidateCache policy using the following elements.

Field Name Description
CacheResource (Mandatory) Specifies the cache resource to be used.
Scope (Optional)

Used to construct the prefix, when Prefix in CacheKey is not explicitly defined. If a CacheKey Prefix is defined, then Scope is ignored.

Allowed values are Global, Application, Proxy, Target, and Exclusive.

See Working with CacheKeys.

CacheContext (Optional) APIProxyName

 Used to construct the CacheKey. Values for APIProxyName, ProxyName and TargetName are mandatory in the following cases:

When a CacheKey Prefix (that is, a custom prefix) is not used
To clear cache entries added by another API proxy

See Working with CacheKeys.

ProxyName
TargetName
CacheKey (Optional) Prefix
Used to create a namespace for matching requests to the cached responses.
 
If defined, the value of Prefix  is used as the prefix value of the CacheKey for entries written to the Cache. Any Prefix element that is defined overrides  any Scope settings that may be present.
 
 
KeyFragment
KeyFragment can either contain a key (a static name that you provide) or a value (a dynamic entry set by referencing a variable).
 
KeyFragment elements are prepended with Prefix and concatenated to define the CacheKey. For example, where Prefix is set to UserToken), and 2 KeyFragments are defined as follows:
<CacheKey>
  <Prefix>UserToken</Prefix>
  <KeyFragment>apiAccessToken</KeyFragment>
  <KeyFragment>request.queryparam.client_id</KeyFragment>
</CacheKey>

The result is a CacheKey of UserToken__apiAccessToken__{value_of_client_id}.

 
 
PurgeChildEntries (Optional) Valid values: true/false
Default value: false

Working with CacheKeys

CacheKeys can be used to control how your data is stored in the Cache. A CacheKey is a unique pointer to a piece of data stored in the Cache. As such, the CacheKey constructs the name of each piece of data stored in the Cache. The CacheKey you define in the PopulateCache policy is the name that you use in the LookupCache policy to get the specific entry that you need from the Cache.

A very simple example of a CacheKey is the following:

<CacheKey>
  <KeyFragment>hello</KeyFragment>
  <KeyFragment>world</KeyFragment>
<CacheKey>

The configuration above creates a CacheKey of hello__world.

If the API proxy is deployed in an organization called 'apigee' and deployed in the environment named 'prod', the Scope will be apigee__prod__.

The string value of the CacheKey is a list of KeyFragment values separated by two underscores: hello__world. Combine the KeyFragment and the Scope to derive the CacheKey: apigee__prod__hello__world.

To use the same CacheKey in different environments, without risking conflicts, you can use the Global Scope. Returning to the example above, the final values for the default environments 'test' and 'prod' would be apigee__test__hello__world and apigee__prod__hello__world, respectively. The CacheKey configuration is the same, but the key refers to different entries depending on the environment. Once the CacheKey has been combined with the Scope, the final value is not a CacheKey, but rather is an unambiguous identifier for that CacheKey/Scope combination.

The Scope element is designed to be used as a default Prefix for CacheKeys. Scopes can be defined with increasing specificity from Global to Exclusive.

A Global scope generalizes a Cache entry across an environment in an organization. Each Cache entry with a Global scope is prefixed with orgName__envName__. Therefore, 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 CacheKey: apifactory__test__apiAccessToken.

An Exclusive Scope is the most specific, and therefore presents minimal risk of namespace collisions within a given Cache. Each Cache entry with an Exclusive scope is prefixed with orgName__envName__apiProxyName__deployedRevisionNumber__proxyOrTargetName__[serializedCacheKey]. A sample CacheKey using Exclusive Scope would look like the following: apifactory__test__weatherapi__16__default__apiAccessToken.

  • Global: CacheKey prepended with orgName__envName__
  • APIProxy: CacheKey prepended orgName__envName__apiProxyName
  • deployedRevisionNumber: CacheKey prepended with orgName__envName__apiProxyName__deployedRevisionNumber
  • Proxy: Cache key prepended with orgName__envName__apiProxyName__deployedRevisionNumber__proxyEndpointName
  • Target: Cache key prepended with orgName__envName__apiProxyName__deployedRevisionNumber__targetEndpointName
  • Exclusive: Cache key prepended with orgName__envName__apiProxyName__deployedRevisionNumber__proxyOrTargetName__[serializedCacheKey], where serializedCacheKey is composed of KeyFragment elements, separated by __ (two underscores).

You can have multiple KeyFragments that can either have an explicit value (for example, apiAccessToken) or that use the value of a context variable.

To include a variable in the Cache Key, identify the variable as a reference in the KeyFragment. For example, to make the CacheKey unique to the Content-Type of the request message, you could set <KeyFragment ref="request.header.Content-Type"/>, which defines a KeyFragment as the value of the context variable request.header.Content-Type.

For example, in the configuration below, the request.header.Content-Type variable has the value application/json.

<CacheKey>
  <KeyFragment>apiAccessToken</KeyFragment>
  <KeyFragment ref="request.header.Content-Type" />
  <KeyFragment>bar</KeyFragment>
</CacheKey>

The result a CacheKey of {Scope}__apiAccessToken__application/json__bar.

If you require an explicit namespace, then use Prefix instead of Scope. Prefix overrides any Scope settings. The Lookup Cache policy that retrieves data from the Cache must refer to the specific Prefix and KeyFragment structure to retrieve data from the Cache.

Cache Flow variables

Flow variables can be used to configure dynamic runtime behavior for policies and flows, based on HTTP headers or message content, or the context available in the Flow. For more information about flow variables, see Variables reference.

The following predefined Flow variables are available after you customize the behavior of the Cache you define in a LookupCache policy.

Variables Type Permission Description
lookupcache.<policy-name>.cachename String Read-Only Returns the cache name used in the policy.
lookupcache.<policy-name>.cachekey String Read-Only Returns the key used.
lookupcache.<policy-name>.cachehit Boolean Read-Only True if the policy execution is successful.
lookupcache.<policy-name>.assignto String Read-Only Returns the variable to which cache is assigned.

Policy-specific 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
InvalidTimeout CacheLookupTimeoutInSeconds {0} value should be greater than zero

Policy schema

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

コメントを追加

Provide your email address if you wish to be contacted offline about your comment.
We will not display your email address as part of your comment.

We'd love your feedback and perspective! Please be as specific as possible.
Type the characters you see in this picture. (verify using audio)

Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.