perf(auth): collapse the session lookup from seven round trips to one
Not a candidate for admin-merge. This touches the auth path for every authenticated request across desktop, web, mobile, CLI and MCP. It's the biggest win available, but it wants a human read — see What to look at below.
The problem
Every authenticated request resolves a session, and each resolution was seven HTTP round trips to Neon. The database is in us-west-2; every Vercel function is in iad1. So one query costs 73-100ms, not a few.
Scale: api's GET /api/trpc/[trpc] alone has 360M Neon spans at 73ms average.
| # | query | |
|---|---|---|
| 1 | findOne sessions | covered by cookieCache ~2/3 of the time |
| 2 | findOne users | ditto |
| 3 | update sessions | updateAge refresh |
| 4 | findMany jwkss | every call, 136ms |
| 5 | members.findMany | customSession |
| 6 | subscriptions.findFirst | customSession |
| 7 | users.findFirst | the same row as #2 |
cookieCache was already hitting on 40 of 60 sampled requests — but customSession re-ran its callback regardless, so 4-7 were paid even on a cache hit.
The changes
#5, #6, #7 → one statement. They were sequential only because the active-organization fallback made the order matter, and that fallback is expressible in SQL. #7 was reading a row better-auth had already handed us; the old comment blamed additionalFields not surfacing on the passed-in user.
#4 cached, not disabled. disableSettingJwtHeader would remove the round trip outright, but desktop (auth-client.ts:142) and mobile (client.ts:45) both read set-auth-jwt off response headers to refresh opportunistically. So the read is cached behind the plugin's adapter.getJwks hook instead, with createJwk writing through and invalidating.
Net: 7 → 1 on a cookie-cache hit, 7 → 3 on a miss.
Verification
A differential harness ran old vs. new against a real database branch across 64 cases — multi-membership users at every active-organization permutation, paid and unpaid, stale organization ids, no active organization, and a user with no memberships.
0 mismatches. 104ms → 36ms per call.
What to look at
The harness caught a genuine bug, which is the best argument for reviewing this carefully:
onboardedAt came back 8 hours off on every user. These are timestamp (not timestamptz) columns, so Postgres returns a naive string with no zone — new Date() reads that as local time, while drizzle's mapping treats it as UTC. Silent, and it would have shifted the onboarding gate by the function's offset. Fixed in toDate(), re-verified.
Specific things worth a second opinion:
toDate()inload-custom-session-data.ts— the fix above. If it's wrong, onboarding and pending-deletion gates move.- The raw SQL. It's the only
db.executeinpackages/auth, deliberately: the single statement is the point. Worth checking the active-org CTE matchesresolveSessionOrganizationState's TS fallback exactly (it takes memberships orderedcreated_at DESCand picks the session's org if present, else the first). - The concurrent-move path. If another request changes the session's active organization between the query and
resolveSessionOrganizationStatesettling, the plan fetched belongs to the wrong org. Handled by comparingplanOrganizationIdand re-reading — rare, but confirm the fallback is right. - JWKS cache TTL (60s). A key created on another instance is absent from
/jwksuntil expiry, so tokens signed with it would fail verification for up to a minute.createJwkinvalidates locally. Keys effectively never rotate here (no expiry configured), but the window is real.
Testing
- 64-case differential harness against a live branch, 0 mismatches
- JWKS cache: 3 calls → 1 read;
createJwkinvalidates - better-auth instance constructs cleanly with the
adapteroption (106 endpoints) - Lint, typecheck, full suite green
https://claude.ai/code/session_014D6wif8HDRCXEFf5Ku4w7V
Summary by cubic
Collapses session resolution from seven DB round trips per request to one on a cookie-cache hit (three on a miss) by combining membership/subscription/user reads into a single SQL statement and caching JWKS reads. This reduces per-request latency and fixes timestamp parsing that could shift onboarding/deletion gates.
Review and rollout
- Verify the raw SQL active-org fallback matches the TypeScript logic: prefer the session’s org if present, else the most-recent membership (
created_at DESC). - Confirm
toDate()treats Postgrestimestamp(no tz) as UTC; a mismatch moves onboarding/deletion gates by the server offset. - Check the concurrent move path: if
planOrganizationIddiffers from the resolved active org, we re-read the subscription; this avoids serializing the common path. - JWKS caching: 60s per-instance TTL. Keys created on another instance may fail verification until expiry;
createJwkinvalidates locally. We keep theset-auth-jwtheader for desktop/mobile refresh behavior. - Expected impact: 7→1 round trip on cache hit (7→3 on miss); ~104ms→36ms per call over 64 cases. No migrations required.
Summary by CodeRabbit
-
New Features
- Improved session loading with memberships, active organization details, subscription plans, onboarding status, and deletion-request status.
- Added caching for authentication keys to improve repeated sign-in and session checks.
- Session data now stays accurate when the active organization changes.
-
Bug Fixes
- Improved fallback behavior when an active organization is unavailable.
- Ensured session timestamps are handled consistently.