Enable Caching in Api Gateway

Api Gateway makes it easy to setup caching for the api and therefore to improve performance and reduce load. For example, the api might be calling lambda function which retrieves data from a database. To improve performance for the api, the api can be cached which will store the data and return from the cache and thus eliminating the lambda call.

The cache settings can be set from the stage settings for the api. It is very easy to set it up, simply click on the "Enable API cache" option and choose the minimum settings which will enable caching. It will take a few minutes for the cache to be created. Settings like cache capacity, cache time-to-live (TTL) and whether cache will be encrypted can be set. Additional details like authorisation will be used for cache validation or not can be set.

Note that caching is not free and the cost varies depending on the cache size used. So, use it wisely as needed.

The above method will set caching for all the apis within the stage. The settings for individual api methods can be modified from the stage settings for the api.

On the following screen, cache settings can be altered.

Once the settings are saved, the new settings will be applied to the api.

Caching by Query Strings and Headers

The cache settings can be customised by the query strings and headers for the api. This is useful since the api with Get method can have query strings attached. To set the cache parameters for the query strings and header, open the api method settings page under resources and open the "Method Request" page. On this page, click on URL query strings parameters section and add the query strings and tick if caching should be applied. The same rule applies for headers.

Note that when the settings are changed in this page, the api will need to be deployed for the changes to take effect.

Check if Caching is Working

Whether caching is working or not can be easily checked by checking the logs for the lambda function and checking if the logs are getting updated when the api is called. Another way to check is to check in the metrics section in cloudwatch by adding the CacheHitCount and CacheMissCount metrics.