fix: retry Valkey once on a dropped connection
The client passed the sync redis.retry.Retry to async connections, so no retry could ever run. Use redis.asyncio.retry.Retry with one immediate retry on ConnectionError only: after a Valkey restart the stale pooled connection is reopened instead of switching the cache off for 5 s. Timeouts are not retried, and asyncio.timeout bounds each cache command (pool wait, connect, retry, reply) by [cache] timeout_seconds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -105,7 +105,8 @@ class Cache(BaseModel):
|
||||
port: int = Field(default=6379, ge=1, le=65535)
|
||||
password: SecretStr = SecretStr("")
|
||||
|
||||
# секунды на соединение и ответ; дольше — запрос идёт в PostgreSQL
|
||||
# секунды на всю команду кэша: ожидание пула, соединение, повтор и
|
||||
# ответ; дольше — запрос идёт в PostgreSQL
|
||||
timeout_seconds: float = Field(default=0.2, gt=0)
|
||||
# секунды, на которые кэш пропускается после отказа Valkey
|
||||
retry_after_seconds: float = Field(default=5, gt=0)
|
||||
|
||||
Vendored
+25
-11
@@ -1,18 +1,24 @@
|
||||
"""Клиент Valkey без повторов и с обходом при отказе.
|
||||
"""Клиент Valkey со сроком на команду и обходом при отказе.
|
||||
|
||||
redis-py по умолчанию повторяет команду с backoff: замороженный Valkey
|
||||
задерживал запрос на 6 с вместо таймаута клиента (design change
|
||||
`membership-cache`, Context). Здесь повторов нет, а после отказа кэш
|
||||
пропускается на `[cache] retry_after_seconds`: запросы идут сразу в
|
||||
PostgreSQL, не дожидаясь таймаута каждый раз.
|
||||
`membership-cache`, Context). Здесь повтор один и только на обрыв
|
||||
соединения (`ConnectionError`): старое соединение пула после рестарта
|
||||
Valkey переоткрывается сразу, а таймаут не повторяется. Вся команда —
|
||||
ожидание пула, соединение, повтор и ответ — ограничена
|
||||
`[cache] timeout_seconds`. После отказа кэш пропускается на
|
||||
`[cache] retry_after_seconds`: запросы идут сразу в PostgreSQL, не
|
||||
дожидаясь таймаута каждый раз.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from redis.asyncio import BlockingConnectionPool, Redis
|
||||
from redis.asyncio.retry import Retry
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import ConnectionError as RedisConnectionError
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
|
||||
from src.config.settings import Cache as CacheSettings
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
@@ -32,10 +38,12 @@ class Cache:
|
||||
client: Redis,
|
||||
*,
|
||||
namespace: str,
|
||||
timeout_seconds: float,
|
||||
retry_after_seconds: float,
|
||||
) -> None:
|
||||
self.namespace = namespace
|
||||
self._client = client
|
||||
self._timeout_seconds = timeout_seconds
|
||||
self._retry_after_seconds = retry_after_seconds
|
||||
# monotonic-время конца пропуска; None — кэш работает
|
||||
self._skip_until: float | None = None
|
||||
@@ -45,7 +53,8 @@ class Cache:
|
||||
if self._skipping():
|
||||
return None
|
||||
try:
|
||||
value = await self._client.get(key)
|
||||
async with asyncio.timeout(self._timeout_seconds):
|
||||
value = await self._client.get(key)
|
||||
except (RedisError, OSError) as e:
|
||||
self._failed(e)
|
||||
return None
|
||||
@@ -57,7 +66,8 @@ class Cache:
|
||||
if self._skipping():
|
||||
return False
|
||||
try:
|
||||
await self._client.set(key, value, ex=ttl_seconds)
|
||||
async with asyncio.timeout(self._timeout_seconds):
|
||||
await self._client.set(key, value, ex=ttl_seconds)
|
||||
except (RedisError, OSError) as e:
|
||||
self._failed(e)
|
||||
return False
|
||||
@@ -74,11 +84,12 @@ class Cache:
|
||||
)
|
||||
|
||||
def _failed(self, error: Exception) -> None:
|
||||
# warning — один на отказ: неудачные пробы после пропуска молчат
|
||||
# warning — один на отказ: неудачные пробы после пропуска молчат.
|
||||
# TimeoutError от asyncio.timeout без текста — тогда repr
|
||||
if self._skip_until is None:
|
||||
logger.warning(
|
||||
"Cache is unavailable",
|
||||
error=str(error),
|
||||
error=str(error) or repr(error),
|
||||
error_type=type(error).__name__,
|
||||
retry_after_seconds=self._retry_after_seconds,
|
||||
)
|
||||
@@ -94,7 +105,9 @@ def create_cache(cache: CacheSettings, *, namespace: str) -> Cache:
|
||||
"""Кэш с пулом и таймаутами из `[cache]`; соединения — лениво."""
|
||||
# BlockingConnectionPool: при всплеске запросов ждёт свободное
|
||||
# соединение, а обычный пул сразу бросал бы MaxConnectionsError, и
|
||||
# здоровый Valkey пропускался бы как отказавший
|
||||
# здоровый Valkey пропускался бы как отказавший.
|
||||
# Retry — из redis.asyncio: синхронный класс асинхронное соединение
|
||||
# вызывает через await, и повтор молча не выполняется
|
||||
pool = BlockingConnectionPool(
|
||||
host=cache.host,
|
||||
port=cache.port,
|
||||
@@ -103,11 +116,12 @@ def create_cache(cache: CacheSettings, *, namespace: str) -> Cache:
|
||||
timeout=cache.timeout_seconds,
|
||||
socket_timeout=cache.timeout_seconds,
|
||||
socket_connect_timeout=cache.timeout_seconds,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
retry=Retry(NoBackoff(), 1, supported_errors=(RedisConnectionError,)),
|
||||
decode_responses=True,
|
||||
)
|
||||
return Cache(
|
||||
Redis.from_pool(pool),
|
||||
namespace=namespace,
|
||||
timeout_seconds=cache.timeout_seconds,
|
||||
retry_after_seconds=cache.retry_after_seconds,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user