Repository navigation
Serve haproxy stderr access logs - #63507
harshit-anyscale wants to merge 26 commits into
Conversation
HAProxy runs in `-db` debug mode and emits hundreds of stderr lines per second under load. The proxy actor captured stderr via `stderr=PIPE` but never read from it, so the 64KB OS pipe buffer fills in seconds and HAProxy blocks on its next `write(2)` — including from threads serving the admin socket. Runtime-API calls then time out and look like a deadlock from outside. Spawn a fire-and-forget asyncio task right after startup that drains stderr to a per-pid log file. Output is bounded to 10 MB per pid via truncate-on-roll so a long-lived proc cannot fill the disk. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Serve controller emits TARGET_GROUPS and FALLBACK_TARGETS long-poll updates independently, often within tens of milliseconds of each other during autoscaling churn. Each broadcast was kicking off its own reload, serializing on the reload lock and amplifying replica thrash into proxy churn. Introduce a coalescing window: a broadcast marks state dirty and starts (or extends) a single asyncio task that sleeps the window and then applies the latest state. Default window is 100ms; tunable via `RAY_SERVE_HAPROXY_BROADCAST_COALESCE_S`, and setting it to 0 falls back to the prior synchronous behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Under autoscaling churn, the first connect attempt to a slot can hit a
replica that is briefly down (just-removed, mid-restart, scaling-up
slot not yet accepting). Today HAProxy returns the resulting 502/503
directly to the client even though a peer slot is up and ready.
Add two defaults-level directives so requests transparently retry to a
healthy peer:
- `option redispatch` — when a retry is allowed, send it to a
different slot (not the same one).
- `retry-on conn-failure empty-response` — only retry in cases that
cannot have leaked partial bytes to the client: TCP connect
failure (no bytes sent) and empty response (slot died before
sending a body). Streaming responses with a partial body are
untouched.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After enabling `option redispatch` + `retry-on conn-failure empty-response` in the HAProxy defaults block, HAProxy retries a failed connect to the next slot. When every slot is down (which is the scenario this test creates by killing the only replica), retries exhaust and HAProxy returns its built-in 503 "Service Unavailable" instead of surfacing the original 502. The 502 errorfile maps 502/504 to 500, but it does not cover 503, so the response the client sees changes from 500 to 503. Both are valid error responses for "the service is currently not available"; loosen the assertion to accept either. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous comment described what the setting does ("window for
coalescing back-to-back controller broadcasts") but not why fast
reloads are harmful. Rewrite to lead with the actual concern:
reloading HAProxy at controller-broadcast speed (every few tens of
ms) bursts process handoffs, saturates the proxy actor's event loop,
and forces overlapping drains on the old proc.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replace the asyncio drain task with a direct file redirect: open a stderr destination file before spawn, pass it as `stderr=...` so the kernel uses dup2 to wire the child's fd 2 to the file, then rename the file to include the child's pid after spawn returns. No pipe is created, so the 64KB kernel buffer that previously deadlocked admin-socket threads when stderr backed up can't form. The fix is structural rather than behavioral — there is no buffer to fill because there is no consumer to be slow. Linux file descriptors bind to inodes rather than paths, so renaming the file after spawn is safe: the child keeps writing to the same inode under the new name. Trade-off: the previous drain task capped each file at 10MB via a periodic truncate. Under the file-redirect model the file grows unbounded until the proc exits. Acceptable for now given realistic stderr volumes; a periodic size-cap task can be layered on later if needed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Shorter wording for two comments that were doing more explaining than the code needs. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Down from 9 lines to 4 — keeps the why (overlapping `-sf` saturates the actor) and drops the rest. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When `_update_haproxy_backends` threw, `_update_pending` had already been flipped to False before the apply, so the loop would exit and the HAProxy state would stay stale until the next broadcast — which may never arrive in a settled cluster. Re-arm `_update_pending` in the except branch so a failed apply is retried on the next coalesce tick. Cap retries at 3 consecutive failures to avoid busy-looping on a persistent error (e.g. a bad config HAProxy refuses to parse); past that, wait for the next broadcast rather than spinning. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Remove the "overlapping `-sf` handoffs saturate the proxy actor's event loop" line — we never confirmed that as the failure mode. Keep the observable problem: under churn, broadcasts can fire reloads tens of ms apart. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
7 lines → 3 lines. Keeps the surprising bit (rename safety via fd-binds-to-inode). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After redirecting HAProxy's stderr to a file at spawn, `proc.stderr` became None and `_wait_for_hap_availability` fell back to b"" when the process crashed. The resulting RuntimeError message was just "exit code N" with no diagnostic — even though HAProxy had written the real error (bind failure, config parse error, etc.) to the on-disk stderr log file. Read the tail of the per-pid stderr file when proc.stderr is None, so startup-crash errors carry the actual reason again. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The pid scheme required an awkward open-with-temp-name then os.replace because the child's pid isn't known until create_subprocess_exec returns. Switch to a monotonic spawn counter held on the HAProxyApi instance: - The stderr path is known pre-spawn, so the file opens at its final name and stays there. - No more `stderr.starting.log` intermediate, no os.replace, no rename race window. - The path is attached to the proc as `_stderr_path` and travels with it, so `_wait_for_hap_availability` reads from the right file whether it was called on a fresh spawn or on an old proc during graceful reload. A new info-level log at spawn time emits the (spawn#, pid, stderr path, args) tuple so the pid → stderr-file mapping is recoverable from the actor log. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`_read_stderr_log_tail` was used in exactly one place and existed only to give a name to "open file, seek to end, read last 4KB." Inline it into `_wait_for_hap_availability` so the entire crash-message logic is visible at the call site. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Add `RAY_SERVE_HAPROXY_LOG_ACCESS_TO_STDERR` env toggle. When enabled, HAProxy's global block gets `log stderr local0 info` as an additional log destination, so per-request access logs (with status codes and termination-state codes) land in the per-spawn stderr file we already capture. Off by default — at high RPS the access-log volume is large and the existing syslog destinations are sufficient when syslog is reachable. Turn on for diagnostics in environments where /dev/log is unavailable and we want to grep termination states for failed requests. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request enhances the HAProxy ingress by implementing update coalescing to batch backend updates and prevent excessive reloads during autoscaling. It also improves stability by redirecting HAProxy's stderr to a file to avoid pipe-related deadlocks and introduces retry logic for connection failures. Furthermore, it adds a configuration option to mirror access logs to stderr for easier debugging. A review comment suggests a more idiomatic use of logger.exception to avoid redundant exception information in log messages.
| self._update_haproxy_backends() | ||
| consecutive_failures = 0 | ||
| except Exception as e: | ||
| logger.exception(f"Coalesced HAProxy update failed: {e}") |
There was a problem hiding this comment.
logger.exception() automatically includes exception information and a stack trace in the log. Formatting the exception object into the message string is redundant. It's better to just provide the message and let logger.exception() handle the rest for cleaner and more standard logging.
| logger.exception(f"Coalesced HAProxy update failed: {e}") | |
| logger.exception("Coalesced HAProxy update failed") |
The replica's HTTP handler returns 404 when an incoming request's path doesn't start with this replica's `_route_prefix`. In a stable cluster this shouldn't happen — HAProxy (or whatever proxy is in front) routes by path prefix and should never dispatch a request to a replica whose deployment doesn't serve that prefix. In practice it does happen, rarely, during scale events. Suspected causes: - Port reuse: a stopped replica's port gets reassigned to a new replica of a different deployment before HAProxy notices the slot is gone. - Stale HAProxy slot during a reload window. - Reconfigure race when route_prefix is changing. Today the failure is silent — the replica just returns 404 and the client sees a confusing "path not found" for a path that genuinely exists elsewhere in the cluster. Add a WARNING log before the 404 so operators can detect and quantify this case from replica logs. No behavior change — still returns 404 — just observability for the race. Whether to return 503 instead (and have HAProxy retry) is a separate decision. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Extend the existing `retry-on conn-failure empty-response` directive to also retry on backend-returned 503 responses. With `option redispatch` already set, the retry goes to a different slot — so a replica returning 503 (e.g. mid drain, transient state, route-prefix race) gets transparently masked behind a retry to a healthy peer. This pairs with the route-prefix mismatch logging added in the previous commit: when a replica is currently returning 404 for that race, the longer-term fix is to make it return 503 instead, at which point this retry-on rule covers it without client-visible failures. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
05cb645 to
c2d025f
Compare
When a replica stops and its port is released, today the port goes straight back into the available pool — and the next replica to be spawned can grab it. If that happens before HAProxy (or any proxy that mirrors deployment state) has propagated the previous replica's slot removal, the proxy still has a slot pointing at host:port for the OLD deployment, but a NEW deployment's replica is now serving that port. Requests routed via the stale slot hit the new replica, which doesn't serve that route, and return 404. We observed this extensively in load tests. Close the race at its source: hold released ports in a quarantine set for RAY_SERVE_PORT_QUARANTINE_S (default 10s) before they re-enter the available pool. Quarantine is drained lazily on each allocate(), so there's no background timer. `block_port=True` (permanent block) bypasses quarantine because it's a strictly stronger guarantee. 10s comfortably covers HAProxy's reconfigure latency (broadcast coalescing + reload) under load. For deployments with long graceful_shutdown windows, the drain itself already provides most of the buffer, and the quarantine only matters for crash/force-kill recoveries. Tunable via env var. Tests: existing port-reuse tests are unaffected because the autouse fixture sets quarantine to 0; four new tests cover the quarantine behavior (held, expires, bypassed by block_port, disabled at 0). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two related changes to absorb the residual 503s observed in load tests: 1. `retries` was previously not configurable — neither the env var nor a HAProxyConfig field existed, so HAProxy was using its built-in default of 3. Add `RAY_SERVE_HAPROXY_RETRIES` (default 250), thread it through HAProxyConfig.retries, and emit `retries N` in the defaults block of the rendered config. With `option redispatch` already in place, each retry redispatches to a peer slot — more retries means more chances to find a healthy slot when many are briefly stale (e.g. mass scale-down, replica recycle event). 2. `timeout_queue_s` defaulted to None, so the `timeout queue` directive wasn't emitted. With no queue, HAProxy 503s requests immediately when a backend has zero UP servers. Default to 30s so the request waits up to 30s for any slot to become UP via the next health-check tick. Set the env var to 0 to disable. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Add two info-level timing log lines so we can observe HAProxy reload latency from the actor logs: - `_graceful_reload`: logs total elapsed ms from entry to "new pid serving" (or to failure). High p99 here points at HAProxy startup being slow (likely many backends in config, slow disk, etc.). - `_coalesce_and_apply`: logs ms from the post-sleep "apply now" point to when `_update_haproxy_backends` returns. High values point at the actor's apply path (config regen + reload scheduling) being slow, distinct from HAProxy reload itself. Together these let us figure out whether the slot-update lag during heavy churn is (a) reload latency, (b) actor-apply latency, or (c) queueing/coalescing — each suggests a different mitigation. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolves conflicts from PR ray-project#63531 (splice + log consolidation): - haproxy_templates.py: collapse to single `log {{ config.log_target }}` per master; layer optional stderr access-log mirror on top. Keep both retry/redispatch (HEAD) and splice-request/splice-response (master) in the defaults block. - haproxy.py: union of imports (LOG_ACCESS_TO_STDERR + new INGRESS_* knobs + LOG_TARGET). - test_haproxy_api.py: expected_config reflects merged template ordering (retry block then splice block).
…c kills
Adds diagnostic log lines to pin down the cause of mid-flight long-runner
502s observed ~30-35s after a downscale event. The investigation so far
suggests one of:
(1) graceful_shutdown_timeout_s not propagating from deployment config
to controller's _shutdown_deadline (falls back to default 20s →
max(20, 30) = 30s).
(2) HAProxyApi.stop() being invoked unexpectedly during the test,
SIGKILL'ing accumulated old HAProxy workers and dropping their
in-flight connections.
Logs added:
deployment_state.py:
- [shutdown-deadline] in DeploymentReplica.stop(): logs `graceful`,
`_actor._ingress`, `RAY_SERVE_ENABLE_DIRECT_INGRESS`, the timeout
returned by `_actor.graceful_stop()`, the value of
`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, whether the floor
was applied, and the final timeout_s used to compute the deadline.
This confirms whether the configured graceful_shutdown_timeout_s
actually reached the controller.
- [force-kill] in DeploymentReplica.check_stopped(): logs elapsed
time since stop() was called, the deadline timestamp, and now,
so we can see exactly when the controller decided to fire
`force_stop()`.
haproxy.py:
- [haproxy-stop] in HAProxyApi.stop(): logs the current proc pid,
the count and pids of tracked old procs, and their returncodes
before any kill happens. Then logs each SIGKILL explicitly.
Fires once per `stop()` invocation; if it fires during normal
load-test operation (not at actor shutdown), that's the smoking
gun for hypothesis (2).
- [old-procs] in _graceful_reload(): logs the size of the
_old_procs list after each reload, distinguishing still-alive
vs. already-exited workers and listing the alive pids. Tracks
whether OLD workers accumulate without dying naturally.
All changes are logs only — no behavior change.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 24ed9ef. Configure here.
…roxy proc kills" This reverts commit 24ed9ef.
…ackends
Two related changes to reduce health-check pressure on the head-node fallback
proxy actor, which was being marked DOWN by HAProxy under load and producing
spurious 503s for scale-to-zero deployments.
The root cause: each HAProxy backend has its own `server check backup` entry
pointing at the head-node fallback proxy. With N apps × 2 protocols × M
worker nodes, the shared fallback proxy receives N × 2 × M × 2 health checks
per second (with default 500ms `inter`). For a 12-app service on 200 nodes
that is ~9,600 checks/sec on a single Python proxy actor, which is enough to
push p99 healthz response past the 500ms check window. Combined with the
inherited `fall 1` from `default-server`, a single 501ms response on any
worker takes that worker's backend offline; positive feedback amplifies the
overload across the cluster.
1. Per-server health-check overrides for the fallback in haproxy_templates.py
The fallback line now emits:
server ... check backup inter 2s fastinter 500ms fall 3
This requires 3 consecutive failures over ~1s to declare DOWN (down from
1 failure at 500ms) and drops steady-state check rate 4x. Primary replica
servers still use the aggressive `default-server` settings — only the
fallback is loosened.
2. RAY_SERVE_HAPROXY_DISABLE_GRPC env var (default 0)
When set, HAProxy skips emitting gRPC backends entirely. Cuts the
fallback-server count in half for services that don't actually use gRPC,
roughly halving the health-check load on the head node and removing
~half of the rendered config file.
Combined effect for a 12-app, 200-node service that doesn't use gRPC:
HTTP+gRPC fallback health-check load drops from ~9,600/sec → ~1,200/sec.
…ined `HAProxyProxyActor.is_drained()` previously gated on: 1. drain time exceeded `PROXY_MIN_DRAINING_PERIOD_S` 2. the current worker's admin-socket stats reported `is_system_idle` This was unsafe. Each graceful reload spawns a new HAProxy worker that owns the listening socket (via `-x` socket transfer), while the OLD worker enters soft-stop and continues to serve its pre-reload in-flight connections in its own process memory. Those in-flight connections are invisible to the admin socket (which is bound by the new worker), so `is_system_idle` could return True while old workers still held long-running connections like 60-120s long-runner requests. Marking the proxy as drained while old workers were alive caused `proxy_state.shutdown()` → `HAProxyApi.stop()` → `proc.kill()` to SIGKILL the old workers and sever their in-flight TCP connections. Clients saw 502 from ALB (target broke connection); replicas saw 499 (uvicorn received an ASGI disconnect mid-request). The fix adds condition (2'): no OLD workers from `_old_procs` are still alive. Each old worker exits cleanly when its in-flight count reaches zero (or `hard-stop-after` reaps it as final safety valve), at which point `returncode` becomes set. The drain check uses this as a precise per-worker signal. This makes the drain adaptive: it lasts exactly as long as the longest in-flight request actually needs, plus the `PROXY_MIN_DRAINING_PERIOD_S` floor that's still useful for ALB target-deregistration propagation. Previously, operators had to guess the right `PROXY_MIN_DRAINING_PERIOD_S` value to exceed the longest expected request duration; with this change, the env var's role reverts to "minimum drain time" (its name) rather than "maximum request time" (its de facto behavior). A new helper `HAProxyApi.has_alive_old_procs()` also prunes already- exited entries from `_old_procs` so the list stays bounded across long-lived proxy actors that perform many reloads. Check order in `is_drained` was reorganized so the cheap, in-memory checks (timer, old-proc list) short-circuit before the async admin socket query.
…s to close 404 routing race (#63628) ### Summary Carved out of #63507 to land independently. When a replica stops and its port is released, the port goes straight back into the available pool today. The next replica to be spawned can grab it. If that happens **before** HAProxy (or any proxy that mirrors deployment state) has propagated the previous replica's slot removal, the proxy still has a slot pointing at `host:port` for the **old** deployment, but a **new** deployment's replica is now serving that port. Requests routed via the stale slot hit the new replica, which doesn't serve that route, and return **404**. We observed this extensively in load tests with autoscaling churn. The fix closes the race at its source by holding released ports in a quarantine set on `NodePortManager` for a configurable window before they re-enter the available pool. - `RAY_SERVE_PORT_QUARANTINE_S` (env var, float seconds, default `10`). 10s comfortably covers HAProxy's reconfigure latency (broadcast coalescing + reload) under load. - Quarantine is drained **lazily** on each `allocate()` call — no background timer. - `block_port=True` (permanent block) bypasses quarantine because it's a strictly stronger guarantee. Why 10s and not larger: for deployments with long `graceful_shutdown` windows, the drain itself already provides most of the buffer, and the quarantine only really matters for crash/force-kill recoveries. High-churn environments can bump the env var; small clusters where port-pool pressure matters can lower it or set to `0` to disable entirely. --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…s to close 404 routing race (ray-project#63628) ### Summary Carved out of ray-project#63507 to land independently. When a replica stops and its port is released, the port goes straight back into the available pool today. The next replica to be spawned can grab it. If that happens **before** HAProxy (or any proxy that mirrors deployment state) has propagated the previous replica's slot removal, the proxy still has a slot pointing at `host:port` for the **old** deployment, but a **new** deployment's replica is now serving that port. Requests routed via the stale slot hit the new replica, which doesn't serve that route, and return **404**. We observed this extensively in load tests with autoscaling churn. The fix closes the race at its source by holding released ports in a quarantine set on `NodePortManager` for a configurable window before they re-enter the available pool. - `RAY_SERVE_PORT_QUARANTINE_S` (env var, float seconds, default `10`). 10s comfortably covers HAProxy's reconfigure latency (broadcast coalescing + reload) under load. - Quarantine is drained **lazily** on each `allocate()` call — no background timer. - `block_port=True` (permanent block) bypasses quarantine because it's a strictly stronger guarantee. Why 10s and not larger: for deployments with long `graceful_shutdown` windows, the drain itself already provides most of the buffer, and the quarantine only really matters for crash/force-kill recoveries. High-churn environments can bump the env var; small clusters where port-pool pressure matters can lower it or set to `0` to disable entirely. --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…s to close 404 routing race (ray-project#63628) ### Summary Carved out of ray-project#63507 to land independently. When a replica stops and its port is released, the port goes straight back into the available pool today. The next replica to be spawned can grab it. If that happens **before** HAProxy (or any proxy that mirrors deployment state) has propagated the previous replica's slot removal, the proxy still has a slot pointing at `host:port` for the **old** deployment, but a **new** deployment's replica is now serving that port. Requests routed via the stale slot hit the new replica, which doesn't serve that route, and return **404**. We observed this extensively in load tests with autoscaling churn. The fix closes the race at its source by holding released ports in a quarantine set on `NodePortManager` for a configurable window before they re-enter the available pool. - `RAY_SERVE_PORT_QUARANTINE_S` (env var, float seconds, default `10`). 10s comfortably covers HAProxy's reconfigure latency (broadcast coalescing + reload) under load. - Quarantine is drained **lazily** on each `allocate()` call — no background timer. - `block_port=True` (permanent block) bypasses quarantine because it's a strictly stronger guarantee. Why 10s and not larger: for deployments with long `graceful_shutdown` windows, the drain itself already provides most of the buffer, and the quarantine only really matters for crash/force-kill recoveries. High-churn environments can bump the env var; small clusters where port-pool pressure matters can lower it or set to `0` to disable entirely. --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…s to close 404 routing race (ray-project#63628) ### Summary Carved out of ray-project#63507 to land independently. When a replica stops and its port is released, the port goes straight back into the available pool today. The next replica to be spawned can grab it. If that happens **before** HAProxy (or any proxy that mirrors deployment state) has propagated the previous replica's slot removal, the proxy still has a slot pointing at `host:port` for the **old** deployment, but a **new** deployment's replica is now serving that port. Requests routed via the stale slot hit the new replica, which doesn't serve that route, and return **404**. We observed this extensively in load tests with autoscaling churn. The fix closes the race at its source by holding released ports in a quarantine set on `NodePortManager` for a configurable window before they re-enter the available pool. - `RAY_SERVE_PORT_QUARANTINE_S` (env var, float seconds, default `10`). 10s comfortably covers HAProxy's reconfigure latency (broadcast coalescing + reload) under load. - Quarantine is drained **lazily** on each `allocate()` call — no background timer. - `block_port=True` (permanent block) bypasses quarantine because it's a strictly stronger guarantee. Why 10s and not larger: for deployments with long `graceful_shutdown` windows, the drain itself already provides most of the buffer, and the quarantine only really matters for crash/force-kill recoveries. High-churn environments can bump the env var; small clusters where port-pool pressure matters can lower it or set to `0` to disable entirely. --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> Signed-off-by: 400Ping <[email protected]>

Description
Related issues
Additional information