PotaLab
← All examples
SnippetTransactionsData APIRLSNext.js

E-commerce: exact stock on purchase

A purchase is one base.transaction() request. Stock is taken with an atomic { $inc: -n } update guarded by qty >= n and .expect({ affected: 1 }), backed by CHECK (qty >= 0), so two buyers can never both get the last unit. Stock rows are locked in product_id order to avoid deadlocks, and prices and totals come from the database, not the client.

Tested with 100 simultaneous buyers over several rounds: stock never went negative, and final stock always equalled starting stock minus the units of successful orders. Carts sent unsorted produced deadlocks and lock timeouts in the same test; sorted carts produced none. One project, one environment: a correctness check, not a performance guarantee. See the Transactions docs.

localhost:3000/shop

Shop

Signed in as ann@acme.com

  • Sneaker $99.903 left
  • T-shirt $19.5012 left
  • Mug $9.001 left

One transaction: order, items, atomic stock decrement ($inc + expect), status. If any item is short, nothing is written.

Preview · sample data
'use client'
import { useState } from 'react'
import { createBrowserClient } from '@potalab/base/next'
import { TransactionError } from '@potalab/base'
import { useQuery } from '@potalab/base/react'
const createBase = () =>
createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY! })
export function Shop() {
const base = createBase()
const [cart, setCart] = useState<Record<number, number>>({})
const [message, setMessage] = useState('')
const products = useQuery(
base.from('shop_products').select('id,name,price,shop_inventory(qty)').order('id'),
)
async function checkout() {
// Sorted by product_id: every buyer locks stock rows in the same order, so two carts
// sharing products can never wait on each other (no deadlock).
const lines = Object.entries(cart)
.map(([id, qty]) => ({ product_id: Number(id), qty }))
.filter((l) => l.qty > 0)
.sort((a, b) => a.product_id - b.product_id)
if (lines.length === 0) return
try {
// One request, one Postgres transaction: all of it commits, or none of it does.
await base.transaction((tx) => {
const order = tx.from('shop_orders').insert({}).returning('id') // user_id = auth.uid() by default
for (const l of lines) {
tx.from('shop_order_items').insert({ order_id: order.ref('id'), ...l }) // price: set by the database
}
for (const l of lines) {
tx.from('shop_inventory')
.update({ qty: { $inc: -l.qty } }) // atomic qty = qty - n, no read-then-write race
.eq('product_id', l.product_id)
.gte('qty', l.qty) // only when there is enough stock ...
.expect({ affected: 1 }) // ... otherwise 0 rows: everything rolls back (409)
}
tx.from('shop_orders').update({ status: 'paid' }).eq('id', order.ref('id'))
}, { retry: 2 }) // optional: resend after a deadlock / lock timeout (nothing was committed)
setCart({})
setMessage('Order placed.')
} catch (e) {
if (e instanceof TransactionError && e.pgCode === 'BT409') setMessage('One item just sold out. Nothing was ordered.')
else if (e instanceof TransactionError && e.retryable) setMessage('Busy, please try again.')
else throw e
}
await products.refetch()
}
return (
<section>
<ul>
{products.data?.map((p) => (
<li key={p.id}>
{p.name} ${p.price}, {p.shop_inventory?.qty ?? 0} left
<input
type="number" min={0} value={cart[p.id] ?? 0}
onChange={(e) => setCart({ ...cart, [p.id]: Number(e.target.value) })}
/>
</li>
))}
</ul>
<button onClick={checkout}>Buy</button>
<p role="status">{message}</p>
</section>
)
}

Snippet for illustration, written for the Next.js App Router with @potalab/base/next,@potalab/base/react and @potalab/base. Set NEXT_PUBLIC_POTALAB_BASE_URL andNEXT_PUBLIC_POTALAB_BASE_KEY, adapt names and redirect URLs, and review policies before production.

Next: Meeting room booking →