Configuration Reference
Conduit is configured with a single file in JSON or YAML format. Both are fully equivalent — YAML is recommended because it supports comments.
conduit -c conduit.yaml # explicit path
conduit -c conduit.json # JSON is fine too
conduit # auto-discover: conduit.json → conduit.yaml → conduit.yml
conduit validate -c conduit.yaml # validate without starting
Fields accept environment variable references — "$MY_VAR" is replaced at
startup. This keeps secrets out of config files. The reference works wherever a value stands,
a number included (port: $PORT in YAML), and the value arrives unchanged: in JSON and in a
YAML "..." it is written as a JSON string, in a YAML '...' a quote is doubled, in an
unquoted YAML value it is written as it is. A value that an unquoted YAML value cannot carry
without changing it (a line break of any kind, a space at the start or end, a start such as *, &,
!, |, - , a : or ` # inside it, a # right after a space, a comma or bracket inside [ ], an empty
value or one that YAML reads as null: null, ~) makes the load fail with a
message that names the variable and never shows the value: put the reference in double quotes
(“$MY_VAR”). A variable that is not set leaves $MY_VAR` as written. A reference in a YAML comment is
not replaced.
Warning, credentials: a password, API key, JWT secret or Admin API token whose whole value is a reference to a variable that is not set keeps the text of the reference, and that text is then the credential: anyone who has seen the configuration, an example or this page can present
$MY_VAR.conduit validate, the start-up log andPOST /reloadwarn about every such credential (the warning names the place and the variable, never a value). Treat the warning as an error in a deployment: set the variable in the environment of the process (for the systemd unit:/etc/conduit/conduit.env). A real credential must not be written as a bare$Word(for example$Hunter2): it cannot be told from a reference to an unset variable, so the warning would print it as a variable name.
Optional build features
Conduit is compiled from Cargo features: a feature that is not compiled in is not in the binary, so it cannot be attacked, and the binary is smaller. There are three kinds, and every name below is described in the tables that follow:
- Baseline features, on by default:
proxy,compression,static,hotreload,mimalloc. - Optional features, off unless you ask for them:
jwt,consumers,forward-auth,rhai,wasm,ext-proc,tcp,upload,redis,cache,disk-cache,acme,fault-injection,otlp,tokio-metrics,kubernetes,jemalloc. - Bundles, which are only a short name for a set of the above:
standard,gateway,static-server,full. A bundle adds no code of its own.
The published downloads and images are full (the plain file names and tags), standard, gateway and
static-server (names ending in -standard, -gateway, -static); npx installs full;
cargo install lopatnov-conduit is the default build. See
docs/cli.md: Build features and
Building for sizes and build commands.
If your config uses something your binary lacks, Conduit does not fail: the section is
parsed, ignored, and a warning is printed at start-up and by conduit validate. That
matters most for the security features and for middleware that can reject a request,
where “ignored” means the check is not applied (jwtAuth without jwt, consumers
without consumers, forwardAuth without forward-auth, a rhai or wasm entry that
was a gate: every request goes through unchecked). The one exception is an ext_proc entry
that is not failOpen: a build without ext-proc refuses to start with it, because
skipping it would switch the check off silently. To see what a config needs, and whether the
binary you run has it:
conduit features -c conduit.yaml # lists the features the config needs; exit 1 if this binary lacks one, 2 if the config cannot be loaded
conduit validate -c conduit.yaml # prints a warning for every ignored section
Baseline features (on by default)
| Feature | What it gives you | Config | If it is compiled out |
|---|---|---|---|
proxy |
Reverse proxying: upstream targets, load balancing, upstream groups, health checks, retry, circuit breaker, traffic mirroring. | proxy, routes[].proxy, groups |
Those sections are ignored; a request that would have gone to an upstream gets the site’s fallback response. See Building without proxy. |
compression |
Response compression (brotli, gzip, deflate, zstd), negotiated with Accept-Encoding, for static files, fallback responses and the metrics page. Proxied responses are not compressed by Conduit (the upstream can do it). |
compression |
Responses are sent uncompressed. |
static |
Static file serving and the fallback responses (404 page, single-page-app shell). | static, fallback |
static and fallback are ignored: every unmatched request gets a plain 404 Not Found. |
hotreload |
Browser live reload: a Server-Sent Events stream and a file watcher that tells open pages to refresh when a served file changes. | hotReload |
hotReload is ignored and /__hot-reload__ is an ordinary unmatched path. |
mimalloc |
The mimalloc memory allocator, in its hardened secure mode, in the conduit binary instead of the system one: about 4 % less CPU per proxied request in our measurement (see building). A build-time choice; nothing to configure. |
no config key | The system allocator is used (--no-default-features); everything works, a little slower. |
Without these (--no-default-features) little is left: TLS, the always-on guards (IP
filter, rate limits, CORS, security headers), redirects, the health endpoint, metrics and the
Admin API.
Optional features
| Feature | What it gives you | Config | If it is compiled out |
|---|---|---|---|
jwt |
Validates JWT bearer tokens: HS256 with a shared secret, RS256/ES256 through a JWKS URL (fetched and refreshed in the background). Claims are available as `` in header templates. | jwtAuth, claim templates |
jwtAuth is ignored: requests are not authenticated by JWT. JWT credentials of consumers are not recognised either. |
consumers |
Named API clients: each with its own API keys, Basic or JWT credentials, its own rate limit and headers added to the proxied request. | consumers |
consumers is ignored: API-key, Basic and JWT consumer authentication is not applied, every request bypasses it. |
forward-auth |
Asks an external HTTP service whether each request may pass (like nginx auth_request or Traefik ForwardAuth) and copies chosen headers from its answer. |
forwardAuth |
forwardAuth is ignored: the external check does not run. |
rhai |
Small scripts as middleware: read or change headers, reject a request, answer it directly. | middleware[].type: "script" |
The entry is ignored: a script that was a gate no longer runs. |
wasm |
WebAssembly plugins (any language that compiles to WASM) run in a Wasmtime sandbox as middleware; a plugin that fails lets the request through (fail-open). Adds the Wasmtime runtime to the binary. | middleware[].type: "wasm" |
The entry is ignored: a plugin that was a gate no longer runs. |
ext-proc |
Sends the request headers to an external processor over gRPC (Envoy’s ext_proc protocol), which can change them or answer the request itself, and fails closed when the processor does not answer. Adds the gRPC client (tonic, prost) to the binary. |
middleware[].type: "ext_proc" |
A fail-closed entry (the default) is refused at validation: the binary will not start with it. A failOpen: true entry is ignored with a warning: requests are not sent to the processor. |
tcp |
A raw TCP proxy site, for protocols that are not HTTP (databases, message brokers, anything else on a TCP port). | type: "tcp" site |
The site is ignored. |
upload |
An endpoint that accepts multipart file uploads and writes them to a directory. | upload |
upload is ignored. |
redis |
Keeps rate-limit counters and cached responses in Redis, so several Conduit instances share them. | global.redis, rateLimit.store: redis, cache.store: redis |
A rate limit falls back to the in-memory store, per instance: with three instances each limit effectively triples. A route with a Redis cache store is not cached. |
cache |
HTTP response cache for proxied responses (memory store). Implies proxy. |
proxy.*.cache |
Responses are not cached. |
disk-cache |
The on-disk cache store, cache.store: "disk:/path": the code that writes cache files under a directory. Implies cache. A cache build without it is a memory (and, with redis, Redis) cache. |
cache.store: "disk:/path" |
The route is not cached and nothing is written under the directory; the start-up log and conduit validate say so. |
acme |
Obtains and renews certificates from Let’s Encrypt on its own. | tls.acme |
tls.acme is ignored: no certificate is requested. |
fault-injection |
Adds delays or errors to a share of the requests, to test how clients and upstreams behave under failure. | faultInjection |
faultInjection is ignored (nothing is broken on purpose). |
otlp |
Exports traces to an OpenTelemetry collector over OTLP. | global.otlp |
global.otlp is ignored: no traces are exported. |
tokio-metrics |
One more Prometheus gauge: conduit_eventloop_lag_ms, the scheduling delay of the admin runtime. |
no config key | The gauge is absent. |
kubernetes |
Reads the sites from ConduitSite resources in a cluster instead of a file. |
--kubernetes-namespace (a command-line flag, not a config field) |
The flag does not exist. |
jemalloc |
The jemalloc memory allocator in the conduit binary, instead of mimalloc. Not in any bundle: mimalloc measured faster and smaller (building); jemalloc is for those who prefer its tuning and profiling. With both on, jemalloc is used. |
no config key | mimalloc (the default) or the system allocator is used. |
Bundles
A bundle is a name for several features. ✓ means the bundle includes the feature.
| Feature | standard |
gateway |
static-server |
full |
|---|---|---|---|---|
proxy |
✓ | ✓ | ✓ | |
compression |
✓ | ✓ | ✓ | ✓ |
static |
✓ | ✓ | ✓ | |
hotreload |
✓ | ✓ | ✓ | |
mimalloc |
✓ | ✓ | ✓ | ✓ |
jwt, consumers, forward-auth, cache, disk-cache, acme |
✓ | ✓ | ✓ | |
rhai, wasm, ext-proc, tcp, upload, redis, fault-injection, otlp, tokio-metrics, kubernetes |
✓ |
standard: the default set plus the authentication, cache and automatic-TLS stack most self-hosted reverse proxies and API gateways need. This is what the published “standard” binaries (-standard) and the:latest-standardimage contain.gateway: for--no-default-featuresbuilds of a pure API gateway: the proxy and the same stack, compression, but no static files and no live reload (cargo build --release --no-default-features --features gateway).static-server: for--no-default-featuresbuilds of a file server that does not proxy: static files, compression, live reload (cargo build --release --no-default-features --features static-server).full: everything above. The plain-named downloads,:latestand the npm package are this build;-standard,-gatewayand-staticdownloads (and:latest-standard,:latest-gateway,:latest-staticimages) are the other three bundles.
Which one to pick:
| You want | Build |
|---|---|
| A reverse proxy with auth, caching and automatic HTTPS | standard (the -standard download, :latest-standard) |
| Everything, including scripting, WASM, TCP, uploads, Redis | full |
| The smallest proxy | the default build, or --no-default-features --features proxy |
| A static site server with no upstream at all | --no-default-features --features static-server |
| A gateway without static files | --no-default-features --features gateway |
| A few extra features on top of the default build | --features "jwt,rhai" |
Download the plain-named (full) binary, or one ending in -standard, -gateway or -static, from GitHub Releases
or build from source: cargo build --release --features full.
Table of Contents
Background
- Concepts — request pipeline, forwarded headers, skipPaths glob
Essentials
Routing
Reliability
Caching
Authentication
Rate Limiting & Load Shedding
Transforms
Observability
Security
Middleware
- Rhai script middleware / Full guide ↗
- WASM middleware / Full guide ↗
- External processing (ext_proc) / Full guide ↗
Advanced
- Connection pool
- Multi-site (virtual hosting)
- PROXY protocol
- Upload
- Admin API — see also admin.md for full reference
- Prometheus metrics reference
Concepts
These sections explain how Conduit behaves — not config fields you set, but background knowledge that helps understand the rest of the reference.
Request pipeline
The order in which configured features are applied for every incoming request:
Incoming request
│
├─ 1. X-Request-ID injection — auto-generate UUID v4 if absent
├─ 2. IP filter — 403 if blocked (before any auth)
├─ 3. CORS preflight — OPTIONS short-circuit
├─ 4. Health / ACME bypass — skip all guards for /__health__ etc.
├─ 5. Inflight limit — 503 if maxInflightRequests exceeded
├─ 6. Site-level rate limit — 429 if over limit
├─ 7. Consumers — identify named client (V1/V2/V3)
├─ 8. Basic Auth — 401 if credentials missing/wrong
├─ 9. API Key — 401 if key missing/wrong
├─ 10. JWT Auth — 401 if token invalid
├─ 11. Forward Auth — delegate to external service
├─ 12. Redirects — 301/308 if path matches
├─ 13. Fault injection — abort/delay (testing only)
├─ 14. Rhai / WASM middleware — custom scripts in order
│
├─ Route matching + per-route rate limit
├─ Circuit breaker check
│
└─ Upstream request
├─ X-Forwarded-For / -Proto / -Host injection
├─ requestTransform (setHeaders / removeHeaders)
├─ Path rewrite (stripPrefix / rewrite rules)
└─ Traffic mirror (fire-and-forget)
Upstream response
├─ CRLF header protection
├─ CORS / security / custom headers injection
├─ responseTransform
├─ X-Response-Time header
├─ Retry-on-error decision
└─ Error masking (5xx body replacement)
Steps 7–11 are mutually exclusive in practice — only one auth method identifies
the client, but multiple may be configured as fallbacks. The consumers guard
runs before basicAuth and apiKey, so a consumer match takes priority.
Forwarded headers
Conduit automatically injects these headers into every proxied upstream request. No configuration is needed — they are always present.
| Header | Value | Notes |
|---|---|---|
X-Forwarded-For |
Client IP | Appended to existing value if already present |
X-Forwarded-Proto |
http or https |
Derived from whether the site has TLS configured |
X-Forwarded-Host |
Original Host header |
Lets upstreams reconstruct full URLs |
X-Request-ID |
UUID v4 | Auto-generated if absent; forwarded as-is if client sends it |
Via |
1.1 conduit |
RFC 7230 §5.7 — identifies the proxy hop; appended to existing value |
To remove any of these before forwarding, use requestTransform.removeHeaders:
# conduit.yaml
requestTransform:
removeHeaders: [X-Forwarded-For, X-Forwarded-Host]
// conduit.json
{
"requestTransform": {
"removeHeaders": ["X-Forwarded-For", "X-Forwarded-Host"]
}
}
skipPaths glob syntax
Many config sections accept a skipPaths list — requests whose path matches
are bypassed by that feature entirely. It is not a top-level field; it
appears inside basicAuth, apiKey, jwtAuth, forwardAuth, consumers,
rateLimit, and logging.
Two pattern forms are supported:
| Pattern | Matches |
|---|---|
/exact/path |
Only that exact path |
/prefix/** |
The prefix itself, /prefix/, and any sub-path |
# conduit.yaml — example inside jwtAuth
jwtAuth:
secret: "$JWT_SECRET"
skipPaths:
- /__health__ # exact match — health check bypasses JWT
- /public/** # /public, /public/, /public/assets/logo.png, …
// conduit.json
{
"jwtAuth": {
"secret": "$JWT_SECRET",
"skipPaths": ["/__health__", "/public/**"]
}
}
Note: only
/**at the end is supported as a wildcard. Patterns like/api/*/detailsor/**.jsonare treated as exact matches (no mid-path or extension wildcards).
Port and Host
# YAML
port: 8080
host: api.example.com # optional — virtual hosting
// JSON
{ "port": 8080, "host": "api.example.com" }
| Field | Type | Default | Description |
|---|---|---|---|
port |
number | 80 / 443 ¹ |
TCP port to listen on |
host |
string | — | Virtual hostname. Omit to match all Host headers (catch-all) |
¹ Default port is
443whentlsis configured,80otherwise. When no sites are configured at all, Conduit listens on8080as a fallback.
Use host when running multiple sites on the same process.
TLS / HTTPS
Manual certificates
# YAML
port: 443
tls:
cert: /etc/tls/server.crt
key: /etc/tls/server.key
httpRedirectPort: 80
// JSON
{
"port": 443,
"tls": {
"cert": "/etc/tls/server.crt",
"key": "/etc/tls/server.key",
"httpRedirectPort": 80
}
}
Auto-TLS via Let’s Encrypt
Requires
cargo build --features acme
# YAML
host: example.com # required: the certificate is ordered for this name
port: 443
tls:
acme:
email: admin@example.com
storage: ./certs
challenge: http-01
// JSON
{
"host": "example.com",
"port": 443,
"tls": {
"acme": {
"email": "admin@example.com",
"storage": "./certs",
"challenge": "http-01"
}
}
}
The certificate is ordered for the site’s host, and the files are stored as
<storage>/<host>.crt.pem and <storage>/<host>.key.pem. Because the host becomes part of a
file name, conduit validate rejects a host that is not a plain DNS name: labels of ASCII
letters, digits and hyphens separated by dots (international names in punycode, xn--…), with
no /, \, .., empty label or other character. A leading *. is accepted, but a CA
validating over HTTP-01, the only challenge Conduit implements, normally refuses wildcards.
A background task renews the certificate on disk when no more than a third of its lifetime is left, and never
later than 30 days before expiry (30 days for a 90-day certificate, 21 for a 64-day one, 15 for a 45-day one), or earlier when the CA’s ACME Renewal Information (RFC 9773) asks for it; the running process keeps serving the one it loaded, so restart Conduit
within that window (with profile: shortlived, a certificate of about 6 days, that window is 2 days: restart at least every day or two, or the process serves an expired certificate). Details: acme in the CLI reference.
The account with the CA is kept in <storage>/acme_account.json, which records the directory URL it was created for.
When you point directory at another CA (staging to production, say), the old account is not tried against the new CA:
a second file, acme_account.<readable part of the URL>.<hash of the whole URL>.json, holds the account for it, and a file that records another directory than the one asked for is refused. A private key that you placed at
<storage>/<host>.key.pem is read only as PKCS#8 (-----BEGIN PRIVATE KEY-----); a PKCS#1 (RSA PRIVATE KEY), SEC1
(EC PRIVATE KEY) or encrypted key is named in the log and then replaced by a newly ordered key, so convert it first
(openssl pkcs8 -topk8 -nocrypt -in old.key -out <host>.key.pem).
TLS field reference
| Field | Type | Default | Description |
|---|---|---|---|
cert |
path | — | PEM certificate file |
key |
path | — | PEM private key file |
ca |
path | — | CA bundle for upstream verification |
httpRedirectPort |
number | — | Port that redirects HTTP to HTTPS. Only Host values of sites using this port are redirected (a site without host, or with "*", allows any valid host); other hosts get 421 Misdirected Request, an invalid Host gets 400 |
acme.email |
string | — | Contact email for ACME account |
acme.storage |
path | — | Directory for certificate persistence |
versions/ciphersare not currently enforced (issue #189). The fields still parse, but the way Conduit builds its TLS listeners (through Pingora’sTlsSettings) gives no way to restrict protocol versions or cipher suites — TLS 1.2 and 1.3 are always both enabled with the default rustls cipher suite set, regardless of config. (Pingora 0.9 still exposes no way to set versions or ciphers on a listener:TlsSettings::build()hard-codes TLS 1.2 and 1.3.) Setting either field is a hard validation error (fails startup with an explanation) rather than a silent no-op, so a misconfigured expectation of TLS restriction can’t go unnoticed. |acme.challenge| string | — |"http-01"(the only challenge implemented; other values are rejected) | |acme.profile| string | — | Certificate profile to ask the CA for (Let’s Encrypt:classic,tlsserver,shortlived); absent = the CA’s default. An empty value is rejected; a profile the CA does not offer fails the order | |acme.orderTimeoutSecs| integer |60| Seconds one request of an order (account setup, new order, finalize, certificate download) may take. 1 to 86400 | |acme.validationTimeoutSecs| integer |180| Seconds the whole challenge validation may take. 1 to 86400 | |acme.ariTimeoutSecs| integer |30| Seconds the whole renewal-information (ARI) probe may take; one request of it gets half. 1 to 86400 | |acme.retryAfterMinSecs| integer |300| The CA’sRetry-Afteris never taken as shorter than this. Must not exceedretryAfterMaxSecs. 60 to 86400 | |acme.retryAfterMaxSecs| integer |86400| The CA’sRetry-Afteris never taken as longer than this. 1 to 86400 | |acme.checkIntervalSecs| integer |43200| Seconds between two renewal checks of a certificate. With several ACME sites the shortest value counts. 300 to 86400 | |acme.directory| string | — | Custom ACME directory URL. Use"https://acme-staging-v02.api.letsencrypt.org/directory"for Let’s Encrypt staging (rate-limit-free testing) | |clientAuth| object | — | mTLS client cert verification |
Note — single cert per port: Conduit does not support per-SNI certificate selection yet. When multiple HTTPS sites share the same port, the first registered cert is used for all. Use separate ports for different certificates. (Pingora 0.9’s rustls backend can pick a certificate per SNI hostname through a custom resolver; Conduit does not install one yet.)
HTTP/2
# YAML
port: 443
tls:
cert: ./certs/cert.pem
key: ./certs/key.pem
http2: {} # enable HTTP/2 with defaults
// JSON
{
"port": 443,
"tls": { "cert": "./certs/cert.pem", "key": "./certs/key.pem" },
"http2": {}
}
Full config with all fields:
http2:
maxConcurrentStreams: 100
initialWindowSize: 65535
h2c: false # HTTP/2 cleartext (internal gRPC without TLS)
// JSON
{
"http2": {
"maxConcurrentStreams": 100,
"initialWindowSize": 65535,
"h2c": false
}
}
| Field | Type | Default | Description |
|---|---|---|---|
maxConcurrentStreams |
number | 100 |
Max parallel streams per connection |
initialWindowSize |
number | 65535 |
Flow-control window in bytes |
h2c |
bool | false |
Serve HTTP/2 on plaintext connections (h2c): a client that starts with the HTTP/2 preface, as gRPC clients do (prior knowledge), works (tested in scripts/e2e/grpc.sh); the HTTP/1.1 Upgrade: h2c handshake is not covered by a test. For TLS ports HTTP/2 is negotiated via ALPN regardless. See gRPC. |
Compression
Add Content-Encoding: br / zstd / gzip / deflate to responses. Applies
to static files, the metrics endpoint, and fallback responses (JSON/text body
or file) — each negotiated independently against the same minBytes/types
thresholds, so a small metrics scrape or error body may stay uncompressed
even with compression enabled.
# YAML — shorthand (enable with defaults)
compression: true
# YAML — fine-grained
compression:
algorithms: [br, zstd, gzip] # Brotli first, then Zstd, then gzip
level: 6 # 1 = fastest, 9 = smallest
minBytes: 1024 # skip responses smaller than 1 KB
// JSON — shorthand
{ "compression": true }
// JSON — fine-grained
{
"compression": {
"algorithms": ["br", "zstd", "gzip"],
"level": 6,
"minBytes": 1024
}
}
The types field filters which response Content-Types are compressed:
compression:
algorithms: [br, gzip]
types:
- "text/"
- "application/json"
- "application/xml"
- "application/javascript"
- "image/svg"
| Field | Type | Default | Description |
|---|---|---|---|
algorithms |
string[] | ["br", "zstd", "gzip"] |
Compression algorithms to offer. Supported: "br" (Brotli), "zstd" (Zstandard), "gzip", "deflate" |
level |
number | 6 |
Compression level (1–9) |
minBytes |
number | 1024 |
Minimum response size to compress (bytes) |
types |
string[] | ["text/", "application/json", "application/xml", "application/javascript", "application/xhtml", "image/svg"] |
Content-Type prefixes to compress. Use ["*"] to compress all types (not recommended for binary content) |
Response Time Header
Inject X-Response-Time: <ms> into every response.
# YAML
responseTime: true
# With custom precision
responseTime:
digits: 3 # decimal places in the millisecond value
// JSON
{ "responseTime": true }
// JSON
{ "responseTime": { "digits": 3 } }
Server-Timing Header
Add a W3C Server-Timing header to proxied responses so
that browser DevTools (Network → Timing) can show where the time went.
# YAML
serverTiming: true
// JSON
{ "serverTiming": true }
server-timing: total;dur=12.4, upstream;dur=11.8
total;dur=<ms>is the time from receiving the request to getting the response headers back.upstream;dur=<ms>is the time the upstream took to return its response headers.
The header is added to responses that come back from an upstream. A response Conduit produces itself (a static file, a redirect, a rejection by a guard) does not carry it. The header is visible to every client, so leave it off if you do not want to expose timings.
Proxy
The proxy object maps URL path prefixes to upstream targets. Each key is a path and starts with / (an empty key means /); a key that
does not can never match a request, and conduit validate warns about it. In particular proxy: { targets: [...] } is
one route named targets, not “these are the targets”: to send every request to one upstream write
proxy: "http://host:port" or proxy: { "/": [...] }. (targets is a field of a route’s object, as in
proxy: { "/api": { targets: [...] } }.)
Single upstream (shorthand)
# YAML
proxy:
/api: "http://backend:4000"
// JSON
{ "proxy": { "/api": "http://backend:4000" } }
Multiple targets
# YAML
proxy:
/api:
targets:
- "http://backend-1:4000"
- "http://backend-2:4000"
strategy: round-robin
stripPrefix: true
// JSON
{
"proxy": {
"/api": {
"targets": ["http://backend-1:4000", "http://backend-2:4000"],
"strategy": "round-robin",
"stripPrefix": true
}
}
}
URL rewriting
Rewrite rules are evaluated in order. The first matching rule is applied.
# YAML
proxy:
/api:
targets: ["http://backend:4000"]
stripPrefix: true
rewrite:
- from: "^/v[0-9]+/(.+)$" # strip version prefix
to: "/$1"
- from: "^/users/([0-9]+)$" # migrate legacy paths
to: "/members/$1"
// JSON
{
"proxy": {
"/api": {
"targets": ["http://backend:4000"],
"stripPrefix": true,
"rewrite": [
{ "from": "^/v[0-9]+/(.+)$", "to": "/$1" },
{ "from": "^/users/([0-9]+)$", "to": "/members/$1" }
]
}
}
}
Proxy route field reference
| Field | Type | Default | Description |
|---|---|---|---|
targets |
string[] or object[] | — | Upstream URLs (plain strings or {url, weight}); http://, https://, and ws:///wss:// as the same two (a WebSocket handshake is an HTTP request) |
strategy |
string | round-robin |
Load balancing — see Load balancing |
stripPrefix |
bool | false |
Remove matched path prefix before forwarding |
rewriteDestination |
bool | false |
WebDAV: apply stripPrefix and rewrite to the paths in the Destination and If request headers too — see WebDAV |
hashKey |
string | — | Key for hash-based strategies: "ip", "url", "header:X-Name" |
rewrite |
object[] | — | URL rewrite rules: [{from, to}] — first match wins |
http2 |
bool or "h2c" |
false |
HTTP/2 to the upstream: true negotiates it through ALPN (TLS upstreams); "h2c" also speaks it to a plaintext upstream (gRPC without TLS) — see gRPC |
timeout.connectMs |
number | 3000 |
TCP connect timeout |
timeout.sendMs |
number | — | Request send timeout |
timeout.readMs |
number | 30000 |
Response read timeout |
timeout.firstByteMs |
number | — | Max ms to wait for first upstream response byte (overrides readMs) |
timeout.perTryMs |
number | — | Per-retry timeout |
websocket |
bool | false |
Allow WebSocket upgrades (101 Switching Protocols) — rejected with 502 by default |
retry.attempts |
number | 0 |
Number of retry attempts (0 = disabled) |
retry.conditions |
string[] | — | connection_error, 5xx, timeout |
retry.backoffMs |
number | 0 |
Wait between retries (ms) |
retry.backoffJitter |
bool | false |
±50% random spread on backoffMs to avoid thundering herd |
retry.budgetPercent |
number | — | Soft cap: max % of in-flight requests that may be retries |
healthCheck |
object | — | Active health probes — see Health checks |
backup |
string | — | Fallback URL when all primaries are unhealthy |
cache |
object | — | Response cache — see Proxy cache |
pool |
object | — | Connection pool — see Connection pool |
rateLimit |
object | — | Per-route rate limit — see Rate limiting |
upstreamTls |
object | — | TLS for HTTPS upstreams — see Upstream TLS |
mirror |
string | — | Shadow URL — see Traffic mirroring |
sticky.cookie |
string | — | Cookie name for sticky sessions |
sticky.secret |
string | — | HMAC-SHA256 secret — Conduit signs + verifies the cookie (prevents forgery) |
sticky.strict |
boolean | false |
Return 503 when the pinned upstream is down (instead of routing elsewhere) |
sticky.secure |
boolean | when tls |
Secure attribute of the cookie Conduit sets (needs secret) |
sticky.maxAgeSecs |
integer | session | Max-Age of the cookie Conduit sets (needs secret) |
groups |
object[] | — | Two-level LB groups: [{name, targets, strategy}] |
groupStrategy |
string | round-robin |
Outer strategy when groups is set |
priority |
number (0–100) | 50 |
Request priority for load shedding — see Priority routing |
Routes
The routes array matches requests before proxy / static. First match wins.
# YAML
routes:
# Route to dedicated API v2 server — checked first
- match:
path: /api/v2/**
method: [GET, POST]
headers:
X-Version: "2"
proxy:
targets: ["http://v2-backend:4000"]
# Write operations go to write cluster
- match:
path: /api/**
method: [POST, PUT, PATCH, DELETE]
proxy:
targets: ["http://write-api:4001", "http://write-api:4002"]
strategy: least-conn
# Beta users via cookie → canary backend
- match:
cookies:
beta: "1" # exact: cookie beta=1
experiment: "blue|green" # regex: blue or green
proxy:
targets: ["http://canary:4000"]
# Everything else → SPA static files
- match:
path: /**
static: ./dist
// JSON
{
"routes": [
{
"match": {
"path": "/api/v2/**",
"method": ["GET", "POST"],
"headers": { "X-Version": "2" }
},
"proxy": { "targets": ["http://v2-backend:4000"] }
},
{
"match": {
"path": "/api/**",
"method": ["POST", "PUT", "PATCH", "DELETE"]
},
"proxy": {
"targets": ["http://write-api:4001", "http://write-api:4002"],
"strategy": "least-conn"
}
},
{
"match": { "path": "/**" },
"static": "./dist"
}
]
}
Each route entry has exactly three top-level fields: match, proxy, and static.
Auth, rate limiting, and other policies come from the site-level config and apply
to all routes uniformly.
A proxy action takes the same route options as an entry of the proxy: {} map
(see Proxy route field reference): groups,
strategy, hashKey, sticky, backup, retry, rewrite, mirror,
upstreamTls, healthCheck and the rest behave identically in both forms. Two
things differ because a routes[] entry has no path-prefix key:
stripPrefixremoves the literal prefix ofmatch.path(/api/**strips/api; an exact path such as/healthstrips the whole path). Without amatch.paththere is nothing to strip.ipHash/consistentHashfollowhashKey(default: the client IP) exactly as in theproxymap. Before this change aroutes[]entry hashed the request path instead.
match field |
Type | Description |
|---|---|---|
path |
glob | Path glob — see skipPaths glob syntax |
method |
string[] | HTTP methods to match (case-insensitive) |
headers |
object | Request headers that must match (exact or regex) |
query |
object | Query parameters that must match (exact or regex) |
cookies |
object | Cookies that must match (exact or regex) |
All headers, query, and cookies values are matched as full-string
regex (anchored ^…$). Plain strings like "v2" or "1" match exactly;
regex patterns like "blue|green" or "Bearer .+" use regex semantics. An
invalid regex falls back to exact-string comparison.
Load Balancing
Set strategy inside a proxy route. All strategies skip upstreams that are
currently unhealthy (failed health probes) or ejected (outlier detection).
proxy:
/api:
targets: ["http://a:4000", "http://b:4000"]
strategy: least-conn # pick a strategy
Choosing a strategy
The algorithm matters less than it looks — every strategy here already skips unhealthy/ejected upstreams (health checks, not the algorithm, are what keeps traffic off a broken backend). Pick based on your actual traffic shape:
| Strategy | Family | Picks based on | Session affinity | Pool change impact | Best for | Weak point |
|---|---|---|---|---|---|---|
round-robin (default) |
Static | Rotation order | ✗ | none | Homogeneous upstreams, simplest default | Ignores load — a slow request still gets the next slot |
weighted-round-robin |
Static | Rotation + fixed weight | ✗ | none | Heterogeneous capacity (big primary + small standby, canary %) | Weights are static — doesn’t adapt to real-time load |
random |
Static | Uniform random pick | ✗ | none | Very large pools where a counter is unnecessary overhead | Worse uniformity than round-robin at small N |
least-conn |
Load-aware | Fewest active connections per unit of weight |
✗ | none | Variable response times (mixed fast reads / slow writes), with or without unequal capacity | O(N) scan of the pool on every request |
least-response-time |
Load-aware | Lowest probed latency | ✗ | none | Upstreams with different hardware/geography | Needs healthCheck configured, or it’s just round-robin |
p2c |
Load- and latency-aware | 2 random samples, lower EWMA latency × (in-flight + 1) ÷ weight wins |
✗ | none | Large pools (10+) where least-conn’s full scan is too slow |
Marginally less precise than true least-conn |
least-bandwidth |
Load-aware | √((bytes per second + 1) × (in-flight + 1)) ÷ weight, two random samples |
✗ | none | Mixed large and small responses, where equal connection counts hide very unequal network load | Counts bytes, not CPU or memory; a route’s meters start at zero and update every 250 ms |
ip-hash |
Affinity | rendezvous hash of the client IP | by IP | only the clients on a peer that leaves (or joins) move; the rest stay put | Soft per-IP affinity without a cookie | Behind a proxy or CDN every request has the proxy’s address and goes to one upstream; clients behind one NAT share an upstream |
consistent-hash |
Affinity | rendezvous hash of the configured key | by key | same as ip-hash — only the keys on a peer that leaves (or joins) move | Per-tenant/per-user routing, cache locality by URL path | Spreads keys, not requests: one very busy key loads one upstream; the header comes from the client |
Rule of thumb: start with round-robin. Move to least-conn or p2c once
request cost varies noticeably. Reach for ip-hash/consistent-hash only for
affinity, not performance — and prefer sticky.cookie over ip-hash when you
control the client, since cookie-based affinity survives the client’s own IP
changing, which ip-hash does not.
┌─────────────┐
client ──requests──▶ │ Conduit │
│ (strategy) │
└──────┬──────┘
┌───────────────────┼───────────────────┐
▼ ▼ ▼
upstream A upstream B upstream C
(healthy) (healthy) (ejected ✗ — skipped
by every strategy)
round-robin / weighted-rr / random → pick by rotation or chance
least-conn / least-response-time / p2c → pick by current load/latency
ip-hash / consistent-hash → pick by rendezvous hash of the key over the healthy set
round-robin (default)
Cycles through the target list in order, one request at a time. A per-route atomic counter is incremented on each request and taken modulo the number of healthy upstreams.
Request 1 → a Request 2 → b Request 3 → a …
Use when: all upstreams are homogeneous (same hardware, same capacity). Simple, predictable, zero overhead.
proxy:
/api:
targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
strategy: round-robin # or omit — this is the default
weighted-round-robin
Like round-robin, but each upstream gets a number of slots proportional to its
weight. If A has weight 3 and B has weight 1, the pattern is A, A, A, B per
four requests (exact interleaving may differ, but ratios are preserved over
time).
Use when: upstreams have different capacities — e.g. a beefy primary and a smaller standby, or a canary deployment receiving a fraction of traffic.
Targets must be { url, weight } objects — plain strings use weight 1.
proxy:
/api:
targets:
- { url: "http://primary:4000", weight: 9 } # 90% of traffic
- { url: "http://canary:4000", weight: 1 } # 10% canary
strategy: weighted-round-robin
// JSON
{
"proxy": {
"/api": {
"targets": [
{ "url": "http://primary:4000", "weight": 9 },
{ "url": "http://canary:4000", "weight": 1 }
],
"strategy": "weighted-round-robin"
}
}
}
Note:
conduit upstreams weightcan change weights at runtime without reloading the config.
least-conn
Routes each new request to the upstream with the fewest active in-flight connections at that instant. The connection counter is incremented before the request is forwarded and decremented when the response completes (including retries and errors).
Use when: requests have highly variable response times — e.g. a mix of fast reads and slow writes. Under uniform load it behaves like round-robin; its advantage emerges when some requests stall.
Ties. When several upstreams have the same count (all of them, whenever the
requests are short enough that none is still in flight when the next arrives),
one of them is chosen at random, in proportion to its weight. Earlier releases
always picked the first target in the list for such a tie, so a lightly loaded pool sent
every request to its first target.
Weights. The comparison is active connections divided by weight, as in
nginx least_conn: an upstream with weight 3 carries three times the in-flight
requests of a weight-1 upstream before the next request goes elsewhere. Plain
string targets have weight 1, so a pool without weights behaves exactly as
plain least-connections. An upstream with weight 0 receives nothing while any
other upstream has a weight above 0. conduit upstreams weight changes the
weight at runtime.
proxy:
/api:
targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
strategy: least-conn
proxy:
/api:
targets:
- { url: "http://big:4000", weight: 3 } # up to 3x the in-flight requests of "small"
- { url: "http://small:4000", weight: 1 }
strategy: least-conn
Tip: combine with
healthCheck.maxConnectionsPerUpstreamfor a circuit breaker that activates when all upstreams are saturated.
least-response-time
Routes each request to the upstream with the lowest measured latency from the most recent active health probe. Falls back to round-robin during the warm-up phase before any probe has completed.
Latency is measured by the health-check prober (a HEAD request to healthCheck.path for a plaintext upstream, the TCP connect time for a TLS one: https://, wss://).
Upstreams without probe data are ranked last (u64::MAX).
Use when: upstreams have meaningfully different hardware or geographic
proximity and you want to bias traffic toward the fastest one. Requires
healthCheck to be configured on the route — without probes, this strategy
falls back to round-robin permanently.
proxy:
/api:
targets:
- "http://us-east:4000"
- "http://eu-west:4000"
strategy: least-response-time
healthCheck:
path: /health
intervalSecs: 10
// JSON
{
"proxy": {
"/api": {
"targets": ["http://us-east:4000", "http://eu-west:4000"],
"strategy": "least-response-time",
"healthCheck": { "path": "/health", "intervalSecs": 10 }
}
}
}
ip-hash
Sends every request from the same client address to the same upstream, without
any cookie. Conduit hashes the address of the TCP peer that connected to it
(FNV-1a) and maps the hash to an upstream by rendezvous (highest-random-weight)
hashing: every healthy upstream is scored against the hash and the highest score
wins. The same address lands on the same upstream for as long as the set of
healthy upstreams is unchanged. An upstream listed twice is scored once, so a
duplicate entry is not a weight: use weighted-round-robin
when the capacities differ.
| Field | Meaning | Default |
|---|---|---|
strategy: ip-hash |
Turns the behaviour on. | round-robin |
hashKey |
What is hashed. The default ip is what this strategy is for; url and header:<Name> make ip-hash behave exactly like consistent-hash, which is the clearer name for them. |
ip |
Use when:
- an application keeps state in memory per client and has no shared session store (a legacy admin panel, a chat or game server where a reconnecting client should find its room), and you cannot add a cookie;
- you want one client’s requests, and so its log lines and its cache, on one backend (support work: “show me everything this address did”);
- you want soft affinity that needs no change in the client or the application.
Do not use it when:
- Conduit sits behind another proxy, a CDN or a cloud load balancer. The peer
address is then the address of that proxy, not of the user, so every request
hashes to the same value and goes to one upstream.
X-Forwarded-Foris not read for this. Hash a header that the proxy in front sets instead:strategy: consistent-hashwithhashKey: "header:X-Real-IP"(orCF-Connecting-IPbehind Cloudflare), and make sure clients cannot reach Conduit without passing through that proxy, otherwise they can set the header themselves and choose their upstream; - many users share one address (an office or mobile carrier behind NAT): they all land on one upstream, so the pool is used unevenly;
- the client’s address changes during a session (a phone moving between Wi-Fi and
mobile data): its next request goes to another upstream. Use
sticky.cookiewhen the session must survive that.
When the pool changes. Removing an upstream, or ejecting it as unhealthy, moves
only the clients that were on it, each to its next-best upstream; everyone else
stays where they are. When it comes back, those clients return. Adding an upstream
takes over about 1/N of the clients. A plain “hash modulo the number of upstreams”
scheme would instead reshuffle nearly everyone on every change.
Spread. With few clients the split is uneven by chance (two clients can hash to
the same upstream); it evens out as the number of distinct addresses grows. If you
need an exact split, use weighted-round-robin; affinity and exact shares do not go
together.
proxy:
/auth:
targets: ["http://auth1:5000", "http://auth2:5000"]
strategy: ip-hash
hashKey: ip # default for ip-hash; can be omitted
// JSON
{
"proxy": {
"/auth": {
"targets": ["http://auth1:5000", "http://auth2:5000"],
"strategy": "ip-hash"
}
}
}
consistent-hash
Hashes a configurable hashKey (the client address, the URL path, or the value
of any request header) and maps it to an upstream by rendezvous hashing. Identical
to ip-hash in implementation, so it behaves the same when the pool
changes: only the keys that were on a removed or ejected upstream move. The
distinction is which value is hashed, and the default here is the same ip.
Use when: requests with the same key must meet the same upstream, and the key is not (only) the client address:
- Multi-tenant shards.
hashKey: "header:X-Tenant-ID": each tenant’s data lives on one shard, or its working set stays warm in one upstream’s memory. - Cache locality.
hashKey: "url": every upstream keeps its own in-memory or disk cache, and the same page always asks the same one, so a page is held in one upstream’s cache instead of in all of them. - Per-user affinity.
hashKey: "header:X-User-ID"(set by an authenticating proxy or by an earlier stage of your own). - The real client address behind a proxy or CDN.
hashKey: "header:X-Real-IP"(see the warning underip-hash).
The hashKey field controls what is hashed:
hashKey value |
Hashes | Example use case |
|---|---|---|
ip (default) |
The address of the TCP peer that connected to Conduit (not X-Forwarded-For) |
Per-client affinity |
url |
The request path, without the query string (/a?x=1 and /a?x=2 hash alike) |
Cache locality: the same page always hits the same backend |
header:X-Name |
The value of header X-Name |
Per-tenant or per-user routing |
Details that decide whether the result is what you expect:
- A missing header is not an error. When the request has no
X-Nameheader (or its value is not valid text), Conduit hashes the client address instead, so those requests are still spread rather than all landing on one upstream. - The whole value is hashed, exactly as sent:
acmeandAcmeare different keys, and so are203.0.113.7and203.0.113.7, 10.0.0.2(what anX-Forwarded-Forlist looks like after one more proxy). Hash a header that holds one stable value. - The header comes from the client. Unless a trusted proxy in front sets or overwrites it, a client can send any value and pick its upstream. Routing by it is fine; deciding anything about access by it is not.
- Uneven keys mean uneven load. One huge tenant puts all of its traffic on one upstream however many you add. Hashing spreads keys, not requests.
- A sticky cookie, when present and honoured, takes precedence
over
hashKey.
proxy:
/api:
targets:
["http://shard-1:4000", "http://shard-2:4000", "http://shard-3:4000"]
strategy: consistent-hash
hashKey: "header:X-Tenant-ID"
// JSON
{
"proxy": {
"/api": {
"targets": [
"http://shard-1:4000",
"http://shard-2:4000",
"http://shard-3:4000"
],
"strategy": "consistent-hash",
"hashKey": "header:X-Tenant-ID"
}
}
}
Cache locality, and the real client address behind a proxy:
proxy:
/static-pages:
targets: ["http://render-1:4000", "http://render-2:4000"]
strategy: consistent-hash
hashKey: url
/app:
targets: ["http://app-1:4000", "http://app-2:4000"]
strategy: consistent-hash
hashKey: "header:X-Real-IP" # set by the proxy in front; clients must not reach Conduit directly
Same behaviour as ip-hash: removing an upstream moves only the keys that were on it.
random
Selects an upstream uniformly at random on each request using a fast thread-local RNG.
Use when: you want an even distribution without any coordination overhead —
useful for very large pools where maintaining a round-robin counter per route
is unnecessary. In practice, round-robin is usually preferred since it
provides better uniformity over small sample sizes.
proxy:
/api:
targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
strategy: random
p2c (Power of Two Choices)
On each request, samples two upstreams at random and forwards to the one with the lower cost:
cost = EWMA latency × (requests in flight + 1) ÷ weight
The latency is the passive, time-decayed measurement over all traffic that
GET /upstreams reports as ewma_latency_ms (an upstream with no measurement
yet counts as 30 ms). The in-flight count is the one least-conn and
healthCheck.maxConnectionsPerUpstream use, reported as active_connections.
This is Tower’s PeakEwma load, which linkerd’s P2C balancer uses, divided by
the weight. Ties are broken in favour of the first sample. Selection costs O(1) —
no scan of the full pool.
Both factors matter. Latency alone would send every request to the faster upstream however busy it was; with the in-flight factor an upstream twice as fast settles at about twice the in-flight requests of the slower one, and a busy upstream hands requests back to its sibling.
Failures count as slow. A response of 500 or more, a connect failure and a timeout are charged to the estimate as at
least one second, however fast the error came. Without that, an upstream that answers every request with an error right
away would have the lowest latency in the pool and attract the traffic (the fast-failing-peer problem). One failure
moves the traffic away from that upstream for a few seconds (the estimate decays with a 10 s time constant); one that
keeps failing stays out. It shows in ewma_latency_ms of GET /upstreams.
Weights. The cost is divided by weight, so at equal latency a weight-3
upstream carries about three times the in-flight requests of a weight-1 upstream
when the pool has two upstreams. With more, only two random samples are compared
and the in-flight counts are small whole numbers, so the split is coarser: weights
3:1:1 with 32 concurrent clients measured 47/26/27 of the requests (60/20/20 would
be proportional). Use least-conn, least-bandwidth or weighted-round-robin
when proportional shares matter.
Plain string targets have weight 1. An upstream with weight 0 loses every
comparison. With nothing in flight the weight-3 upstream is simply the cheaper
one every time, so serial requests all go to it; the in-flight shares become
proportional once requests overlap.
With a single upstream in the pool, P2C falls back to round-robin.
Use when: the upstream pool is large (10+) and least-conn would scan the
entire list on every request. Also useful as a drop-in replacement for
least-conn when you want reduced coordination overhead.
proxy:
/api:
targets:
- "http://a:4000"
- "http://b:4000"
- "http://c:4000"
- "http://d:4000"
strategy: p2c
// JSON
{
"proxy": {
"/api": {
"targets": [
"http://a:4000",
"http://b:4000",
"http://c:4000",
"http://d:4000"
],
"strategy": "p2c"
}
}
}
least-bandwidth
Routes each request to the upstream that is currently moving the least traffic. Of two upstreams sampled at random (all of them, when the pool has two), it picks the one with the lower cost:
cost = √((bytes per second + 1) × (requests in flight + 1)) ÷ weight
- Bytes per second is the request-body and response-body bytes Conduit moves for the upstream, both directions added together, as each chunk passes. The rate is an exponentially decayed average with a time constant of 10 seconds, refreshed at most every 250 ms, so a burst is remembered for a few seconds and an idle upstream’s rate falls towards zero.
- Requests in flight is the same count
least-connandhealthCheck.maxConnectionsPerUpstreamuse (active_connectionsinGET /upstreams). The rate alone is stale for a quarter of a second at a time, so every request in a window would go to the one upstream that was quietest when the window opened; and an upstream that is slow moves few bytes and looks idle. Requests piling up on it give it away at once. - The square root keeps
weightproportional: both factors grow with an upstream’s share of the traffic, so their product grows with its square. With weights 3:1:1 and traffic flowing, the shares come out near 60/20/20. With no traffic and nothing in flight the weight-3 upstream is simply the cheaper one every time, so serial requests all go to it until they overlap.
Use when: responses differ a lot in size, for example large downloads next
to small API calls, so equal connection counts hide very unequal network load
and the upstream’s network is the bottleneck. When the limit is CPU or memory,
least-conn or p2c is the better signal.
Typical cases:
- a file or media route where one request may be a 2 KB thumbnail and the next a
2 GB video:
least-connsees “one connection” on each upstream,least-bandwidthsees which one is moving the gigabytes; - upstreams on links of different speed, or on shared hosts where one neighbour
is busy: give the faster one a higher
weightand let the measured rate correct the rest; - streaming (server-sent events, long downloads), where requests last long and a byte rate is a better picture of the load than a request count.
Not a good fit: very short, equal-sized requests (the rate is noise and the
in-flight term does the work, so least-conn or p2c is simpler), and routes where
the upstream’s limit is CPU, memory or a database, which bytes do not show.
Parameters. There are none of its own: strategy: least-bandwidth is the whole
setting. The only input you control is each target’s weight (default 1, as
{ url, weight }). The 10-second time constant and the 250 ms refresh are fixed.
What it does in practice. In the load-balancing report that CI posts on pull
requests (four local upstreams, upstream 0 taking 8 ms per request and the other
three answering at once, one worker thread), round-robin gave each upstream 25 %
of the requests while least-bandwidth gave the slow one 12 % and the others 29 %
each. The report’s “even” scenario (four equal upstreams) shows the same strategy
splitting 25 / 25 / 25 / 25, so it costs nothing when there is nothing to correct.
proxy:
/files:
targets:
- { url: "http://store-1:4000", weight: 1 }
- { url: "http://store-2:4000", weight: 2 }
strategy: least-bandwidth
- Only routes that use this strategy are metered, so no other route pays for it (one atomic add per body chunk, 29 ns single-threaded in a release build, 110–130 ns when 4–8 threads hit one upstream). A route’s meters start at zero and update at most every 250 ms, so the first requests are chosen on weight and in-flight requests alone. After an idle spell the rate keeps the earlier traffic and fades with the 10-second time constant.
- A body is counted as its chunks arrive, so a long download or stream counts continuously, not only when it ends. The bytes are those the client sent and the upstream sent, before Conduit’s own compression or body replacement.
- Prior art: Citrix ADC
leastbandwidth(bytes sent plus received over the previous 14 seconds, weighted), which has neither the in-flight factor nor the sampling.
Sticky sessions
Keep a browser session on one upstream by looking at a cookie. There are two
modes, chosen by whether you set sticky.secret:
Without secret |
With secret (recommended) |
|
|---|---|---|
| Who sets the cookie | Your application (a session id it already sets) | Conduit, on every response |
| What the cookie holds | whatever the application put there | a signature that names the upstream that served the request |
| How routing uses it | the value is a hash key: the same value always maps to the same upstream | Conduit verifies the signature and sends the request straight to that upstream |
| Forged or invalid cookie | still used as a key: a client can steer itself to the upstream a chosen value hashes to | ignored: the request is balanced normally |
strict |
has no effect | true: answer 503 if the pinned upstream is down; false: move to another |
All the options of sticky:
| Option | Type | Default | Meaning |
|---|---|---|---|
cookie |
string | required | Cookie name to read (and, with secret, to set). |
secret |
string | none | Key for signing and verifying. Use an environment variable ("$STICKY_SECRET"). |
strict |
boolean | false |
With secret: refuse with 503 (reason sticky_upstream_unavailable) instead of relocating when the pinned upstream is unhealthy. |
secure |
boolean | Secure when the site has tls |
With secret: the Secure attribute of the cookie. true always (use it behind a load balancer that terminates TLS: Conduit then sees plain HTTP); false never. |
maxAgeSecs |
integer ≥ 1 | session cookie | With secret: the Max-Age of the cookie. |
Use when: the application keeps session state in the memory of one process (a shopping cart, a login held in the worker, an upload that must finish on the node that started it) and a shared session store is not an option. If you can add a shared store (Redis, a database), do so: sessions then survive an upstream restart and no stickiness is needed.
Before the first cookie. A request with no cookie is balanced by the route’s
strategy as usual. In secret mode Conduit then sets the cookie on the response,
and the following requests follow it. In the mode without secret Conduit sets
nothing: the first request is balanced normally, and affinity starts only once your
application has set the cookie and the client sends it back. While a cookie is
present and honoured, it replaces the route’s strategy for that request.
Not with groups. A route that has groups ignores sticky: no cookie is set and none is
honoured. conduit validate and the start-up log say so. strict without secret is ignored
too, and is reported the same way.
It is affinity, not a guarantee. If the pinned upstream is unhealthy (or at its
maxConnectionsPerUpstream) and strict is off, the session moves to another
upstream and loses whatever state the first one held. Sticky routing cannot keep a
session on an upstream that is down; it only prefers the same one while it is up.
proxy:
/app:
targets: ["http://a:4000", "http://b:4000"]
strategy: consistent-hash
sticky:
cookie: session_id
// JSON
{
"proxy": {
"/app": {
"targets": ["http://a:4000", "http://b:4000"],
"strategy": "consistent-hash",
"sticky": { "cookie": "session_id" }
}
}
}
Without a secret, your application must set the cookie (see “Before the first
cookie” above); Conduit never sets it.
HMAC-signed sticky cookies
Without a secret, the cookie value is used as a raw consistent-hash key.
An attacker can craft a cookie to force routing to any backend they choose.
Set sticky.secret to make Conduit sign cookies with HMAC-SHA256 and
verify them on every request. Forged cookies silently fall back to normal
load-balancing rather than pinning to an attacker-controlled backend.
proxy:
/app:
targets: ["http://a:4000", "http://b:4000"]
strategy: consistent-hash
sticky:
cookie: srv_id # Conduit sets this cookie on every response
secret: "$STICKY_SECRET" # HMAC key — use an env var, never hardcode
strict: false # true = 503 when pinned upstream is down
| Option | Behaviour |
|---|---|
No secret |
Cookie value is the raw consistent-hash key (legacy, no forgery protection) |
secret set |
Conduit signs the URL with HMAC-SHA256 and injects a Set-Cookie on every response |
strict: false (default) |
If the pinned upstream is unhealthy, fall back to the next available backend |
strict: true |
If the pinned upstream is unhealthy, return 503 Service Unavailable immediately |
The injected cookie attributes are Path=/; HttpOnly; SameSite=Lax, plus Secure and Max-Age as configured, and
SameSite as sameSite says:
-
sameSiteislax(the default),strictornone.nonelets the browser send the cookie on cross-site requests (an application embedded in, or called from, another origin). Browsers refuse aSameSite=Nonecookie that is notSecure, sononealways addsSecure, even on a plain-HTTP site (where the browser then drops the cookie: serve such a site over TLS), andsecure: falsetogether withnoneis a validation error. secureunset means “when the matched site hastls”. A plain-HTTP site gets noSecure, because a browser drops aSecurecookie it received over HTTP and the affinity would silently end. Behind a load balancer that terminates TLS, Conduit itself sees plain HTTP: setsecure: truethere.maxAgeSecsunset means a session cookie (it ends with the browser session). It is an instruction to the browser, not a check on the server: the signed value carries no expiry, so a client that keeps the cookie can still send it. The pin is a preference for an upstream, not a credential.0is rejected (it would delete the cookie).- With
strict: truethe refusal is503with"reason":"sticky_upstream_unavailable"(the upstream is down; the circuit breaker’supstream_overloadedis a different case).
How the pin is applied. With a secret set, the verified cookie names one
exact upstream, and Conduit routes to that upstream directly — the
configured strategy is not consulted at all while the pin can be honored.
A pin is honored whenever its upstream is healthy and below
maxConnectionsPerUpstream; otherwise Conduit falls back to the strategy and:
- pinned upstream saturated (but healthy) — relocate for this request and leave the cookie untouched, so the session returns to its original upstream as soon as capacity frees up;
- pinned upstream unhealthy — relocate and re-sign the cookie onto the new upstream, since the original is gone.
Without a secret, there is no pinned URL to honor — the cookie value is only
a hash key, and routing goes through consistent-hash as usual.
Security note: store the HMAC secret in an environment variable (
secret: "$STICKY_SECRET"). Rotate by changing the value and reloading; existing cookies will silently fall through to normal load-balancing for one request and then get a new signed cookie.
Upstream groups (two-level balancing)
Instead of one flat pool, a route can have several named groups of
upstreams. Balancing then takes two steps: the outer strategy (groupStrategy)
picks a group for the request, and the group’s own strategy picks an upstream
inside it. Use it when the upstreams are not interchangeable and you want to say
which ones a request may use, for example one pool per region, per customer tier,
or per hardware generation.
| Field | Where | Type | Default | Meaning |
|---|---|---|---|---|
groups |
route | array | none | The groups. Use it instead of targets (a route needs one of the two). |
groups[].name |
group | string | required | Name of the group; the outer strategy chooses among these names. |
groups[].targets |
group | array | required | The group’s upstreams, as on a flat route (URLs or { url, weight }). |
groups[].strategy |
group | strategy | round-robin |
How an upstream is picked inside this group. Any of the strategies, each group can differ. |
groupStrategy |
route | strategy | round-robin |
How a group is picked. See the table below for which values make sense. |
hashKey |
route | string | ip |
What ip-hash / consistent-hash hash, for the outer pick and for a hash strategy inside a group (see consistent-hash). |
Typical shapes:
- Regions with affinity.
groupStrategy: ip-hash(orconsistent-hashwith a header such asX-Region), aleast-connpool per region: a client keeps using its region, and inside the region the load is balanced. - Tiers.
groupStrategy: consistent-hashwithhashKey: "header:X-Plan": paying customers go to the group on bigger machines, free ones to the other. - Rolling a new hardware generation. Two groups,
round-robinoutside: half of the requests to each, whatever the number of machines in each group.
Which outer strategy to use:
groupStrategy |
Result |
|---|---|
round-robin, random |
The groups take turns / are chosen at random, regardless of how many upstreams each has. |
ip-hash, consistent-hash |
A client (or key) keeps its group. |
least-conn, p2c, least-bandwidth, least-response-time |
Not meaningful: see below. |
The outer strategy chooses among the group names, and a name has no load of
its own: nothing is in flight on it, no latency is measured for it and no bytes
move through it. So round-robin, random, ip-hash and consistent-hash
work as described, while least-conn, p2c, least-bandwidth and
least-response-time cannot tell the groups apart by load (the first three
choose at random, the last one in turn) and Conduit logs a warning for them.
Put the load-aware strategy on each group’s own strategy instead, as below.
proxy:
/api:
groups:
- name: us-east
targets: ["http://us-east-1:4000", "http://us-east-2:4000"]
strategy: least-conn
- name: eu-west
targets: ["http://eu-west-1:4000", "http://eu-west-2:4000"]
strategy: least-conn
groupStrategy: ip-hash # outer: same client IP always hits same region
// JSON
{
"proxy": {
"/api": {
"groups": [
{
"name": "us-east",
"targets": ["http://us-east-1:4000", "http://us-east-2:4000"],
"strategy": "least-conn"
},
{
"name": "eu-west",
"targets": ["http://eu-west-1:4000", "http://eu-west-2:4000"],
"strategy": "least-conn"
}
],
"groupStrategy": "ip-hash"
}
}
}
See examples/upstream-groups.yaml
What happens when a group fails
A group is a unit of affinity, not (yet) of failover. Measured with the real
server (two groups of one upstream each, eu-west down, 40 requests from one client):
| Setup | Result |
|---|---|
groupStrategy: round-robin |
Every second request goes to eu-west and fails (20 of 40). |
groupStrategy: ip-hash |
A client that hashes to eu-west fails on every request (40 of 40); a client that hashes to us-east is never affected. |
Route backup: set to a live upstream |
No difference: backup is not used on a route with groups. |
Why: the outer pick chooses among group names and does not look at the health of their upstreams. Inside a group, unhealthy upstreams are skipped, but when none is healthy the group does not refuse: it hands the request to one of them anyway (so a group whose health checks are all failing still gets traffic). Nothing moves a failed group’s traffic to another group, so with a hash outer strategy the problem stays local to the clients of that group, and with a rotating one it hits a fixed share of everyone. Tracked in #643.
Also true of a route with groups today:
- A group whose upstreams are all at
healthCheck.maxConnectionsPerUpstreamanswers503; Conduit does not spill into another group that has room. retry,mirrorandstickyare not applied (andstickygives no warning, #644). Put sticky sessions on flat routes.slowStartSecsapplies to the pick inside a group, not to the choice of group.
If you need regional failover today: keep the regions out of groups: use two
routes or sites behind a DNS or external load balancer that health-checks the
regions, or one flat pool with weighted-round-robin (a small weight for the far
region): a flat pool skips its unhealthy upstreams, so a failed region’s share moves
to the others.
Static Files
Simple directory
# YAML
static: ./dist
// JSON
{ "static": "./dist" }
Multiple directories
# YAML
static:
- ./dist
- ./public
// JSON
{ "static": ["./dist", "./public"] }
Path-mapped directories
# YAML
static:
/: ./dist
/docs: ./docs-dist
// JSON
{ "static": { "/": "./dist", "/docs": "./docs-dist" } }
Static options
# YAML
static: ./dist
staticOptions:
index: [index.html] # default files for directory requests
dotFiles: ignore # "ignore" | "allow" | "deny"
preCompressed: true # serve .br / .gz if present
etag: true # ETag / 304 Not Modified support
lastModified: true # Last-Modified header
maxAge: "1y" # Cache-Control max-age (humantime: "1d", "30m", "1y")
// JSON
{
"static": "./dist",
"staticOptions": {
"index": ["index.html"],
"dotFiles": "ignore",
"preCompressed": true,
"etag": true,
"lastModified": true,
"maxAge": "1y"
}
}
| Field | Type | Default | Description |
|---|---|---|---|
index |
string[] | ["index.html"] |
Default files for directory requests |
dotFiles |
string | "ignore" |
"ignore", "allow", or "deny" |
preCompressed |
bool | false |
Serve pre-compressed .br / .gz files |
etag |
bool | true |
ETag + conditional GET support |
lastModified |
bool | true |
Last-Modified header |
maxAge |
string | — | Cache-Control: max-age — humantime duration string |
Symlinks
A symlink below a static root is never served, whether it points to a file or to a directory:
the request is treated as if the file did not exist. Every component under the root is also opened
relative to the directory above it without following links (openat with O_NOFOLLOW on Unix,
NtCreateFile with FILE_OPEN_REPARSE_POINT on Windows, which covers directory junctions too), so
a directory swapped for a symlink or junction between the check and the open is refused as well.
On Windows, a file or directory that is a reparse point but not a link (a OneDrive placeholder, a
deduplicated file) is opened normally after an identity check; that path is written from the API
contract and has not been run against a real placeholder, so such a file may be refused rather than
served: answered as not found when the second open lands on another file, and as a 500 when the
second open itself fails (for example a reparse tag nothing handles). On any other platform the check
runs before the open, so a symlink swapped in between the two could still be followed: keep the
served tree writable by trusted accounts only.
The file is opened once, before the first response header is written, and its size, modification
time, ETag and Last-Modified are read from that open handle, which the body is then streamed
from. A file that disappears or turns into a link between the lookup and the open is answered as not
found (the fallback runs) before anything is sent, never as a 200 cut off after its headers; so is
a directory that took the file’s place on Unix (on Windows that case is reported by the system as
access denied, a 403). A file the server cannot read is a 403, any other open failure a 500,
both before the headers. A 304 or a HEAD request therefore also opens the file.
On Windows, NTFS keeps a second, 8.3 short name for each long name on a volume that creates them (the
system volume by default), and resolves it to the same file: /HTPASS~1 would open .htpasswd
without dotFiles ever seeing a dot. A name shaped like a generated short name (BASE~N or
BASE~N.EXT, at most 8 characters before the last dot and 3 after, with a ~ and digits at the end of
the base) is therefore answered as not found, in any path segment and as an index name. A real file
named like that (report~1.pdf) is not served on Windows; a longer base or extension (report~1.html)
is. A short name an administrator chose by hand (fsutil file setshortname) is not recognised: that
needs the same rights as planting a link.
The access-log file (logging.file) gets the same protection for its last path component: a symlink
planted at the log path is refused, and on Windows so is a junction or any other reparse point (a
OneDrive placeholder, a deduplicated file), so keep the log on a plain folder there. The directories
above it are not checked, so keep the log directory writable by trusted accounts only.
The root path itself is resolved normally: a symlinked root such as current -> releases/42 works,
and switching that link takes effect on the next request. Whoever can replace the root path, or one
of its parent directories, decides what is served, so keep those writable by the operator only.
Redirects
redirects is an array of redirect rules.
# YAML
redirects:
- from: /old-path
to: "https://example.com/new-path"
status: 301
- from: "/blog/(.+)" # regex capture group
to: "https://blog.example.com/$1"
status: 308
// JSON
{
"redirects": [
{
"from": "/old-path",
"to": "https://example.com/new-path",
"status": 301
},
{ "from": "/blog/(.+)", "to": "https://blog.example.com/$1", "status": 308 }
]
}
| Field | Type | Default | Description |
|---|---|---|---|
from |
string | — | Path or regex pattern to match |
to |
string | — | Destination URL (capture groups $1…$N are expanded) |
status |
number | 301 |
HTTP redirect status code |
Fallback
Return a response when no route matches.
# YAML — SPA: serve index.html for all unmatched browser routes
fallback:
file: ./dist/index.html
status: 200
# YAML — content-type-aware fallback (Accept header negotiation)
fallback:
byAccept:
html:
file: ./dist/index.html
status: 200
json:
body: { "error": "Not Found", "status": 404 }
status: 404
status: 404
body: "Not Found"
// JSON
{
"fallback": {
"file": "./dist/index.html",
"status": 200
}
}
// JSON
{
"fallback": {
"byAccept": {
"html": { "file": "./dist/index.html", "status": 200 },
"json": { "body": { "error": "Not Found", "status": 404 }, "status": 404 }
},
"status": 404,
"body": "Not Found"
}
}
| Field | Type | Default | Description |
|---|---|---|---|
file |
path | — | File to serve |
body |
any | — | Response body (string or JSON object) |
status |
number | 200 |
HTTP status code |
headers |
object | — | Response headers to set |
byAccept |
object | — | Content-type-aware rules keyed by Accept type (see key matching below) |
byAccept keys are matched against the request’s Accept header (the header value is
lowercased before matching; a configured key like xml is matched case-sensitively
against it, so a literal-substring key should be written in lowercase), checked in the
order they’re defined, first match wins:
| Key | Matches when Accept contains |
|---|---|
html |
text/html |
json |
application/json |
text |
text/plain or text/ |
image |
image/ |
| any other key | the key itself, as a literal substring (e.g. xml matches application/xml) |
* |
wildcard fallback, checked only after every other key has been tried |
Health Checks
“Health check” means three different things in Conduit. Only the first two decide where a request goes:
| What it is | Configured with | Does the balancer use it? | |
|---|---|---|---|
| Active probes | Conduit sends a request to every upstream of a route on a timer and marks it healthy or unhealthy | healthCheck on the route (below) |
Yes. Every strategy skips an unhealthy upstream |
| Passive ejection | Conduit watches the real responses and ejects an upstream that returns too many 5xx | outlierDetection |
Yes, the same way |
| Site health endpoint | A URL Conduit itself serves (/__health__) so that something in front of it (a cloud load balancer, Kubernetes) can ask whether Conduit is alive |
healthCheck on the site (see below) |
No: it is for others to call |
What the balancer does with the health state
An upstream that is unhealthy (a failed probe series or an ejection) is left out of the
candidates of every pick: round-robin, least-conn, the hash strategies, sticky pins, the
inside of an upstream group and the retry list all choose among the healthy ones only. When
it recovers it is a candidate again; slowStartSecs can bring it back gradually (see
Slow start for when it does not: the hash strategies and sticky pins send it its
clients at once, and a route that fails open has no ramp). If every upstream of a
route (or of a group) is unhealthy, all of them stay candidates and the strategy picks one as
usual: it does not try them in turn, and a route with groups has no retry. So a wrongly
failing probe cannot take a route down by itself, but nothing protects the requests then.
A passive ejection ends only through a real request: when it expires, one request is offered to
the upstream as a probe (a success restores it, a failure ejects it again for twice as long, up
to maxEjectionTimeSecs). If the strategy sends that request to another upstream, the offer
lapses after 10 seconds and is repeated; measured with two upstreams, the upstream was back
after about 10 seconds (before #650 it stayed out for good). Active probes do not lift a
passive ejection.
Without active probes and without outlierDetection the balancer knows nothing: a dead
upstream keeps receiving its share of the requests until you fix it. Both are off by default.
Measured with the real server (two upstreams, round-robin, one of them stopped, 20 requests
right after and 20 six seconds later):
| Configuration | Right after the stop | Six seconds later |
|---|---|---|
| nothing configured | 10 ok, 10 502 |
10 ok, 10 502: it never stops |
healthCheck every 1 s, unhealthyThreshold: 2 |
10 ok, 10 502 |
20 ok |
outlierDetection, consecutive5xx: 2, maxEjectionPercent: 50 |
18 ok, 2 502 |
20 ok |
So there is always a window in which some requests still go to the dead upstream. For probes
it is about (unhealthyThreshold − 1) to unhealthyThreshold times intervalSecs (it depends on
where the failure falls between two probe ticks), plus the time the probes take. The measurement
above used an upstream that refuses connections, which fails at once; one that hangs takes up to
timeoutMs (default 5000, one deadline for the whole probe) before the probe counts as failed, so
the window grows by that much per failed probe: lower it for upstreams that answer in a few
milliseconds. Passive ejection closes it after
consecutive5xx failed requests, as long as the ejection cap below allows another ejection,
and it reacts only to real requests (an upstream that gets none is never examined). To lose
fewer requests during that window add retry, which repeats a failed request on
another upstream (on a flat route: a route with groups ignores it). A real deployment usually
wants active probes (they find a dead upstream before a user does and also bring it back),
plus outlierDetection for upstreams that answer probes but fail real requests.
maxEjectionPercent limits how many upstreams passive ejection may remove at once: that
percentage (default 10%) of all the upstreams Conduit tracks, not only this route’s, rounded
down but never below one. So one upstream can always be ejected however low the percentage
is; with the default 10%, more than one needs at least 20 tracked upstreams. The cap is
checked and applied without a lock, so when several upstreams reach the threshold at the same
moment the limit can briefly be exceeded.
Also: least-response-time takes its latencies from the active probes, so it needs
healthCheck or it behaves like round-robin; and a route with groups skips unhealthy
upstreams only inside the chosen group, it does not move traffic to another group (see
Upstream groups).
Active upstream probes
Probing is optional and off by default: nothing is sent to an upstream for health unless the
route has a healthCheck. When it has, Conduit sends each of the route’s upstreams one HEAD
request (a new TCP connection, Connection: close) to path every intervalSecs (default 10
seconds), one upstream after the other. A probe passes when the upstream answers with any HTTP
status below 500 (waiting at most 5 seconds for each step: connect, send, answer); a refused or timed-out connection, a missing answer or a
5xx is a failure. So the service does not need a health endpoint: any path that answers (the
default is /) is enough, a 404 counts as alive, and a service that cannot or must not be
asked simply gets no healthCheck (and, if wanted, outlierDetection instead, which sends
nothing and judges the real requests).
What can be set today: the path, the interval, and how many failures or passes change the state. What cannot: the probe timeout (fixed, #652), the method, what counts as a pass (the status below 500 rule is fixed), probing after a number of requests instead of after a time, or switching probes off for one upstream of a route. Two timings of the passive side are fixed as well: how long a probe offer to an ejected upstream waits for its answer (10 seconds) and the backoff after a failed offer (30 seconds, doubling up to 300). All of this is tracked in #653.
# YAML
proxy:
/api:
targets: ["http://a:4000", "http://b:4000"]
healthCheck:
path: /health
intervalSecs: 10
unhealthyThreshold: 3
healthyThreshold: 1
slowStartSecs: 30
unhealthyStatus: [429, 500, 502, 503, 504] # real responses with these status codes count as failures
unhealthyLatencyMs: 2000 # real responses slower than 2 s count as failures
// JSON
{
"proxy": {
"/api": {
"targets": ["http://a:4000", "http://b:4000"],
"healthCheck": {
"path": "/health",
"intervalSecs": 10,
"unhealthyThreshold": 3,
"healthyThreshold": 1,
"slowStartSecs": 30,
"unhealthyStatus": [429, 500, 502, 503, 504],
"unhealthyLatencyMs": 2000
}
}
}
}
Site health endpoint (for load balancer probes)
# YAML
healthCheck: true
healthCheck:
path: /__health__
includeUpstreams: true # include per-upstream health in JSON response
// JSON
{ "healthCheck": { "includeUpstreams": true } }
Health check field reference
| Field | Type | Default | Description |
|---|---|---|---|
path |
string | / |
Path of the probe’s HEAD request (a path without a leading / gets one; an https:// or wss:// upstream is probed by opening a TCP connection only, because the probe is plaintext HTTP/1.1 and a TLS listener would not understand it, so path is not used for it). The default is /, not /__health__ (that is the path of Conduit’s own site health endpoint) |
intervalSecs |
number | 10 |
Seconds between probes of each upstream (minimum 1) |
unhealthyThreshold |
number | 3 |
Consecutive failed probes before the upstream is left out |
healthyThreshold |
number | 1 |
Consecutive passed probes before it is brought back |
timeoutMs |
number | 5000 |
Probe timeout in milliseconds (minimum 1): one deadline for the whole probe, connecting, sending the request and receiving the first line of the answer together. A probe that does not finish in time fails like one that is refused |
unhealthyStatus |
number[] | none | Real responses, not probes (passive): a response from the upstream with one of these status codes counts as a failure of that upstream; enough of them in a row eject it when outlierDetection is configured. Example: [429, 500, 502, 503, 504] |
unhealthyLatencyMs |
number | — | Real responses, not probes (passive): a response slower than this (ms) counts as a failure of that upstream, even if its status is 2xx; ejects it only with outlierDetection |
slowStartSecs |
number | 0 |
Traffic ramp-up period after recovery. Ignored for ipHash/consistentHash and sticky routes. |
maxConnectionsPerUpstream |
number | — | Circuit breaker threshold |
prewarmConnections |
number | 0 |
Pre-establish N keepalive connections at startup (max 8). 🚫 Blocked — warms a throwaway client, not Conduit’s real upstream pool (Pingora 0.9 has no public API for it) — see note below. |
includeUpstreams |
bool | false |
Include upstream health in /__health__ response |
Circuit Breaker
maxConnectionsPerUpstream enforces a per-upstream connection cap for every
load-balance strategy, across all three config shapes (proxy: {} map,
routes[] array, and groups):
- Requests are only routed to upstreams currently below the cap.
- When all healthy upstreams for a route are at or above the cap,
Conduit returns
503immediately instead of queuing. IpHash/ConsistentHash(and sticky sessions, which forceConsistentHash) don’t shrink the hash space when a peer is at capacity — they forward-probe to the next candidate on the ring. This means only the client(s) whose preferred peer is currently saturated get relocated (to a deterministic fallback peer); every other client’s mapping is unaffected. For sticky sessions specifically, a capacity relocation does not re-sign the session cookie — the client keeps its original pin and retries it on the next request, so the session genuinely returns to its original upstream once that upstream has capacity again, rather than permanently migrating to the fallback.- The cap is a soft limit under concurrency: it is checked, then
acquired, in two separate steps (not atomically), so a burst of
simultaneously-arriving requests can briefly overshoot it by the number of
concurrent racers. This self-corrects on the next request and is the same
trade-off
retry.budgetPercentmakes — a spurious503for a request that actually had capacity is worse than brief overshoot. - For a
groups-configured route, only the selected group’s targets are checked — if every target in that group is at capacity, the request 503s even if a different group has room. Group selection itself is not capacity-aware (it’s typically hash/affinity-driven). - A retry attempt re-checks the cap. The first attempt uses whatever peer
routing already chose (the usual strategy- and capacity-aware pick); each
retry attempt after that forward-probes the route’s retry candidate list,
starting from its position in the rotation, for the next peer currently
under the cap — skipping (not permanently removing) a saturated one,
the same forward-probe shape
IpHash/ConsistentHashalready use above. If every candidate is saturated, it fails open to the naive rotation target rather than 503ing a request that has already spent attempts — the same soft-cap trade-off as the rest of this section.
Known limitations still open after the 2026-08-03 integrity audit — see the repo’s issue tracker for current status:
prewarmConnectionsis blocked, not just unimplemented. It warms a short-lived, throwaway HTTP client rather than Conduit’s real upstream connection pool — Pingora 0.9 has no public API to reach or pre-populate the poolupstream_peer()actually uses for real traffic (HttpProxy’sclient_upstreamfield is private with no accessor). Same class of gap as OCSP stapling / the request-queue item below — waiting on a future Pingora release.
# YAML
proxy:
/api:
targets: ["http://a:4000", "http://b:4000", "http://c:4000"]
healthCheck:
maxConnectionsPerUpstream: 100
backup: "http://replica:4000"
// JSON
{
"proxy": {
"/api": {
"targets": ["http://a:4000", "http://b:4000", "http://c:4000"],
"healthCheck": { "maxConnectionsPerUpstream": 100 },
"backup": "http://replica:4000"
}
}
}
See examples/circuit-breaker.yaml
Slow start
healthCheck.slowStartSecs ramps traffic to an upstream that just recovered
from an unhealthy state, instead of sending it 100% of its normal share
immediately (the classic thundering-herd-into-a-just-recovered-backend
scenario).
For the slowStartSecs seconds immediately after recovery, the upstream
participates in each pick with a probability equal to how far through the
ramp window it is (0% right after recovery, rising linearly to 100% once the
window elapses). This applies to every load-balance strategy except
ipHash/consistentHash and sticky sessions:
RoundRobin,Random,WeightedRoundRobin,LeastConn,LeastResponseTime, andP2call honor it.LeastConnandLeastResponseTimebenefit the most — a freshly-recovered peer’s connection count and probe latency both look artificially good (drained to near-zero, or measured under no real load), so without this they’d win every pick until real traffic caught them up, which is itself a form of thundering herd.ipHash/consistentHash(and sticky sessions, which forceconsistentHash) are deliberately exempt. A client’s hash must map to a fixed upstream for the strategy’s own consistency guarantee to hold — a probabilistic ramp gate would divert some hashed clients to a different peer mid-window, breaking exactly the property those strategies exist to provide, and would flap a sticky client’s session for the entire ramp. ConfiguringslowStartSecstogether with a hash strategy orstickyon the same route logs a warning at config-load/reload time rather than silently doing nothing.- The ramp never produces a 503 and never empties an otherwise-routable candidate list (fails open): if every healthy candidate happens to be mid-ramp, or a route has only one upstream, the gate steps aside and normal selection proceeds. Two consequences worth knowing: a single-upstream route can’t ramp (there’s nowhere to shift traffic to), and if your entire upstream pool recovers at once (e.g. after a fleet-wide outage), full traffic resumes immediately rather than being shed — no admission scheme can shape load when there’s no non-ramping sibling to route to instead.
- Applies to retry rotation too — a retry-configured route won’t rotate a
failed request into a peer that’s still mid-ramp, on either the
proxy: {}map path or theroutes[]array path.
Recovery is recorded both when an active health-check probe flips an
upstream back to healthy, and when a half-open outlier-detection probe
succeeds — the latter is the only recovery signal available for upstreams
configured on a route that has no healthCheck block (active probes run for the
proxy: {} map, the routes[] array and groups; without a healthCheck there is no probe).
# YAML — pairs well with least-conn, since that's the strategy slow-start
# benefits the most
proxy:
/api:
targets: ["http://a:4000", "http://b:4000"]
strategy: least-conn
healthCheck:
slowStartSecs: 30
// JSON
{
"proxy": {
"/api": {
"targets": ["http://a:4000", "http://b:4000"],
"strategy": "least-conn",
"healthCheck": { "slowStartSecs": 30 }
}
}
}
Retry
# YAML
proxy:
/api:
targets: ["http://a:4000", "http://b:4000"]
retry:
attempts: 3
conditions:
- connection_error
- "5xx"
- timeout
backoffMs: 100
backoffJitter: true # add ±50% random spread to backoffMs
budgetPercent: 20
timeout:
perTryMs: 2000
// JSON
{
"proxy": {
"/api": {
"targets": ["http://a:4000", "http://b:4000"],
"retry": {
"attempts": 3,
"conditions": ["connection_error", "5xx", "timeout"],
"backoffMs": 100,
"backoffJitter": true,
"budgetPercent": 20
},
"timeout": { "perTryMs": 2000 }
}
}
}
Retry field reference
| Field | Type | Default | Description |
|---|---|---|---|
attempts |
number | 0 |
Number of retry attempts (0 = disabled) |
conditions |
string[] | — | Triggers: "connection_error", "5xx", "timeout". Retries only happen when at least one matches. |
backoffMs |
number | 0 |
Fixed wait between attempts (ms). 0 = immediate retry. |
backoffJitter |
bool | false |
Apply ±50% random spread to backoffMs to avoid thundering herd. Effective delay: [ms/2, ms*3/2) |
budgetPercent |
number | — | Soft cap: at most this fraction of in-flight requests may be retries. Prevents retry storms under mass failure. |
Body buffering for retry — POST/PUT/PATCH requests are only retried when
limits.maxBodyBufferBytesis set. Without it, request bodies are not buffered andconnection_errorretries on non-GET methods are skipped silently.
1xx interim responses
Some upstream backends (Spring Boot, CDNs, gRPC gateways) send one or more
1xx informational responses before the final response — for example
103 Early Hints for browser resource preloading, or 100 Continue after a
Expect: 100-continue request header.
Conduit passes 1xx responses through to the client without running any middleware (retry logic, error masking, response transforms, etc.), then continues waiting for the real response. No configuration is required.
Exception: 101 Switching Protocols (WebSocket upgrade) is handled
separately by the websocket: true route option — see the field reference table.
Outlier Detection
Passively eject upstreams that return too many 5xx responses from real traffic.
Tracks and ejects for every load-balance strategy, not just LeastConn.
# YAML
outlierDetection:
consecutive5xx: 5
baseEjectionTimeSecs: 30
maxEjectionTimeSecs: 300
maxEjectionPercent: 33
// JSON
{
"outlierDetection": {
"consecutive5xx": 5,
"baseEjectionTimeSecs": 30,
"maxEjectionTimeSecs": 300,
"maxEjectionPercent": 33
}
}
Ejection uses exponential backoff: 30 s → 60 s → 120 s → … up to
maxEjectionTimeSecs.
Half-open circuit breaker: when the ejection period expires, the first
request is allowed through as a probe. If the probe succeeds (non-5xx), the
upstream is fully restored and ejection_count is reset. If it fails, the
upstream is re-ejected with the next backoff level. All other requests during
the probe are blocked until the probe completes.
| Field | Type | Default | Description |
|---|---|---|---|
consecutive5xx |
number | 5 |
Consecutive errors before ejection |
baseEjectionTimeSecs |
number | 30 |
Initial ejection duration |
maxEjectionTimeSecs |
number | 300 |
Maximum ejection duration (cap on backoff) |
maxEjectionPercent |
number | 10 |
Max % of cluster that may be ejected at once |
Limits
# YAML
limits:
maxBodyBytes: 10485760 # reject request bodies over 10 MB (413)
maxHeaderBytes: 65536 # reject headers over 64 KB
timeoutSecs: 30 # global request timeout (seconds)
maxInflightRequests: 1000 # return 503 when 1000 requests are in flight
maxBodyBufferBytes: 1048576 # buffer up to 1 MB per request for retry replay
maxConnectionsPerIp: 50 # max simultaneous connections from one IP (429)
keepaliveRequestLimit: 1000 # recycle connections after this many requests
priorityThreshold: 0.8 # shed low-priority routes above 80% concurrency
minUploadRateBytesPerSec: 1024 # reject uploads slower than 1 KiB/s (408)
// JSON
{
"limits": {
"maxBodyBytes": 10485760,
"maxHeaderBytes": 65536,
"timeoutSecs": 30,
"maxInflightRequests": 1000,
"maxBodyBufferBytes": 1048576,
"maxConnectionsPerIp": 50,
"keepaliveRequestLimit": 1000,
"priorityThreshold": 0.8,
"minUploadRateBytesPerSec": 1024
}
}
| Field | Type | Default | Description |
|---|---|---|---|
maxBodyBytes |
number | — | Max request body size — returns 413 if exceeded (declared Content-Length, or the bytes actually received for a chunked body) |
maxHeaderBytes |
number | — | Max request header size |
timeoutSecs |
number | — | Global request timeout |
maxInflightRequests |
number | — | Max concurrent requests — returns 503 if exceeded (must be ≥ 1) |
maxBodyBufferBytes |
number | — | Max body buffered per request for retry replay |
maxConnectionsPerIp |
number | — | Max simultaneous open connections from a single client IP — returns 429 if exceeded |
maxRequestHeaders |
number | — | Max number of request headers — returns 431 Request Header Fields Too Large if exceeded |
keepaliveRequestLimit |
number | — | Max requests per keepalive connection; closes and recycles after. Equivalent to nginx’s keepalive_requests. |
priorityThreshold |
number | 0.8 |
Fraction of maxInflightRequests at which low-priority routes are shed (0.0–1.0) — see Priority routing |
minUploadRateBytesPerSec |
number | — | Minimum upload rate in bytes/s — closes slow uploads with 408 Request Timeout (slow-loris protection) |
Priority Routing
Priority routing lets high-value routes continue to be served when the site is
under load, while low-priority routes are shed with 503 Load Shedding.
How it works
- Set
limits.maxInflightRequeststo cap total concurrency. - Set
limits.priorityThreshold(default0.8) — the fraction of the cap at which shedding begins. - Mark routes with
priority: 0–100(50= normal, omitted = normal). - When
inflight / maxInflightRequests ≥ priorityThreshold, any request whose effective priority is below 50 receives503 Load Shedding.
Requests with priority ≥ 50 (normal or high) are never shed by this
mechanism. The X-Priority: <0–100> request header can raise the
effective priority above the configured route value (useful for trusted
internal callers).
# YAML
limits:
maxInflightRequests: 2000
priorityThreshold: 0.8 # shed low-priority at 1600+ concurrent
routes:
- match:
path: /api/critical/**
proxy:
targets: [http://api:4000]
priority: 90 # always served
- match:
path: /api/batch/**
proxy:
targets: [http://api:4000]
priority: 10 # shed first when overloaded
- match:
path: /api/**
proxy:
targets: [http://api:4000]
# no priority → defaults to 50 (normal, not shed)
{
"limits": {
"maxInflightRequests": 2000,
"priorityThreshold": 0.8
},
"routes": [
{
"match": { "path": "/api/critical/**" },
"proxy": { "targets": ["http://api:4000"], "priority": 90 }
},
{
"match": { "path": "/api/batch/**" },
"proxy": { "targets": ["http://api:4000"], "priority": 10 }
}
]
}
| Field | Type | Default | Description |
|---|---|---|---|
limits.priorityThreshold |
number | 0.8 |
Load fraction at which shedding begins (0.0–1.0) |
proxy.*.priority |
number (0–100) | 50 |
Route priority; below 50 = sheddable |
Note: Priority routing only applies when both
maxInflightRequestsandpriorityThresholdare configured on the site.
Fault Injection
Requires
cargo build --features fault-injectionFor testing only — do not use in production.
# YAML
faultInjection:
abort:
percent: 5
status: 503
body: "Injected fault"
delay:
percent: 10
ms: 500
// JSON
{
"faultInjection": {
"abort": { "percent": 5, "status": 503, "body": "Injected fault" },
"delay": { "percent": 10, "ms": 500 }
}
}
Proxy Cache
Requires
cargo build --features cacheFor Redis-backed cache also add--features redis; for disk cache add--features disk-cache.
Size limit:
cache.maxSizeMbbounds the store with an LRU eviction manager (least-recently-used entries are purged once the total exceeds the budget). There is no per-body cap: a single response larger than the budget is written and then evicted again, because capping bodies without aContent-Lengthwould abort the client mid-transfer. Limits of the current implementation: the budget of a store is fixed by the first route that uses it (changingmaxSizeMbneeds a restart, not a reload), routes sharing astoreshare its budget, and fordisk:/redis://stores only entries admitted since the process started are counted, so entries left over from a previous run are not included until they are rewritten.
# YAML
proxy:
/api:
targets: ["http://backend:4000"]
cache:
store: memory
ttlSecs: 60
maxSizeMb: 256 # store budget (MiB), LRU eviction
staleWhileRevalidateSecs: 300 # serve stale up to 5 min while refreshing
staleIfErrorSecs: 600 # serve stale up to 10 min if upstream fails
varyHeaders: [Accept-Language, Accept-Encoding]
skipPaths: [/api/me, /api/cart] # never cache these paths
skipIfCookie: true
methods: [GET, HEAD]
// JSON
{
"proxy": {
"/api": {
"targets": ["http://backend:4000"],
"cache": {
"store": "memory",
"ttlSecs": 60,
"maxSizeMb": 256,
"staleWhileRevalidateSecs": 300,
"staleIfErrorSecs": 600,
"varyHeaders": ["Accept-Language", "Accept-Encoding"],
"skipPaths": ["/api/me", "/api/cart"],
"skipIfCookie": true,
"methods": ["GET", "HEAD"]
}
}
}
}
Cache field reference
| Field | Type | Default | Description |
|---|---|---|---|
store |
string | — | "memory", "redis" (the address of global.redis.url, --features redis), "disk:/path" (--features disk-cache); a "redis://..." address here still works but is deprecated |
ttlSecs |
number | — | Fresh cache TTL (seconds) |
maxSizeMb |
number | — | Size budget of the store in MiB (LRU eviction) (≥ 1; unset = unlimited) |
staleWhileRevalidateSecs |
number | 0 |
Serve stale while refreshing in background (RFC 5861) |
staleIfErrorSecs |
number | 0 |
Serve stale when upstream returns 5xx, including after retries are exhausted (RFC 5861) |
earlyRefreshSecs |
number | 0 |
Refresh cache in the background when remaining TTL < this value (see below) |
varyHeaders |
string[] | — | Vary cache key by these request headers |
skipPaths |
string[] | — | Paths to never cache |
skipIfCookie |
bool | false |
Skip caching when request has a cookie |
methods |
string[] | [GET, HEAD] |
Cacheable HTTP methods |
Cache key — scheme + host + path + query string. Request body is never
part of the key, so POST responses are not cached by default (add "POST" to
methods only for idempotent endpoints). Use varyHeaders to differentiate
responses by Accept-Language or Accept-Encoding.
Upgrading from a Pingora 0.8 based release: the key is now built with an explicit boundary between the host and the rest, so every key hashes differently. A persistent store (
disk:orredis://) starts cold once; Redis entries expire on their own TTL, but the olddisk:files are never read again and are not removed automatically — delete the cache directory to reclaim the space.
Age header (RFC 7234 §5.1): Conduit automatically injects an `Age: