perf: cache get_user_by_username on the login hot path

Locust @task(2) hammers /auth/login in steady state on top of the
on_start burst. After caching the uuid-keyed user lookup and every
other read endpoint, login alone accounted for 47% of total
_execute at 500c/u — pure DB queueing on SELECT users WHERE
username=?.

5s TTL, positive hits only (misses bypass so a freshly-created
user can log in immediately). Password verify still runs against
the cached hash, so security is unchanged — the only staleness
window is: a changed password accepts the old password for up to
5s until invalidate_user_cache fires (it's called on every write).
This commit is contained in:
2026-04-17 20:36:39 -04:00
parent 255c2e5eb7
commit e967aaabfb
2 changed files with 43 additions and 4 deletions

View File

@@ -9,7 +9,7 @@ from decnet.web.auth import (
averify_password,
create_access_token,
)
from decnet.web.dependencies import repo
from decnet.web.dependencies import get_user_by_username_cached
from decnet.web.db.models import LoginRequest, Token
router = APIRouter()
@@ -27,7 +27,7 @@ router = APIRouter()
)
@_traced("api.login")
async def login(request: LoginRequest) -> dict[str, Any]:
_user: Optional[dict[str, Any]] = await repo.get_user_by_username(request.username)
_user: Optional[dict[str, Any]] = await get_user_by_username_cached(request.username)
if not _user or not await averify_password(request.password, _user["password_hash"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,