kong/kong
🦍 The API and AI Gateway
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".
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
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
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)
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
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
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
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
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
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
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
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
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
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
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
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.
- 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
- 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)
- 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]
- 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]
- 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]
- 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]
- 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.
scripts/explain_manifest/main.pyobject 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
spec/fixtures/external_plugins/py/py-hello.pydict 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
spec/fixtures/external_plugins/go/go-hello.goKong 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
spec/fixtures/proxy_wasm_filters/response_transformer/src/filter.rsRust 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
scripts/explain_manifest/expect.pyobject 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
Thread-local HashMap storing metric IDs keyed by name, persisting across filter invocations
Kong's shared context store for passing data between plugin phases using SetShared/GetShared
Global caches dict storing parsed ELF metadata to avoid re-analyzing same binaries
Delays
- plugin_instantiation (warmup) — First request to each plugin type incurs class instantiation overhead
- wasm_compilation (compilation) — WebAssembly filters must be compiled before first execution
- docker_extraction (async-processing) — Docker image analysis requires pulling image and extracting filesystem before manifest generation
Control Points
- plugin_priority (runtime-toggle) — Controls: Order of plugin execution during request phases. Default: 0
- explain_opts (feature-flag) — Controls: Which binary metadata to extract (symbols, architecture, RPATH)
- merge_rpaths_runpaths (architecture-switch) — Controls: Whether to treat RPATH and RUNPATH as equivalent during analysis
Technology Stack
Parses ELF binaries to extract symbols, RPATH, RUNPATH, and architecture information for package validation
WebAssembly runtime interface enabling high-performance request/response filters in Kong
Multi-language plugin development kit providing consistent APIs across Go, Python, JavaScript runtimes
Testing framework for validating plugin behavior and binary distribution integrity
Container runtime used for extracting and analyzing Kong distribution images
Systems language for implementing high-performance WebAssembly filters
JSON serialization/deserialization for WebAssembly filter configuration
Serverless compute platform demonstrated in Kong integration samples
Key Components
- manifest_analyzer (analyzer) — Extracts and analyzes binary packages or Docker images, gathering file metadata including ELF binary information
scripts/explain_manifest/main.py - ExplainOpts (transformer) — Configures what metadata to extract from binaries (symbols, architecture, RPATH) and transforms ELF files into structured data
scripts/explain_manifest/explain.py - ExpectChain (validator) — Validates binary distributions against expected file patterns, permissions, and dependencies using fluent assertion syntax
scripts/explain_manifest/expect.py - PythonPlugin (processor) — Processes HTTP requests during Kong's access phase, reading request headers and setting response headers
spec/fixtures/external_plugins/py/py-hello.py - GoPlugin (processor) — Handles Kong plugin lifecycle in Go, processing requests and maintaining shared context between phases
spec/fixtures/external_plugins/go/go-hello.go - JavaScriptPlugin (processor) — Implements async plugin logic for Kong using Node.js, demonstrating parallel header operations
spec/fixtures/external_plugins/js/js-hello.js - ResponseTransformerContext (transformer) — WebAssembly filter that transforms HTTP responses using proxy-wasm interface, configured via JSON
spec/fixtures/proxy_wasm_filters/response_transformer/src/filter.rs - TestHttpFilter (processor) — Test WebAssembly filter that manipulates HTTP headers and records metrics during request processing
spec/fixtures/proxy_wasm_filters/tests/src/filter.rs - MetricsCollector (monitor) — Thread-local metrics system for WebAssembly filters, defining and recording counters, gauges, and histograms
spec/fixtures/proxy_wasm_filters/tests/src/metrics.rs - LambdaHandler (adapter) — AWS Lambda function that processes API Gateway proxy events, demonstrating Kong's serverless integration patterns
spec/fixtures/sam-app/hello_world/app.py
Explore the interactive analysis
See the full architecture map, data flow, and code patterns visualization.
Analyze on CodeSeaRelated 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 Karolina Sarna.