Skip to content

Fix Sentinel 100% CPU busy-loop on async socket error (EPOLLERR) - #15107

Merged
sundb merged 2 commits into
redis:unstablefrom
vitahlin:fix-hiredis
Sep 23, 2026
Merged

sundb merged 2 commits into
redis:unstablefrom
vitahlin:fix-hiredis

Conversation

@vitahlin

@vitahlin vitahlin commented Apr 25, 2026 •

Copy link
Copy Markdown
Contributor

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:

 Kernel: sets sk_err on the TCP socket (hard error)
   ↓
 epoll:  EPOLLERR is level-triggered, fires every epoll_wait
   ↓
 ae:     ae_epoll.c maps EPOLLERR → AE_READABLE|AE_WRITABLE
   ↓
 hiredis: recv() returns EAGAIN, redisNetRead returns 0 (BUG)
   ↓
 Loop:   SO_ERROR never consumed → EPOLLERR persists → repeat

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 with EHOSTUNREACH during tcp_transmit_skb(), which directly sets sk->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:

    /* rfc1122 4.2.3.9 — treat as hard error only if IP_RECVERR */
    if (!sock_owned_by_user(sk) && inet_test_bit(RECVERR, sk)) {
        WRITE_ONCE(sk->sk_err, err);       /* hard error */
    } else {
        WRITE_ONCE(sk->sk_err_soft, err);  /* soft error */
    }

    When IP_RECVERR is not set (the default for Redis), ICMP errors on ESTABLISHED connections only set sk_err_soft — which does not trigger EPOLLERR. This is why local iptables REJECT cannot 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 sets sk_err regardless of IP_RECVERR.

References:

Layer 2 — epoll: EPOLLERR is level-triggered

tcp_poll() returns EPOLLERR whenever sk->sk_err != 0:

/* net/ipv4/tcp.c — tcp_poll() */
if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
    mask |= EPOLLERR;

EPOLLERR is always level-triggered even in edge-triggered mode (per epoll(7) man page). As long as SO_ERROR is not consumed via getsockopt(), every epoll_wait() call returns immediately.

Layer 3 — Redis event loop: EPOLLERR mapped to readable

src/ae_epoll.c:

if (e->events & EPOLLERR) mask |= AE_WRITABLE|AE_READABLE;

This dispatches hiredis's read handler (redisAsyncHandleRead).

Layer 4 — hiredis: EAGAIN swallowed without checking SO_ERROR

deps/hiredis/net.c — redisNetRead() (before fix):

ssize_t nread = recv(c->fd, buf, bufcap, 0);
if (nread == -1) {
    if ((errno == EWOULDBLOCK && !(c->flags & REDIS_BLOCK)) || ...) {
        return 0;  // ← BUG: "try later", SO_ERROR not consumed
    }
}

recv() only drains the receive queue; it does not inspect SO_ERROR. An empty receive queue returns EAGAIN regardless of any pending socket error. By returning 0, 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. Since redisNetRead returns 0 (not -1), redisAsyncRead sees REDIS_OK and 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]):

  1. The old pod is marked Terminating; kubelet sends SIGTERM.
  2. kube-proxy removes the endpoint from iptables/IPVS rules.
  3. After the grace period (default 30s), the pod is killed and its network namespace is destroyed.
  4. kube-proxy does not flush TCP conntrack entries for the deleted pod ([kubernetes#104098]) — by design, to allow graceful shutdown.
  5. Sentinel still holds TCP connections to the old pod IP.
  6. The next send() from Sentinel hits a routing failure → sk_err = EHOSTUNREACH → EPOLLERR → busy-loop.

Sentinel maintains two connections per master:

  • cc (commands): periodic PINGs cause send() to consume SO_ERROR → normal disconnect → not stuck.
  • pc (pubsub): read-only after SUBSCRIBE, no writes → SO_ERROR is never consumed → busy-loop persists.

References:

How the fix works

  1. getsockopt(SOL_SOCKET, SO_ERROR) atomically reads and clears sk_err. Once cleared, tcp_poll() no longer returns EPOLLERR — the trigger for the loop is removed.

  2. Returns -1 with REDIS_ERR_IO — the async layer calls __redisAsyncDisconnect(), which fires Sentinel's disconnect callback → link->disconnected = 1 → sentinelReconnectInstance() establishes a fresh connection.

  3. When SO_ERROR == 0 (genuine spurious wakeup), the function falls through to the existing return 0 — behavior unchanged.

Why the check is only for non-blocking + EWOULDBLOCK

  • EINTR (signal interrupted) is not a socket error.
  • Blocking mode EWOULDBLOCK comes from SO_RCVTIMEO timeout, not from epoll wakeup.
  • The non-blocking + EWOULDBLOCK combination is the only path that the Sentinel/event-loop scenario can reach.

Behavior before and after

Scenario Before After
Normal data read recv returns data → process Unchanged
Peer graceful close (FIN) recv returns 0 → EOF → disconnect Unchanged
Peer RST recv returns ECONNRESET → disconnect Unchanged
Async error (ICMP/route) recv EAGAIN → busy-loop 100% CPU getsockopt → disconnect → reconnect
Spurious EAGAIN (rare) return 0, retry later getsockopt finds SO_ERROR=0 → return 0

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 EWOULDBLOCK path.

Overview
Avoids a potential 100% CPU busy-loop when a non-blocking socket has a pending asynchronous error but recv() returns EWOULDBLOCK.

redisNetRead() now checks getsockopt(SO_ERROR) on that path and, if a pending error exists, returns -1 with REDIS_ERR_IO so callers can tear down the dead connection; EINTR handling 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.

@augmentcode

augmentcode Bot commented Apr 25, 2026

Copy link
Copy Markdown
🤖 Augment PR Summary

Summary: Fixes a Redis Sentinel 100% CPU busy-loop when epoll repeatedly reports EPOLLERR due to an unconsumed async socket error.
Change: redisNetRead() now peeks/consumes SO_ERROR on non-blocking EWOULDBLOCK and reports it as an I/O error so the async layer can disconnect and reconnect.

🤖 Was this summary useful? React with 👍 or 👎

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

Review completed. 1 suggestion posted.

Fix All in Augment

Comment augment review to trigger a new review at any time.

Comment thread deps/hiredis/net.c Outdated
* 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 &&

@augmentcode augmentcode Bot Apr 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.

@sundb
sundb requested a review from oranagra April 25, 2026 09:55
@sundb sundb added this to Redis 8.8 Apr 25, 2026
@sundb sundb added this to Redis 8.10 May 21, 2026
@sundb sundb removed this from Redis 8.8 May 21, 2026
@sundb sundb moved this from Todo to In Review in Redis 8.10 Jul 17, 2026
@sundb sundb removed this from Redis 8.10 Aug 4, 2026
@sundb sundb added this to Redis 8.12 Aug 4, 2026
@swills

swills commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

See also redis/hiredis#1375

@oranagra oranagra left a comment

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.

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)..

@oranagra oranagra linked an issue Sep 21, 2026 that may be closed by this pull request
@oranagra

Copy link
Copy Markdown
Member

@sundb FYI

@swills

swills commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

@swills i see your PR to hiredis is completely different and i understand it serves the same purpose? @michael-grunder to confirm.

They overlap in symptom, but I don’t think either supersedes the other. #15107 handles an established connection where EPOLLERR corresponds to a pending SO_ERROR; surfacing that error and reconnecting is appropriate.

redis/hiredis#1375 handles a different Linux condition during connection establishment: sk_error_queue can remain nonempty while SO_ERROR is already zero. In that case the getsockopt(SO_ERROR) check in #15107 sees zero and returns “try again,” leaving EPOLLERR asserted. redis/hiredis#1375 instead drains MSG_ERRQUEUE while the connect is pending and after successful completion, including the blocking-connect wait path, while preserving a usable successful connection.

Conversely, redis/hiredis#1375 does not replace 15107’s handling of a hard SO_ERROR that appears later on an established socket. So merging #15107 first for the direct fix/backport and later updating the vendored hiredis once 1375 lands seems reasonable to me.

@swills

swills commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

@swills i see your PR to hiredis is completely different and i understand it serves the same purpose? @michael-grunder to confirm.

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 scanner-dev. The Sentinel 100% CPU symptom eventually recurred.

A trace of the affected process showed the repeated sequence EPOLLERR → recv(EAGAIN) → getsockopt(SO_ERROR) == 0. That does not mean #15107 is incorrect; its check was operating as intended, but this particular occurrence had no pending SO_ERROR to surface. The persistent readiness came from a separate nonempty socket error queue, which led to hiredis#1375.

So these appear to be two distinct, rare bugs producing the same event-loop symptom. #15107 handles a hard SO_ERROR on an established connection, while hiredis#1375 handles stale MSG_ERRQUEUE state during connection establishment. Neither supersedes the other, and both fixes are useful.

@oranagra

Copy link
Copy Markdown
Member

@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?

@vitahlin

Copy link
Copy Markdown
Contributor Author

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)..

I'm happy with whatever approach is safest or most convenient for backporting. Thanks for getting this looked at

@swills

swills commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

@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?

Based on my experience testing both, yes, that's correct.

@oranagra

Copy link
Copy Markdown
Member

@vitahlin please make a PR to https://github.com/redis/hiredis/ too. either way, both fixes need to be there.
then we need to figure out which way to take them here (PRs, cherry-pick, or pull a new hiredis version).

@vitahlin

Copy link
Copy Markdown
Contributor Author

@vitahlin please make a PR to https://github.com/redis/hiredis/ too. either way, both fixes need to be there. then we need to figure out which way to take them here (PRs, cherry-pick, or pull a new hiredis version).

Done, I just opened a PR there : redis/hiredis#1376

@sundb
sundb merged commit f12f2a1 into redis:unstable Sep 23, 2026
16 of 17 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Redis 8.12 Sep 23, 2026
bjosv pushed a commit to valkey-io/libvalkey that referenced this pull request Sep 25, 2026
## 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]>
@vitahlin
vitahlin deleted the fix-hiredis branch September 26, 2026 18:20
@kamilzzz

Copy link
Copy Markdown

Is it going to be backported to 8.10?

@sundb sundb added the release-notes indication that this issue needs to be mentioned in the release notes label Oct 21, 2026
@sundb

sundb commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Is it going to be backported to 8.10?

yes, it'll be backported to 8.10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-notes indication that this issue needs to be mentioned in the release notes

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[BUG] redis sentinel 100% cpu usage

5 participants