Enable Proxy Caching

Uses: Kong Gateway Operator
TL;DR

Apply the proxy-cache plugin using the KongPlugin CRD.

Prerequisites

This page is part of the Get Started with the Kong Gateway Operator series.

Complete the previous page, Apply Rate Limiting before completing this page.

Set up the proxy-cache plugin

Use the KongPlugin CRD to enable proxy caching on a KongService. The following example:

  • Caches 200 OK responses
  • Applies to GET and HEAD requests
  • Targets responses with application/json content type
  • Stores cached data in memory
  • Sets the cache TTL to 300 seconds (5 minutes)
echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: proxy-cache-all-endpoints
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
plugin: proxy-cache
config:
  response_code:
  - 200
  request_method:
  - GET
  - HEAD
  content_type:
  - application/json
  cache_ttl: 300
  strategy: memory
" | kubectl apply -f -

Next, apply the KongPlugin resource by annotating the KongKongservice resource:

kubectl annotate -n kong  service konghq.com/plugins=rate-limiting,proxy-cache-all-endpoints --overwrite

Validation

Send six requests to the same endpoint and inspect the cache status. The first request will miss, but subsequent ones will hit because they are served from the cache.

for _ in {1..6}; do
  curl  -sv $PROXY_IP/anything \
       -H "apikey:example-key" 2>&1 | grep -E "(Status|< HTTP)"
  echo
done


The first request results in X-Cache-Status: Miss. This means that the request is sent to the upstream service. The next four responses return X-Cache-Status: Hit which indicates that the request was served from a cache. If you receive an HTTP 429 from the first request, wait 60 seconds for the rate limit timer to reset.


< HTTP/1.1 200 OK
< X-Cache-Status: Miss

< HTTP/1.1 200 OK
< X-Cache-Status: Hit

< HTTP/1.1 200 OK
< X-Cache-Status: Hit

< HTTP/1.1 200 OK
< X-Cache-Status: Hit

< HTTP/1.1 200 OK
< X-Cache-Status: Hit

< HTTP/1.1 429 Too Many Requests
Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!