Atomic updates and transactions
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
let qty=4;function reserve(n){if(!Number.isSafeInteger(n)||n<1||n>qty)return false;qty-=n;return true;}console.log(reserve(3),qty);console.log(reserve(3),qty);console.log(reserve(-1),qty);Run node main.mjs in a disposable directory with the files shown. Expected standard output:
true 1false 1false 1How it works
For a positive integer request, match the record ID, tenant and sufficient quantity; decrement via $inc. If no document matched, report a domain failure rather than forcing stock negative. An update of multiple documents does not make the entire batch atomic; use supported transactions when cross-document invariants require them, with a session and topology verified for that driver. The local function models the invariant sequentially; actual concurrent safety and server transaction behavior remain untested. If retries may duplicate a reservation, use an idempotency design.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial driver function; tenant is already authorized, books is a fixture collection.export async function reserve(books,tenant,id,n){ if(!Number.isSafeInteger(n)||n<1||n>100)throw Error('Invalid quantity'); const result=await books.updateOne({tenant,_id:id,qty:{$gte:n}},{$inc:{qty:-n}}); return result.matchedCount===1;}True only if a matching document with enough stock was updated. NOT RUN; requires acknowledged writes and approved fixture.
Common mistake
Do not perform an unchecked read-modify-write sequence or treat matchedCount as a complete authorization decision. Validate the caller and requested quantity first.
Practice
Start at quantity 4 and reserve 3 twice. The second reservation must fail without changing remaining stock.
Documentation: primary source. Candidate lookup: node-atomic-updates-and-transactions-lookup. Prerequisite: node-indexes-and-validation (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Atomic updates and transactions — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Where should the sufficient-stock check appear?
Does single-document atomicity make a multi-document operation atomic as a whole?
Why reject a negative reservation?