Skip to content

[core] Enable TCP keepalive on GCS<->Redis connections - #65424

Merged
rueian merged 4 commits into
ray-project:masterfrom
zzchun:gcs-redis-tcp-keepalive
Oct 6, 2026
Merged

rueian merged 4 commits into
ray-project:masterfrom
zzchun:gcs-redis-tcp-keepalive

Conversation

@zzchun

@zzchun zzchun commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Description

Idle GCS-to-external-Redis connections can become unreachable without a FIN or
RST. This PR enables TCP keepalive centrally in ConnectWithoutRetries before
TLS, AUTH, or commands, covering sync, async, Sentinel, cluster redirects, and
cleanup connections. Probes can also preserve flows through network devices
that count TCP keepalive as activity.

Config Default Valid values
redis_tcp_keepalive_interval_seconds 30 0..32767; 0 disables keepalive
redis_tcp_keepalive_probes 3 1..127 when enabled

Linux with the relevant TCP options, including musl, applies idle time, probe
interval, and count explicitly. With all settings applied, an idle blackholed
connection is detected after approximately interval * (1 + probes), or 120
seconds by default. This is not a command timeout or a complete recovery bound.
macOS applies idle time only. Windows applies idle and probe intervals with an
OS-controlled probe count. Other POSIX platforms retain OS timing defaults.

Invalid configuration fails before DNS. On POSIX, failure to enable
SO_KEEPALIVE fails the connection immediately; rejected timing options warn
and leave the connection usable. Successful options remain applied and failed
options retain their previous values, so degraded connections do not promise
the requested detection window. Windows retains hiredis' combined enable/tune
operation and failure behavior.

Unexpected async disconnects log hiredis err/errstr and label RayConfig
values as current configuration, not the failed socket's actual policy or proof
of the cause of failure. The guide documents tuning, platform differences,
degradation, and the crash risk in versions without in-place Redis reconnect.

Context leak fix

The PR also fixes an existing leak in ConnectWithoutRetries: hiredis can return
an allocated context with err set on connection failure. Acquiring unique_ptr
ownership immediately releases that context on every early return, including
both connection errors and keepalive enable failures.

Related work and duplicate check

The open-PR search for redis keepalive on 2026-10-06 returned this PR, #65298
(in-place Redis reconnect), and #65840 (a Redis TLS documentation example).
The reconnect change complements detection and prevention; it does not add
keepalive socket policy. No competing PR is being opened. Documentation uses
conditional language so it does not become incorrect when reconnect lands.
Issue #66074 tracks coordinated keepalive, request, and reconnect defaults.

Testing

Validation after rebasing onto upstream/master 6703877370 on 2026-10-06:

  • git range-diff confirmed the four commits retain their patches, with only
    the upstream documentation move to doc/source/kuberay/user-guides/gcs-ft.md.
    The keepalive implementation and tests are unchanged; the relocated guide
    is byte-for-byte identical to its previous contents.

  • git diff --check upstream/master...HEAD: passed.

  • Pre-commit passed on all seven changed files:

    pre-commit run --files \
      doc/source/kuberay/user-guides/gcs-ft.md \
      src/ray/common/ray_config_def.h \
      src/ray/gcs/store_client/BUILD.bazel \
      src/ray/gcs/store_client/redis_context.cc \
      src/ray/gcs/store_client/redis_tcp_keepalive.h \
      src/ray/gcs/store_client/tests/BUILD.bazel \
      src/ray/gcs/store_client/tests/redis_context_test.cc
  • bazel test //src/ray/gcs/store_client/tests:all --test_output=errors --jobs=2 --nocache_test_results: started, then stopped during the fresh
    dependency build because this rebase made no C++ content changes. No tests
    executed (0/11).

Previous validation on 2026-09-11, before this rebase:

  • bazel test //src/ray/gcs/store_client/tests:redis_context_test --test_output=errors --jobs=1 --nocache_test_results: passed, 18 cases,
    including six production-connection-path failure scenarios.
  • bazel test //src/ray/gcs/store_client/tests:all --test_output=errors --jobs=1: passed, 11/11 tests (9 executed, 2 cached).

@zzchun
zzchun requested review from a team and andrewsykim as code owners August 12, 2026 13:52

@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 TCP keepalive configuration and tuning for external Redis connections in Ray GCS. It adds new configuration options for keepalive intervals and probes, validates these configurations before establishing connections, and improves error reporting for Redis I/O and unexpected disconnects. Additionally, documentation has been updated and comprehensive unit tests have been added to verify socket options and validation behavior. I have no feedback to provide.


/// Number of unanswered TCP keepalive probes before an external Redis
/// connection is declared dead, so detection takes roughly
/// redis_tcp_keepalive_interval_seconds * (1 + this value).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

9 as a default seems really high? Basically this means 30s (1 + 9), so we wouldn't declare a connection dead until 300s. Am I understanding that correctly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, your reading is exactly right: on glibc Linux it's 30 * (1 + 9) = 300s before the connection is declared dead. That's deliberate, and it's the number I went back and forth on the most — happy to change it if you'd rather.

The reason it isn't the more natural-looking 60s is that the two settings need opposite tuning, and hiredis ties them together:

  • The probe interval wants to be short. Its job is to keep the flow alive, so it has to stay below the shortest idle timeout on the path (cloud LBs are commonly 60–350s).
  • The time to declare dead wants to be long, because right now that verdict is unrecoverable.

redisEnableKeepAliveWithInterval() derives TCP_KEEPINTVL = interval/3 and TCP_KEEPCNT = 3, so dead lands at 2 * interval — you can't shorten the keepalive cadence without also shortening the death sentence. This PR overrides both socket options on glibc Linux so the two can be set independently.

The reason the death sentence needs to be slow is that, until in-place reconnect lands (#65298), "connection declared dead" means the GCS exits: RedisRequestContext::Run hits RAY_LOG(FATAL) once the retry budget is gone, and the periodic health check in gcs_server.cc does RAY_CHECK_OK on the result. So a stall that the connection would have ridden out becomes a GCS crash. Given that, I'd rather find out late than kill the GCS over a 4-minute network hiccup — the old behavior was to never find out at all, so even 300s is strictly better than today.

Once #65298 merges, this default should absolutely come down; 60–90s would be reasonable when detection just triggers a reconnect. I called that out as a follow-up in the PR description, and I'm glad to file it as an issue so it doesn't get lost.

That said, if you think 300s is too far in the "slow" direction even under the current crash semantics, I'm fine dropping it — 3 probes (120s) or 5 (180s) both still decouple the two knobs, which is the part that actually matters. Your call.

@andrewsykim

Copy link
Copy Markdown
Member

@zzchun overall this makes sense, but can you share how you tested it end to end to verify the expected behavior?

@zzchun

zzchun commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@andrewsykim Good question — worth separating two levels here. The tests in the PR verify configuration: getsockopt() on both the sync and async fds confirms the policy reaches the kernel. They don't verify behavior — nothing exercises a flow that actually dies. So I ran that separately against a real blackholed connection.

Setup. A RedisContext against a live Redis, all inside a network namespace. To reproduce what a NAT/LB eviction actually looks like I blackhole only the return path — iptables -I INPUT -p tcp --sport <redis> -j DROP — so the peer never sends a RST or a FIN, packets just stop coming back. The connection is then left completely idle, so anything detected is keepalive rather than a retransmission timeout on in-flight data. I used interval=2, probes=3 to make the budget ~8s instead of ~300s.

Keepalive on, polling ss on the client socket:

t=0.02s  ESTAB 127.0.0.1:49022 -> 127.0.0.1:3671  timer:(keepalive,1.953sec,0)
t=2.13s  ESTAB ...                                timer:(keepalive,1.859sec,1)
t=4.22s  ESTAB ...                                timer:(keepalive,1.814sec,2)
t=6.32s  ESTAB ...                                timer:(keepalive,1.768sec,3)
t=8.41s  <socket gone>

E2E RESULT: kernel gave up at t=8.41s; next command returned NULL in 2.5e-05s,
err=1 errstr='Connection timed out' errno=110 (Connection timed out)

The third field of timer:(keepalive, …, N) is the unanswered-probe count. It walks 0 → 1 → 2 → 3 and the connection dies right after the third — probes=3 honored exactly, 8.41s against a predicted 2 * (1 + 3) = 8s. Reproduced at 8.41 / 8.41 / 8.48s across runs.

Two things in that output beyond the timing:

  • errno == ETIMEDOUT (110) is precisely what DescribeRedisIoError() keys on to emit "TCP-level timeout: keepalive probes or retransmissions exhausted", so the classification path is exercised by the same run.
  • The next command fails in 25 microseconds instead of hanging. That's the user-visible win — the GCS finds out immediately rather than blocking on a peer that is already gone.

Control — identical blackhole, interval=0:

before:                          ESTAB 127.0.0.1:54578 -> 127.0.0.1:2252   (no timer)
after 15.0s of blackholed idle:  ESTAB 127.0.0.1:54578 -> 127.0.0.1:2252   (no timer)

Still ESTABLISHED, no timer armed, the stack has no idea the peer is unreachable. That's today's behavior, and why the first command after an eviction hangs.

It needs CAP_NET_ADMIN and ~25s of wall time, so I'd keep it out of the default suite behind a tag rather than run it on every CI job.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Aug 12, 2026
Comment thread src/ray/common/ray_config_def.h Resolved
@andrewsykim

Copy link
Copy Markdown
Member

cc @jhasm

@jhasm jhasm 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.

I checked the platform claims against the hiredis Ray actually pins (bazel/ray_deps_setup.bzl → commit 60e5075), since the whole design rests on what redisKeepAlive() does and doesn't set:

  • SO_KEEPALIVE unconditionally on POSIX;
  • TCP_KEEPALIVE (idle) on Apple, and nothing else — matches the docs;
  • TCP_KEEPIDLE = interval, TCP_KEEPINTVL = interval/3, TCP_KEEPCNT = 3 under __GLIBC__ — which is exactly the coupling this PR overrides, and the rationale in the config comment is a fair description of why that coupling is wrong for the GCS;
  • win32_redisKeepAlive(fd, interval * 1000) → SIO_KEEPALIVE_VALS on Windows, so "idle and probe interval, OS-controlled count" is right;
  • nothing beyond SO_KEEPALIVE elsewhere, including musl.

So the per-platform table in kuberay-gcs-ft.md and the interval * (1 + probes) arithmetic both check out. The validation bounds match the kernel caps (TCP_KEEPIDLE/TCP_KEEPINTVL at 32767, TCP_KEEPCNT at 127), there's no overflow risk in the interval * (1 + probes) formatting (32767 × 128 is nowhere near int64_t), and applying the policy in ConnectWithoutRetries before TLS/AUTH does cover every socket including the Sentinel probe and the cleanup connection. The tests assert real socket state via getsockopt rather than just exercising the code, which is the right call.

Two things I'd like to see addressed before merge, neither of them correctness bugs:

  1. The unrelated context leak fix bundled in here deserves to be visible — see the inline comment on ConnectWithoutRetries. It's a real bug fix that a reader of this PR's title and description would never know about.
  2. The failure policy for the tuning setsockopt calls: right now a kernel that accepts SO_KEEPALIVE but rejects TCP_KEEPINTVL fails the connect with a non-retryable status, which takes the GCS down at startup. Given the feature is a hardening measure, degrading to a warning once SO_KEEPALIVE succeeded seems like the safer default. Interested in your view.

And a coordination note: this PR and #65298 both rewrite the same region of doc/source/cluster/kubernetes/user-guides/kuberay-gcs-ft.md, and #65298 makes the "Ray does not yet reconnect to Redis in place" paragraph false. Worth agreeing a merge order between the two now rather than discovering the conflict at rebase time.

Nice, well-scoped change overall — the decision to configure this in exactly one place rather than at each call site is what makes it reviewable.

@jhasm jhasm 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.

Second pass. The head is unchanged since my last review (4324bf2), so I spent this round checking the open threads from other reviewers and the E2E evidence rather than restating my own comments.

The earlier reviewer threads look resolved by the current code — worth confirming so they can be closed:

  • @andrewsykim's "9 as a default seems really high ... 300s" — the default is now redis_tcp_keepalive_probes = 3, giving 30 * (1 + 3) = 120s, and the docs, the config comment and DescribeRedisTcpKeepalivePolicy all agree on that number. Reads as settled to me.
  • @zhjwpku's point about setsockopt failing above 32767 — handled: kMaxRedisTcpKeepaliveIntervalSeconds = 32767, rejected in ValidateRedisTcpKeepaliveConfig before any network work, and the boundary test you asked for is there ({-1, 32768} for the interval and {0, 128} for the probe count, all asserting IsInvalidArgument). The AppliesMaximumPolicyToSyncAndAsyncSockets test also pins the accepted maximum via getsockopt. Nice.
  • @zhjwpku's int32_t nit is still open, and it's a fair one — every consumer immediately does static_cast<int>, and the validated range fits int32_t trivially. Zero-risk change if you want to take it.

I verified the "one place covers everything" claim, since it's what the design rests on: redisConnect and redisAsyncConnect are each reached from exactly one site in redis_context.cc, both inside ConnectWithRetries → ConnectWithoutRetries, and the Sentinel and cluster-redirect paths re-enter through RedisContext::Connect, so they inherit it. RedisDelKeyPrefixSync goes through Connect too. I couldn't find a socket that escapes the policy. Also confirmed the dup(c->fd) that RedisAsyncContext's constructor performs is harmless here — dup shares the open file description, so the socket options set on the hiredis fd apply to the asio socket as well.

One thing I'd like cleared up: the E2E writeup references a function that isn't in this PR.

Your reply to @andrewsykim says:

errno == ETIMEDOUT (110) is precisely what DescribeRedisIoError() keys on to emit "TCP-level timeout: keepalive probes or retransmissions exhausted", so the classification path is exercised by the same run.

There is no DescribeRedisIoError in this diff, and grep finds none anywhere in the tree — the only such helper here is DescribeRedisTcpKeepalivePolicy, which takes an interval and a probe count and never inspects errno. The disconnect callback in this PR logs context->c.err and errstr and then appends the configured policy; it does no errno classification at all.

I'd guess the E2E run happened on a working branch that carried extra diagnostics which were later dropped — entirely reasonable, and the ss output showing the probe counter walking 0 → 1 → 2 → 3 and the socket dying at 8.41s against a predicted 8s is good evidence for the part that matters. But since that writeup is what @andrewsykim asked for and will be what a maintainer leans on when deciding this is verified, it'd be worth a short correction noting which parts of it correspond to the code under review. The keepalive timing evidence clearly does; the error-classification claim doesn't, because that code isn't here.

Related, and this is the substantive version of the question: is DescribeRedisIoError something you intended to include? Distinguishing "keepalive gave up" (ETIMEDOUT) from "peer sent RST" (ECONNRESET) in the disconnect log is genuinely useful for the operator this feature is aimed at, and right now that log line reports the configured policy without saying whether the policy is what actually fired. If it was dropped for scope reasons that's fine — worth saying so explicitly.

My round-1 comments are still open; the one I care most about is the failure policy for the tuning setsockopt calls, since as written a kernel that rejects TCP_KEEPINTVL turns a hardening feature into a GCS that won't start.

Comment thread src/ray/common/ray_config_def.h Resolved

@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 61eb994. Configure here.

@zzchun

zzchun commented Sep 11, 2026

Copy link
Copy Markdown
Contributor Author

@jhasm @andrewsykim Thanks for the detailed reviews, especially the feedback on the failure policy and the
correction to the E2E writeup. I've pushed the updates in 61eb994.

On POSIX, rejected timing options now log warnings and leave the connection usable once SO_KEEPALIVE
succeeds. Invalid configuration and keepalive enable failures remain non-retryable. Six Linux regression
cases exercise these failures through RedisContext::Connect, verifying successful sync PING and async ECHO
after rejected tuning, and no retries after an enable failure.

I also need to correct my earlier E2E reply: my claim that the run exercised DescribeRedisIoError() was
incorrect. That function is absent from this PR. The disconnect callback logs hiredis err/errstr without
classifying the cause. The blackhole experiment verifies idle-connection failure detection; additional error
classification is outside this PR's scope.

@jhasm jhasm 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.

👍 LGTM

@zzchun

zzchun commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

@andrewsykim Could you please help to review #65424 when you have a chance, than you 🙏🏻

@rueian rueian self-assigned this Sep 29, 2026
@rueian rueian added the go add ONLY when ready to merge, run all tests label Sep 30, 2026
@rueian

rueian commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

@zzchun, could you help resolve the conflicts?

Idle GCS-to-Redis connections can be silently removed by NAT, proxies,
load balancers, or managed-service gateways. Enable TCP keepalive centrally
in ConnectWithoutRetries so sync, async, Sentinel, redirect, and cleanup
connections receive the policy before TLS, AUTH, or any command.

Add two independently tunable settings:

- redis_tcp_keepalive_interval_seconds: default 30, range [0, 32767];
  0 restores the previous behavior.
- redis_tcp_keepalive_probes: default 3, range [1, 127] while enabled.

On glibc Linux, override hiredis' derived TCP_KEEPINTVL and TCP_KEEPCNT
values, giving an approximately 120-second detection window by default.
Report platform-accurate policy details elsewhere, where the OS controls
some or all probe timing.

Validate settings before DNS or TCP connection attempts and stop retrying
non-Redis configuration or socket-option errors. Warn on unexpected async
disconnects and take ownership of hiredis contexts before new failure paths.

Document the settings, platform differences, and the current lack of
in-place Redis reconnection. Cover enabled, disabled, maximum, and invalid
boundary values on real sync and async Redis sockets.

Signed-off-by: zzchun <[email protected]>
@zzchun
zzchun force-pushed the gcs-redis-tcp-keepalive branch from 61eb994 to f45c919 Compare October 6, 2026 05:24
@zzchun
zzchun requested a review from a team as a code owner October 6, 2026 05:24
@zzchun

zzchun commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

@rueian Thanks for the hands up! I have fixed conflicts, ready for another look when you have a chance.

@rueian
rueian merged commit 74f4b6b into ray-project:master Oct 6, 2026
6 checks passed
rueian pushed a commit that referenced this pull request Oct 19, 2026
## Description
We have recently observed after
#65424 (introduced keep alive tcp
connection between gcs and redis on all operating systems) was merged,
`redis_async_context_test` would fail periodically on Windows in
postmerge. Initial investigation on the failed runs showed each of the
failed test logging something similar to the following before failure:

```bash
[2026-10-13T20:48:54Z] [2026-10-13 20:48:49,026 I 4644 8916] (redis_async_context_test.exe) redis_context.cc:725: Attempting to connect to address 127.0.0.1:3768.
[2026-10-13T20:48:54Z] [2026-10-13 20:48:49,026 E 4644 8916] (redis_async_context_test.exe) redis_context.cc:735: Giving up connecting to Redis due to a non-retryable error: IOError: Failed to enable TCP keepalive on the Redis connection to 127.0.0.1:3768: Input/output error. Set RAY_redis_tcp_keepalive_interval_seconds=0 to disable TCP keepalive if this platform cannot support it.
[2026-10-13T20:48:54Z] [2026-10-13 20:48:49,026 E 4644 8916] (redis_async_context_test.exe) redis_context.cc:735: Giving up connecting to Redis due to a non-retryable error: IOError: Failed to enable TCP keepalive on the Redis connection to 127.0.0.1:3768: Input/output error. Set RAY_redis_tcp_keepalive_interval_seconds=0 to disable TCP keepalive if this platform cannot support it.
[2026-10-13T20:48:54Z] src/ray/gcs/store_client/tests/redis_async_context_test.cc(325): error: Value of: context.Connect("127.0.0.1", TEST_REDIS_SERVER_PORTS.front(), "", "").ok()
```

We have managed to replicate the issue on our CI machine, and upon
adding more detailed logging, we have observed the following.

On Windows, when we attempt to configure `keepalive` via hiredis's
`redisEnableKeepAliveWithInterval` immediately after making the async
connection, we periodically run into the IO error shown above. However,
when we broke down the individudal components of
`redisEnableKeepAliveWithInterval`, we observed that the system actually
failed due to `WSA error=10022` when we attempted to set `SO_KEEPALIVE`
on the async connection.

### What this PR introduces
Thus, this PR introduces a select to wait on the async connection in
windows. With this change, we will only write keepalive to the
connection once we are sure it is ready (per `select`'s [documentation
](https://learn.microsoft.com/en-us/windows/win32/api/Winsock2/nf-winsock2-select#remarks)).
The change has been stress tested on the `redis_async_context_test` and
we have observed the original flaky failures go away.


## Related issues

## Additional information
Passing redis test run in post merge:
https://buildkite.com/ray-project/postmerge/builds/20371#01a14b8e-d72f-4de4-8426-35d38340f0bc

---------

Signed-off-by: davik <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core docs An issue or change related to documentation go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants