Rate Limiting

TL;DR

Create a KongPlugin resource containing a rate-limiting configuration. Set config.minute to the number of requests allowed per minute.

Prerequisites

This page is part of the Getting Started with KIC series.

Complete the previous page, Services and Routes before completing this page.

About rate limiting

Rate limiting is used to control the rate of requests sent to an upstream service. It can be used to prevent DoS attacks, limit web scraping, and other forms of overuse. Without rate limiting, clients have unlimited access to your upstream services, which may negatively impact availability.

Kong Gateway imposes rate limits on clients through the Rate Limiting plugin. When rate limiting is enabled, clients are restricted in the number of requests that can be made in a configurable period of time. The plugin supports identifying clients as consumers based on authentication or by the client IP address of the requests.

This tutorial uses the Rate Limiting plugin. The Rate Limiting Advanced plugin is also available. The advanced version provides additional features such as support for the sliding window algorithm and advanced Redis support for greater performance.

Create a rate-limiting KongPlugin

Configuring plugins with Kong Ingress Controller is different compared to how you’d do it with Kong Gateway. Rather than attaching a configuration directly to a service or route, you create a KongPlugin definition and then annotate your Kubernetes resource with the konghq.com/plugins annotation.

echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: rate-limit-5-min
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
plugin: rate-limiting
config:
  minute: 5
  policy: local
" | kubectl apply -f -

Next, apply the KongPlugin resource by annotating the httproute or ingress resource:

Test the rate-limiting plugin

To test the rate-limiting plugin, rapidly send six requests to $PROXY_IP/echo:

for _ in {1..6}; do
  curl  -i $PROXY_IP/echo \
       -H "apikey:example-key" 
  echo
done
for _ in {1..6}; do
  curl  -i $PROXY_IP/echo \
       -H "apikey:example-key" 
  echo
done

On the last request, you should get a 429 response with the message API rate limit exceeded.

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!