Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 70 ยท Projects

Project: Inventory with Safe Concurrent Updates

Keep stock counts correct when many users act at once: atomic decrements, optimistic locking with a version field, order transactions and idempotent retries.

Selling the last item twice is the most famous bug in e-commerce. It does not come from a missing feature; it comes from two requests that read the same stock number, both decide "there is enough", and both write. This project builds the inventory side of a shop and defends it against exactly that: atomic decrements so stock cannot go negative, optimistic locking so two editors cannot silently overwrite each other, an order transaction so a failed order leaves no half-finished state, and idempotent retries so a repeated request is harmless.

Real MongoDB makes a single-document write atomic (see Atomicity and Single-Document Writes), and that one guarantee carries most of this project. For multi-document steps you need a transaction (see Multi-Document Transactions). The code here runs on the tutorial's practice engine, a JavaScript stand-in (see The Practice Engine Used in This Tutorial). The engine is single-threaded, so we simulate concurrency by running two "clients" in an interleaved order that a real server could produce. The filters and updates are real MongoDB; the interleaving and the transaction wrapper are simulations.

Four defences

Atomic decrement Check and change in one write.
Version field Reject writes based on stale reads.
Transaction All lines of an order, or none.
Idempotency key A retry does nothing new.
1 / 2

Defence 1: the atomic decrement

The broken version of "buy" is read, check, write: read the product, see stock: 5, compute 5 - 3 = 2 in your application, write stock: 2. Between the read and the write another request can do the same thing. If both read 5, the first buys 3 and the second buys 4, and each writes its own result. The last write wins, and the shop has sold 7 items from a stock of 5.

The fix is to move the check into the write. A filter can include the stock condition, and $inc changes the number relative to what is stored rather than relative to what you read earlier:

JavaScript
db.products.updateOne(
  { _id: "desk", stock: { $gte: 3 } },   // only match if enough stock remains
  { $inc: { stock: -3 } }
)

The server finds the document, tests the filter and applies the update as one atomic step. If the stock is too low the filter does not match, the result reports matchedCount: 0 (and modifiedCount: 0), and nothing changes. Your code treats "nothing matched" as "sold out". Notice that no second query is needed: the answer to "did it work?" is in the write result.

The TryIt below plays both versions with the same two customers. Customer A wants 3 desks, customer B wants 4, and 5 are in stock. The naive version interleaves their reads before either write.

JS Overselling: read-check-write versus atomic decrement

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The naive store sold seven desks it did not have and ended with a stock of 1, which is wrong in two ways at once. The atomic version sells 3, refuses the 4, and still lets B buy 2 afterwards. In real MongoDB the same property holds with thousands of simultaneous clients, because the server serializes writes to one document.

Defence 2: optimistic locking with a version field

Atomic operators work when the change is expressible as an operator. Many edits are not: an admin opens a product form, thinks for two minutes, and saves the whole form. If someone else changed the product meanwhile, the save would overwrite their change with stale values (a lost update). You cannot hold a lock for two minutes on a web request, so you use optimistic concurrency: assume conflicts are rare, detect them when they happen, and retry.

Add a version number to the document. Every write includes the version you read in its filter and increments it:

JavaScript
db.products.updateOne(
  { _id: "desk", version: 3 },
  { $set: { name: "Standing Desk" }, $inc: { version: 1 } }
)

If someone else saved first, the stored version is now 4, the filter matches nothing, and modifiedCount is 0. That is your signal: re-read the document, re-apply the change, and try again with the new version. The next TryIt shows the lost update first, then the versioned write, using a hook that makes another client sneak in between our read and our write.

JS Lost update versus optimistic locking

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The blind write ends with the new name and the old price, silently undoing B's work. The versioned save detects the conflict on its first attempt, re-reads (now seeing price 90 and version 2) and succeeds on the second attempt, so both changes survive. Two practical rules: put a retry limit on the loop, and re-apply the change to the freshly read document rather than reusing old values.

Defence 3: an order is several writes

Placing an order touches several documents: one orders document and one products document per line. If the second product is sold out, the first product's stock has already been reduced and the order cannot be completed. You need either a way to undo, or all-or-nothing behaviour.

Real MongoDB offers multi-document transactions on replica sets and sharded clusters. You start a session and run the writes inside withTransaction; if the callback throws, every write in it is rolled back:

JavaScript
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    await orders.insertOne(order, { session });
    for (const line of lines) {
      const r = await products.updateOne(
        { _id: line.sku, stock: { $gte: line.qty } },
        { $inc: { stock: -line.qty } },
        { session }
      );
      if (r.modifiedCount === 0) throw new Error("Out of stock: " + line.sku);
    }
  });
} finally {
  await session.endSession();
}

Transactions are real but not free: they add latency and locking, have time and size limits, and a conflicting write raises a retryable error. If one document can hold the data that must change together, prefer that (embedding avoids transactions). For orders spanning products, a transaction is the honest answer. The stand-in below has a tiny withTransaction that snapshots the collections and restores them if the callback throws. It models the outcome of a rollback; it is not the real protocol.

Defence 4: idempotent retries

Networks fail in the middle. A client sends an order, the server commits it, the response is lost, the client retries. Without protection the customer is charged twice and the stock drops twice. The cure is an idempotency key: the client generates a unique requestId once and sends it with every retry. The server uses it as the order's _id. Because _id is unique, the second insert fails with a duplicate-key error (code 11000), which the server interprets as "already done" and answers with the existing order instead of repeating the work.

The same TryIt covers both the transaction and the retry. Watch the stock numbers after each call.

JS Order transaction with an idempotency key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first order succeeds and takes 2 desks and the last lamp. The retry with the same requestId returns "already processed" and the stock does not move. The second order fails on the lamp after the desk line already ran, yet the desk stock is back to 3: the rollback undid it, and no req-2 order document is left behind.

Putting it together

A production placeOrder follows the same order of operations every time: insert the order with the idempotency key first (cheap duplicate detection), decrement each product with a guarded atomic update, and treat any shortfall as a reason to abort the transaction. Add a retry wrapper around the transaction for transient errors (the driver's withTransaction helper retries those for you), and index nothing extra for this path: _id lookups are already indexed. Product edits made through forms use the version field instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a read-check-write sequence oversell stock?

    The check happens in the application against a stale value. Putting the condition in the update filter and using $inc makes check and change one atomic step.
  2. 2. An updateOne with filter { _id: 'desk', version: 3 } reports modifiedCount 0. What should the code do?

    A version mismatch means someone else saved first. Re-reading and re-applying the edit on fresh data resolves the conflict without losing their change.
  3. 3. How does an idempotency key stored as the order _id protect against a retried request?

    _id is unique. The second insert with the same key is rejected, and the server can return the already-created order.
  4. 4. In the order example, why does the desk stock return to its old value when the lamp is sold out?

    All writes inside a transaction commit together or not at all. The thrown error aborted the transaction, undoing the desk decrement and the order insert.

Summary

  • Put the stock condition inside the update filter and use $inc: one atomic write both checks and changes the value.
  • Treat matchedCount or modifiedCount of 0 as a business signal such as "sold out" or "conflict".
  • A version field in the filter, incremented on every write, gives optimistic locking; on conflict re-read and retry with a limit.
  • Multi-document changes that must succeed together need a transaction (on a replica set); the stand-in only models the rollback outcome.
  • Use a client-generated idempotency key as _id so retries are harmless.

Now practice everything you have learned in Practice: Query and Update Exercises.