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.
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.
'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> )}// app/shop/page.tsx (Server Component)import { redirect } from 'next/navigation'import { baseServer } from '@/lib/base-server'import { Shop } from './Shop'
export default async function ShopPage() { const base = await baseServer() const { data: { user } } = await base.auth.getUser() if (!user) redirect('/login') // orders need a signed-in user (RLS: user_id = auth.uid())
return ( <main> <h1>Shop</h1> <Shop /> </main> )}// Variant: interactive transaction (Go and Pro on Cloud, Community self-host).// Use it when your code must READ data before deciding what to write.// base.transaction() in Shop.tsx is cheaper and faster; prefer it when the database can decide// (.expect, .when, { $inc }, a SQL function).import { createBrowserClient } from '@potalab/base/next'
const base = createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY!,})
export async function checkoutInteractive(lines: { product_id: number; qty: number }[]) { // Same rule as the one-request form: lock stock rows in product_id order. const sorted = [...lines].sort((a, b) => a.product_id - b.product_id)
// Awaited statements resolve with data and reject on error. If the callback throws, everything // rolls back. A deadlock or serialization failure (409) re-runs the WHOLE callback (retries: 3), // so keep it free of side effects outside the database. Limit: 5 s on Go, 10 s on Pro/Community. return base.transaction.interactive(async (tx) => { const order = await tx.from('shop_orders').insert({}).select('id').single()
for (const l of sorted) { const row = await tx.from('shop_inventory').select('qty').eq('product_id', l.product_id).forUpdate().single() if (row.qty < l.qty) throw new Error(`out of stock: product ${l.product_id}`) // rolls back await tx.from('shop_inventory').update({ qty: row.qty - l.qty }).eq('product_id', l.product_id) await tx.from('shop_order_items').insert({ order_id: order.id, ...l }) }
await tx.from('shop_orders').update({ status: 'paid' }).eq('id', order.id) return order.id }, { isolation: 'read committed', retries: 3 })}// lib/base-server.ts// One client PER REQUEST: it holds the signed-in user's session.import { cookies } from 'next/headers'import { createServerClient } from '@potalab/base/next'
export async function baseServer() { const store = await cookies() return createServerClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY!, // pb_pub_... cookies: { getAll: () => store.getAll(), setAll: (list) => list.forEach((c) => store.set(c.name, c.value, c.options)), }, })}-- Products, stock, orders. Prices and totals are computed by the database, never trusted from the client.create table public.shop_products ( id bigint generated always as identity primary key, name text not null unique, price numeric(12,2) not null check (price >= 0));create table public.shop_inventory ( product_id bigint primary key references public.shop_products (id) on delete cascade, qty int not null check (qty >= 0) -- last line of defence: stock can never go negative);create table public.shop_orders ( id uuid primary key default gen_random_uuid(), user_id uuid not null default auth.uid(), status text not null default 'pending' check (status in ('pending', 'paid', 'cancelled')), total numeric(12,2) not null default 0 check (total >= 0), created_at timestamptz not null default now());create table public.shop_order_items ( id bigint generated always as identity primary key, order_id uuid not null references public.shop_orders (id) on delete cascade, product_id bigint not null references public.shop_products (id), qty int not null check (qty > 0), price numeric(12,2) not null default 0);
-- price comes from the catalog; a price sent by the client is overwrittencreate function public.shop_item_price() returns triggerlanguage plpgsql security invoker set search_path = '' as $$begin select p.price into new.price from public.shop_products p where p.id = new.product_id; if new.price is null then raise exception 'unknown product' using errcode = '23503'; end if; return new;end $$;create trigger shop_item_price before insert on public.shop_order_items for each row execute function public.shop_item_price();
-- order total is accrued here. DEFINER because clients have no UPDATE right on "total";-- it is a trigger function, so it is not callable as an API function.create function public.shop_item_total() returns triggerlanguage plpgsql security definer set search_path = '' as $$begin update public.shop_orders o set total = o.total + new.price * new.qty where o.id = new.order_id; return new;end $$;revoke all on function public.shop_item_total() from public;create trigger shop_item_total after insert on public.shop_order_items for each row execute function public.shop_item_total();
-- Conditional decrement as a function (Shop.tsx does the same with { $inc } + .expect(), without it): the UPDATE takes the row-- lock and checks the stock in ONE statement. No read-then-write, so two buyers can never both see "1 left". SECURITY INVOKER.create function public.shop_take_stock(p_product_id bigint, p_qty int) returns intlanguage plpgsql security invoker set search_path = '' as $$declare v_left int;begin if p_qty is null or p_qty <= 0 then raise exception 'bad qty' using errcode = '22023'; end if; update public.shop_inventory set qty = qty - p_qty where product_id = p_product_id and qty >= p_qty returning qty into v_left; if not found then raise exception 'out of stock: product %', p_product_id using errcode = 'P0001'; -- rolls the whole transaction back end if; return v_left;end $$;revoke all on function public.shop_take_stock(bigint, int) from public;grant execute on function public.shop_take_stock(bigint, int) to authenticated;
-- A signed-in user may only DECREASE stock (never restock). Admin roles are unrestricted.create function public.shop_inventory_guard() returns triggerlanguage plpgsql security invoker set search_path = '' as $$begin if current_user in ('anon', 'authenticated') and new.qty > old.qty then raise exception 'stock cannot increase' using errcode = '42501'; end if; return new;end $$;create trigger shop_inventory_guard before update on public.shop_inventory for each row execute function public.shop_inventory_guard();
-- RLS + grantsalter table public.shop_products enable row level security;alter table public.shop_inventory enable row level security;alter table public.shop_orders enable row level security;alter table public.shop_order_items enable row level security;
create policy shop_products_read on public.shop_products for select to anon, authenticated using (true);create policy shop_inventory_read on public.shop_inventory for select to authenticated using (true);create policy shop_inventory_take on public.shop_inventory for update to authenticated using (true) with check (true);create policy shop_orders_select on public.shop_orders for select to authenticated using (user_id = (select auth.uid()));create policy shop_orders_insert on public.shop_orders for insert to authenticated with check (user_id = (select auth.uid()));create policy shop_orders_update on public.shop_orders for update to authenticated using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));create policy shop_items_select on public.shop_order_items for select to authenticated using (exists (select 1 from public.shop_orders o where o.id = order_id and o.user_id = (select auth.uid())));create policy shop_items_insert on public.shop_order_items for insert to authenticated with check (exists (select 1 from public.shop_orders o where o.id = order_id and o.user_id = (select auth.uid())));
revoke all on public.shop_products, public.shop_inventory, public.shop_orders, public.shop_order_items from anon, authenticated;grant select on public.shop_products to anon, authenticated;grant select on public.shop_inventory to authenticated;grant update (qty) on public.shop_inventory to authenticated;grant select, insert on public.shop_orders, public.shop_order_items to authenticated;grant update (status) on public.shop_orders to authenticated;
-- Known limit: a signed-in user can still call shop_take_stock without buying (denial of stock).-- Stricter variant: make shop_inventory read-only and decrement inside a trigger on shop_order_items.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 →