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 / load-balancing

Upstream load balancing

Upstream load balancing chooses a healthy target for each request that reaches a service. It separates write traffic from read traffic, spreads requests across the eligible targets, and removes targets from service when health checks show that they cannot accept traffic. This page extends the proxy server architecture and connects with services and upstream targets, request routing, and traffic pause and rollout controls.

Target pools

Each service load balancer holds one target set and derives two live pools from it: writer targets and read-only targets. A target enters a pool only while its state is healthy; targets that are adding, draining, or unhealthy do not receive new requests. Read-only targets serve read traffic only, while normal targets form the writer pool and can also serve reads when no reader is available.

Health changes rebuild these pools. The load balancer therefore keeps the configured target set separate from the currently eligible set, so a target can remain part of service configuration while it is temporarily excluded from forwarding.

Request selection

The load balancer classifies the request before it selects a target. It prefers the reader pool for read requests and uses the writer pool for write requests. A read request is a GET or HEAD request. WebSocket upgrades count as writes by default unless the service allows read targets to accept them.

Selection follows this order:

  1. Use a healthy read-only target for an eligible read request.
  2. Use a healthy writer target when the request is a write, when no reader is available, or when writer affinity applies.
  3. Return a service-unavailable response when the required pool has no eligible target.

The service can hold an active load balancer and a separate rollout load balancer. The rollout rules choose which load balancer receives the request first. The selected load balancer then applies the same read-versus-write rules to its own healthy pools.

The following flow shows how a request moves from classification to an upstream target.

flowchart TD
    Request[Incoming service request] --> Group{Active or rollout group?}
    Group --> LB[Selected load balancer]
    LB --> Kind{Read request?}
    Kind -->|Yes| Affinity{Valid writer affinity?}
    Affinity -->|No| Reader{Healthy reader available?}
    Affinity -->|Yes| Writer[Healthy writer pool]
    Reader -->|Yes| ReaderPool[Healthy reader pool]
    Reader -->|No| Writer
    Kind -->|No| Writer
    ReaderPool --> Forward[Forward request]
    Writer --> Forward
    Reader -->|No writer| Unavailable[503 Service Unavailable]
    Writer -->|Empty| Unavailable

Round-robin state

Each load balancer keeps a separate position for its writer pool and reader pool. For each new selection, it advances the position and chooses the next target in that pool, then wraps at the end. A lock protects both positions and the pool changes so concurrent requests do not corrupt selection state.

The positions belong to the load balancer, not to an individual client. A health change can rebuild a pool while requests continue, so the next selection uses the current eligible targets rather than a stale target list.

Writer affinity

Writer affinity keeps a client on a writer for a short period after a write. When the service has read-only targets and the affinity timeout is greater than zero, a successful write response sets the kamal-writer cookie. A later read with an unexpired cookie uses the writer pool instead of the reader pool.

An upstream can opt out of this cookie for a response by setting X-Writer-Affinity: false. The proxy removes that control header before the response returns to the client. If there are no read-only targets or the timeout is zero, the proxy does not create writer-affinity cookies.

Request forwarding

After selection, the load balancer marks the target request as in flight before forwarding it. This lets target draining wait for existing work while preventing new work from entering a draining target. The proxy also sets X-Kamal-Target to the selected target address so downstream handling and request logs can identify the upstream.

If a target becomes unavailable between pool selection and request start, the target rejects the new request. The load balancer reports the failed claim as service unavailable rather than forwarding to a target that is draining.

Health and availability

Health checks run for every configured target and report success or failure to the load balancer. A successful check moves a new or unhealthy target into the healthy pool. A failed check moves a healthy target out of the pool. The service can therefore continue with the remaining healthy targets while an unavailable target recovers.

New load balancers normally wait for all configured targets to become healthy before deployment installs them. A deployment can force installation without that wait, but requests still use only the healthy subset after installation. When no eligible target remains, the request receives HTTP 503 instead of being sent to an unhealthy target.

stateDiagram-v2
    [*] --> Adding
    Adding --> Healthy: health check succeeds
    Healthy --> Unhealthy: health check fails
    Unhealthy --> Healthy: health check succeeds
    Healthy --> Draining: target removal or replacement
    Draining --> [*]: in-flight work ends
    Adding --> [*]: target removed before readiness

Change checklist

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

  • Keep the request method and WebSocket classification aligned with the read-target contract and the read_targets_accept_websockets service option.
  • Keep health-state changes connected to pool rebuilding so a target cannot remain eligible after a failed check or while draining.
  • Preserve the writer-affinity cookie name, opt-out header, expiry meaning, and response-header removal as one client-facing contract.
  • Keep active and rollout load balancers subject to the same health and selection rules when rollout selection changes.
  • Preserve the 503 behavior when no eligible target exists so callers do not receive requests forwarded to an unavailable target.

Important failure modes

TriggerConsequenceGuard
All writer targets fail health checksWrites and reads without a usable reader return 503Health state removes failed targets from the eligible pools
A read-only target is the only healthy targetWrite requests have no eligible target and return 503Read-only targets are kept out of the writer pool
A target starts draining during selectionThe new request is rejected instead of entering the draining targetTarget request start checks the draining state
A deployment target does not become healthy before the deploy timeoutThe new load balancer is not installedCreation waits for health unless the deployment is forced

Key files

FileWhy to read it
internal/…/load_balancer.goDefines target pools, request classification, round-robin state, writer affinity, and forwarding failure behavior.
internal/…/target.goDefines target availability states, in-flight request tracking, and draining behavior used by the load balancer.
internal/…/health_check.goShows how target health results are produced and returned to the target state machine.
internal/…/service.goConnects active and rollout load balancers to service requests and service options.
internal/…/router.goShows how a new load balancer waits for healthy targets and is installed during deployment.
internal/…/load_balancer_test.goSummarizes the supported selection, reader fallback, WebSocket, affinity, and target-header behavior.