feat: cache chat cards in Valkey

Valkey 9.1 in compose caches the immutable chat card (title, members,
created_at) used by GET /chats/{id} and by the membership check of the
message endpoints. Cache-aside with a write after commit, keys per
database, TTL plus allkeys-lru, persistence off. redis-py runs without
retries; on failure the cache is skipped for a few seconds and requests
go to PostgreSQL. Readiness does not depend on Valkey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 21:17:55 +03:00
co-authored by Claude Opus 5.5
parent c7681b0e18
commit cae4b09147
46 changed files with 1769 additions and 210 deletions
+8 -2
View File
@@ -8,6 +8,7 @@ from src.api import errors
from src.api.middlewares import RequestContextMiddleware
from src.api.routers import health_router, v1_router
from src.config import settings
from src.infra.cache.instance import cache
from src.infra.db.session import engine
from src.infra.logger import AbstractLogger, get_logger
from src.infra.password import prepare_dummy_hash
@@ -19,10 +20,12 @@ logger: AbstractLogger = get_logger().bind(module="startup")
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
database = settings.database
# engine подключается лениво: без Postgres сервис стартует, а
# /health/ready отвечает 503
# engine и кэш подключаются лениво: без Postgres сервис стартует, а
# /health/ready отвечает 503; без Valkey запросы идут в Postgres
if not database.password.get_secret_value():
logger.warning("Database password is empty")
if not settings.cache.password.get_secret_value():
logger.warning("Cache password is empty")
# ~30 мс CPU при старте: время ответа на вход с неизвестным username
# ровное с первого запроса
await prepare_dummy_hash()
@@ -34,11 +37,14 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
database_host=database.host,
database_port=database.port,
database_name=database.name,
cache_host=settings.cache.host,
cache_port=settings.cache.port,
)
try:
yield
finally:
await engine.dispose()
await cache.aclose()
logger.info("Stopped API")