Skip to content

[11/N] [HAProxy stability] - Add close-spread-time in HAProxy template - #63996

Merged
eicherseiji merged 6 commits into
ray-project:masterfrom
harshit-anyscale:serve-haproxy-close-spread-time
Jul 14, 2026
Merged

eicherseiji merged 6 commits into
ray-project:masterfrom
harshit-anyscale:serve-haproxy-close-spread-time

Conversation

@harshit-anyscale

@harshit-anyscale harshit-anyscale commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

After a config reload, a soft-stopping (old) HAProxy worker keeps its idle frontend connections open and keeps serving them from a frozen, pre-reload server list until hard-stop-after fires. option idle-close-on-response (already in Serve's template) only sheds a connection on its next response, so a connection that stays idle across the reload is never shed and can linger on the old worker for the entire hard-stop-after window. Two failure modes follow from that, both observed in staging:

  • Late request killed at the hard stop (KH-- 502). An idle connection picks up a long-running request shortly before the hard stop, which then kills it mid-request (termination code K), surfacing as an unretryable 502 at the client or the external load balancer. Under sustained load (15-18K RPS) with hard-stop-after 300s, requests sleeping 30-120s were killed exactly 300s after fleet-wide reload waves, clustered to the same second across proxy nodes; a large in-flight response was also cut mid-transfer and the load balancer minted its own 502 (Server: awselb/2.0).
  • Stale routing to removed replicas (SC-- 503). The old worker runs no health checks and keeps routing from its frozen server list. An external-LB keep-alive connection pinned to that worker (new connections go to the new worker; existing ones stay) keeps reaching replicas that have since been downscaled or migrated, so the connect is refused and the request returns an unretryable 503. This showed up after a node-compaction event removed a deployment's replicas: the pinned connection kept getting 503s from the old worker for minutes, until hard-stop-after.

Both stem from the same root: idle connections, and the frozen config they carry, linger on the old worker until hard-stop-after.

HAProxy's close-spread-time closes a soft-stopping worker's idle frontend connections spread over a window at soft-stop, so clients migrate to the new (correct-config) worker within that window instead of lingering until hard-stop-after. Sizing hard-stop-after >= close-spread-time + max expected request duration then ensures no request is alive when the hard stop fires. This covers workers that are properly soft-stopped; a worker that never receives the soft-stop signal is a separate concern.

What does this change do?

Adds a close_spread_time_s field to HAProxyConfig, set via RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S, rendered in the template global section next to hard-stop-after:

close-spread-time {{ config.close_spread_time_s }}s

Defaults to None (directive omitted), so there is no behavior change unless the env var is set. Unset or empty values fall back to None, matching the existing optional HAProxy timeout constants (RAY_SERVE_HAPROXY_TIMEOUT_SERVER_S). Unit test covers both the rendered and omitted cases.

🤖 Generated with Claude Code

@harshit-anyscale harshit-anyscale self-assigned this Jun 10, 2026
@harshit-anyscale harshit-anyscale added the go add ONLY when ready to merge, run all tests label Jun 10, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for HAProxy's close-spread-time configuration option via the RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S environment variable, which helps spread the closing of idle frontend connections during soft-stops. The configuration is integrated into HAProxyConfig and the HAProxy configuration template, with corresponding unit tests added. The feedback suggests using the existing helper function get_env_int_non_negative to parse the environment variable safely and consistently.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread python/ray/serve/_private/constants.py Resolved
@harshit-anyscale harshit-anyscale changed the title [serve] Add RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S for HAProxy close-s… [9/N] [HAProxy stability] - Add close-spread-time in HAProxy template Jun 10, 2026
@harshit-anyscale
harshit-anyscale marked this pull request as ready for review June 10, 2026 18:37
@harshit-anyscale
harshit-anyscale requested a review from a team as a code owner June 10, 2026 18:37
@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Jun 10, 2026
@harshit-anyscale harshit-anyscale changed the title [9/N] [HAProxy stability] - Add close-spread-time in HAProxy template [11/N] [HAProxy stability] - Add close-spread-time in HAProxy template Jul 6, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 74574ab. Configure here.

Comment thread python/ray/serve/_private/constants.py Resolved
@harshit-anyscale
harshit-anyscale force-pushed the serve-haproxy-close-spread-time branch from 74574ab to e99e48f Compare July 7, 2026 05:29
…pread-time

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@harshit-anyscale
harshit-anyscale force-pushed the serve-haproxy-close-spread-time branch from e99e48f to a7c0f8f Compare July 7, 2026 05:48

@eicherseiji eicherseiji left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment nit

Comment thread python/ray/serve/_private/constants.py Resolved
Co-authored-by: Seiji Eicher <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@eicherseiji
eicherseiji enabled auto-merge (squash) July 9, 2026 18:00
@github-actions
github-actions Bot disabled auto-merge July 10, 2026 07:57
@eicherseiji
eicherseiji merged commit cc8eb83 into ray-project:master Jul 14, 2026
3 checks passed
johntaylor-cell added a commit to johntaylor-cell/ray that referenced this pull request Jul 14, 2026
ray-project#63996 added int(os.environ.get("RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S"))
guarded by a separate os.environ.get() truthiness check. The two
independent lookups mean neither mypy nor pyrefly can narrow the value
to non-None, so int(str | None) fails both checkers -- which currently
turns the serve type-check lint shard red for every Serve PR (the
mypy/pyrefly serve hooks run --all-files).

Use the existing get_env_int helper, matching how the other int env
vars in this file are read (per review). Behavior is equivalent for all
real inputs; an explicitly-empty value is now rejected at import rather
than treated as unset, consistent with the other get_env_int call
sites. Restores the serve type-check allowlist to green.

Related to ray-project#64643.

Signed-off-by: john.taylor <[email protected]>
johntaylor-cell added a commit to johntaylor-cell/ray that referenced this pull request Jul 14, 2026
ray-project#63996 added int(os.environ.get("RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S"))
guarded by a separate os.environ.get() truthiness check. The two
independent lookups mean neither mypy nor pyrefly can narrow the value
to non-None, so int(str | None) fails both checkers -- which currently
turns the serve type-check lint shard red for every Serve PR (the
mypy/pyrefly serve hooks run --all-files).

Read the env var once into a local so the truthiness guard narrows it.
Runtime behavior is identical to ray-project#63996 (single lookup, empty value
still treated as unset -> None). get_env_int() is intentionally avoided:
it raises ValueError at import on an empty value, which would change
ray-project#63996 behavior. Restores the serve type-check allowlist to green.

Related to ray-project#64643.

Signed-off-by: john.taylor <[email protected]>
johntaylor-cell added a commit to johntaylor-cell/ray that referenced this pull request Jul 14, 2026
ray-project#63996 added int(os.environ.get("RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S"))
guarded by a separate os.environ.get() truthiness check. The two
independent lookups mean neither mypy nor pyrefly can narrow the value
to non-None, so int(str | None) fails both checkers -- which currently
turns the serve type-check lint shard red for every Serve PR (the
mypy/pyrefly serve hooks run --all-files).

Use the existing get_env_int helper, matching how the other int env
vars in this file are read. A non-parsable or empty value now fails at
import, which is the intended behavior. Restores the serve type-check
allowlist to green.

Related to ray-project#64643.

Signed-off-by: john.taylor <[email protected]>
eicherseiji added a commit to eicherseiji/ray that referenced this pull request Jul 14, 2026
The merged mypy/pyrefly enforcement (ray-project#64662) runs on the full allowlist,
surfacing type issues that per-commit hooks never checked on these files:

- AutoscalingContext.prometheus_metrics now accepts a callable returning
  Optional, matching the cache getter that returns None when there is no
  data.
- get_prometheus_config_by_deployment narrows the Optional queries and
  address inline so its return type is satisfied.

Also narrows a pre-existing int(os.environ.get(...)) in
RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S (added in ray-project#63996) that the same
enforcement flags on master; needed for the shared mypy hook to pass.

Signed-off-by: Seiji Eicher <[email protected]>
abrarsheikh pushed a commit that referenced this pull request Jul 14, 2026
…64752)

#63996 added
int(os.environ.get("RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S")) guarded by
a separate os.environ.get() truthiness check. The two independent
lookups mean neither mypy nor pyrefly can narrow the value to non-None,
so int(str | None) fails both checkers -- which currently turns the
serve type-check lint shard red for every Serve PR (the mypy/pyrefly
serve hooks run --all-files).

Read the env var once into a local so the truthiness guard narrows it;
runtime behavior is identical (single lookup, same empty-string -> None
handling). Restores the serve allowlist to green.

Related to #64643

Signed-off-by: john.taylor <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ay-project#64752)

ray-project#63996 added
int(os.environ.get("RAY_SERVE_HAPROXY_CLOSE_SPREAD_TIME_S")) guarded by
a separate os.environ.get() truthiness check. The two independent
lookups mean neither mypy nor pyrefly can narrow the value to non-None,
so int(str | None) fails both checkers -- which currently turns the
serve type-check lint shard red for every Serve PR (the mypy/pyrefly
serve hooks run --all-files).

Read the env var once into a local so the truthiness guard narrows it;
runtime behavior is identical (single lookup, same empty-string -> None
handling). Restores the serve allowlist to green.

Related to ray-project#64643

Signed-off-by: john.taylor <[email protected]>
Signed-off-by: 400Ping <[email protected]>
eicherseiji pushed a commit that referenced this pull request Sep 9, 2026
…eregistration window ends (#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently #63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (#65502 draining-node accessor on the
controller, #65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
NightWing1998 pushed a commit to NightWing1998/ray that referenced this pull request Sep 11, 2026
…eregistration window ends (ray-project#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently ray-project#63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (ray-project#65502 draining-node accessor on the
controller, ray-project#65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…eregistration window ends (ray-project#65698)

## Description

What happens today when a direct-ingress replica behind HAProxy
(`RAY_SERVE_ENABLE_HA_PROXY=1`) shuts down, in sequence:

1. A replica starts draining (scale-down, upgrade, or its node is being
removed).
2. Every node's HAProxy receives the updated backend list and reloads.
3. A reload starts a **new** HAProxy process. The **old** process keeps
running until its connections finish (bounded by `hard-stop-after`,
minutes) — and it still routes with the **old** backend list. It cannot
be corrected: config reloads and runtime commands only reach the new
process.
4. So a stale worker can keep sending brand-new requests to the draining
replica for minutes.
5. Today the replica accepts them: it keeps serving for as long as
requests arrive, not just for the deregistration window
(`RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S`, default 30s).
6. The replica/node is only guaranteed to live through that window. When
the node then goes away (e.g. spot interruption), the late-admitted
requests are cut mid-flight — the client sees an error nothing can
safely retry.

We measured ~40 such failures per spot-interruption event in a staging
fleet.

**The fix** — behind HAProxy, drain in two phases:

1. Stay fully reachable for the deregistration window, exactly as today.
2. Then close the direct-ingress HTTP listener and wait for in-flight
requests.

A late request from a stale worker is now refused at connect time
instead of admitted. HAProxy retries refused connections on another
replica (`retry-on conn-failure` + `option redispatch`), so the client
sees no error.

**Without HAProxy nothing changes**: there is no retrying proxy in
front, a refusal would reach the client, so that path keeps the existing
drain.

## Related issues

N/A (follow-up to the HAProxy stability series, most recently ray-project#63996).

## Additional information

- Adds a `Replica._is_direct_ingress` property (mirrors the one on
`ReplicaMetricsManager`), used to pick the drain path.
- Only the HTTP listener closes early; direct-ingress gRPC keeps the
existing behavior until the post-drain quiesce. Candidate follow-up.
- Gated on `RAY_SERVE_ENABLE_HA_PROXY` because the early refusal is only
safe with a retrying proxy in front.
- A live-cluster reproduction with keep-alive connections against a
stale HAProxy worker is a planned follow-up.

### Not a duplicate

Checked open PRs before and after opening this one (`gh pr list --search
"haproxy"`, `--search "drain replica graceful shutdown"`): no open PR or
issue touches replica drain or direct-ingress listener shutdown. The
nearest neighbours are unrelated (ray-project#65502 draining-node accessor on the
controller, ray-project#65542 lazy jinja2 import).

### Tests run

```
pytest python/ray/serve/tests/unit/test_replica_quiesce.py -v
```

12 passed — the 7 pre-existing tests plus 5 new ones covering:
drain-path selection with and without HAProxy, phase ordering, the
deregistration window being served in full before the listener closes,
the minimum period not being applied twice, and the no-HTTP-server case.

```
pre-commit run --files python/ray/serve/_private/replica.py python/ray/serve/tests/unit/test_replica_quiesce.py
```

All hooks passed, including `mypy (ray serve)` and `pyrefly (ray
serve)`.

### AI assistance

This change was developed with AI assistance (Claude Code). A human
author reviewed every changed line and ran the tests above locally
before requesting review.

---------

Signed-off-by: harshit-anyscale <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants