AlgoViz

Kong

medium 27 min

Kong Gateway is an API gateway built on NGINX and Lua.

Video lesson · Chapter 1 of 5

One order crosses the gateway

0:00 / 4:04

Kong in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Kong Gateway is a proxy for APIs. It matches each request to a route, runs the plugins attached to it, and passes it to a service. The documentation calls it a Lua application that loads and runs modules; underneath are NGINX and OpenResty, which add Lua to NGINX.

The difference from a plain proxy is the model. Kong knows consumers (who is calling), credentials, permissions and limits per consumer, and all of it can be changed through an API or a declarative file while it runs.

Kong Inc. sells an Enterprise edition of the gateway and Konnect, a hosted control plane. This page says which parts belong to which.

Why it exists

Ten services that each check keys, count requests, log, and answer browsers' CORS questions contain the same code ten times, in several languages and with ten different mistakes.

An API gateway does this once at the door. Kong's answer to "but every company needs something different" is the plugin: a small module with hooks at fixed moments of a request, switched on per route, service or consumer.

A short history

  1. April 2015

    Version 0.2.0-2 is listed in the change log. The GitHub repository dates from November 2014.

  2. December 2018

    Version 1.0.0.

  3. March 2019

    Version 1.1.0 adds declarative configuration and DB-less mode.

  4. January 2020

    Version 2.0.0 adds hybrid mode and Go plugins, and removes its service mesh feature in favour of Kuma.

  5. September 2022

    Version 3.0.0 brings a new router written in Rust and tracing for OpenTelemetry.

  6. March 2025

    Enterprise 3.10: free mode ends. Without a licence it behaves like an expired one.

  7. November 2026

    Version 3.9.5 patches the open source line, which stays at 3.9. Enterprise is at 3.16.

Words to know

Service
One API behind the gateway: an address plus timeouts and retries.
Route
A rule (host, path, method, header) that sends requests to a service.
Consumer
A user or application that calls the APIs. Credentials belong to it.
Plugin
A module that runs at fixed phases of a request.
Upstream and target
A virtual host with several addresses to balance over.
Data plane
Kong nodes that carry traffic.
Control plane
Kong nodes that hold the configuration and the Admin API.
decK
Kong's command line tool that compares a file with a running gateway and applies the difference.

How it works

Step through the idea, or press Play.

Step 1 of 3

Match. The router finds the route with the highest priority

Understand it

Start here

The gangway of inspectors

Imagine a ship. Everybody who wants to come on board walks over one gangway, and the gangway has places where inspectors can stand.

Each inspector checks one thing
SHIPNobody checks, the crew is tired

The ship does not know how many inspectors there are.

The idea

One door for many APIs

Kong in front of two services

Apps and partners send HTTPS to one Kong machine that handles key, limit, transformation and log. It asks Redis for limit counters and passes HTTP to two separate services, orders and payments.
Counters can live in Redis so that several Kong nodes share them.
  • Identity

    key-auth, JWT, basic auth, HMAC, OAuth 2.0 and LDAP. OpenID Connect is Enterprise.

  • Permission

    ACL groups per consumer, IP allow and deny lists.

  • Limits

    Requests per second up to per year, size limits, response based limits.

  • Change

    Rewrite headers, bodies and paths; gRPC to JSON; end a request early.

  • Record

    Prometheus, OpenTelemetry, Zipkin, Datadog, HTTP and file logs.

  • AI traffic

    Plugins that route to language model providers and guard prompts.

Why gateways exist and when not to have one is on the API gateway page. API authentication, rate limiting and idempotency have pages too. Here is how the product does it.

Model

Service, route, consumer, plugin

How the objects hang together

Solid: where requests go. Dotted: where a plugin is attached.
YAML
_format_version: "3.0"services:  - name: orders    url: http://orders.internal:8080    connect_timeout: 1000     # milliseconds; the default is 60000    read_timeout: 5000    retries: 2                # the default is 5    routes:      - name: orders        paths: ["/orders"]        strip_path: false     # the default true removes /orders    plugins:      - name: key-auth        config:          key_names: ["apikey"]          key_in_query: false          hide_credentials: true      - name: rate-limiting        config:          minute: 100          limit_by: consumer          policy: localconsumers:  - username: acme    keyauth_credentials:      - key: replace-me
A complete kong.yml for DB-less mode. Keep real keys out of the file, for example with a vault reference.

Routing

Which route answers?

The router sorts routes by priority and takes the first that matches. With the traditional JSON fields, a route with more kinds of conditions (host, path, method, headers) is more specific, and longer paths beat shorter ones. The expressions router lets you write the condition and its priority yourself. The documentation recommends it for 3.4 and later; router_flavor is traditional_compatible by default.

From request to route

Regular expressions cost more than prefixes. With thousands of routes the documentation advises prefixes.

Plugins

Phases and order

When plugin code runs

PhaseMomentExample
certificateDuring the TLS handshakeChoose a certificate
rewriteBefore a route is known, so only for global pluginsCorrelation ID
accessAfter routing, before the service is calledKeys, limits, transformation
header_filter, body_filterWhile the response passesChange headers or body
logAfter the client has the answerMetrics, logs

Priority of some bundled plugins (higher runs first)

PluginPrioritySo that
correlation-id100001Every later step can log the ID
cors2000Browser checks need no login
jwt1450The consumer is known
key-auth1250The consumer is known
ip-restriction990Runs after authentication
acl950Groups of the consumer are checked
rate-limiting910Counts per consumer
request-transformer801Changes what the service will see
proxy-cache100Only allowed requests reach the cache
prometheus13Counts at the end
Numbers of Kong 3.16. The order can be changed per plugin in Enterprise.

One request with a key and a limit

The most specific configuration wins

  1. 1

    Once per request

    A plugin may be attached many times, but one request runs it once, with one configuration.

  2. 2

    More parts beat fewer

    Consumer, route and service together are the strongest match.

  3. 3

    Then the kind

    With one part each: consumer, then consumer group, then route, then service.

  4. 4

    Global is last

    It applies when nothing else fits.

Own plugins are written in Lua, or in Go, Python or JavaScript, which run in a separate plugin server process and cost a hop between processes for each call.

Limits

What a rate limit counts

Three places for the counter of the Rate Limiting plugin

PolicyCounterGood forPrice
local (default)Memory of each nodeProtecting a backendNodes do not know each other
clusterKong's databaseExact, nothing extra to runA read and a write per request. Not in hybrid mode or Konnect
redisA Redis serverExact with less cost than clusterOne more system. Exact only with synchronous counting

A local limit on several nodes

worst case=5×30=150even share=1005=20\text{worst case} = 5 \times 30 = 150 \qquad \text{even share} = \frac{100}{5} = 20
The documentation's example: for 100 a second over 5 equal nodes, set about 30 locally. More than 20, so that uneven traffic is not refused wrongly.

The plugin uses calendar windows: minute 1 starts with a fresh counter. So a client can send 100 requests at the end of one minute and 100 at the start of the next. Set a limit per second as well, or use Rate Limiting Advanced (Enterprise), which has sliding windows. The ideas are compared in rate limiter algorithms.

Storage

Three ways to run it

ModeConfiguration lives inChange it byKeep in mind
TraditionalPostgreSQL, read by all nodesAdmin API, Kong Manager, decKEvery node can change everything; other nodes notice by polling, every 5 seconds by default
DB-lessA YAML or JSON file in memoryA new file or POST to /config, on each nodeAdmin API is read-only otherwise (405); plugins that need a database do not work
HybridDatabase at the control plane, a copy on each data planeAdmin API at the control plane, or KonnectMutual TLS certificates between the planes

Hybrid mode

Operators change the configuration at a control plane, which is the only part connected to the PostgreSQL database. It sends configuration over port 8005 to two data planes, each with its own copy. Apps send HTTPS only to the data planes.
Traffic never needs the database.

Which mode?

When the control plane is gone, data planes go on with their last copy from disk, also after a restart. A completely new data plane needs the resilience feature, which keeps a copy in object storage. The local copy is an LMDB file; it is not encrypted unless you switch that on.

On Kubernetes the Kong Ingress Controller, and newer Kong Operator, translate Gateway API and Ingress resources into this configuration. New features go into the operator.

Upstreams

Balancing and health

AlgorithmRuleUse it when
round-robin (default)In turn, by weightTargets are alike
least-connectionsFewest requests in flightRequest times differ
consistent-hashingHash of consumer, IP, header, cookie and othersCaches in the targets
latencyPeak EWMA: lately fastest, without weightsSimilar requests, targets near and far
sticky-sessionsA cookie names the target (newer Enterprise versions)Sticky sessions you cannot avoid

Active checks

  • Probe a path on a timer
  • Can bring a target back
  • Off by default: interval 0

Passive checks alone

  • Watch real answers
  • Cannot bring a target back by themselves
  • Off by default: all counters 0

The documentation calls passive checks circuit breakers. Per target, they work like the open state of a circuit breaker; the way back needs an active probe or an operator.

Safety

Keep the door closed

PortPurposeWho may reach it
8000, 8443Proxy: HTTP and HTTPSClients, through a load balancer
8001, 8444Admin API; listens on 127.0.0.1 by defaultOperators on a private network
8002, 8445Kong Manager, the web pageOperators
8005Configuration for data planesData planes, with mutual TLS
8007Status: health and metricsMonitoring
  1. 1

    No way around

    Services accept calls from Kong only: network rules or mutual TLS. They still check what the consumer may do with a single record.

  2. 2

    Trust the right address

    Set trusted_ips and real_ip_header, or all clients share the address of the balancer.

  3. 3

    Configuration from Git

    deck gateway diff in the review, deck gateway sync after it. Nobody edits by hand.

  4. 4

    Global plugins first

    Correlation ID, logging and a generous limit for everything; strict limits per route.

Operations

Running and paying for it

What the gateway may cost in time

t=tKong+tRedis2 ms+1 ms=3 ms per requestt = t_{\text{Kong}} + t_{\text{Redis}} \qquad 2\,\text{ms} + 1\,\text{ms} = 3\,\text{ms per request}
Assumed numbers. Each plugin adds work, and each plugin that asks another system adds a round trip. Measure with your plugins; Kong publishes a test suite for that.
  • Scale

    Data planes hold no request state. Add nodes behind a balancer; then look at local limits again.

  • Watch

    Kong's own latency against the latency of the service, 4xx and 5xx per route, certificate expiry between the planes.

  • Change

    Routes and plugins without a restart. Version upgrades are rolling; control planes first.

  • Fail

    It is on every path: at least two nodes in two zones, and a decision for each plugin that depends on a store.

Editions in November 2026

Open sourceEnterprise and Konnect
LicenceApache 2.0Commercial
Newest version3.9.5, patches of the 3.9 line3.16; long-term support 3.14 and 3.10
Imagekongkong/kong-gateway
PluginsAbout 45 bundledAlso OpenID Connect, advanced limits and caching, and others
Without a licenceNot neededSince 3.10 like an expired licence: traffic flows, configuration is read-only

Decide

Kong or something else

ProductStrong atChoose it instead when
AWS API GatewayNothing to runYou are on AWS and the managed limits fit
NGINXA proxy and a cacheNo consumers, few rules
Envoy with Envoy GatewayDynamic proxy, Gateway APIYou want an open project on Kubernetes
TraefikFinds containers, gets certificatesRouting is the job, not API products
A mesh such as IstioCalls between servicesThe problem is inside, not at the door

Strengths

  • Clear model with consumers
  • Many plugins, own ones in four languages
  • Change by API, file or Git
  • Traffic survives a lost control plane

Costs

  • One more system on every request
  • Useful features sit in Enterprise
  • Business logic creeps into plugins
  • Local counters surprise people

Summary

The whole topic in one minute.

Kong is an NGINX based gateway whose behaviour comes from plugins. Services, routes, consumers and plugins are the whole model; the most specific plugin configuration wins and the plugin with the highest priority runs first.

Choose how it stores configuration (database, file, or hybrid with a control plane), where limits are counted, and what happens when that store fails. Keep the Admin API private, block every way around the gateway, and check the edition: the open source line stays at 3.9.

  • Service, route, consumer, plugin. The most specific plugin configuration wins.
  • The highest priority runs first: identity, then permission, then limits, logs last.
  • Limits are local by default and open when the store is down.
  • DB-less, traditional or hybrid. In hybrid mode traffic needs no database.
  • Admin API private, no way around the gateway, and check the edition.

Sources