Repository navigation
[core] Enable TCP keepalive on GCS<->Redis connections - #65424
Conversation
There was a problem hiding this comment.
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). |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
@zzchun overall this makes sense, but can you share how you tested it end to end to verify the expected behavior? |
|
@andrewsykim Good question — worth separating two levels here. The tests in the PR verify configuration: Setup. A Keepalive on, polling The third field of Two things in that output beyond the timing:
Control — identical blackhole, 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 |
f1974cf to
4324bf2
Compare
|
cc @jhasm |
There was a problem hiding this comment.
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_KEEPALIVEunconditionally on POSIX;TCP_KEEPALIVE(idle) on Apple, and nothing else — matches the docs;TCP_KEEPIDLE = interval,TCP_KEEPINTVL = interval/3,TCP_KEEPCNT = 3under__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_VALSon Windows, so "idle and probe interval, OS-controlled count" is right;- nothing beyond
SO_KEEPALIVEelsewhere, 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:
- 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. - The failure policy for the tuning
setsockoptcalls: right now a kernel that acceptsSO_KEEPALIVEbut rejectsTCP_KEEPINTVLfails 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 onceSO_KEEPALIVEsucceeded 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
left a comment
There was a problem hiding this comment.
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, giving30 * (1 + 3) = 120s, and the docs, the config comment andDescribeRedisTcpKeepalivePolicyall agree on that number. Reads as settled to me. - @zhjwpku's point about
setsockoptfailing above 32767 — handled:kMaxRedisTcpKeepaliveIntervalSeconds = 32767, rejected inValidateRedisTcpKeepaliveConfigbefore 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 assertingIsInvalidArgument). TheAppliesMaximumPolicyToSyncAndAsyncSocketstest also pins the accepted maximum viagetsockopt. Nice. - @zhjwpku's
int32_tnit is still open, and it's a fair one — every consumer immediately doesstatic_cast<int>, and the validated range fitsint32_ttrivially. 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 whatDescribeRedisIoError()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.
4324bf2 to
61eb994
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 61eb994. Configure here.
|
@jhasm @andrewsykim Thanks for the detailed reviews, especially the feedback on the failure policy and the On POSIX, rejected timing options now log warnings and leave the connection usable once SO_KEEPALIVE I also need to correct my earlier E2E reply: my claim that the run exercised DescribeRedisIoError() was |
|
@andrewsykim Could you please help to review #65424 when you have a chance, than you 🙏🏻 |
|
@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]>
Signed-off-by: zzchun <[email protected]>
Signed-off-by: zzchun <[email protected]>
Signed-off-by: zzchun <[email protected]>
61eb994 to
f45c919
Compare
|
@rueian Thanks for the hands up! I have fixed conflicts, ready for another look when you have a chance. |
## 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]>

Description
Idle GCS-to-external-Redis connections can become unreachable without a FIN or
RST. This PR enables TCP keepalive centrally in
ConnectWithoutRetriesbeforeTLS, 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.
redis_tcp_keepalive_interval_seconds300..32767;0disables keepaliveredis_tcp_keepalive_probes31..127when enabledLinux 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_KEEPALIVEfails the connection immediately; rejected timing options warnand 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/errstrand labelRayConfigvalues 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 returnan allocated context with
errset on connection failure. Acquiringunique_ptrownership 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
6703877370on 2026-10-06:git range-diffconfirmed the four commits retain their patches, with onlythe 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:
bazel test //src/ray/gcs/store_client/tests:all --test_output=errors --jobs=2 --nocache_test_results: started, then stopped during the freshdependency 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).