Skip to content

Fix async socket error busy-loop in redisNetRead - #1376

Open
vitahlin wants to merge 1 commit into
redis:masterfrom
vitahlin:fix-socket-error
Open

vitahlin wants to merge 1 commit into
redis:masterfrom
vitahlin:fix-socket-error

Conversation

@vitahlin

@vitahlin vitahlin commented Sep 21, 2026 •

Copy link
Copy Markdown

Issue

A non-blocking socket can return EWOULDBLOCK while an asynchronous error remains pending in SO_ERROR. The event loop continues reporting EPOLLERR, but hiredis returns 0 without consuming or reporting the error, causing an async busy-loop.

Related issue in redis repo: redis/redis#9956
More detail can check the origin PR in redis repo: redis/redis#15107

Change

Check SO_ERROR when recv() returns EWOULDBLOCK on a non-blocking socket. Return REDIS_ERR_IO when getsockopt() fails or reports a socket error, while preserving retry behavior when no socket error is pending. Keep EINTR handling unchanged.


Note

Medium Risk
Changes core non-blocking read error handling in hiredis; behavior is narrower and fixes a production CPU spin, but mis-handling SO_ERROR could affect connection teardown on edge cases.

Overview
Fixes a 100% CPU busy-loop in non-blocking event-driven clients (e.g. Redis Sentinel) when a peer becomes unreachable and the kernel reports an async socket error via EPOLLERR while recv() only returns EWOULDBLOCK/EAGAIN.

In redisNetRead, when recv fails with EWOULDBLOCK on a non-blocking connection, the code now reads SO_ERROR with getsockopt before returning “try again later.” If a pending socket error exists, it sets REDIS_ERR_IO and returns -1 so the connection is torn down instead of spinning the event loop. EINTR is handled in a separate branch, unchanged in behavior (still retry with return 0).

Reviewed by Cursor Bugbot for commit d6710d4. Bugbot is set up for automated code reviews on this repo. Configure here.

@vitahlin vitahlin changed the title Fix Sentinel 100% CPU busy-loop on async socket error (EPOLLERR) Fix async socket error busy-loop in redisNetRead Sep 21, 2026
@michael-grunder

Copy link
Copy Markdown
Collaborator

Do we know when linux will append to the extended error queue even if you don't opt-in? It seemed like the kernel bug was only during connect but perhaps I misread that.

@vitahlin

vitahlin commented Sep 23, 2026 •

Copy link
Copy Markdown
Author

Do we know when linux will append to the extended error queue even if you don't opt-in? It seemed like the kernel bug was only during connect but perhaps I misread that.

sorry fro later reply , the origin pr opend for so long i need some time to refresh my memory

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

Copy link
Copy Markdown
Author

Sorry for the delayed response. I have rethought this problem, I would like to share my updated thoughts and concerns regarding this PR.

@sundb The original Redis PR https://github.com/redis/redis/pull/15107 has been merged. Please take a look at this as well.

What the problem looks like

The flow chart below is how I understand the busy-loop:

sequenceDiagram
    participant K as Linux kernel / socket
    participant E as epoll / ae event loop
    participant H as hiredis
    participant S as Sentinel

    Note over K,S: Original problem before the fix

    loop EPOLLERR condition remains and the fd stays registered
        E->>K: 1. Call epoll_wait()
        K->>E: 2. Return the fd with EPOLLERR
        E->>E: 3. Map EPOLLERR to AE_READABLE and AE_WRITABLE
        E->>H: 4. Invoke the registered read callback
        H->>K: 5. Call recv(fd, buf, len, 0)
        K->>H: 6. Return -1 with EAGAIN or EWOULDBLOCK
        H->>H: 7. redisNetRead returns 0 and redisBufferRead returns REDIS_OK
        H->>E: 8. Finish the current read callback
        E->>S: 9. No disconnect callback is triggered
        Note over E,H: 10. The fd remains registered, so the next epoll_wait immediately returns EPOLLERR again
    end

    Note over E,S: Result: the read callback repeats and the event loop enters a CPU busy-loop
Loading

For this loop to happen, all of these need to be true at the same time:

  1. The error condition in kernel is still there after the callback returns.
  2. The fd is still registered in epoll.
  3. The normal read does not consume or report the error, it just returns EAGAIN / EWOULDBLOCK.
  4. hiredis treats it as "try again later", so no async disconnect happens.

Step 3 is in aeApiPoll(), see: https://github.com/redis/redis/blob/20bb2cfc54aa08c8fdfb8c4c0a8b8258e811711e/src/ae_epoll.c#L105-L106:

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

Step 6 and step 7 are in redisNetRead(), see

hiredis/net.c

Lines 86 to 89 in 058ebcd

if ((errno == EWOULDBLOCK && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) {
/* Try again later */
return 0;
} else if(errno == ETIMEDOUT && (c->flags & REDIS_BLOCK)) {

So in this model, what we see is: epoll_wait() keeps returning EPOLLERR for the same fd immediately, and the hiredis read path keeps getting EWOULDBLOCK. Nobody clears the error in kernel, and nobody closes or unregisters the fd.

Root cause analysis

When does epoll return EPOLLERR

In Linux v6.4, the TCP poll code in [net/ipv4/tcp.c](https://github.com/torvalds/linux/blob/v6.4/net/ipv4/tcp.c#L593-L598) has:

smp_rmb();
if (READ_ONCE(sk->sk_err) ||
    !skb_queue_empty_lockless(&sk->sk_error_queue))
    mask |= EPOLLERR;

return mask;

So for a normal IPv4 TCP socket, there are two states that set EPOLLERR:

  1. sk_error_queue is not empty. I think PR Drain Linux socket error queue after nonblocking TCP connect #1375 already fixed this one so I will not talk about it again here.
  2. sk_err != 0. In this PR I tried to read SO_ERROR after recv() returns EWOULDBLOCK. My assumption at that time was: on an established connection, sk_err may keep triggering EPOLLERR, but the normal read never shows it to hiredis.

Below I only look at the second case.

What sk_err means

sk_err keeps the hard error that the socket has not delivered to the application yet. The value is a positive errno, like ECONNRESET or ETIMEDOUT. In sock.h it is described as last error. The other one, sk_err_soft, is for soft errors which do not make the connection fail right away.

sk_err is a one-shot state. Kernel reads it with sock_error(), and the core of it is xchg(&sk->sk_err, 0), so the caller gets the error and clears sk_err at the same time.

After reading more of the Linux TCP receive path, I found one sentence in my earlier analysis of redis/redis#15107 is probably not correct:

However, recv() does not consume SO_ERROR — it only drains the receive queue — so it returns EAGAIN.

At least for the Linux v6.4 normal TCP receive path I checked, this seems not true. When there is no data to return, tcp_recvmsg_locked() checks sk_err before it returns EAGAIN, see [net/ipv4/tcp.c](https://github.com/torvalds/linux/blob/v6.4/net/ipv4/tcp.c#L2528-L2531). According to this code, if sk_err != 0, recv() should return -1 and give the hard error to the application as errno, not EAGAIN.

And hiredis redisNetRead() handles this errno as an I/O error, it just calls __redisSetError(c, REDIS_ERR_IO, strerror(errno));, see [hiredis/net.c](https://github.com/redis/hiredis/blob/058ebcdf36c5b05b759c613564fb958ec363c90f/net.c#L83-L103):

If the receive queue already has data, recv() can return the data first and leave the hard error for a later read. So I can't say it loops at most one more time, and I can't give a fixed number either. But on the normal Linux TCP receive path, once the data is used up, the next recv() will get and clear sk_err. Then hiredis returns REDIS_ERR_IO, and the async layer (redisAsyncRead() → __redisAsyncDisconnect() in [hiredis/async.c](https://github.com/redis/hiredis/blob/058ebcdf36c5b05b759c613564fb958ec363c90f/async.c)) disconnects and unregisters the old fd.

Based on my current understanding of this normal Linux TCP path, sk_err != 0 alone seems not able to keep the busy-loop condition ("EPOLLERR every round, but recv() always returns EAGAIN") for a long time. But this only covers the kernel version and the normal TCP receive path above. I'm not sure if other kernel versions, protocol implementations, OSes or special receive paths behave differently. It would be great if someone familiar with these paths can help to confirm.

My concern about the current PR

Current PR calls getsockopt(SO_ERROR) after a non-blocking recv() returns EWOULDBLOCK. In Linux v6.4 the implementation is in [net/core/sock.c](https://github.com/torvalds/linux/blob/v6.4/net/core/sock.c#L1656-L1660):

case SO_ERROR:
    v.val = -sock_error(sk);
    if (v.val == 0)
        v.val = xchg(&sk->sk_err_soft, 0);
    break;

So SO_ERROR first gets and clears the hard error sk_err. If there is no hard error, it also gets and clears sk_err_soft. This is what worries me: #1376 treats any non-zero SO_ERROR as a fatal I/O error, so it may turn a soft error, which should not kill the connection, into a disconnect.

But I also understand this risk needs some specific conditions. sk_err_soft itself does not make tcp_poll() set EPOLLERR. Only when the fd enters the callback because of some other readable, writable or error event, and the normal recv() returns EWOULDBLOCK, and sk_err_soft is still there at that moment, then #1376 will read the soft error and disconnect. I don't have a reproduction or test showing Sentinel can really reach this path, so this is more a concern from kernel semantics. Please correct me if I'm wrong.

Current understanding

Based on the Linux v6.4 normal TCP path I checked, I now think my sk_err busy-loop explanation in #1376 probably doesn't hold. When there is no data to return, recv() itself gets and clears sk_err and gives the real errno to hiredis, then hiredis goes into the error and disconnect flow.

At the same time, #1376 reads SO_ERROR after every non-blocking EWOULDBLOCK, so it may also pick up sk_err_soft. I'm afraid the current implementation makes the error handling scope bigger, and some non-fatal async errors will become disconnects.

So with the evidence now, I tend to close my own #1376, to avoid a change that doesn't have enough basis and may enlarge the error handling scope. Especially getsockopt(SO_ERROR) looks a bit dangerous here, because it can read the soft error directly.

That said, I'm not very familiar with the Linux network stack, other kernel versions, or all the platforms hiredis supports, so I may have missed some important paths.
If my understanding is wrong, or there are kernel paths, platform differences or real reproductions I didn't consider, I'd really like to hear from the maintainers and anyone who knows this code well.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants