The cache that was documented but didn't exist
From Kosher Kav
- React Native
- testing
- caching
Symptom
None, from the user's side. The app started, the session loaded, screens rendered. The only trace was in the Workers logs: four identical /session requests per cold start, a few milliseconds apart, from the same device.
Why the UI couldn't show it
Every one of the four requests succeeded and returned the same session, so every consumer got the right data. Extra requests cost latency and quota, not correctness. Nothing on screen could distinguish one fetch from four.
Diagnosis
The session module had a cache, a comment saying so, and a code review that had confirmed it. What it cached was the result: after the fetch resolved, the value was stored, and later calls returned it. The gap is the window between the first call and the first resolve. The tab bar, the map, the feed and the profile all mount during that window, all find the cache empty, and all start a fetch.
// Before: cached on resolve — the in-flight window is unprotected.
let cached: Session | undefined;
export async function getSession() {
if (cached) return cached;
cached = await fetchSession();
return cached;
}Fix
Cache the promise, not the value. The first caller creates it; everyone in the window awaits the same one. A failed fetch clears it so the next caller retries instead of inheriting the rejection forever.
let inflight: Promise<Session> | undefined;
export function getSession() {
inflight ??= fetchSession().catch((e) => {
inflight = undefined;
throw e;
});
return inflight;
}Test
The test that found it was budgeted as a formality: mock fetchSession, call getSession four times without awaiting between them, assert the mock was called once. It failed on the first run against code that everyone had read and agreed was cached. That is the argument for writing the boring test: reading code confirms what the code claims, and a test confirms what it does. This one took ten minutes and has been guarding the in-flight window through every refactor since.