"The House Across the Street" has been fully booked since the first day of the course. Whoever reaches its event page reads "Fully booked" and leaves, and if someone cancels tomorrow, that spot is left free for the first person who happens to drop by. In a municipal theater, that means empty seats and people who wanted to go.
You're going to build a waitlist end to end: data with concurrency, actions, an interface with an optimistic state, email that can't be lost, and tests. It's a small feature chosen for a reason: it touches every layer of the application, and each one must respect the rules you wrote in the previous lesson. If it fits without forcing anything, the architecture works. At the end, the portal's other gaps are closed.
- Deciding before programming
A waitlist seems obvious until you ask the questions:
| Question | Options | Decision |
|---|---|---|
| When a spot frees up, is it offered or assigned? | Offering needs a deadline to answer, and another one for the next person | It's assigned: whoever joins has already said they want to go. If they can't, they cancel |
| Who goes first? | Strict order, or the first one who fits | In order, skipping anyone who asks for more spots than there are |
| What if the person skipped never gets served? | Hold spots for them until there are enough | They aren't held: an empty seat doesn't help anyone |
| Until when? | Until the start, or earlier | Until two hours before: nobody should find out too late |
| Can you book without going through the queue? | Yes or no | Yes, if there are spots left after serving it |
| Can people see their position? | Yes, no, approximately | Yes. It reveals nothing about anyone else |
The second one is worth discussing with whoever commissions the product, because it's a question of fairness and not of programming: with strict order, a family of four at the front of the queue would block single spots for weeks. The chosen rule is defensible and can be explained in one sentence, which is what you ask of a rule.
The last column of the first row has a technical consequence. If we assign without asking, notifying becomes an obligation: someone who doesn't know they have a spot will leave it empty. Because of 07-04, that rules out plain after.
- The tables
// lib/db/schema.ts (addition; import primaryKey if it wasn't already)
export const waitlist = pgTable(
'waitlist',
{
eventId: text('event_id').notNull().references(() => events.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
seq: integer('seq').notNull().generatedAlwaysAsIdentity(),
spots: integer('spots').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
primaryKey({ columns: [table.eventId, table.userId] }),
index('waitlist_seq_idx').on(table.eventId, table.seq),
check('waitlist_positive_spots', sql`${table.spots} > 0`),
],
)
export const NOTIFICATION_TYPES = ['spot-assigned'] as const
// What we owe someone and haven't told them yet
export const pendingNotifications = pgTable(
'pending_notifications',
{
id: text('id').primaryKey().default(generatedId),
type: text('type', { enum: NOTIFICATION_TYPES }).notNull(),
eventId: text('event_id').notNull().references(() => events.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
attempts: integer('attempts').notNull().default(0),
nextAttempt: timestamp('next_attempt', { withTimezone: true }).notNull().defaultNow(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
sentAt: timestamp('sent_at', { withTimezone: true }),
},
(table) => [
index('pending_notifications_idx').on(table.nextAttempt).where(sql`${table.sentAt} is null`),
],
)
// lib/db/client.ts (addition)
export type Transaction = Parameters<Parameters<Database['transaction']>[0]>[0]- The primary key is the pair of event and user: one person, one place in the queue. It plays the role of the bookings'
unique. - The order is a number the database sets, not a date. In PostgreSQL,
now()is the time the transaction started: if two compete for the lock, the one who arrived first could end up behind. The number is assigned on insert, once the turn has been obtained. - The outbox index is partial. It only contains what's waiting to be sent, which is a handful of rows even if the table piles up years.
enumon atextcolumn only affects the TypeScript type. Adding a value in 11-03 won't require a migration.onDelete: 'cascade'because this is accessory data: if the person disappears, it disappears. Bookings don't have it, on purpose.
- Allocating
The heart of the feature is what happens when spots are freed. It's called from several places (canceling and, in 11-03, increasing the capacity), always inside the transaction that frees them. That's why it takes tx: it can't be used any other way.
// lib/rules/waitlist.ts — neutral: the interface uses it too
const MIN_NOTICE = 2 * 60 * 60 * 1000
export function isWaitlistOpen(startsAt: Date, now: Date): boolean {
return startsAt.getTime() - now.getTime() >= MIN_NOTICE
}// lib/data/allocation.ts
import 'server-only'
import { and, asc, eq, inArray } from 'drizzle-orm'
import type { Transaction } from '@/lib/db/client'
import { bookings, events, pendingNotifications, waitlist } from '@/lib/db/schema'
import { isWaitlistOpen } from '@/lib/rules/waitlist'
export interface Allocation {
spotsLeft: number // The ones left afterwards
assigned: number // People served
}
// No permission check: it can only be called inside an operation that already did one
export async function allocateSpots(tx: Transaction, eventId: string): Promise<Allocation> {
const [event] = await tx
.select({ status: events.status, startsAt: events.startsAt, spotsLeft: events.spotsLeft })
.from(events)
.where(eq(events.id, eventId))
.for('update')
if (!event) return { spotsLeft: 0, assigned: 0 }
if (event.status !== 'published' || !isWaitlistOpen(event.startsAt, new Date())) {
return { spotsLeft: event.spotsLeft, assigned: 0 }
}
const queue = await tx
.select({ userId: waitlist.userId, spots: waitlist.spots })
.from(waitlist)
.where(eq(waitlist.eventId, eventId))
.orderBy(asc(waitlist.seq))
.for('update') // Anyone leaving at this very moment either leaves or waits
let spotsLeft = event.spotsLeft
const served = queue.filter(({ spots }) => {
if (spots > spotsLeft) return false
spotsLeft -= spots
return true
})
if (served.length === 0) return { spotsLeft, assigned: 0 }
const people = served.map(({ userId }) => userId)
await tx
.delete(waitlist)
.where(and(eq(waitlist.eventId, eventId), inArray(waitlist.userId, people)))
await tx.insert(bookings).values(served.map((entry) => ({ ...entry, eventId })))
await tx.insert(pendingNotifications).values(
people.map((userId) => ({ type: 'spot-assigned' as const, eventId, userId })),
)
await tx.update(events).set({ spotsLeft }).where(eq(events.id, eventId))
return { spotsLeft, assigned: served.length }
}- The event lock is once again the single gate. Booking, canceling, joining and allocating all go through it; two at once on the same event take turns.
- The notification is written with the booking. If the transaction commits, it exists; if it's rolled back, so is the notification. This is the outbox that 07-04 left as a sketch.
filterwith a variable that changes isn't elegant, but it's exactly the rule: go through in order and serve whoever fits.- There's no email here. No external call while a row is locked.
// lib/data/bookings.ts, changes
// In createBooking, step 4, after inserting the booking: there's nothing left to wait for
await tx
.delete(waitlist)
.where(and(eq(waitlist.eventId, eventId), eq(waitlist.userId, user.id)))
// In cancelBooking, after the UPDATE that gives the spots back
const allocation = await allocateSpots(tx, canceled.eventId)
return {
status: 'canceled',
spotsBefore: event.spotsLeft - canceled.spots,
spotsAfter: allocation.spotsLeft,
assigned: allocation.assigned,
}
// CancellationResult, 'canceled' case: + assigned: numberuser is what ensureUser() has returned at the start of the function since 08-04. notifyIfAvailabilityChanges(0, 0) does nothing, and that's correct: if the canceled spot went to someone else, the listings keep saying "Fully booked" without having been wrong for a single moment.
3.1. Joining and leaving
// lib/data/waitlist.ts
import 'server-only'
import { and, count, eq, lte } from 'drizzle-orm'
import { ensureUser } from '@/lib/authorization'
import { getDb } from '@/lib/db/client'
import { bookings, events, waitlist } from '@/lib/db/schema'
import { isWaitlistOpen } from '@/lib/rules/waitlist'
export interface MyWaitlistEntry {
spots: number
position: number
}
export type WaitlistResult =
| { status: 'joined' }
| { status: 'spots-available'; spotsLeft: number }
| { status: 'already-joined' | 'already-booked' | 'unavailable' }
export async function addToWaitlist(eventId: string, spots: number): Promise<WaitlistResult> {
const user = await ensureUser()
const db = await getDb()
return db.transaction(async (tx): Promise<WaitlistResult> => {
const [event] = await tx
.select({ status: events.status, startsAt: events.startsAt, spotsLeft: events.spotsLeft })
.from(events)
.where(eq(events.id, eventId))
.for('update')
if (event?.status !== 'published' || !isWaitlistOpen(event.startsAt, new Date())) {
return { status: 'unavailable' }
}
const [booking] = await tx
.select({ id: bookings.id })
.from(bookings)
.where(and(eq(bookings.eventId, eventId), eq(bookings.userId, user.id)))
if (booking) return { status: 'already-booked' }
if (event.spotsLeft >= spots) return { status: 'spots-available', spotsLeft: event.spotsLeft }
const inserted = await tx
.insert(waitlist)
.values({ eventId, userId: user.id, spots })
.onConflictDoNothing()
.returning({ seq: waitlist.seq })
return { status: inserted.length > 0 ? 'joined' : 'already-joined' }
})
}
// Idempotent: leaving twice is leaving
export async function removeFromWaitlist(eventId: string): Promise<boolean> {
const user = await ensureUser()
const db = await getDb()
const deleted = await db
.delete(waitlist)
.where(and(eq(waitlist.eventId, eventId), eq(waitlist.userId, user.id)))
.returning({ seq: waitlist.seq })
return deleted.length > 0
}
export async function getMyWaitlistEntry(eventId: string): Promise<MyWaitlistEntry | null> {
const user = await ensureUser()
const db = await getDb()
const forThisEvent = eq(waitlist.eventId, eventId)
const [mine] = await db
.select({ spots: waitlist.spots, seq: waitlist.seq })
.from(waitlist)
.where(and(forThisEvent, eq(waitlist.userId, user.id)))
if (!mine) return null
const [{ position }] = await db
.select({ position: count() })
.from(waitlist)
.where(and(forThisEvent, lte(waitlist.seq, mine.seq)))
return { spots: mine.spots, position }
}They all find out who's asking, and none of them takes a userId. listMyWaitlistEntries() is missing: the join of the two tables filtered by the person, published events and a future start, in date order. Write it using listMyBookings as a model. removeFromWaitlist doesn't need to lock the event: if it coincides with an allocation, the queue row decides. Either the person leaves first and the allocation no longer sees them, or the allocation deletes the row first and leaving finds nothing, in which case the person has a booking and will get an email.
- The outbox
// lib/data/pending-notifications.ts — tasks: no session
import 'server-only'
import { and, asc, eq, inArray, isNull, lt, lte, sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { bookings, events, pendingNotifications, users, venues } from '@/lib/db/schema'
const MAX_ATTEMPTS = 8
export async function takeNotifications(max: number) {
const db = await getDb()
const ids = await db.transaction(async (tx) => {
const rows = await tx
.select({ id: pendingNotifications.id })
.from(pendingNotifications)
.where(
and(
isNull(pendingNotifications.sentAt),
lt(pendingNotifications.attempts, MAX_ATTEMPTS),
lte(pendingNotifications.nextAttempt, sql`now()`),
),
)
.orderBy(asc(pendingNotifications.nextAttempt))
.limit(max)
.for('update', { skipLocked: true })
const taken = rows.map(({ id }) => id)
if (taken.length > 0) {
await tx
.update(pendingNotifications)
.set({
attempts: sql`${pendingNotifications.attempts} + 1`,
// 5, 10, 20, 40 minutes… If the process dies, the row comes back on its own
nextAttempt: sql`now() + interval '5 minutes' * power(2, ${pendingNotifications.attempts})`,
})
.where(inArray(pendingNotifications.id, taken))
}
return taken
})
if (ids.length === 0) return []
return db
.select({
id: pendingNotifications.id,
type: pendingNotifications.type,
email: users.email,
title: events.title,
slug: events.slug,
status: events.status,
startsAt: events.startsAt,
venue: venues.name,
spots: bookings.spots, // null if they no longer have a booking
})
.from(pendingNotifications)
.innerJoin(users, eq(pendingNotifications.userId, users.id))
.innerJoin(events, eq(pendingNotifications.eventId, events.id))
.innerJoin(venues, eq(events.venueId, venues.id))
.leftJoin(
bookings,
and(
eq(bookings.eventId, pendingNotifications.eventId),
eq(bookings.userId, pendingNotifications.userId),
),
)
.where(inArray(pendingNotifications.id, ids))
}
export type OutgoingNotification = Awaited<ReturnType<typeof takeNotifications>>[number]
export async function markSent(id: string): Promise<void> {
const db = await getDb()
await db.update(pendingNotifications).set({ sentAt: sql`now()` }).where(eq(pendingNotifications.id, id))
}// lib/tasks/send-notifications.ts
import 'server-only'
import { sendEmail } from '@/lib/mail'
import { type OutgoingNotification, markSent, takeNotifications } from '@/lib/data/pending-notifications'
import { composeNotification } from '@/lib/compose-notification'
const BATCH_SIZE = 5
export async function sendNotifications(max = 20): Promise<{ sent: number; deferred: number }> {
const notifications = await takeNotifications(max)
let sent = 0
for (let i = 0; i < notifications.length; i += BATCH_SIZE) {
const results = await Promise.all(notifications.slice(i, i + BATCH_SIZE).map(sendOne))
sent += results.filter(Boolean).length
}
return { sent, deferred: notifications.length - sent }
}
async function sendOne(notification: OutgoingNotification): Promise<boolean> {
const message = composeNotification(notification)
if (message) {
const result = await sendEmail({
to: notification.email,
...message,
key: `notification:${notification.id}`,
})
if (result.status !== 'accepted') return false
}
await markSent(notification.id)
return true
}// lib/compose-notification.ts — pure, so it can be tested without a database or email
import { formatDateTime, formatSpots } from './format'
import { SITE_NAME, SITE_URL } from './site'
import type { OutgoingNotification } from '@/lib/data/pending-notifications'
export interface Message {
subject: string
text: string
}
// null: it no longer makes sense to send it
export function composeNotification(notification: OutgoingNotification): Message | null {
const eventUrl = new URL(`/events/${notification.slug}`, SITE_URL).href
const myBookingsUrl = new URL('/my-bookings', SITE_URL).href
const when = `${formatDateTime(notification.startsAt)}, at ${notification.venue}.`
switch (notification.type) {
case 'spot-assigned':
if (notification.spots === null || notification.status !== 'published') return null
return {
subject: `You've got a spot: ${notification.title}`,
text: [
`A spot has opened up and we've booked ${formatSpots(notification.spots)} in your name.`,
when,
`If you can't go, cancel at ${myBookingsUrl} and the spot will go to someone else.`,
eventUrl,
SITE_NAME,
].join('\n\n'),
}
}
}- The batch is taken in a short transaction and sent outside it.
skipLockedlets two simultaneous runs pick up different rows. - The data is read at send time. If the person canceled in the meantime,
spotsisnulland the notification is considered done without sending anything. - The idempotency key is the notification's identifier. If the process dies between sending and marking, the retry doesn't duplicate the message.
- Eight attempts are more than ten hours with this backoff. Whatever reaches the maximum stays there, unsent, and someone has to see it: it's the new alert in section 7. A permanent rejection, such as an address that doesn't exist, also uses up its eight attempts; telling it apart by the status code is an easy improvement, taking care not to include 401 and 403, which are usually the fault of our key.
- The type import (
import type) disappears at build time, socompose-notification.tsdoesn't drag inserver-only. - The
switchhas nodefault. When 11-03 adds a notification type, TypeScript will point out that this function can end without returning anything.
The endpoint is missing: app/api/tasks/send-notifications/route.ts. It's a copy of the cleanup one from 07-04 (key, guarded, log('info', 'notifications.sent', …)) that calls sendNotifications() and declares maxDuration = 120: that's four batches, and each email can take 20 seconds to give up. The scheduler will call it every five minutes (11-04 and 11-05). It's the safety net; normally the notification goes out right away, because the action also triggers it with after.
- The actions
// actions/waitlist.ts
'use server'
import { refresh } from 'next/cache'
import { addToWaitlist, removeFromWaitlist } from '@/lib/data/waitlist'
// … plus the same imports as actions/bookings.ts
export type WaitlistState = FormState<'spots'>
export async function joinWaitlist(
eventId: string,
_previous: WaitlistState,
formData: FormData,
): Promise<WaitlistState> {
const values = readTextFields(formData, ['spots'])
const reject = (message: string, spots?: string[]): WaitlistState => ({
status: 'error', message, errors: { spots }, values,
})
const user = await getCurrentUser()
if (!user) return reject('Sign in to join the waitlist.')
if (!identifier.safeParse(eventId).success) return reject('Invalid event.')
const { maxSpotsPerBooking: max } = readEnv()
const parsed = z.object({ spots: integer({ min: 1, max }) }).safeParse(values)
if (!parsed.success) {
return reject("You haven't joined the waitlist.", z.flattenError(parsed.error).fieldErrors.spots)
}
if (!(await withinLimits(writeLimits(user.id)))) {
return reject("You're going too fast. Please wait a minute.")
}
const { spots } = parsed.data
const result = await addToWaitlist(eventId, spots)
refresh()
switch (result.status) {
case 'joined':
audit(user.id, 'waitlist.joined', eventId)
return {
status: 'success',
message: `We'll email you if ${formatSpots(spots)} open up.`,
}
case 'spots-available':
return reject(`${formatSpots(result.spotsLeft)} just opened up: you can book.`)
case 'already-joined':
return reject("You're already on the waitlist.")
case 'already-booked':
return reject('You already have a booking for this event.')
case 'unavailable':
return reject('The waitlist for this event is closed.')
}
}
export async function leaveWaitlist(eventId: string): Promise<void> {
const user = await getCurrentUser()
if (!user || !identifier.safeParse(eventId).success) throw new Error('Invalid request')
if (await removeFromWaitlist(eventId)) audit(user.id, 'waitlist.left', eventId)
refresh()
}
// actions/bookings.ts, in cancelMyBooking, if the status is 'canceled'
if (result.assigned > 0) afterResponse('send notifications', () => sendNotifications(5))
// app/(public)/my-bookings/page.tsx: the cancel action runs on this route
export const maxDuration = 30It's the anatomy from 08-06 step by step, and that's why it reads effortlessly. Add waitlist.joined and waitlist.left to AuditedAction. sendNotifications(5) is a single batch, which fits in the 30 seconds; the task will pick up the rest.
Whoever cancels doesn't need to know that their spot went to someone else, and they aren't told. Nor do they wait for the email to go out.
- The interface
// app/(public)/events/_components/event-booking.tsx (complete)
export async function EventBooking({ event }: { event: AgendaEvent }) {
if (event.status === 'canceled') return null
const user = await getCurrentUser()
const [booking, availability, entry] = await Promise.all([
user ? getMyBooking(event.id) : null,
getAvailability(event.slug),
user ? getMyWaitlistEntry(event.id) : null,
])
const now = new Date()
if (!booking && (!availability || event.endsAt <= now)) return null
const spotsLeft = availability?.spotsLeft ?? 0
const canWait = !booking && spotsLeft === 0 && isWaitlistOpen(event.startsAt, now)
if (!user) {
if (spotsLeft === 0 && !canWait) return null
return (
<Link href={signInPath(`/events/${event.slug}`)} className="underline">
{spotsLeft > 0 ? 'Sign in to book' : 'Sign in to join the waitlist'}
</Link>
)
}
const { maxSpotsPerBooking } = readEnv()
return (
<>
<BookingPanel
eventId={event.id}
slug={event.slug}
bookedSpots={booking?.spots ?? null}
max={Math.min(maxSpotsPerBooking, spotsLeft)}
/>
<WaitlistPanel
eventId={event.id}
entry={entry}
open={canWait}
max={maxSpotsPerBooking}
/>
</>
)
}// app/(public)/events/_components/waitlist-panel.tsx
'use client'
import { useActionState, useEffect, useOptimistic, useRef, useState, useTransition } from 'react'
import { joinWaitlist, leaveWaitlist } from '@/actions/waitlist'
// … Field, SubmitButton, FormMessage, BUTTON, TEXT_FIELD, formatSpots, INITIAL_STATE
interface Props {
eventId: string
entry: { spots: number; position: number } | null
open: boolean
max: number
}
export function WaitlistPanel({ eventId, entry, open, max }: Props) {
const [state, formAction] = useActionState(joinWaitlist.bind(null, eventId), INITIAL_STATE)
const [visible, update] = useOptimistic(entry)
const [notice, setNotice] = useState('')
const [, startTransition] = useTransition()
const box = useRef<HTMLParagraphElement>(null)
const error = state.status === 'error' ? state : null
useEffect(() => {
if (notice) box.current?.focus() // The button that had focus is gone
}, [notice])
function handleLeave() {
setNotice('')
startTransition(async () => {
update(null)
let message = "You've left the waitlist."
try {
await leaveWaitlist(eventId)
} catch {
message = "We couldn't take you off the waitlist. Please try again."
}
startTransition(() => setNotice(message))
})
}
// A "we'll let you know" stops being true as soon as you leave
const shown = state.status === 'success' && !visible ? INITIAL_STATE : state
return (
<section aria-label="Waitlist" className="mt-4">
<FormMessage state={shown} />
<p ref={box} role="status" tabIndex={-1}>{notice}</p>
{visible && (
<>
<p>
You're on the waitlist for {formatSpots(visible.spots)}. Your position is{' '}
{visible.position}.
</p>
<button type="button" onClick={handleLeave} className={BUTTON.secondary}>
Leave the waitlist
</button>
</>
)}
{!visible && open && (
<form action={formAction}>
<p>If someone cancels, we'll assign you the spots and email you.</p>
<Field label="Spots you need" errors={error?.errors.spots}>
{(attributes) => (
<input
{...attributes}
type="number" name="spots" min={1} max={max} required
defaultValue={error?.values.spots ?? '1'}
className={TEXT_FIELD}
/>
)}
</Field>
<SubmitButton pendingText="Joining…" className={BUTTON.primary}>
Join the waitlist
</SubmitButton>
</form>
)}
</section>
)
}- Joining isn't optimistic; leaving is. The first can be rejected for a real reason, and we say so with the pending button. The second almost never fails, and if it does, the block comes back with its explanation (06-04).
- Both panels are always mounted in the same position. When a spot is assigned or the others run out, the props change and the messages are kept.
- Without JavaScript, joining works, because
actionreceives the action directly. Leaving doesn't; it can be done, for example, from another device, or the button could be turned into a form if it mattered. event.statuscomes from the cached event page, and that's enough:cancelEventwill invalidate it. The data that decides is read uncached.- The label says "Spots you need", different from "Spots", so that tests and a screen reader can tell the two fields apart.
On /my-bookings, add another block below the list, with its own <Suspense>, that renders listMyWaitlistEntries() as links to each event page. It's a fifteen-line Server Component, just like UserBookings.
- Tests and monitoring
The delicate part is the allocation, and it's tested where it happens. Extract the beforeEach from 10-03 into tests/db/data.ts (prepareData(): an event e with one spot, and the people ana, bruno and carla) and add a delete for the two new tables:
// tests/db/waitlist.test.ts (vi.mock of authorization and actingAs(), same as in bookings.test.ts)
beforeEach(prepareData)
async function book(person: string): Promise<string> {
const result = await actingAs(person, () => createBooking('e', 1))
if (result.status !== 'booked') throw new Error('The booking should have been made')
return result.bookingId
}
async function spotsOf(person: string): Promise<number | undefined> {
const db = await getDb()
const [row] = await db
.select({ spots: bookings.spots })
.from(bookings)
.where(and(eq(bookings.eventId, 'e'), eq(bookings.userId, person)))
return row?.spots
}
test('the canceled spot goes to the first person who fits', async () => {
const id = await book('ana')
await actingAs('bruno', () => addToWaitlist('e', 3)) // Earlier, but doesn't fit
await actingAs('carla', () => addToWaitlist('e', 1))
expect(await actingAs('ana', () => cancelBooking(id))).toMatchObject({ spotsAfter: 0, assigned: 1 })
expect(await spotsOf('carla')).toBe(1)
expect(await spotsOf('bruno')).toBeUndefined()
const db = await getDb()
expect(await db.select().from(pendingNotifications)).toMatchObject([
{ type: 'spot-assigned', userId: 'carla', sentAt: null },
])
})
test('leaving while spots are being allocated leaves a single consistent result', async () => {
const id = await book('ana')
await actingAs('bruno', () => addToWaitlist('e', 1))
const [canceled, left] = await Promise.all([
actingAs('ana', () => cancelBooking(id)),
actingAs('bruno', () => removeFromWaitlist('e')),
])
if (canceled.status !== 'canceled') throw new Error('It should have been canceled')
// Either they left and have no spot, or the spot reached them and there was nothing to leave
expect(left).toBe(canceled.assigned === 0)
expect(await spotsOf('bruno')).toBe(left ? undefined : 1)
})
test('if there are spots, nobody queues', async () => {
expect(await actingAs('ana', () => addToWaitlist('e', 1))).toEqual({ status: 'spots-available', spotsLeft: 1 })
})// e2e/waitlist.spec.ts
import { ACCOUNTS } from './accounts'
import { expect, test } from './base'
test.use({ storageState: ACCOUNTS.visitor.file })
test('joining and leaving the waitlist', async ({ page }) => {
await page.goto('/events/the-house-across-the-street')
await page.getByRole('spinbutton', { name: 'Spots you need' }).fill('2')
await page.getByRole('button', { name: 'Join the waitlist' }).click()
await expect(page.getByRole('status').filter({ hasText: "We'll email you" })).toBeVisible()
const leave = page.getByRole('button', { name: 'Leave the waitlist' })
await leave.click()
await expect(page.getByRole('status').filter({ hasText: "You've left" })).toBeVisible()
await page.reload()
await expect(page.getByRole('button', { name: 'Join the waitlist' })).toBeVisible()
await expect(leave).toHaveCount(0)
})The second test doesn't say who wins, because nobody knows. It says which combinations are impossible. That's the right way to test a race: run it many times (with the { repeats: 20 } option as the second argument to test) and remove the queue's .for('update') to watch it fail. In actions/bookings.test.ts you also have to mock @/lib/tasks/send-notifications.
composeNotification is tested at the unit level: with spots: null it returns null, with a canceled event too, and the text contains the time as the guide shows it.
For operations, a query and an alert: unsent notifications with a created_at older than 30 minutes ago. It's the requirement from 11-01 put into practice. Expose it as a metric, or add it to the daily report:
select count(*) from pending_notifications
where sent_at is null and created_at < now() - interval '30 minutes';
- Closing off the portal
With the feature finished, it's time to go over what surrounds it. This is the closing checklist, with what changes in each place:
| Piece | Does it change? | Why |
|---|---|---|
| Cache and tags | No | No new function is cached; the availability notifications are the usual ones |
EventCard |
No | "Fully booked" is still true |
| Metadata, JSON-LD, sitemap | No | The event page doesn't promise spots, which is why availability isn't published (09-04) |
v1 API |
No | hasSpots is calculated the same way |
routePattern |
No | There are no new public routes |
| CSP | No | There are no new domains |
| Entry points table from 08-06 | Two rows | joinWaitlist and leaveWaitlist; and the task |
| Budget | Measure | WaitlistPanel is loaded on every event page |
| Privacy policy | Yes | We store who's waiting, and we write to them |
The middle column is the test of the architecture: a new feature that touches every layer has left untouched the ones that weren't its business. If in your project a row like this fills up with "yes", responsibilities are mixed up.
The second-to-last one is settled by measuring with npm run budget. Since WaitlistPanel is only used on fully booked events, it could go behind next/dynamic; first, check how much it weighs. It shares almost all its code with BookingPanel, and splitting off two or three kilobytes would cost one more request precisely for whoever lands on a full event.
Common Mistakes and Tips
- Programming before deciding the allocation rule.
- Assigning without guaranteeing the notification.
- Ordering by
now()things that compete for a lock. - Sending the email inside the transaction.
- Allocating outside the transaction that frees the spots: another booking sneaks in between.
- Forgetting a path that frees spots. They all have to end in
allocateSpots. - Invalidating
eventsevery time someone joins: nothing public has changed. - Making optimistic what can be rejected.
- Leaving a success message that's already false.
- Retrying without a limit, or without anyone seeing what doesn't go out.
- Testing a race by expecting a winner.
Exercises
Exercise 1: offering instead of assigning
The client changes their mind: when a spot frees up, the first person must accept it within 12 hours; otherwise it goes to the next one. Describe what changes in the tables, in the allocation and in the tasks, and three new problems that come up.
Solution
The offered spot is neither free nor booked: it has to be deducted from spots_left and an offer with an expiry has to be stored. The simplest approach is to add an offered_until column to waitlist, and have allocateSpots fill it in and deduct instead of inserting the booking. Accepting creates the booking and deletes the row; declining, or a task that looks for expired offers every few minutes, gives the spot back and calls allocateSpots again.
Problems: (1) every offer holds capacity while waiting, and close to the start twelve hours is far too long: the deadline must shrink depending on the date; (2) accepting from a link in the email can't be a GET, because mail filters would open it (08-02): the link leads to a page with a button and requires a session; (3) the offer expires exactly while the person is clicking: the condition offered_until > now() goes in the where of the statement that consumes it, and the message has to explain it. Besides, people who don't check their email make the spot go round several times; that's the reason we chose to assign.
Exercise 2: password recovery
Build the recovery outlined in 08-02, section 10. Write the two functions in lib/data/accounts.ts and explain where each step runs so as not to reveal whether an account exists.
Solution
// lib/data/accounts.ts (import sessions)
const HALF_AN_HOUR = 30 * 60 * 1000
export async function createRecoveryLink(email: string): Promise<string | null> {
if (!(await findCredentials(email))) return null
const token = generateToken()
const db = await getDb()
await db.transaction(async (tx) => {
// Requesting another one invalidates the earlier ones
await tx
.delete(emailLinks)
.where(and(eq(emailLinks.email, email), eq(emailLinks.purpose, 'recovery')))
await tx.insert(emailLinks).values({
id: hashToken(token),
purpose: 'recovery',
email,
expiresAt: new Date(Date.now() + HALF_AN_HOUR),
})
})
return token
}
export async function redeemRecovery(token: string, hash: string): Promise<string | null> {
const db = await getDb()
return db.transaction(async (tx) => {
const [link] = await tx
.delete(emailLinks)
.where(
and(
eq(emailLinks.id, hashToken(token)),
eq(emailLinks.purpose, 'recovery'),
gt(emailLinks.expiresAt, new Date()),
),
)
.returning({ email: emailLinks.email })
if (!link) return null
const [user] = await tx
.update(users)
.set({ passwordHash: hash })
.where(eq(users.email, link.email))
.returning({ id: users.id })
if (!user) return null
await tx.delete(sessions).where(eq(sessions.userId, user.id))
await tx.delete(emailLinks).where(eq(emailLinks.email, link.email))
return user.id
})
}requestRecovery validates the email address, applies the sign-up limits, schedules the lookup and the sending with afterResponse, and always replies "If there's an account with that email address, you'll receive a message". Everything that depends on whether the account exists happens once the response has gone out, so neither the text nor the timing gives it away. resetPassword(token, …) copies completeSignUp: it validates the password, limits by IP, checks the token's shape, hashes and redeems. When it finishes it does not sign the person in: it redirects to /sign-in, and a second email reports the change, with a text that says what to do if it wasn't them who asked for it.
/sign-in/recover and /sign-in/reset go in (account). The second one carries the token in the address: add it to the no-referrer rule in next.config.ts (08-05). In routePattern they would end up as other, which is what you want, or they can be added to the fixed routes.
Conclusion
The waitlist runs through all of AgendaViva: two tables, an allocation that only exists inside a transaction, data functions that find out who's asking, actions with the usual anatomy, an interface that's optimistic where it can be, and an outbox that turns "we'll let you know" into something enforceable. The tests say which results are impossible, and the closing table shows that the cache, the metadata and the API haven't noticed a thing.
On the other side of the counter, organizers still can't fix a typo, see who's coming or call off an event. With the outbox and the allocation done, a good part of the work is already ahead: Building the Organizer Dashboard.
