Skip to Content
Meubles Morinière

Engineering choicesTechnical case studies7 min read

Holding a piece during payment

The storefront and the store sell the same stock, and the money arrives through Stripe minutes or days later. Here’s how we keep a one-of-a-kind piece from selling twice, with no reservation table to expire or clean up.

The problem

The store sells a lot of one-of-a-kind pieces: a painting hung in the showroom, a display model, the last item of a series. On September 1, 2026, 40 products out of 215 existed as a single unit (293ee3e03b). These pieces sell in the store as well as on the storefront.

Online payment happens at Stripe, outside the application. Several minutes can pass between the checkout page and the confirmation. And between the payment and the webhook that tells the ERP about it, it’s sometimes several hours. At first, checkout verified the stock without holding anything, and the stock only went down when the webhook arrived. The stock audit of September 1 showed what that led to. Two buyers pass the check ten minutes apart and both pay. When the second webhook arrives, the stock is already at zero. The order stays paid and an alert goes out, but two customers have been charged for one object. Back then, a Stripe session lasted twenty-four hours.

The constraints

  • Stripe sets its own limits. A session expires between thirty minutes and twenty-four hours after it’s created, and Stripe rejects an expires_at less than thirty minutes ahead of its own clock. An unacknowledged webhook is redelivered for three days (STRIPE_EVENT_RETRY_SECONDS). So a paid session can stay “pending” in the database long after it has expired.
  • Only the ERP can mark an order as paid. The storefront only creates orders that are awaiting payment (The storefront only has the rights it needs). So whatever holds the piece has to be readable from that order.
  • A made-to-order piece doesn’t need to be held. If two customers order the same model, the workshop builds two. In that case, giving the customer twenty-four hours to think is just comfort, and it carries no risk.
  • The store has to see what the storefront is holding, and the other way round. And the product page shouldn’t show “out of stock” for the length of a payment.
  • No scheduled job runs every minute. There’s only one, the daily check, and it runs once a day. You can’t rely on it to clean up expired reservations.

The alternatives

There were four ways to do it.

  • Shorten the session. That’s what was done on September 1 (293ee3e03b): thirty minutes as soon as a line has tracked stock, when it used to be twenty-four hours. The commit says so itself: “This is NOT a reservation […] Shrinking the window does not close the hole, it makes it 48 times smaller”. It was a stopgap.
  • Create a reservation table. The same commit put it off: it was waiting to know which furniture families the store keeps in stock, because without that, you don’t know what to reserve. A real reservation “persists the intent to TAKE the piece and costs a column, an expiry to sweep and a release path”. And every forgotten path leaves a piece blocked, or releases it too early.
  • Decrement the stock when the order is created and give it back on expiry. That comes down to the same thing as a table. On top of that, the balance is wrong for as long as the session is open, and you have to write a stock movement for a sale that didn’t happen.
  • Derive the hold from a state that already exists. A storefront order that’s pending and recent enough to still be payable holds its pieces. Nothing is written to reserve, so there’s nothing to expire or release.

The decision

The hold isn’t written anywhere, we derive it. An order holds its pieces as long as it meets four conditions: it was placed on the storefront, it’s awaiting payment, the workshop hasn’t cancelled it, and it was created less than its window ago (pendingReservationWhere, packages/domain/src/stock-reservation.ts). The order already carries these four facts for other reasons.

Stripe’s events can release the piece earlier, through transitions that payment handling already has. When the payment is collected, the piece leaves the stock. When the session expires, the order moves to CANCELED. When a delayed payment fails, it moves to FAILED. In every other case, time releases the piece.

The rule is a single query condition. A test replays it on a real database, with two buyers for a single piece. Comments and test names are in French, as in the rest of the code.

pendingReservationWherepackages/domain/src/stock-reservation.ts · lines 25–51
/**
 * Les commandes du site qui tiennent encore leurs pièces : impayées, et ouvertes depuis moins
 * longtemps que leur session de paiement (et le délai de reprise des événements Stripe, quand une
 * session est partie). Une commande que l'atelier a annulée avant son paiement n'en tient plus :
 * payée quand même, elle ne prend rien au stock (`settleCanceledOrder`). Une pièce réservée n'est pas
 * libre pour le paiement du site, son panier et sa page de commande (`withFreeStock`), ni pour les
 * gestes de l'ERP qui servent une commande déjà payée (changement de variante, rupture servie). La
 * vente au magasin (vente hors site, devis accepté au comptoir), elle, la prend sur le stock brut :
 * le client est là, la pièce en main ; le paiement en ligne qui la tenait se ferme ensuite
 * (`releaseSoldReservations`). Les soldes AFFICHÉS de la fiche et le « Disponible » de
 * la console restent le stock brut : la caisse dit au client que la pièce est en cours de paiement
 * (`StockShortage.isInPayment`).
 */
export function pendingReservationWhere(nowMs: number): Prisma.OrderWhereInput {
	return {
		channel: SaleChannel.WEB,
		paymentStatus: PaymentStatus.PENDING,
		fulfillmentStatus: { not: FulfillmentStatus.CANCELED },
		OR: [
			{ createdAt: { gt: new Date(nowMs - CHECKOUT_RESERVATION_WINDOW_MS) } },
			{
				stripeSessionId: { not: null },
				createdAt: { gt: new Date(nowMs - CHECKOUT_PAYABLE_RESERVATION_WINDOW_MS) },
			},
		],
	};
}

The implementation

Two time windows

Both durations are computed from Stripe’s rules (packages/domain/src/checkout-session.ts).

  • An order with no Stripe session holds its pieces for the length of a session, plus an hour of margin (CHECKOUT_RESERVATION_WINDOW_MS).
  • An order that has opened a session also holds them for the three days during which Stripe can still redeliver the payment event (CHECKOUT_PAYABLE_RESERVATION_WINDOW_MS). So if the webhook of a paid session gets lost, the piece doesn’t go to someone else.
The two windows during which a pending order holds its piecesNo Stripe session was opened : length of a session 31 min + margin 1 h = 1 h 31 min, piece released. A Stripe session was opened : Stripe session 31 min + Stripe redelivery 3 d + margin 1 h = 3 d 1 h 31 min, piece released. A Stripe event that arrives releases the piece sooner. When the order is paid, the piece leaves stock. When the session expires or the payment is refused, the order closes.No Stripe session was opened0order createdlength of a session31 minmargin1 h1 h 31 minpiece releasedA Stripe session was opened0order createdStripe session31 min31 minthe session expiresStripe redelivery3 d3 d 31 minredelivery endsmargin1 h3 d 1 h 31 minpiece releasedA Stripe event that arrives releases the piece sooner. When the order is paid, the pieceleaves stock. When the session expires or the payment is refused, the order closes.
Durations read from packages/domain/src/checkout-session.ts at every build of this documentation. Segments are to scale with each other, except redelivery, which is cut. An order where everything is made to order holds nothing, and its session lasts 23 h 59 min.

When in doubt, it’s better to hold the piece too long than not long enough. At worst, we lose a sale. A piece released too early makes two customers pay. When an order is still pending after its session has ended, the team is warned (STALE_PENDING_TRACKED_SESSION_MAX_AGE_MS). The instruction is to look at the session in Stripe before touching anything, because the customer may have paid.

A session that lasts according to what it holds

The session lasts thirty-one minutes as soon as a line has tracked stock, and twenty-four hours minus one minute when everything is made to order (checkoutSessionTtlSeconds). The one-minute margin above Stripe’s minimum wasn’t always enough. Between the SDK’s retries and clock drift, it went quickly, and the customer landed on “payment unavailable”. So when Stripe refuses only because of the time, we create the session once more, with a recomputed expiry and a different idempotency key (createCheckoutSessionWithFreshExpiry).

The same rule everywhere

Before accepting an order, the storefront locks the tracked variants with FOR UPDATE, in ascending identifier order to avoid deadlocks. Then it subtracts what the other orders are holding (reservedElsewhereByVariant), and compares the rest with the stock (findTrackedStockShortage). The cart does the same subtraction before showing what’s left, so it doesn’t promise a piece that payment will refuse. In the ERP, variant changes go through the same rule. In-store sales don’t: they take the piece from the raw stock, then close the Stripe sessions that were holding it (releaseSoldReservations). So do limited-use promo codes: a paid session whose event arrives hours later keeps its code until then (promotion-redemptions.ts).

Not blocking yourself

A customer who comes back from Stripe to fix her email address shouldn’t be blocked by her own hold. So the pending order from her browser (kept in the sealed cart) doesn’t count against her, nor, when she is signed in to her account, the ones placed with the same address. As soon as she opens a new session, her earlier sessions on the same pieces are closed (supersedeEarlierSessions). An address typed by a guest proves nothing: it lifts no hold and closes nobody’s session, otherwise a stranger who knows a customer’s address could close her payment page (CheckoutGuard#isEmailProven).

The display stays the same

The product page and the “Available” figure in the ERP still show the raw stock. If the stock is enough but a payment in progress is holding the piece, checkout says exactly that (StockShortage.isInPayment). It doesn’t mention a shortage.

The results

Now the second buyer is refused before paying. Before, she was charged and then refunded. apps/site/test/db/tracked-stock-reservation.db.test.ts replays the situation on a real database. A one-of-a-kind piece produces a single order. An order created while waiting for the lock is seen when the stock is read again. The piece comes back when the session expires or when the window has passed. A customer who starts over doesn’t block themselves, and an order from another browser still holds the piece.

There’s nothing to clean up. There’s no reservation column, no expiry job and no release path to maintain. An abandoned order stops holding anything, even if no code ever touches it again.

A test also checks the lock order: apps/erp/test/variant-lock-order.regression.test.ts reads through checkout, batch counting and off-site sales.

And if a piece is still missing at collection time, it shows. The ERP collects the payment, marks the line as out of stock and raises the webhook.stock alert (webhook-session.service.ts).

The limits

  • On every read, we recompute the holds by aggregating pending orders. At the volume of one store, that’s a few rows. A large shop would need a dedicated index or a counter.
  • The three-day window can hold a piece for nothing if the expiry event gets lost. In that case, the piece stays blocked until the window ends, or until the team closes the session. That’s what the daily check’s alert is for.
  • A guest who resumes payment from another device is blocked by their own hold until the first session expires: only the account proves two orders come from the same person.
  • A payment left pending holds its pieces. One connection holds at most CHECKOUT_MAX_RESERVED_PIECES_PER_IP, on top of the cap on pending orders: three full carts never paid used to freeze the whole online stock.

On this page