Introducing a new way to review your PRs.

Read the announcement

basecamp / kamal-proxy

Lightweight proxy server for Kamal

View on GitHub

15 documents · Updated Nov 18, 2026

docs / proxy-server

Proxy server architecture

Kamal Proxy is an HTTP proxy for zero-downtime application deployments. The process accepts client traffic, maps each request to a registered service, and sends it to healthy upstream targets while a local control interface manages service changes. Its runtime state can survive a process restart, so the proxy can resume its service map before it accepts new work.

Runtime model

The proxy has a data plane and a control plane. The data plane serves HTTP traffic through one shared request pipeline. The control plane uses a local Unix socket to register services and change their runtime state. Both planes act on the same router and service registry.

The main runtime flow is:

flowchart TD
    A[run command] --> B[Build runtime configuration]
    B --> C[Create router]
    C --> D[Restore saved service state]
    D --> E[Start listeners and control socket]
    E --> F[Serve client requests]
    E --> G[Accept service commands]
    G --> H[Update service registry]
    H --> I[Save service state]
    F --> J[Select service and healthy target]
    J --> K[Return upstream or proxy response]

The process stays active until it receives SIGTERM or SIGINT. Shutdown closes the control socket and listeners, then gives active HTTP servers a bounded period to finish before it closes the remaining connections. See internal/…/run.go and internal/…/server.go.

Configuration and startup

The kamal-proxy run command creates the process configuration from command flags and environment variables. There is no required configuration file. HTTP and HTTPS use ports 80 and 443 by default. Metrics are off unless a metrics port is set, and HTTP/3 is optional. The process also accepts time limits for request headers, idle connections, and request bodies.

Environment values may use either the normal option name or the KAMAL_PROXY_ prefix. The prefixed value takes priority when both are present. Invalid environment values fall back to the option default rather than stopping startup. See internal/…/run.go and internal/…/util.go.

The configuration also defines the process paths that connect runtime pieces:

ResourcePurpose
State pathStores the service registry and its active or rollout target information.
Unix socketCarries operator commands to the running process.
Certificate directoryStores certificates used by automatic TLS.

These paths use the configured data directory, with a user configuration directory as the normal default. The Unix socket can be set with KAMAL_PROXY_SOCKET, and an alternate data directory can be supplied through the runtime configuration. See internal/…/config.go.

References: internal/…/run.go• L20-58 internal/…/util.go• L10-76 internal/…/config.go• L11-65

Process startup and shutdown

Startup restores the last saved service state before the server opens its traffic and control interfaces. The server then starts the optional metrics listener, the HTTP and HTTPS listeners, the optional HTTP/3 listener, and the Unix command handler. This order gives the router its known services before it begins normal request handling.

Shutdown runs the server shutdown steps together. It uses a ten-second limit for graceful shutdown. A listener close completes the stop even when an active connection does not finish within that limit. See internal/…/run.go and internal/…/server.go.

References: internal/…/run.go• L40-58 internal/…/server.go• L41-99 internal/…/server.go• L183-215

Listener and interface model

The process exposes separate interfaces for public traffic, operational metrics, and service management. Public HTTP and HTTPS requests share the same application handler. HTTP/3 uses that handler as well, so protocol choice does not change service routing or target selection.

InterfaceRoleAvailability
HTTPReceives plain HTTP requests and can support redirects for TLS-enabled services.Always started.
HTTPSReceives TLS traffic and chooses a certificate from the router.Always started.
HTTP/3Receives QUIC traffic with the same request behavior as HTTP and HTTPS.Started when enabled.
MetricsServes Prometheus metrics outside the public request path.Started when a metrics port is configured.
Unix control socketReceives service and rollout commands from local operators or deployment tools.Always started for a running proxy.

The HTTPS and HTTP/3 listeners ask the router for a certificate based on the requested server name. This keeps certificate selection tied to the service that owns the host. TLS modes and certificate approval are described in TLS and on-demand certificates.

References: internal/…/server.go• L27-39 internal/…/server.go• L111-180 internal/…/server.go• L183-208

HTTP handler composition

The public handler is a layered request path around the router. Outer layers add request timing context and request identity, then apply request logging and client-body limits. The error-page layer turns errors recorded by the inner handlers into client responses. The router is the final dispatch layer in this process-level chain.

The request path is conceptually:

flowchart LR
    A[Client request] --> B[Request start and ID]
    B --> C[Logging and body timeout]
    C --> D[Process error page handling]
    D --> E[Router]
    E --> F[Service middleware]
    F --> G[Load balancer]
    G --> H[Healthy upstream target]

The router and service layers add the rules that are specific to a deployment: host and path matching, TLS redirects, paused or stopped service behavior, target choice, and response handling. The child page Request routing and middleware covers the request path in detail. Error classification and client-facing pages are covered in Proxy error responses.

References: internal/…/server.go• L218-229 internal/…/service.go• L586-632

Router and service registry

The router is the shared boundary between incoming requests and service management. It owns the service registry, matches a request to a service by host and path, and exposes operations for deployment, removal, pause, stop, resume, and rollout changes.

Each service combines routing settings with two possible target groups:

  • The active group serves normal traffic.
  • The rollout group receives only the requests selected by the rollout policy.

A service update first prepares its target group and waits for health unless the deployment is forced. The router checks for host and path conflicts before it installs the group. When a group is replaced, the old group drains its in-flight requests before it is removed. This is the main relationship between service management and zero-downtime deployment.

The service registry rebuilds its request map when services change. It prefers the most specific matching path and supports exact hosts, wildcard host suffixes, and the default host. A service change is saved to the state file so the process can restore the registry on its next start. See Services and upstream targets for service and target state, and Upstream load balancing for target selection.

References: internal/…/router.go• L50-64 internal/…/router.go• L104-149 internal/…/router.go• L151-177 internal/…/router.go• L382-429 internal/…/service_map.go• L66-96 internal/…/service_map.go• L145-195

Control interface

The control interface is a local RPC service over a Unix socket. Deployment tools connect to it to change the router without restarting the proxy. The command handler maps control calls to router operations rather than maintaining a second copy of service state.

The control surface covers these groups of actions:

  • Register or replace active targets.
  • Add, split, enable, disable, or remove rollout targets.
  • List active services and their published state.
  • Pause, stop, resume, or remove a service.

This separation lets the public listeners keep serving traffic while the control plane changes the service map. The command handler and router share the same in-process state, with router locks protecting concurrent reads and updates. Traffic pause and progressive rollout behavior are described in Traffic pause and rollout controls.

References: internal/…/commands.go• L14-17 internal/…/commands.go• L78-121 internal/…/commands.go• L124-168 internal/…/router.go• L261-308

Cross-system responsibilities

The proxy process coordinates several concerns, but each concern remains attached to the same service and request model. A service can define its host and path scope, TLS behavior, client address handling, custom error pages, metrics exclusions, and target policy. The router supplies the service context; the service then applies its own policy before it forwards traffic.

Use these pages for the focused behavior:

ConcernRelated page
Host and path dispatch, request context, buffering, and request limitsRequest routing and middleware
Service registration, target health, replacement, and drainingServices and upstream targets
Writer and reader target choice and target availabilityUpstream load balancing
Pause, stop, resume, and progressive rollout stateTraffic pause and rollout controls
Listener TLS, certificate sources, and on-demand host checksTLS and on-demand certificates
Failure classes and rendered client responsesProxy error responses

References: internal/…/service.go• L101-118 internal/…/service.go• L314-323 internal/…/service.go• L642-665 internal/…/service.go• L668-707

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to Config path rules must stay aligned with state restore, command-socket startup, and certificate storage.
  • Changes to the handler order in buildHandler must preserve the error-response context and the request context used by logging and metrics.
  • Changes to service host or path rules must preserve conflict checks, longest-prefix matching, and TLS options inherited by path services.
  • Changes to command arguments must keep the Unix RPC method names and router operations aligned with the operator CLI.
  • Changes to service state encoding must keep restore behavior compatible with state written by earlier proxy versions.

Important failure modes

TriggerConsequenceGuard
The state file cannot be decoded.The proxy does not restore its service registry and startup returns an error.Keep state shape compatible when changing service persistence.
HTTP, HTTPS, metrics, or the Unix socket cannot bind.Startup stops before the proxy is ready.Check port and socket ownership in the process environment.
A deployment target does not become healthy before its deploy timeout.The new target group is rejected and existing traffic remains on the prior group.Make the health endpoint and target settings match the application.
A service claims a host and path already used by another service.The router rejects the change to prevent ambiguous dispatch.Use unique host/path bindings.
The graceful shutdown limit expires.Active connections are closed instead of fully drained.Allow the proxy time to stop before removing its host or targets.
TLS is enabled without a valid host or certificate mode.Service setup fails or TLS cannot select a certificate for the request.Use configured hosts, a valid on-demand policy, or a readable certificate pair.

Key files

FileWhy to read it
cmd/…/main.goShows the executable entry point.
internal/…/run.goShows how configuration becomes a running proxy and how signals stop it.
internal/…/config.goDefines listener settings and persistent resource paths.
internal/…/server.goComposes listeners, the public handler, metrics, TLS, and shutdown.
internal/…/router.goConnects request dispatch, service management, state restore, and state save.
internal/…/service_map.goDefines the host and path view used for request dispatch.
internal/…/commands.goDefines the local control interface used by deployment and operator commands.
internal/…/service.goShows how service policy joins routing, target groups, TLS, and request handling.