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

Check, then act on stale state

Put the status check inside the UPDATE

A status check followed by an update by ID is a race; put the status condition into the update's where so the database enforces it at write time.

01 · Before and afterThe pattern

TypeScript
// before: check, then write by id
if (isMutable(c.payment?.status)) await db.credit.updateMany({ where: { id: { in: ids } }, data });

// after: the check is part of the write
await db.credit.updateMany({
  where: { id: { in: ids }, OR: [{ paymentId: null }, { payment: { status: { in: MUTABLE } } }] },
  data,
});

02 · Run it on your appThe check

When you move or edit money records, is the “still editable” condition inside the UPDATE statement, not just in an earlier read?

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.