Poseidonas

payload stock reservation

by Poseidonas
Stores & catalogs
v3
>=3.88 <4
MIT

Overview

Summary generated from the README

Extends the official Payload ecommerce plugin by wrapping its payment initiate and confirm-order endpoints. It checks stock and price for products and variants before the payment provider is contacted, then reserves stock with expiring holds. It requires Payload 3.88 or newer and the official ecommerce plugin, and must be listed after it.

Features

  • Validates variant stock and price before the payment provider is called
  • Writes expiring holds so concurrent checkouts cannot claim the same last unit
  • Returns HTTP 400 with machine-readable reasons such as OutOfStock and MissingPrice
  • Releases expired holds via checkout sweep, a secured endpoint or a local API function
  • Exposes an availableStock helper that returns recorded stock minus live holds
  • Configurable hold lifetime, collection slugs and inventory field name

Use cases

  • Prevent overselling the last unit of a product variant when several shoppers check out together
  • Reject checkouts for variants with insufficient stock or missing price before payment starts
  • Show real storefront availability that accounts for stock held in active carts

From the author

Validates variant stock and price for Payload ecommerce, which the official plugin never does, and holds stock from checkout until payment settles.

Installation

npm i payload-stock-reservation

1

Stars

0

Forks

0

Open Issues

2 weeks ago

Last Updated

152

Weekly Downloads

v1.0.1

npm Version

38.5 KB

Unpacked Size

0

Dependencies

GitHub stars

10 since Sep 7

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20261
Dec 5, 20261
Dec 4, 20261
Dec 3, 20261
Dec 2, 20261
Dec 1, 20261
Nov 30, 20261
Nov 29, 20261
Nov 28, 20261
Nov 27, 20261
Nov 26, 20261
Nov 25, 20261
Nov 24, 20261
Nov 23, 20261
Nov 22, 20261
Nov 21, 20261
Nov 20, 20261
Nov 19, 20261
Nov 18, 20261
Nov 17, 20261
Nov 16, 20261
Nov 15, 20261
Nov 14, 20261
Nov 13, 20261
Nov 12, 20261
Nov 11, 20261
Nov 10, 20261
Nov 9, 20261
Nov 8, 20261
Nov 7, 20261
Nov 6, 20261
Nov 5, 20261
Nov 4, 20261
Nov 3, 20261
Nov 2, 20261
Nov 1, 20261
Oct 31, 20261
Oct 30, 20261
Oct 29, 20261
Oct 28, 20261
Oct 27, 20261
Oct 26, 20261
Oct 25, 20261
Oct 24, 20261
Oct 23, 20261
Oct 22, 20261
Oct 21, 20261
Oct 20, 20261
Oct 19, 20261
Oct 18, 20261
Oct 17, 20261
Oct 16, 20261
Oct 15, 20261
Oct 14, 20261
Oct 13, 20261
Oct 12, 20261
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20261
Oct 5, 20261
Oct 4, 20261
Oct 3, 20261
Oct 2, 20261
Oct 1, 20261
Sep 30, 20261
Sep 29, 20261
Sep 28, 20261
Sep 27, 20261
Sep 26, 20261
Sep 25, 20261
Sep 24, 20261
Sep 23, 20261
Sep 22, 20261
Sep 21, 20261
Sep 20, 20261
Sep 19, 20261
Sep 18, 20261
Sep 17, 20261
Sep 16, 20261
Sep 15, 20261
Sep 14, 20261
Sep 13, 20261
Sep 12, 20261
Sep 11, 20261
Sep 10, 20261
Sep 9, 20261
Sep 8, 20261
Sep 7, 20261
npm weekly downloads

156+143 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026156
Dec 5, 202690
Dec 4, 202665
Dec 3, 202638
Dec 2, 202647
Dec 1, 202647
Nov 30, 202649
Nov 29, 202659
Nov 28, 202672
Nov 27, 202679
Nov 26, 2026258
Nov 25, 2026252
Nov 24, 2026271
Nov 23, 2026271
Nov 22, 2026254
Nov 21, 2026236
Nov 20, 2026223
Nov 19, 202638
Nov 18, 202631
Nov 17, 202610
Nov 16, 20264
Nov 15, 20263
Nov 14, 20264
Nov 13, 20264
Nov 12, 20264
Nov 11, 20264
Nov 10, 20263
Nov 9, 20269
Nov 8, 202612
Nov 7, 202612
Nov 6, 202612
Nov 5, 202614
Nov 4, 202614
Nov 3, 202613
Nov 2, 20267
Nov 1, 20264
Oct 31, 20264
Oct 30, 20264
Oct 29, 20261
Oct 28, 20261
Oct 27, 20262
Oct 26, 20263
Oct 25, 20263
Oct 24, 20262
Oct 23, 20262
Oct 22, 20264
Oct 21, 20264
Oct 20, 20263
Oct 19, 20263
Oct 18, 20263
Oct 17, 20263
Oct 16, 20263
Oct 15, 20263
Oct 14, 20263
Oct 13, 20263
Oct 12, 20262
Oct 11, 20263
Oct 10, 20263
Oct 9, 20263
Oct 8, 20263
Oct 7, 20263
Oct 6, 20264
Oct 5, 20264
Oct 4, 20265
Oct 3, 20267
Oct 2, 20269
Oct 1, 20268
Sep 30, 20269
Sep 29, 20269
Sep 28, 20269
Sep 27, 20267
Sep 26, 20268
Sep 25, 20266
Sep 24, 20265
Sep 23, 20265
Sep 22, 20265
Sep 21, 20266
Sep 20, 20269
Sep 19, 20267
Sep 18, 20267
Sep 17, 202611
Sep 16, 202616
Sep 15, 202615
Sep 14, 202617
Sep 13, 202615
Sep 12, 202614
Sep 11, 202615
Sep 10, 202611
Sep 9, 20268
Sep 8, 202610
Sep 7, 202613

Each point is npm's rolling 7-day download count.

Health Score

76/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1340410744-root.svg)](https://payloaddirectory.dev/plugins/1340410744-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1340410744-root"><img src="https://payloaddirectory.dev/badge/1340410744-root.svg" alt="Payload Directory"></a>
Updated Nov 17, 2026Created Aug 20, 2026Published Nov 17, 2026

README

payload-stock-reservation

npm node license payload

Validates the stock and the price of a variant before a Payload checkout reaches the payment provider, which @payloadcms/plugin-ecommerce never does, and holds what it validated until the payment settles or the hold expires.

  • Extends @payloadcms/plugin-ecommerce, wrapping its checkout endpoints instead of replacing them
  • Availability means recorded stock minus live holds, not raw stock
  • No runtime dependencies
  • No admin components, so it survives minor releases

Install

Requires Payload 3.88 or newer and @payloadcms/plugin-ecommerce 3.88 or newer. Verified against Payload 3.88.0 with the official plugin installed.

pnpm add payload-stock-reservation
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
import { stockReservationPlugin } from 'payload-stock-reservation'

export default buildConfig({
  plugins: [
    ecommercePlugin({ ... }),
    stockReservationPlugin({
      ttlSeconds: 900,
    }),
  ],
})

stockReservationPlugin must come after ecommercePlugin, because it wraps the endpoints that plugin registers. If it comes first there is nothing to wrap, and it says so in the server log on startup rather than staying quiet.

What was measured

Read in the published @payloadcms/[email protected], in the original TypeScript carried by its source maps.

Variant stock and price are never validated

In src/endpoints/initiatePayment.ts the variant check sits inside a branch that requires the item to have no variant:

201   if (item.product && !item.variant) {
253     if (item.variant) {
310     }
311   }

The inner condition can never be true. Reproduced on a live Payload 3.88 install: a product with inventory 2 and no variant is refused with HTTP 400 and cause.code: OutOfStock, while the same quantity of a variant with inventory 2 passes validation completely and reaches the payment provider.

confirmOrder then decrements that variant correctly, with payload.db.updateOne and $inc, so the stock goes negative. In the same handler productsValidation is destructured out of the arguments and never called.

What the official checkout actually checks, per cart line:

Cart linePrice checkedStock checkedStock decremented after payment
product, no variantyesyesyes
product with a variantnonoyes

Stock is validated but never held

Availability is read in initiatePayment and the decrement happens in confirmOrder. Nothing is written between the two, so two shoppers can both pass validation holding the same last unit.

Where the check has to go

Three interception points were read before one was chosen:

PointWhy it was rejected or chosen
products.validation, the official overrideRejected. For a line with a variant the loop never reaches the call, so the override is never invoked
A hook on the transactions collectionRejected. The Stripe adapter creates the payment intent first and the transaction record second, so a hook there fires after the provider has been contacted
The post /payments/:adapter/initiate endpointChosen. It is a root endpoint on the config, it runs before any adapter code, and wrapping it leaves the original handler in place

How a hold decides a race

Every Payload request runs in its own transaction, so a hold that is written inside the request transaction is invisible to a competing request until commit. Holds are therefore written outside it, which makes them visible immediately and carries the connection cost described under Honest limits.

A write alone still cannot serialise two checkouts, so the hold is written first and judged afterwards. All live holds on the same product or variant are read back, ranked oldest first, and their quantities accumulated. A hold keeps its stock only if the running total up to and including it fits inside the recorded stock. Of two checkouts racing for the last unit, the older keeps it and the newer deletes its own hold and is refused. Ties on the creation time are broken on the identifier, so the ranking is a total order and the two racers always agree on who won.

Options

OptionDefaultMeaning
cartsSlug'carts'Slug of the carts collection
defaultCurrency''Currency for the price check when the cart carries none. Empty means the price check is skipped and only stock is validated
disabledfalseStops validating and holding but keeps the collection, so the database keeps its shape
holdScanLimit500Highest number of holds read for one item when ranking a new hold
holdsSlug'stock-holds'Collection holding reserved stock
inventoryFieldName'inventory'Numeric field holding stock on products and variants
productsSlug'products'Slug of the products collection
refuseNegativeInventorytrueRefuses an item already recorded below zero with the reason NegativeInventory
releaseEndpointPath'/stock-reservation/release-expired'Path of the endpoint that deletes expired holds
releaseSecret''Secret accepted by that endpoint as Authorization: Bearer <secret>. Empty means only a signed in user may call it
sweepOnCheckouttrueDeletes the expired holds of the items in the cart at the start of every checkout
ttlSeconds900How long a hold survives, in seconds
variantsSlug'variants'Slug of the variants collection

A value that cannot be used is replaced by its default rather than being applied. A ttlSeconds of 0 becomes 900, 90.9 becomes 90, and a slug given as an empty string becomes its default. A releaseEndpointPath without a leading slash gains one.

What it adds to your database

CollectionFieldTypeNotes
stock-holdscarttextindexed. The cart that owns the hold
stock-holdsstockCollectiontextindexed. products or variants
stock-holdsstockDocumenttextindexed. Identifier of the held product or variant
stock-holdsquantitynumberminimum 1
stock-holdsexpiresAtdateindexed

Nothing is added to your products, variants, carts or orders. The holds collection is closed to create, read, update and delete through the API and hidden in the admin panel. It is written only by the plugin.

What it adds to your API

EndpointMethodPurpose
/api/payments/:adapter/initiatepostWrapped. Validates and holds, then calls the original handler
/api/payments/:adapter/confirm-orderpostWrapped. Calls the original handler, then releases that cart's holds
/api/stock-reservation/release-expiredpostAdded. Deletes expired holds and returns { "released": n }

A refused line returns HTTP 400 with a readable sentence and a machine readable reason:

{
  "message": "Only 2 left of variants 41.",
  "cause": { "code": "OutOfStock", "collection": "variants", "document": "41" }
}

The codes are OutOfStock, MissingPrice, NegativeInventory and NotFound, exported as refusalCodes.

Releasing expired holds

Expired holds never count towards availability, so nothing breaks if they are left in place. Deleting them only keeps the collection small, and there are three ways to do it, none of which needs a scheduler in your dependencies:

  1. Leave sweepOnCheckout on. Every checkout deletes the expired holds of the items in its own cart.

  2. Point your existing scheduler at the endpoint.

    curl -X POST https://example.com/api/stock-reservation/release-expired \
      -H "Authorization: Bearer $STOCK_RELEASE_SECRET"
    
  3. Call it yourself, from a route handler or a script.

    import { releaseExpiredHolds } from 'payload-stock-reservation'
    
    const released = await releaseExpiredHolds(payload)
    

Showing real availability

import { availableStock } from 'payload-stock-reservation'

const left = await availableStock(payload, { collection: 'variants', document: variantID })

It returns the recorded stock minus every live hold, or null when the item does not exist or does not track stock.

Honest limits

PostgreSQL needs a large enough connection pool. A hold is written outside the request transaction, so that a competing checkout can see it. That opens a second connection while the request holds the first. The same mechanism was measured for payload-order-numbers on a live install: with the pg default pool of 10, ten simultaneous checkouts succeed and fifteen do not. Set the pool to at least twice the number of checkouts you expect in the same instant.

postgresAdapter({
  pool: { connectionString: process.env.DATABASE_URI, max: 60 },
})

MongoDB is not affected and needs no change.

A hold is written before it is judged. The hold has to exist before it can be ranked against the others, and the cart is read with access checks overridden so that guest carts behave the same way. A checkout that is then refused, whether by this package or by the original handler, deletes its own holds before returning, so nothing is left behind, but the write happens.

It guards the checkout endpoints, nothing else. An order written straight through the local API, the admin panel or a payment webhook does not pass through this package and is not validated or held.

The decrement still belongs to the official plugin. This package stops a sale that cannot be fulfilled from starting; it does not change how confirmOrder decrements stock afterwards. Stock that is already negative stays negative until you correct it.

Both settings of refuseNegativeInventory refuse the sale. The option changes the reason, not the outcome: NegativeInventory when it is on, OutOfStock when it is off. It exists so a storefront can tell an oversold record apart from an ordinary sell out.

An item with no stock value is unlimited and is never held. That is what the official plugin does with an empty inventory field, and this package does not change it.

A price of zero is refused as a missing price. That is also what the official plugin does. Free items cannot go through this checkout, with or without this package.

Holds are deleted, not archived. There is no history of who held what. If you need an audit trail, that is a different guarantee and belongs in a different package.

Above holdScanLimit holds on one item the ranking window truncates. With more than 500 live holds on a single product or variant, the ranking reads the oldest 500 and a hold outside that window is refused rather than mis-sold.

The release endpoint path must not start with a collection slug. Payload resolves the first path segment to a collection before it looks at root endpoints, so /stock-holds/... would never reach the handler. The default avoids this, and a path that would be shadowed is reported in the server log on startup.

If the package cannot do its job, the sale goes through. A database error while validating or holding is logged as an error and the checkout is handed to the original handler unchanged, leaving you exactly where you were without this package. Only a real refusal, one this package decided on, stops a checkout. Losing a sale to a broken sweep is worse than the oversell it was meant to prevent.

License

MIT. Copyright George Vasiliades, https://github.com/Poseidonas

Similar plugins