Thirty Places, One Race: Event Capacity and Waitlists in Postgres / Dec 4, 2026
CREED Aberdeen is the empowerment platform of a church parish in Aberdeen, and describes itself as a training institute. I built its website and the application system behind it: each event defines its own application form, takes submissions, ranks them against a capacity and emails applicants their outcome. The site is live at creedaberdeen.uk.
The flagship programme is a machine learning bootcamp for teenagers with thirty places. That one number shaped a lot of the engineering, because places are finite, and two people applying at the same moment must not both take the last one.
The obvious version, and why it fails
The first version anyone writes looks like this:
const taken = await countActiveApplications(eventId);
if (taken >= event.capacity) return "full";
await insertApplication(eventId, applicant);
return "admitted";It reads well and it's wrong. Between the count and the insert, another request can do the same count. Both see one place left, both insert, and the event has 31 people.
It's easy to wave this away as rare. It's easy to reproduce, too. In Postgres 17, with a
deliberate one-second gap between the check and the insert to stand in for a busy server, two
simultaneous applications for one remaining place both come back admitted. Launch day for a
popular programme is exactly when applications arrive together.
Rank after the row exists
The approach CREED Aberdeen uses doesn't ask "is there room?" before writing. It writes every application first, then works out who is in by ranking them. Applications are ordered by submission time, and anything past the capacity goes to a waitlist with a position. Whichever request happens to run first, the same set of people is admitted.
Here is a simplified version of the idea in plain SQL:
CREATE TABLE applications (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id int NOT NULL REFERENCES events(id),
email text NOT NULL,
submitted_at timestamptz NOT NULL DEFAULT clock_timestamp(),
declined_at timestamptz,
UNIQUE (event_id, email) -- one application per person per event
);
CREATE VIEW application_outcomes AS
SELECT id, event_id, email,
CASE WHEN place <= capacity THEN 'admitted' ELSE 'waitlisted' END AS outcome,
CASE WHEN place > capacity THEN place - capacity END AS waitlist_position
FROM (
SELECT a.id, a.event_id, a.email, e.capacity,
ROW_NUMBER() OVER (PARTITION BY a.event_id ORDER BY a.submitted_at, a.id) AS place
FROM applications a
JOIN events e ON e.id = a.event_id
WHERE a.declined_at IS NULL
) ranked;Five applications for three places:
| Applicant | Outcome | Waitlist |
|---|---|---|
| 1 | admitted | |
| 2 | admitted | |
| 3 | admitted | |
| 4 | waitlisted | 1 |
| 5 | waitlisted | 2 |
Now applicant 2 declines. Nothing else has to run. Applicant 4 is admitted and applicant 5 moves to position 1, because the outcome is calculated from the rows, not stored and kept in sync. For an organiser, that's the property that matters: declining someone frees their place with nobody having to remember a step.
Two details matter:
- The tie-breaker. Ordering by
submitted_at, idmeans two applications with the same timestamp still get a fixed order. - The unique constraint. A double-clicked submit button can't create a second application for the same person.
The catch: the answer you give right away can change
Ranking after the write makes the final list correct. It doesn't make the first answer final.
Picture two applications for the last place. Application A is inserted first but its
transaction takes a moment to commit. Application B is inserted a moment later and commits
straight away. When B asks "where am I?", A isn't visible yet, so B sees admitted. Then A
commits with an earlier timestamp, and B is now on the waitlist.
That sequence is easy to reproduce in Postgres too: the late application sees admitted, and
the final list shows the early one admitted and the late one waitlisted. The list is right. What
B was told for a moment was not.
How much that matters depends on what you do with the answer:
- Show "application received", and send outcomes later, once applications close or an organiser reviews them. The ranking alone is then enough.
- Tell people immediately, and you need each request to see every earlier one. That means making applications for an event go one at a time.
When you need an instant answer: lock the event
Locking the event row serialises applications for that event and leaves every other event untouched. Wrapping it in a function keeps the lock, the insert and the answer in one transaction:
CREATE FUNCTION apply_for_event(p_event int, p_email text)
RETURNS TABLE (outcome text, waitlist_position bigint)
LANGUAGE plpgsql AS $$
DECLARE
new_id bigint;
BEGIN
-- One applicant per event at a time: the next caller waits here until this one commits.
PERFORM 1 FROM events WHERE id = p_event FOR UPDATE;
-- Everyone is recorded, because the waitlist needs them.
INSERT INTO applications (event_id, email) VALUES (p_event, p_email)
RETURNING id INTO new_id;
-- With the lock held, every earlier application is visible, so this answer is final.
RETURN QUERY
SELECT o.outcome, o.waitlist_position
FROM application_outcomes o
WHERE o.id = new_id;
END $$;Notice that every applicant is still inserted. That's deliberate: the people over capacity are
the waitlist. The capacity rule itself lives in the application_outcomes view from earlier, and
the lock only guarantees that the outcome each person is told is the one that sticks. If your
event has no waitlist and you'd rather refuse people, check the count inside the same locked
function and return "full" without inserting.
Two tests in Postgres 17 show it working. With one place left, the first applicant's transaction
is held open for two seconds while a second applicant applies. The second call waits the full two
seconds for the lock, then comes back waitlisted, position 1, which matches the final list.
Five applicants calling at once for two places are told two admitted and three waitlisted, and
the final list says the same.
The cost is that applications for one event can't run in parallel. For a few hundred applicants to a bootcamp, that's nothing. For a ticket sale with thousands of buyers a second, you'd look at a different design, such as pre-created numbered places that each buyer claims with a single conditional update.
Capacity isn't the only rule that has to hold
The same thinking applies to the other rules in an application system that handles children's data:
- Under-18 applications are their own code path. An event marked as involving minors collects guardian details, sends confirmations to the guardian, and fixes that classification when the application is submitted. Editing the event later can't change how an existing record is treated.
- Content editors can't read applications. Access is separated into roles, and the editor role has no access to application records at all.
- Photo consent is checked when an image is requested, not only when a page decides whether to show it. A photo withheld from the gallery can't be downloaded by anyone who asks for it directly.
Each one is a rule enforced where the data is, not where it's displayed.
Test it against a real database
The project has 334 tests across 18 suites, and 8 of those suites run against a real Postgres instance rather than a mock. A mock can't reproduce a window function, a unique constraint or two transactions racing. A real database in a container can, and starting one locally is one command:
docker run --rm -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17-alpineThe same race this post started with makes a good first test: fire two applications for the last place at once, and assert that only one is admitted.
The short version
- Check-then-insert lets two people take one place. It's easy to reproduce.
- Writing first and ranking afterwards makes the final list correct, and declines free places with no extra code.
- The instant answer can still change. Either announce outcomes later, or lock the event row so applications go one at a time and each answer is final.
- Test these rules against a real database, because a mock can't race.
Further reading: the PostgreSQL docs on window functions and explicit locking. For the same "only one request can change the state" idea applied to payments, see Accepting Paystack Payments in Next.js Without Losing Money.
Frequently asked questions
- Why does checking capacity before inserting not work?
- Two requests can both read the count before either has written its row. Both see a free place, both insert, and the event is over capacity. The check and the write need to happen as one step, or the outcome needs to be worked out after the rows exist.
- How do you build a waitlist in Postgres?
- Store every application, then rank them with a window function such as ROW_NUMBER() ordered by submission time and id. Rows within the capacity are admitted, the rest are waitlisted with a position. Declining an application removes it from the ranking, so the next person moves up without extra code.
- When should I use SELECT FOR UPDATE for capacity?
- When you need to tell an applicant their outcome immediately and be sure it will not change. Locking the event row makes applications for that event go one at a time, so each request sees every earlier one.