Explain why a check followed by an insert can double-book even when each statement is correct.
Explain what PostgreSQL's default Read Committed isolation does and does not protect against.
Close a race with a row lock, a database constraint or serializable isolation, and choose between them.
Implement Idempotency-Key handling so that retries return the original response and never create duplicates.
Prove a concurrency fix with a test that sends requests in parallel and fails against the broken code.
Prerequisites
Comfortable reading TypeScript and SQL.
Knows what a database transaction is (BEGIN, COMMIT, ROLLBACK).
Has used Promise.all or another way of running asynchronous work in parallel.
Concepts
Check-then-act
Most double bookings come from one pattern: the code checks a condition, then acts on it, and assumes nothing changed in between.
const overlapping = await db.query("SELECT 1 FROM bookings WHERE resource_id = $1 AND … LIMIT 1", […]);
if (overlapping.rows.length > 0) throw conflict("SLOT_UNAVAILABLE", "…");
await db.query("INSERT INTO bookings …", […]);
With one request at a time this is correct, and every sequential test passes. With two requests for the same slot arriving together, both can run their SELECT before either has inserted, both see a free slot, and both insert. Nothing failed, nothing was logged, and the room is booked twice. The window between check and act is only milliseconds, but a busy service, a slow query or a client that double-submits a form will find it.
Why a transaction alone does not fix it
Wrapping those statements in BEGIN … COMMIT makes them atomic: they commit together or not at all. It does not, by itself, make them isolated from other transactions in the way this code needs.
PostgreSQL's default isolation level is Read Committed. Each statement sees the data committed before that statement began. A plain SELECT takes no lock, so two concurrent transactions can still both read "no overlap" and both insert; neither of their rows is visible to the other until it commits. The race is the same as before, just inside two transactions.
There are three sound ways to close the window.
Lock something both requests must touch. In the base booking app, POST /bookings starts its transaction with . takes a row lock that a second on the same row must wait for until the first transaction commits or rolls back. Every booking for that resource therefore queues on the resource row, and by the time the second request runs its overlap check, the first booking is committed and visible, because under Read Committed each new statement takes a fresh snapshot. You lock the parent row because the row that would conflict does not exist yet: there is nothing in to lock. Bookings for different resources do not wait for each other.
Worked example
The situation
This walk-through uses a different race from the one in the exercise: cancelling a booking twice at the same moment. Suppose the service has the cancellation endpoint from the lesson Implement a scoped feature, POST /bookings/:id/cancel, and that a later change makes it send each refund to a payment provider. A user taps "Cancel" twice on a slow connection. Both requests arrive within a few milliseconds.
The first version an agent wrote looks like this:
const { rows } = await db.query("SELECT * FROM bookings WHERE id = $1 AND user_id = $2", [id, user.id]);
if (rows.length === 0) throw notFound("BOOKING_NOT_FOUND", `Booking ${id} does not exist`);
if (rows[0].status === "CANCELLED") throw conflict("ALREADY_CANCELLED", "The booking is already cancelled");
const refund = refundFor(rows[0]);
await db.query(
"UPDATE bookings SET status = 'CANCELLED', refund_cents = $2, cancelled_at = now() WHERE id = $1",
[id, refund],
);
await payments.refund(rows[0].id, refund); // the external call
It is check-then-act again: both requests read CONFIRMED, both pass the check, both update, and both call the payment provider. The database row looks fine afterwards. The money went out twice.
Step 1: reproduce it before changing anything
A sequential test cannot show this, so the test fires the requests together. (bookTomorrow and fakePayments are small helpers in this example's test file: one creates a booking through the API, the other records refunds instead of sending them.)
it("refunds a booking once when cancel is sent twice at the same time", async () => {
const id = await bookTomorrow(ADA);
const cancel = () =>
app().inject({ method: "POST", url: `/bookings/${id}/cancel`, headers: auth(ADA) });
const responses = await Promise.all([cancel(), cancel(), cancel(), cancel()]);
const statuses = responses.map((r) => r.statusCode).sort((a, b) => a - b);
assert.deepEqual(statuses, [200, 409, 409, 409]);
assert.equal(fakePayments.refunds.length, 1);
});
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
Your task
In this version of the booking service, POST /bookings looks up the resource, checks for overlapping bookings and inserts the new one as separate queries, with no transaction and no lock. Requests arriving at the same moment can all pass the check, so one slot can be booked several times. The existing tests pass, because they send one request at a time.
Make booking safe under concurrency, then make it safe to retry by adding Idempotency-Key support to POST /bookings.
Required behaviour
Concurrency. However many requests for the same or overlapping periods of one resource arrive at once, exactly one is created (201); every other gets 409 SLOT_UNAVAILABLE, and the database holds exactly one confirmed booking for that time.
Idempotency. The Idempotency-Key request header is optional.
Without the header, POST /bookings behaves exactly as it does today.
Keys belong to the user who sent them: Ada and Grace may use the same key string without affecting each other.
The same user sending the same key with the same body gets the original response (the same status and body, so the same booking id) and nothing new is created.
The same user sending the same key with a different body gets 409 with the code .
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: Explain why the starting code could create two bookings for the same time, what in your change now makes a second request wait or fail, and what a client that retries after a dropped connection gets back. Would your approach still hold if the service ran as several processes? Why?
Let the database enforce the rule. PostgreSQL can reject overlapping rows itself with an exclusion constraint on a time range, for example EXCLUDE USING gist (resource_id WITH =, tstzrange(starts_at, ends_at) WITH &&) WHERE (status = 'CONFIRMED'). Plain columns such as resource_id need the btree_gist extension. The database then raises error 23P01 for the loser, which the code must translate into 409 SLOT_UNAVAILABLE. A constraint protects every code path, including ones written later, but it moves the rule into the schema, and the error mapping must be right.
Use Serializable isolation and retry. At SERIALIZABLE, PostgreSQL detects that two transactions could not have run one after the other and aborts one with SQLSTATE 40001. The application must then retry the whole transaction. It is correct, but every caller needs the retry loop.
What does not work: a lock in Node's memory (a mutex or a Map of busy resources). It covers one process only, so the race comes back as soon as the service runs on two instances or restarts mid-request.
Retries and idempotency
Concurrency has a second face. A client sends POST /bookings, the connection drops before the 201 arrives, and the client cannot tell whether the booking was made. If it retries, it may book twice; if it does not, it may have nothing. POST is not idempotent, so a blind retry is unsafe.
The Idempotency-Key header, specified in an IETF HTTP API working group draft, solves this. The client generates a unique key per logical operation and sends the same key on every retry. The server records each key with a fingerprint of the request and the response it produced:
a new key is processed normally, and its response is stored;
a repeat of the key with the same request returns the stored response without doing the work again;
a repeat with a different request is an error, because the client has mixed up two operations;
a repeat that arrives while the first is still running must not run the work a second time: the server either answers with a conflict or waits for the first to finish.
The draft suggests 422 for a key reused with a different request and 409 for one still in progress. This service answers 409 in both cases and tells them apart by error code, which fits its own convention of naming the reason in error.code.
Keys are scoped to the caller, so two users who happen to choose the same key do not collide. The record must be written in the same transaction as the booking, protected by a unique constraint, otherwise two concurrent retries can both decide they are first: the same check-then-act race, one level up.
Working with an agent on concurrency
Ask an agent to "fix the double-booking bug" and it will often produce something that looks right and passes every existing test: a transaction with no lock, a check moved inside a try, or an in-memory lock. Sequential tests cannot tell these apart from a real fix.
So start with a failing reproduction. Ask for a test that fires many requests at once with Promise.all and asserts that exactly one succeeds, then run it against the unfixed code and watch it fail. Watch for tests that await each request in a loop: they never overlap and prove nothing. Then ask the agent to explain which lock or constraint makes the second request wait or fail, and check that explanation against the PostgreSQL documentation yourself. Run the concurrent test several times; a race that is fixed passes every time, while a race that is merely less likely passes most of the time.
Run against the code above, it fails most of the time with several 200s. Run it five or six times: a race test that passes once has not proved much.
Step 2: understand why the obvious fix is not enough
Wrapping the three statements in the transaction() helper from src/db.ts does not help. PostgreSQL runs at Read Committed by default, the SELECT takes no lock, and both transactions still read CONFIRMED.
Step 3: make the state change itself the check
Here the row that matters already exists, so the database can do the check and the change in one statement:
const updated = await db.query<BookingRow>(
`UPDATE bookings
SET status = 'CANCELLED', refund_cents = $3, cancelled_at = now()
WHERE id = $1 AND user_id = $2 AND status = 'CONFIRMED' AND starts_at > now()
RETURNING *`,
[id, user.id, refund],
);
When two of these run at once, the second UPDATE finds the row locked by the first and waits. The PostgreSQL documentation on Read Committed describes what happens next: once the first commits, the second re-evaluates its WHERE clause against the updated row. The status is now CANCELLED, so the row no longer matches and nothing is updated. Exactly one request gets a row back; the others get none and can then look the booking up to choose between 404, 409 ALREADY_CANCELLED and 409 BOOKING_STARTED. (Computing refund needs the booking's start time, so in practice you either read the booking first or compute the refund inside the UPDATE with a CASE expression; either way, only the conditional update decides who wins.)
The external call happens only for the request that won, after the database has recorded the cancellation. Passing the booking id to the payment provider as its own idempotency key means that even a retry of that one call cannot refund twice.
Why the exercise needs a different tool
A conditional UPDATE works because there is an existing row to lock. Creating a booking is different: the row that would conflict has not been inserted yet, so there is nothing in bookings to lock, and a WHERE clause cannot wait for a row that does not exist. That is why the base app locks the resource row instead, and why an exclusion constraint is the other strong option. Choosing the right mechanism starts with asking: which existing row, or which constraint, will make the second request wait or fail?
Step 4: confirm, then keep the test
With the conditional update in place, the concurrent test passes every time you run it. Keep it: it is the only thing that will catch someone, human or agent, "simplifying" the statement back into a read followed by a write.
IDEMPOTENCY_KEY_REUSED
If a request arrives while an earlier request with the same key is still being processed, it either gets 409 IDEMPOTENCY_KEY_IN_PROGRESS or waits and then receives the original response. Either way, only one booking is created.
Steps
Reproduce the race first. Add a test under test/ that sends about 20 bookings for the same period at once and counts the 201s:
Run npm test and see it fail before you change anything. A test that awaits each request in turn never overlaps and will pass against the broken code.
Fix the race in src/routes/bookings.ts. The transaction() helper in src/db.ts runs work on one connection inside BEGIN … COMMIT; decide what inside it makes a second request wait or fail. Run the race test several times.
Design the idempotency record. You will need a table, so add a new migration such as db/migrations/002_idempotency_keys.sql. Decide what identifies a key, what you store to recognise "the same body", and what you store to replay the response.
Implement and test the key behaviour: a repeat with the same body, a repeat with a different body, the same key from two users, and about 10 identical requests with one key sent at once.
Try it by hand against the running service:
npm run db:reset && npm start
START=$(date -u -d '+5 days' +%Y-%m-%dT09:00:00Z); END=$(date -u -d '+5 days' +%Y-%m-%dT10:00:00Z)
BODY="{\"resource_id\":3,\"starts_at\":\"$START\",\"ends_at\":\"$END\"}"
# three users at once, same slot: expect one 201 and two 409s
for token in dev-token-ada dev-token-grace dev-token-edsger; do
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:3000/bookings \
-H "Authorization: Bearer $token" -H 'Content-Type: application/json' -d "$BODY" &
done; wait
# the same request twice with one key: expect the same booking both times
for attempt in 1 2; do
curl -s -w ' %{http_code}\n' -X POST localhost:3000/bookings -H 'Authorization: Bearer dev-token-ada' \
-H 'Idempotency-Key: 6f1c2a7e-retry-demo' -H 'Content-Type: application/json' \
-d "{\"resource_id\":2,\"starts_at\":\"$(date -u -d '+6 days' +%Y-%m-%dT15:00:00Z)\",\"ends_at\":\"$(date -u -d '+6 days' +%Y-%m-%dT15:30:00Z)\"}"
done
Run npm run verify before you check your work.
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. The assessment starts your service with the starter's pinned dependencies; a changed lockfile means it is not started.
Never edit db/migrations/001_init.sql: the migration runner records a checksum for each applied migration and refuses to start if one changes. Put schema changes in a new file.
The fix must hold in the database, not in the Node process: the assessment uses a fresh database, and a real deployment may run several processes.
Keep the other endpoints, the response shapes and the error format as they are.
How Check work assesses this
When you select Check work, the platform takes a snapshot of your workspace's source files and assesses it outside the lab. Your service is started with node src/server.ts against a fresh PostgreSQL database, so your migrations must create everything your code needs. The checks then call it over HTTP from outside, including many parallel requests for the same and overlapping periods from different users, and parallel retries with one key, and they count the bookings in the database directly. Nothing printed in the lab and no change to the tests in test/ affects the result.
Tools
You can do this exercise with any compatible tool in the lab. If you use an agent, have it write the failing concurrency test first and run it before it changes the route. Ask it which lock or constraint makes the second request wait, and check that answer yourself.
Acceptance criteria
AC1Concurrent requests for the same or overlapping times create exactly one booking; the others get 409 SLOT_UNAVAILABLE.Verified behaviour
AC2Retrying with the same Idempotency-Key and the same body returns the original booking and creates nothing new.Verified behaviour
AC3Reusing a key with a different request body is refused with 409 IDEMPOTENCY_KEY_REUSED.Verified behaviour
AC4Concurrent retries with one key create exactly one booking.Verified behaviour
AC5Bookings without a key, and the same key used by different users, still work.Verified behaviour
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
How long idempotency keys are kept and how old keys are cleaned up.
Throughput or latency under sustained load; the checks look at outcomes, not speed.
Which mechanism you chose (row lock, exclusion constraint or serializable retries), as long as the behaviour is correct.
The concurrency tests you add under test/; the assessment runs its own checks instead.
Code structure and readability.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.