Skip to Content
TutorialsPrevent Overbooking

Prevent Overbooking

This tutorial uses conditional updates and services.transaction, which are available on the Buildpad Engine backend.

The problem

A products collection has a stock field. The obvious checkout reads the product, checks stock > 0, then writes stock - 1. When two buyers do this at the same moment, both read stock = 1, both pass the check, and both write 0. You sold two items and had one.

The fix is to make the check and the write one step that nobody can get between. There are two layers, depending on how much has to change together.

Layer 1: a conditional PATCH from the client

When only one row changes, let the database do the check. Send the condition with the PATCH and decrement the stock with _dec:

curl -X PATCH "https://your-domain.com/api/items/products/42" \ -G --data-urlencode 'condition={"stock":{"_gte":1}}' \ -H "Authorization: Bearer <token>" \ -H "Content-Type: application/json" \ -d '{"stock": {"_dec": 1}}'

The condition and the decrement run as one atomic UPDATE under a row lock. With two buyers and one item, the first gets 200 and the second gets 409 CONDITION_NOT_MET. See Conditional & atomic updates for every response.

Layer 2: a hook with a transaction

Usually the stock and the order must change together: no order without stock, and no stock taken without an order. Let the client create a checkout_requests item and do the work in a filter hook on checkout_requests.items.create:

const result = await services.transaction(async (tx) => { const products = tx.items('products', { elevated: true }); const product = await products.readOne(payload.product, { lock: 'update' }); if (product.stock < payload.qty) throw new HookError('Sold out', 409, 'SOLD_OUT'); await products.updateOne(payload.product, { stock: { _dec: payload.qty } }); return tx.items('orders').createOne({ product: payload.product, qty: payload.qty }); }); payload.order = result; return payload;
  • readOne(id, { lock: 'update' }) locks the product row. A second checkout for the same product waits at this line until the first one commits, and then reads the new stock.
  • If the hook throws, the stock change and the order are both rolled back, and the client gets 409 SOLD_OUT.
  • Action hooks on orders (an email, for example) run only after the commit, so they never fire for an order that was rolled back.
  • The buyer does not need write access to products: elevated: true lets the hook change stock while orders is still written with the buyer’s permissions.

See Transactions for timeoutMs, lockTimeoutMs, retries and the error codes.

Optimistic locking for edits

Stock is a counter, but some records are edited by people: a booking that two staff open at once. Keep a numeric version field, and save with the version you read as the condition:

curl -X PATCH "https://your-domain.com/api/items/bookings/7" \ -G --data-urlencode 'condition={"version":{"_eq":5}}' \ -H "Authorization: Bearer <token>" \ -H "Content-Type: application/json" \ -d '{"status": "approved", "version": {"_inc": 1}}'

The first save wins and raises the version to 6. The second gets 409 CONDITION_NOT_MET. Read the booking again, show or merge the changes, and retry.

Why there is no lock across requests

You cannot lock a row in one request and release it in the next. A browser that closes, a lost connection or a slow user would keep the row locked and block everyone else. Locks live only inside one services.transaction, and a transaction still open when the script ends is rolled back.

For work that spans a user’s think time, use optimistic locking: no lock is held, and a conflict shows up as a 409 when the user saves.

Pick the smallest tool that works: a conditional PATCH for one row, a transaction in a hook when several rows must change together, and a version field when people edit the same record.