Repository navigation
Fix Sentinel 100% CPU busy-loop on async socket error (EPOLLERR) - #15107
Conversation
🤖 Augment PR SummarySummary: Fixes a Redis Sentinel 100% CPU busy-loop when 🤖 Was this summary useful? React with 👍 or 👎 |
| * the dead connection down. */ | ||
| int so_error = 0; | ||
| socklen_t errlen = sizeof(so_error); | ||
| if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &so_error, &errlen) == 0 && |
There was a problem hiding this comment.
deps/hiredis/net.c:77 — If getsockopt(SO_ERROR) fails here, this path returns 0 and may leave the pending async error unconsumed, potentially allowing the same EPOLLERR busy-loop to persist. Consider whether a getsockopt failure should be surfaced as an I/O error instead of "try again later".
Severity: medium
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
|
See also redis/hiredis#1375 |
oranagra
left a comment
There was a problem hiding this comment.
LGTM. thank you for pinning it down and writing a detailed description.
sorry it took so long, i must have missed the notification thinking it's yet another comment in #9956
@swills i see your PR to hiredis is completely different and i understand it serves the same purpose? @michael-grunder to confirm.
ideally, i'd rather pull a new version from hiredis repo, but maybe the fix in this PR is slightly safer (smaller) and more suitable for backport to older versions?
also, considering this PR that pinpointed the problem was first, it'll be nice to merge it first just to give credit.
@vitahlin please let me know if you see any problem with this approach, or the fix in redis/hiredis#1375 (which i didn't personally bother to review)..
|
@sundb FYI |
They overlap in symptom, but I don’t think either supersedes the other. #15107 handles an established connection where redis/hiredis#1375 handles a different Linux condition during connection establishment: Conversely, redis/hiredis#1375 does not replace 15107’s handling of a hard |
I also tested #15107 directly. I built Redis 8.6.6 with its complete two-commit diff and deployed it as a multi-architecture canary in A trace of the affected process showed the repeated sequence So these appear to be two distinct, rare bugs producing the same event-loop symptom. #15107 handles a hard |
|
@swills thank you (i didn't bother to read your PR 😄). so you're saying that neither fix on it's own won't (completely) solve the problem, but merging both will? |
I'm happy with whatever approach is safest or most convenient for backporting. Thanks for getting this looked at |
Based on my experience testing both, yes, that's correct. |
|
@vitahlin please make a PR to https://github.com/redis/hiredis/ too. either way, both fixes need to be there. |
Done, I just opened a PR there : redis/hiredis#1376 |
## Summary When `recv()` returns `EAGAIN` on a non-blocking socket, a pending `SO_ERROR` (`sk_err`) is left unconsumed. `EPOLLERR` is level-triggered, so the async event loop can spin at 100% CPU while treating the connection as healthy. `valkeyNetRead()` now checks `getsockopt(SO_ERROR)` on that path and returns `VALKEY_ERR_IO` if a socket error is pending, so callers disconnect and reconnect. `EINTR` is unchanged (still retry). The successful `recv()` path is unchanged. This is the same fix as redis/redis#15107 and redis/hiredis#1376. It complements the already-merged connect-time `MSG_ERRQUEUE` drain ("Drain socket error queue on connect") and does not replace it. Related: valkey-io/valkey#4766 ## Why this is a separate fix `tcp_poll()` reports `EPOLLERR` if either `sk_err != 0` or `sk_error_queue` is non-empty. | Condition | How to clear | Where we handle it | |---|---|---| | ICMP / stale error queue during connect, `SO_ERROR == 0` | `recvmsg(MSG_ERRQUEUE)` | Already in `valkeyCheckConnectDone` | | Established connection, `sk_err` set, `recv` still `EAGAIN` | `getsockopt(SO_ERROR)` | This PR | Neither check supersedes the other. ## Test plan - [x] `make` with `-Werror` - [x] Existing `client_test` (including connect error-queue cases) still pass - [ ] Review: no behavior change when `SO_ERROR == 0` (genuine `EAGAIN`) Signed-off-by: quanyeyang <[email protected]>
|
Is it going to be backported to 8.10? |
yes, it'll be backported to 8.10 |
Description
Fix 100% CPU busy-loop in Redis Sentinel caused by unconsumed SO_ERROR on non-blocking sockets.
When a monitored Redis instance becomes unreachable (e.g. after a Kubernetes pod IP rotation), the kernel stores an asynchronous error in the socket's SO_ERROR field and raises EPOLLERR. Because EPOLLERR is level-triggered and ae_epoll.c maps it to AE_READABLE, hiredis's read callback is invoked repeatedly. However, recv() does not consume SO_ERROR — it only drains the receive queue — so it returns EAGAIN. The old code treated EAGAIN as "try again later" and returned 0 without clearing the error, causing epoll_wait to fire again immediately in an infinite loop.
The fix adds a getsockopt(SO_ERROR) check in redisNetRead() when recv() returns EWOULDBLOCK on a non-blocking socket. If a pending socket error is found, it is consumed (which clears EPOLLERR) and reported to the caller as REDIS_ERR_IO, allowing the async layer to tear down the dead connection. Sentinel then reconnects normally.
The check is zero-cost on healthy connections: the EWOULDBLOCK branch is only reached when epoll says "readable" but recv finds nothing, which does not happen during normal data flow.
Related issue #9956
Root Cause Analysis
The problem
Redis Sentinel enters a 100% CPU busy-loop after the monitored Redis instance becomes network-unreachable. This is most commonly triggered by Kubernetes pod rolling updates, but can occur in any environment where an established TCP connection's destination suddenly disappears.
The four-layer chain
The bug requires four layers to interact — remove any one and the loop breaks:
Layer 1 — Kernel: async error on the socket
When the destination IP becomes unreachable the kernel sets
sk_err(the "hard error" field) on the TCP socket. This happens through several paths:Route disappears — The pod's IP is no longer in any routing table.
ip_route_output_flow()fails withEHOSTUNREACHduringtcp_transmit_skb(), which directly setssk->sk_err.Network namespace destroyed — Kubernetes tears down the pod's network namespace; the veth pair is removed, ARP entries expire, and subsequent sends fail at the routing layer.
ICMP unreachable with
IP_RECVERR—tcp_v4_err()in the Linux kernel ([net/ipv4/tcp_ipv4.c]) handles incoming ICMP errors for established connections:When
IP_RECVERRis not set (the default for Redis), ICMP errors on ESTABLISHED connections only setsk_err_soft— which does not triggerEPOLLERR. This is why localiptables REJECTcannot reproduce the bug. In the Kubernetes pod-deletion path, the error comes from the send path (routing failure), not from an incoming ICMP, so it always setssk_errregardless ofIP_RECVERR.References:
tcp_v4_err(): https://github.com/torvalds/linux/blob/v6.13-rc6/net/ipv4/tcp_ipv4.ctcp_poll(): https://github.com/torvalds/linux/blob/v6.4/net/ipv4/tcp.cLayer 2 — epoll: EPOLLERR is level-triggered
tcp_poll()returnsEPOLLERRwheneversk->sk_err != 0:EPOLLERRis always level-triggered even in edge-triggered mode (perepoll(7)man page). As long asSO_ERRORis not consumed viagetsockopt(), everyepoll_wait()call returns immediately.Layer 3 — Redis event loop: EPOLLERR mapped to readable
src/ae_epoll.c:This dispatches hiredis's read handler (
redisAsyncHandleRead).Layer 4 — hiredis: EAGAIN swallowed without checking SO_ERROR
deps/hiredis/net.c—redisNetRead()(before fix):recv()only drains the receive queue; it does not inspectSO_ERROR. An empty receive queue returnsEAGAINregardless of any pending socket error. By returning0, hiredis tells the async layer "nothing happened, connection is fine" — no disconnect, no reconnect.Why Sentinel's reconnect logic does not help
Sentinel has reconnection logic (
sentinelReconnectInstance()), but it only triggers when hiredis reports an error via its disconnect callback. SinceredisNetReadreturns0(not-1),redisAsyncReadseesREDIS_OKand never calls__redisAsyncDisconnect. The reconnect precondition is bypassed.Why this is most common in Kubernetes
Kubernetes pod rolling updates create the exact conditions for this bug ([kubernetes#86280], [kubernetes#104098]):
send()from Sentinel hits a routing failure →sk_err = EHOSTUNREACH→EPOLLERR→ busy-loop.Sentinel maintains two connections per master:
cc(commands): periodic PINGs causesend()to consumeSO_ERROR→ normal disconnect → not stuck.pc(pubsub): read-only after SUBSCRIBE, no writes →SO_ERRORis never consumed → busy-loop persists.References:
How the fix works
getsockopt(SOL_SOCKET, SO_ERROR)atomically reads and clearssk_err. Once cleared,tcp_poll()no longer returnsEPOLLERR— the trigger for the loop is removed.Returns
-1withREDIS_ERR_IO— the async layer calls__redisAsyncDisconnect(), which fires Sentinel's disconnect callback →link->disconnected = 1→sentinelReconnectInstance()establishes a fresh connection.When
SO_ERROR == 0(genuine spurious wakeup), the function falls through to the existingreturn 0— behavior unchanged.Why the check is only for non-blocking + EWOULDBLOCK
EINTR(signal interrupted) is not a socket error.EWOULDBLOCKcomes fromSO_RCVTIMEOtimeout, not from epoll wakeup.EWOULDBLOCKcombination is the only path that the Sentinel/event-loop scenario can reach.Behavior before and after
Note
Medium Risk
Touches low-level socket read error handling; incorrect handling could cause unexpected disconnects or missed retries on non-blocking connections, but the change is narrowly scoped to the
EWOULDBLOCKpath.Overview
Avoids a potential 100% CPU busy-loop when a non-blocking socket has a pending asynchronous error but
recv()returnsEWOULDBLOCK.redisNetRead()now checksgetsockopt(SO_ERROR)on that path and, if a pending error exists, returns-1withREDIS_ERR_IOso callers can tear down the dead connection;EINTRhandling is split out but keeps the prior retry behavior.Reviewed by Cursor Bugbot for commit e0df683. Bugbot is set up for automated code reviews on this repo. Configure here.