Skip to content

Caddy load balancing policies in depth

Picking the right Caddy load balancing policy — round_robin, least_conn, ip_hash, header, cookie, random — and the active and passive health checks an MSP wires in production.

Caddy’s reverse_proxy directive doubles as a load balancer when given more than one upstream. Picking the right policy is the difference between an even, predictable workload distribution and a hotspot that pages you at 2am. This article is the policy-by-policy reference, the health check tuning, and the production examples we use at clients running multi-upstream Caddy edges.

How to verify

A working load balancer distributes traffic and reroutes around failures:

for i in $(seq 1 20); do curl -s https://app.example.com/whoami; done | sort | uniq -c
sudo systemctl stop my-app-on-host2  # take one out
for i in $(seq 1 20); do curl -s https://app.example.com/whoami; done | sort | uniq -c
curl -s http://localhost:2019/reverse_proxy/upstreams | jq .
sudo journalctl -u caddy --since '5m ago' | grep -iE 'upstream|health|unavail'

The first loop shows the distribution across upstreams. The second confirms Caddy stopped sending to the stopped host. The /reverse_proxy/upstreams endpoint shows current health state from Caddy’s perspective.

What’s happening

When reverse_proxy has multiple dial upstreams, every request runs through a picker that selects which upstream to use. The picker’s behavior is set by lb_policy. The choices:

  • random (default) — uniformly random. Simple, distributes evenly over time, but has no awareness of upstream load.
  • round_robin — cycle through the list. Each request picks the next upstream in order. Deterministic distribution.
  • least_conn — pick the upstream with the fewest active connections. Adapts to slow requests; good for workloads with variable request duration.
  • ip_hash — hash the client’s source IP, mod number of upstreams. Same client always lands on the same upstream — useful for session stickiness when you cannot use a cookie.
  • uri_hash — hash the request URI. Same path always goes to the same upstream. Useful for cache locality in a fleet of cache servers.
  • header — hash a request header (lb_policy header X-Tenant-ID). Stickiness by an arbitrary value the application controls.
  • cookie — set and read a sticky cookie (lb_policy cookie lb_route plus optional secret for signed cookies). Session affinity for browser clients.
  • first — always pick the first available upstream. Effectively an active-passive failover pattern.
  • random_choose <n> — random across all, but pick the least-loaded among n random choices. Power-of-two-choices, the academically optimal compromise between random and least-conn.
  • weighted_round_robin <weights> — round_robin with per-upstream weights. Useful when upstreams have different capacity (e.g., a beefier box during a fleet upgrade).

Each picker is paired with health checks: passive (failed requests evict the upstream temporarily) and active (a periodic ping to a configured health endpoint). Both can coexist; they cover different failure modes.

Reference

round_robin example. Three same-capacity backends:

app.example.com {
    reverse_proxy host-a:3000 host-b:3000 host-c:3000 {
        lb_policy round_robin
        health_uri /health
        health_interval 5s
        health_timeout 1s
        health_status 2xx
        fail_duration 30s
        max_fails 2
    }
}

health_uri is the active health check endpoint. health_interval is the polling cadence. health_timeout is how long Caddy waits for the health response before counting it as a failure. health_status 2xx accepts any 2xx as healthy. fail_duration is how long a passive failure (real request returning 5xx) keeps the upstream out of rotation. max_fails is consecutive failures before active eviction.

least_conn example. A mix of fast and slow request types:

api.example.com {
    reverse_proxy api-1:3000 api-2:3000 api-3:3000 {
        lb_policy least_conn
        health_uri /health
        health_interval 3s
    }
}

Caddy tracks active in-flight connections per upstream. The slowest backend on a given moment receives the fewest new requests — naturally backs off the struggling one.

ip_hash for session stickiness. A legacy app with in-memory session state:

legacy.example.com {
    reverse_proxy legacy-1:3000 legacy-2:3000 {
        lb_policy ip_hash
    }
}

Same IP, same upstream — as long as the upstream is healthy. If one upstream goes down, ip_hash falls back to the next healthy one but loses the affinity for those clients.

cookie-based stickiness. Browser sessions on a stateful app:

app.example.com {
    reverse_proxy app-1:3000 app-2:3000 app-3:3000 {
        lb_policy cookie lb_route s0meRandomSecret
        lb_try_duration 5s
    }
}

Caddy sets a Set-Cookie: lb_route=<signed> on the first response. Subsequent requests from the same browser carry the cookie; Caddy reads it and routes to the same upstream. The secret signs the cookie so clients cannot tamper.

weighted_round_robin during a roll. Drain one host while a deploy lands:

app.example.com {
    reverse_proxy {
        to host-a:3000
        to host-b:3000
        to host-c:3000
        lb_policy weighted_round_robin 10 10 1
    }
}

host-a and host-b get 10 weight each, host-c gets 1 — effectively host-c is in pre-drain mode. Reload Caddy when ready to drop weight to 0.

Active-passive failover. Primary upstream with a hot standby:

api.example.com {
    reverse_proxy primary:3000 standby:3000 {
        lb_policy first
        health_uri /health
        health_interval 2s
    }
}

Caddy always picks primary while it is healthy. If primary fails health checks, Caddy promotes standby. When primary recovers, Caddy switches back. Useful for stateful backends where running both writes simultaneously would corrupt state.

The procedure

  1. Pick the policy from the workload shape. Stateless API: random or round_robin. Variable request times: least_conn. Browser session affinity: cookie. Cache fleet by URI: uri_hash. Active-passive: first. Anything else: start with random and revisit when you have data.

  2. Enable both active and passive health checks. Active catches “the box is up but the app crashed” before any real request hits the failure; passive catches “the upstream is timing out under load”:

    health_uri /health
    health_interval 5s
    health_timeout 2s
    health_status 200
    fail_duration 30s
    max_fails 2
  3. Tune lb_try_duration for retries. A failed first attempt re-tries on a different upstream:

    lb_try_duration 5s
    lb_try_interval 250ms

    Set both to zero to fail fast; raise them when transient upstream errors are common and you want client-invisible retry.

  4. Inspect upstream health via the API. curl http://localhost:2019/reverse_proxy/upstreams returns the live health state per registered upstream. Wire this into your monitoring — a passive failure on a specific backend is visible here before the metrics roll up.

  5. Reload-safe policy changes. A systemctl reload caddy after an lb_policy change is in-process — no dropped connections. But existing keep-alive connections continue using the old policy until they close.

Operational notes

  • The random policy is unbiased over many requests but unbalanced over few. A burst of 10 requests to a 3-host pool may land 7/2/1, not 3/3/4. For tight distribution requirements, use round_robin or least_conn.
  • ip_hash is sensitive to the client population. If 80% of traffic comes from one corporate NAT, 80% of requests pile onto one upstream. Look at the actual IP distribution before picking ip_hash.
  • Cookie-based stickiness leaks across HTTPS and HTTP if not pinned with Secure. Caddy sets Secure automatically when the listener is HTTPS, but verify on edges that handle both.
  • Health check requests count against the upstream’s connection budget. If your upstream is sized for 100 concurrent connections and you have 10 Caddy instances polling every second, that is 10 health checks per second on top of real traffic.
  • fail_duration 30s is short for some workloads. An upstream that times out under load may be marked unhealthy, then re-added, then time out again — flapping. Tune to 1-5 minutes for stable production.

Stack Harbor selects load balancing policies as a workload-fitted choice rather than a default — health checks tuned to the application’s actual liveness signal, retry durations matched to the SLO, and the upstream health surface monitored alongside the access logs. If you have a multi-upstream Caddy edge whose policy was picked at boot and never revisited, this is the kind of work covered by our Managed Operations practice.