kong/kong

🦍 The API and AI Gateway

43,222 stars Lua 10 components

15 hidden assumptions · 7-stage pipeline · 10 components

Like any codebase, this backend api makes assumptions it never checks — most are routine. The ones worth your attention are below.

Routes API requests through extensible plugins for authentication, rate limiting, and proxying

Kong's plugin architecture enables request/response transformation through multiple language runtimes. HTTP requests enter through the gateway core, flow through configured plugins during specific lifecycle phases (access, header_filter, body_filter, log), and exit as modified responses. The build system analyzes resulting binaries to ensure dependency compliance across platforms.

Under the hood, the system uses 3 data pools, 3 control points to manage its runtime behavior.

A 10-component backend api. 25 files analyzed. Data flows through 7 distinct pipeline stages.

Hidden Assumptions

Most of what this code assumes is routine. These 3 are the ones most likely to cause trouble here. The rest are minor; they're under "Show everything".

Worth your attention first

If Docker is not installed or daemon is not running, the gather_files() function will silently fail with os.system() returning non-zero, but the error message 'Failed to extract image %s' doesn't indicate Docker availability issues

Worth your attention first

If Kong PDK changes its API structure or the kong.kong object is malformed, accessing kong.request.get_header or kong.response.set_header will raise AttributeError, causing the plugin to crash without graceful error handling

Worth your attention first

If the function is invoked outside of API Gateway context or with a different event format, accessing expected event properties will raise KeyError, but the function doesn't validate event structure before processing

Show everything (12 more)
Temporal

Docker container name generated from time.time() will be unique across concurrent executions

If this fails: If two processes run explain_manifest simultaneously, they generate containers named 'explain_manifest_<timestamp>' that could collide if time.time() returns identical values, causing docker create to fail

scripts/explain_manifest/main.py:gather_files
Resource

Global caches dict can grow indefinitely without memory constraints during binary analysis

If this fails: When analyzing large numbers of ELF files, the caches dict accumulates parsed metadata without any eviction policy, potentially causing out-of-memory errors on systems with limited RAM

scripts/explain_manifest/explain.py:caches
Shape

kong.Request.GetHeader('host') returns a non-empty string when successful

If this fails: If the Host header is present but empty, the plugin sets response header 'x-hello-from-go' to 'Go says <message> to ' with trailing space, and stores empty string in shared context, which may confuse downstream plugins expecting meaningful host values

spec/fixtures/external_plugins/go/go-hello.go:Access
Shape

this.config is a plain object where this.config.message can be safely accessed

If this fails: If the plugin configuration is null, undefined, or not an object, accessing this.config.message will not throw but may return undefined, leading to 'Javascript says undefined to <host>' in the response header

spec/fixtures/external_plugins/js/js-hello.js:access
Ordering

Promise.all() executes setHeader calls in the order they can complete, not necessarily array order

If this fails: If one setHeader call fails while the other succeeds, only partial headers are set with no indication which one failed, potentially leaving the response in an inconsistent state for debugging

spec/fixtures/external_plugins/js/js-hello.js:access
Domain

get_plugin_configuration() returns valid UTF-8 bytes that can be parsed as JSON matching the Config struct

If this fails: If the configuration contains invalid UTF-8 or malformed JSON, serde_json::from_slice will fail and the filter returns false, but the error message only shows parsing failure without indicating whether it was UTF-8 or JSON structure issue

spec/fixtures/proxy_wasm_filters/response_transformer/src/filter.rs:on_configure
Resource

Thread-local METRICS HashMap can store metric IDs indefinitely without cleanup

If this fails: In long-running proxy processes, the metrics HashMap accumulates entries for every unique metric name ever defined, potentially consuming unbounded memory if metric names are dynamically generated or contain unique identifiers

spec/fixtures/proxy_wasm_filters/tests/src/metrics.rs:get_metric_id
Shape

FileInfo object f has rpath and runpath attributes that are either None or strings containing colon-separated paths

If this fails: If ELF parsing produces rpath/runpath as unexpected types (lists, bytes, etc.), the 'expected_rpath in f.rpath' check will raise TypeError instead of gracefully handling malformed binary metadata

scripts/explain_manifest/config.py:transform
Scale

Command line argument processing handles reasonable numbers of glob patterns and file paths

If this fails: If --file_list points to a file with thousands of glob patterns, the read_glob() function loads them all into memory at once without pagination, potentially causing memory issues with very large file lists

scripts/explain_manifest/main.py:parse_args
Temporal

TemporaryDirectory cleanup via atexit.register() will execute before process termination

If this fails: If the process is killed with SIGKILL or crashes unexpectedly, the temporary directory containing extracted Docker image data will not be cleaned up, potentially filling up disk space over time

scripts/explain_manifest/main.py:gather_files
Domain

kong.Nginx.GetCtxFloat('KONG_ACCESS_START') returns a valid timing measurement from Kong's request processing

If this fails: If Kong's internal timing context is not set or contains non-numeric data, GetCtxFloat will error but the error handling is incomplete (code is cut off), potentially causing the Log phase to fail silently

spec/fixtures/external_plugins/go/go-hello.go:Log
Environment

os.getpid() returns a meaningful process identifier that can be converted to string

If this fails: While os.getpid() should always work on POSIX systems, in containerized environments or process namespaces, the PID may not be meaningful for debugging, leading to confusing 'x-python-pid' header values

spec/fixtures/external_plugins/py/py-hello.py:access

Open the standalone hidden-assumptions report for kong →

How Data Flows Through the System

Kong's plugin architecture enables request/response transformation through multiple language runtimes. HTTP requests enter through the gateway core, flow through configured plugins during specific lifecycle phases (access, header_filter, body_filter, log), and exit as modified responses. The build system analyzes resulting binaries to ensure dependency compliance across platforms.

  1. Request ingress through gateway — Kong core receives HTTP request and creates language-specific request objects (pdk.PDK for Go, kong.request for JS, kong.kong for Python) containing headers, body, and routing context
  2. Plugin configuration loading — Kong loads plugin-specific configuration from admin API or declarative config, instantiating plugin classes with their Config objects (message field in examples)
  3. Access phase plugin execution — Plugins execute their access() methods in priority order - Python plugin reads host header and sets x-hello-from-python response header, Go plugin calls Access() and stores shared context, JS plugin runs async operations [KongRequest → ModifiedResponse]
  4. WebAssembly filter processing — Proxy-WASM filters like ResponseTransformerContext receive HTTP context, parse JSON configuration in on_configure(), and transform responses using proxy_wasm traits [proxy_wasm HttpContext → Modified HTTP Response]
  5. Log phase execution — Plugins execute log() methods for analytics - Go plugin reads KONG_ACCESS_START timing, Python plugin can record request metrics, WASM filters update counters/histograms [KongRequest → Metrics]
  6. Binary distribution analysis — The explain_manifest tool extracts files from packages/images, analyzes ELF binaries using LIEF library to read symbols/RPATH, and validates against expected file patterns in test suites [FileSystem → FileInfo]
  7. Package validation — ExpectChain runs fluent assertions against FileInfo objects, checking file existence, permissions, library dependencies, and binary metadata to ensure distribution integrity [FileInfo → ValidationResults]

Data Models

The data structures that flow between stages — the contracts that hold the system together.

FileInfo scripts/explain_manifest/main.py
object with path: str, size: int, mode: str, owner: str, group: str, plus ELF-specific fields like rpath, runpath, imported_symbols, exported_symbols for binary files
Created during file system traversal, enriched with ELF metadata if binary, used for validation and manifest generation
PluginConfig spec/fixtures/external_plugins/py/py-hello.py
dict with message: str field, varies by plugin type - Python plugins use dict, Go plugins use struct with Message field, JS plugins use object with message property
Loaded from Kong configuration, passed to plugin constructor, used during request lifecycle phases
KongRequest spec/fixtures/external_plugins/go/go-hello.go
Kong PDK request object with methods like GetHeader(name) -> (value, error), varies by language - Go uses pdk.PDK, Python uses kong.kong, JS uses kong.request
Created by Kong core for each HTTP request, passed to plugin hooks during access/log phases
WebAssemblyFilter spec/fixtures/proxy_wasm_filters/response_transformer/src/filter.rs
Rust struct implementing HttpContext trait with config: Config field, using proxy_wasm traits for HTTP interception
Instantiated by proxy-wasm runtime, configured via JSON, processes HTTP requests/responses through trait methods
ExpectSuite scripts/explain_manifest/expect.py
object with file patterns, validation rules, and expected properties for binary distribution testing
Defined in test suites, executed against file manifests to verify package integrity

System Behavior

How the system operates at runtime — where data accumulates, what loops, what waits, and what controls what.

Data Pools

plugin_metrics (in-memory)
Thread-local HashMap storing metric IDs keyed by name, persisting across filter invocations
shared_context (state-store)
Kong's shared context store for passing data between plugin phases using SetShared/GetShared
binary_cache (cache)
Global caches dict storing parsed ELF metadata to avoid re-analyzing same binaries

Delays

Control Points

Technology Stack

LIEF (library)
Parses ELF binaries to extract symbols, RPATH, RUNPATH, and architecture information for package validation
proxy-wasm (runtime)
WebAssembly runtime interface enabling high-performance request/response filters in Kong
Kong PDK (sdk)
Multi-language plugin development kit providing consistent APIs across Go, Python, JavaScript runtimes
pytest (testing)
Testing framework for validating plugin behavior and binary distribution integrity
Docker (runtime)
Container runtime used for extracting and analyzing Kong distribution images
Rust (framework)
Systems language for implementing high-performance WebAssembly filters
serde_json (serialization)
JSON serialization/deserialization for WebAssembly filter configuration
AWS Lambda (infra)
Serverless compute platform demonstrated in Kong integration samples

Key Components

Explore the interactive analysis

See the full architecture map, data flow, and code patterns visualization.

Analyze on CodeSea

Related Backend Api Repositories

Frequently Asked Questions

What is kong used for?

Routes API requests through extensible plugins for authentication, rate limiting, and proxying kong/kong is a 10-component backend api written in Lua. Data flows through 7 distinct pipeline stages. The codebase contains 25 files.

How is kong architected?

kong is organized into 5 architecture layers: Gateway Core, Plugin System, WebAssembly Filters, Build & Verification, and 1 more. Data flows through 7 distinct pipeline stages. This layered structure keeps concerns separated and modules independent.

How does data flow through kong?

Data moves through 7 stages: Request ingress through gateway → Plugin configuration loading → Access phase plugin execution → WebAssembly filter processing → Log phase execution → .... Kong's plugin architecture enables request/response transformation through multiple language runtimes. HTTP requests enter through the gateway core, flow through configured plugins during specific lifecycle phases (access, header_filter, body_filter, log), and exit as modified responses. The build system analyzes resulting binaries to ensure dependency compliance across platforms. This pipeline design reflects a complex multi-stage processing system.

What technologies does kong use?

The core stack includes LIEF (Parses ELF binaries to extract symbols, RPATH, RUNPATH, and architecture information for package validation), proxy-wasm (WebAssembly runtime interface enabling high-performance request/response filters in Kong), Kong PDK (Multi-language plugin development kit providing consistent APIs across Go, Python, JavaScript runtimes), pytest (Testing framework for validating plugin behavior and binary distribution integrity), Docker (Container runtime used for extracting and analyzing Kong distribution images), Rust (Systems language for implementing high-performance WebAssembly filters), and 2 more. A focused set of dependencies that keeps the build manageable.

What system dynamics does kong have?

kong exhibits 3 data pools (plugin_metrics, shared_context), 3 control points, 3 delays. These runtime behaviors shape how the system responds to load, failures, and configuration changes.

What design patterns does kong use?

5 design patterns detected: Plugin Development Kit (PDK), Proxy-WASM Integration, Fluent Validation DSL, Cross-Language Plugin Support, Binary Analysis Pipeline.

Analyzed on April 20, 2026 by CodeSea. Written by .