By BluffKing · · Updated
Read Cache Security
An August 2026 read cache started with a contract: how stale, what invalidates it, which fields. Production auth now reads startup-restored memory; revocation stays synchronous.
In an authenticated service, “add a cache” can keep a logged-out cookie alive, show users stale profile data, or cache a field the original query never meant to return. When we added an in-process read cache to the server in August 2026, the first thing we wrote was not a HashMap but a contract: how stale each read may be, which writes must invalidate it at once, and which fields the cached value may contain.
| Read model | Window | Safety rule |
|---|---|---|
| Session verification lease | 5 seconds | Logout/revocation evicts synchronously; the cache never extends the real session expiry |
/api/auth/me | 5 seconds | Profile, email and session changes invalidate it at once |
| Table avatar/display name | 60 seconds | Only fields already public at the table; no email |
The easy mistakes are races. If a session is revoked while a read is waiting on the database, that read’s result must not be written back after the revocation; background renewal only replaces a lease whose sequence number (seq) is unchanged, so it cannot revive a deleted entry. The regression tests at the time pinned these edges: after logout the same token was rejected immediately, a session with 150 milliseconds left was not extended by the 5-second cache, and an avatar write invalidated the cached /me. The only performance check was an in-process p95 under 5 milliseconds, not a production latency promise.
The current code has moved further: in production, session, /api/auth/me and avatar reads come straight from in-process data restored from the database at startup, and the 5-second lease is used only when that mode is off. Revocation is still synchronous and the avatar response still has no email. The lesson is unchanged: you cache a contract, not a SQL query, so write down how stale it may be, what invalidates it and which fields it may hold before you write the code.