PotaLab
← All examples
SnippetTransactionsData APIWebhooksNext.js

Timed ticket hold

A hold is a row with an expiry, taken in one short transaction, never an open transaction waiting for payment. Expiry is lazy: a hold stops counting the moment it ends, with no job needed. The payment provider calls a webhook (signature checked, idempotent) that turns the hold into gapless ticket numbers; a payment that arrives late is flagged for refund instead of overselling.

Tested with many simultaneous buyers: holds, payments and delayed callbacks (including duplicates and late payments) never confirmed more tickets than the capacity, and ticket numbers had no gaps. The webhook secret in the schema is a placeholder: keep the real one in a secret store. One project, one environment: a correctness check, not a performance guarantee. See the Transactions docs.

localhost:3000/tickets

Summer concert

$20.00 per ticket. 6 tickets left

Held for a short time so you can pay.

    A hold is a row with an expiry, not an open transaction. The payment webhook confirms it; after the timer the tickets go back on sale on their own.

    Preview · sample data
    'use client'
    import { useEffect, useState } from 'react'
    import { createBrowserClient } from '@potalab/base/next'
    const createBase = () =>
    createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY! })
    type Hold = { id: string; qty: number; status: string; expires_at: string }
    export function Tickets({ eventId }: { eventId: number }) {
    const base = createBase()
    const [available, setAvailable] = useState<number | null>(null)
    const [holds, setHolds] = useState<Hold[]>([])
    const [tickets, setTickets] = useState<{ number: number }[]>([])
    const [now, setNow] = useState(() => Date.now())
    const [message, setMessage] = useState('')
    // One request, one consistent snapshot of my holds and tickets (RLS: only mine).
    async function load() {
    const r = await base.transaction((tx) => ({
    holds: tx.from('tix_holds').select('id', 'qty', 'status', 'expires_at').eq('event_id', eventId).order('created_at', { ascending: false }),
    tickets: tx.from('tix_tickets').select('number').eq('event_id', eventId).order('number'),
    }))
    setHolds(r.of(r.value.holds).rows as Hold[])
    setTickets(r.of(r.value.tickets).rows as { number: number }[])
    const left = await base.rpc('tix_available', { p_event_id: eventId })
    setAvailable(left.data as number)
    }
    useEffect(() => {
    void load()
    const t = setInterval(() => setNow(Date.now()), 1000) // countdown only; the server decides what is expired
    return () => clearInterval(t)
    }, [])
    // A hold is a ROW with an expiry, taken in one short transaction (tix_hold). Nothing stays open afterwards.
    async function hold(qty: number) {
    const { error } = await base.rpc('tix_hold', { p_event_id: eventId, p_qty: qty, p_ttl_seconds: 600 })
    if (error?.message?.includes('tix_sold_out')) setMessage('Not enough tickets left.')
    else if (error?.message?.includes('tix_user_limit')) setMessage('At most 4 tickets per person.')
    else if (error) throw error
    else setMessage('Held for 10 minutes. Pay before the timer ends.')
    await load()
    }
    // Creates a pending payment intent (amount from the catalog). The provider calls our webhook when the money arrives.
    async function pay(holdId: string) {
    const { data, error } = await base.rpc('tix_start_payment', { p_hold_id: holdId })
    if (error?.message?.includes('tix_hold_not_active')) setMessage('The hold expired. Tickets went back on sale.')
    else if (error) throw error
    else window.location.href = `https://pay.example.com/checkout/${(data as { provider_ref: string }).provider_ref}`
    await load()
    }
    const left = (h: Hold) => Math.max(0, Math.round((Date.parse(h.expires_at) - now) / 1000))
    return (
    <section>
    <p>{available ?? '...'} tickets left</p>
    <button onClick={() => hold(2)}>Hold 2 tickets</button>
    <ul>
    {holds.map((h) => (
    <li key={h.id}>
    {h.qty} tickets, {h.status === 'held' && left(h) > 0 ? `${left(h)} s left` : h.status === 'held' ? 'expired' : h.status}
    {h.status === 'held' && left(h) > 0 && <button onClick={() => pay(h.id)}>Pay</button>}
    </li>
    ))}
    </ul>
    {tickets.length > 0 && <p>Your tickets: {tickets.map((t) => `#${t.number}`).join(', ')}</p>}
    <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: Live cursors and presence →