> For the complete documentation index, see [llms.txt](https://docs.kangal.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kangal.dev/concepts/architecture.md).

# Architecture

Kangal separates gateway management from request processing. The control plane owns desired configuration and operational history. A data plane owns the live request path for one gateway and applies the configuration it has accepted.

```
Operators and automation
        |
        | Console, Admin API, kangalctl
        v
+---------------------- Kangal control plane ----------------------+
| Gateway configuration | Admin RBAC | Audit | Rollouts | Workers  |
| MongoDB-backed desired state     | Redis-backed runtime services |
+-------------------------------+----------------------------------+
                                |
                                | scoped, checksummed config bundle
                                | heartbeat, ACK/NACK, telemetry
                                v
+----------------------- Kangal data plane ------------------------+
| Route match -> consumer identification -> plugins -> target      |
| selection -> upstream proxy -> response plugins -> telemetry     |
+-------------------------------+----------------------------------+
                                |
                                v
                         Customer services
```

## Main components

| Component           | Responsibility                                                                                                        | Operational note                                                                                 |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Console             | Customer-facing gateway, route, policy, certificate, domain, and rollout workflows.                                   | Management traffic stays separate from the public request path.                                  |
| Admin API           | Tenant-scoped CRUD, validation, entitlement checks, audit events, snapshots, and rollout coordination.                | Verify data-plane acknowledgement after each production change.                                  |
| Configuration store | Stores gateways, services, routes, upstreams, targets, plugins, credentials, certificates, and related desired state. | Data planes receive scoped bundles instead of querying the database.                             |
| Redis services      | Shared rate-limit counters and job delivery for components configured to use them.                                    | Each traffic policy documents whether its state is shared or per process.                        |
| Background workers  | Integration jobs and custom-domain certificate issuance, renewal, and reconciliation.                                 | Operators publish DNS ownership records; verification is read-only.                              |
| Data plane          | Matches and proxies traffic with an accepted gateway bundle.                                                          | The independent runtime is proxy-only and carries no management endpoints or MongoDB dependency. |
| Edge or ingress     | Publishes public addresses, terminates TLS where configured, and forwards traffic to a data plane.                    | Operators apply Kangal certificate and domain bindings to the selected edge.                     |

## Configuration model

The main runtime graph is:

```
Gateway
  +-- Service --------------------------> direct URL or host
  |       |
  |       +-----------------------------> Upstream -> Targets
  |
  +-- Route -> Service or Upstream
          |
          +-- request match rules
          +-- route-level plugins
```

* A **gateway** is the tenant-scoped configuration and runtime boundary.
* A **service** describes how to reach one application. It can use a direct URL or refer to an upstream pool.
* A **route** decides which requests use a service or upstream.
* An **upstream** groups concrete **targets** for health-aware selection.
* A **plugin** runs at one or more request lifecycle stages.
* Certificates, SNIs, consumers, credentials, Redis configurations, vaults, and AI Gateway settings are also included in data-plane bundles.

Configuration is scoped by both `tenant_id` and `gateway_id`. Reusing a name in another tenant or gateway does not make the two resources equivalent.

## Request lifecycle

1. The edge forwards a request to `/proxy/{path}` on a reachable Kangal runtime.
2. When both `X-Tenant-ID` and `X-Gateway-ID` are supplied, they take precedence for scope selection. Otherwise, a mapped gateway host fills whichever scope value is missing. An unmapped request must provide `X-Tenant-ID` and should also provide `X-Gateway-ID` whenever the tenant has more than one gateway.
3. Active route candidates are evaluated by path, method, host, SNI, headers, and query parameters.
4. If multiple routes match, Kangal compares explicit priority first, then path type and length, followed by host, SNI, header/query, and method specificity.
5. The selected route resolves its service and, when applicable, an upstream target.
6. `before_request` plugins may authenticate, reject, transform, or annotate the request before proxying.
7. Kangal removes hop-by-hop request headers, preserves the original host only when `preserve_host` is enabled, and builds the upstream URL according to `strip_path`.
8. The response passes through configured response and error stages. Kangal records request, route, status, latency, and correlation metadata without the request or response body in the analytical event path.

No route match returns `404`. A request that matches all configured criteria except its HTTP method returns `405`. An unresolved service or target returns a gateway error, normally `502`.

## Control-plane to data-plane synchronization

Each registered node has a stable `node_id` and a one-time-visible node token. The node heartbeats, asks whether a new configuration is available, and pulls a bundle for exactly one tenant and gateway.

The control plane builds a deterministic bundle, calculates per-collection checksums and a full SHA-256 checksum, and derives the public version from the first 24 checksum characters. A node validates scope, shape, checksum, version, and any configured signature before atomically activating the bundle.

The node reports:

* `ACK` after a bundle is validated, cached, and activated;
* `NACK` with validation errors when it refuses a bundle;
* current and desired versions;
* heartbeat and last-seen times;
* last-known-good version and runtime mode.

An independent data plane can continue with its signed last-known-good cache when the control plane is unavailable. It is not ready until at least one valid bundle has been loaded. A stale or invalid cache must not be treated as a fresh configuration simply because the process is running.

## Rollout strategies

| Strategy    | Behavior                                                    | Typical use                                       |
| ----------- | ----------------------------------------------------------- | ------------------------------------------------- |
| `immediate` | Makes the generation available without staged waves.        | Small, low-risk node sets.                        |
| `staged`    | Delivers bounded waves that an operator promotes.           | Routine production changes.                       |
| `canary`    | Starts with a small canary group, then waits for promotion. | High-risk routes, plugins, or credential changes. |

Rollouts pin a captured gateway snapshot so later control-plane edits cannot silently change an in-progress generation. Failure count and failure-rate thresholds are evaluated against the active wave. When automatic rollback is enabled and a usable last-known-good snapshot exists, Kangal can publish that snapshot as a rollback generation.

A rollout is operationally complete when the node summary shows no waiting or in-progress nodes, every required node has an `ACK`, and current versions match the rollout target.

## Deployment shapes

Kangal supports two runtime shapes:

* In a combined deployment, the main API process exposes both management routes and proxy routes. This is convenient for development and smaller installations.
* In an independent deployment, a proxy-only data-plane process runs separately from the control plane and has no MongoDB dependency. This is the stronger production isolation boundary and supports last-known-good operation.

Creating a gateway with a deployment profile records the desired commercial and hosting metadata and generates proxy/workspace metadata. The create operation does not, by itself, prove that a node, DNS record, load balancer, or TLS listener has been provisioned. Verify the data-plane node and edge independently.

## Trust boundaries

* Admin API calls use an authenticated administrator and tenant-aware RBAC.
* Runtime consumer authentication belongs in route or global plugins; never put an Admin API token in a consumer application.
* On public entrypoints, a trusted edge must strip client-supplied `X-Tenant-ID` and `X-Gateway-ID` values and inject the authoritative values wherever these administrative scope headers are used. Block direct runtime access that could bypass this edge policy.
* Data-plane node tokens are stored as hashes and are returned in plaintext only when issued or rotated.
* A node may also be pinned to a client-certificate fingerprint injected by a trusted TLS terminator after certificate verification.
* Configuration bundles and local caches support signatures and anti-rollback checks. Losing the stable cache trust material can prevent safe offline start.
* Custom-domain DNS and issuer credentials are redacted in responses and audits.

## Operational responsibilities

* Treat a generated `proxy_url` as configuration metadata until DNS, ingress, TLS, and a proxy request have been verified.
* After changing a certificate or SNI record, verify that the external edge is serving the expected certificate.
* Custom-domain bindings require a deployment-specific edge reconciler or release-time ingress configuration.
* Size traffic policies according to the state scope documented for each plugin; per-process counters and circuits protect each worker independently.
* Remove or repoint dependent resources before deleting a gateway, service, or upstream because those deletes are not dependency-cascading.

Continue with [Gateways and data planes](/gateway/gateways-data-planes.md) for node registration and rollouts, or [Services and routes](/gateway/services-routes.md) for request matching.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.kangal.dev/concepts/architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
