fix(redis): add opt-in TCP socket keepalive on all client connections (#23571)

Introduces REDIS_SOCKET_KEEPALIVE and wires socket_keepalive=True
through to every Redis client created by get_redis_connection
(plain, cluster and sentinel paths, sync and async). When enabled,
the kernel sends TCP keepalive probes on idle connections so
half-closed sockets (e.g. after a silent firewall/LB reset or a NIC
flap) are detected before the next command lands on them and the
request never sees a "Connection reset by peer" error.

Defaults to off so existing deployments see no behavioural change.
Operators who want the protection set REDIS_SOCKET_KEEPALIVE=true
in their environment.

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Classic298
2026-04-11 16:09:12 -06:00
committed by GitHub
co-authored by Claude
parent aacf95cf76
commit db7f122cb0
2 changed files with 20 additions and 0 deletions
+9
View File
@@ -426,6 +426,15 @@ try:
except ValueError:
REDIS_SOCKET_CONNECT_TIMEOUT = None
# Whether to enable TCP SO_KEEPALIVE on Redis client sockets. Opt-in:
# defaults to off so behavior is unchanged for existing deployments. When
# enabled, the kernel sends TCP keepalive probes on idle connections so
# half-closed sockets (e.g. after a silent firewall/LB reset or a NIC
# flap) are detected before the next command lands on them.
REDIS_SOCKET_KEEPALIVE = (
os.environ.get('REDIS_SOCKET_KEEPALIVE', 'False').lower() == 'true'
)
REDIS_RECONNECT_DELAY = os.environ.get('REDIS_RECONNECT_DELAY', '')
if REDIS_RECONNECT_DELAY == '':