Invental/Review lessons/Check, then act on stale state

Check, then act on stale state

Restate the condition in every destructive write

Every destructive or claiming SQL statement should restate the condition it was decided on (still trashed, still the slot I read, still the current run) in its own WHERE clause, because the read that justified it is already stale.

01 · Before and afterThe pattern

TypeScript
// before: decided on an earlier read, executed unconditionally
await db.delete(items).where(eq(items.id, id));

// after: the condition travels with the write
const [gone] = await db.delete(items)
  .where(and(eq(items.id, id), eq(items.isDeleted, true)))
  .returning();
if (!gone) return; // restored meanwhile: keep it

02 · Run it on your appThe check

If your job queue delivers the same message twice, does the job run twice?

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.