Invental/Review lessons/Client state that goes stale

Client state that goes stale

Guard cache writes with scope and a version

In a persisted client cache, every async write needs two guards captured before the await: whose data it is (identity scope) and whether something newer was written meanwhile (a version or mutation counter), because timestamps alone can tie.

01 · Before and afterThe pattern

TypeScript
// before: scope and freshness resolved after the request returns
const doc = await api.get(id);
cache.replace(id, doc);

// after: capture both before awaiting, re-check after
const scope = cache.scope.get();
const seen = writes.get(id) ?? 0;
const doc = await api.get(id);
if (scope !== cache.scope.get() || (writes.get(id) ?? 0) !== seen) return;
cache.replace(id, doc, scope);

02 · Run it on your appThe check

If a user switches account while a request is in flight, can that response end up in the new account's local cache?

If the honest answer is no or not sure, this is worth a look before it reaches production.

Want this checked on your code?

Tell us what you are building and what worries you. We match a senior reviewer to your code and confirm scope before anything starts.

— Get in touch
hi@invental.co ↗
— Or
— What to include

A link or short description of the code or system, what you want checked, your stack, and when you need the answer. No repository access is needed until scope is agreed.

— Or leave a note
We reply within one business day.