End-to-End Feature Design and Development Questions
The integrated 'build a complete feature' walkthrough: taking one concrete feature (a follow button, a like button, a comments thread, a create-post form, a profile editor, a large file upload) from the user-facing flow through the API contract, backend logic, data model and storage in a single coherent answer. Includes optimistic UI and the backend idempotency it needs, concurrent and repeated requests, denormalized counts that must stay correct, client and server validation with errors mapped back to the right field, a contract shared by web and mobile clients, and how the feature is tested, rolled out behind a flag and observed end to end. Tests whether the candidate connects the layers and makes consistent trade-offs across them rather than depth in any one. Deep dives in a single layer (UI state, API style, schema, caching, pipelines, observability, security and authentication, rate limiting), payments and notification delivery, feature-flag platforms, migrations and deployment pipelines, and standalone large-scale system design are covered elsewhere.
Take the follow button on a profile page from tap to database row. Cover what the client shows, the API calls involved, how follows are stored, and what happens when a user double-taps, two people follow the same account at once, or the account has millions of followers.
Sample Answer
Direct answer
A follow is one row in an edge table (a table whose rows are the links between two things, here two users), follows(follower_id, followee_id), with a composite primary key (a key made of two columns together) so the same pair can exist only once. The button flips at once on tap (an optimistic update), sends an idempotent "make this follow exist" request, and settles to the {following, follower_count} the server returns. A double tap and a retry are harmless because the database rejects the duplicate row. Two people following at once are safe because each inserts a different row and the counter increments are serialised (made to run one after another) by the row lock (while one transaction is changing a row, any other transaction that wants to change that same row waits until the first one commits; a transaction is a group of statements that succeed or fail together). A million-follower account needs a different counter (spread across several rows) and cursor-based follower lists (each page asks for "rows after the last one you saw" instead of "skip N rows"), but the same edge table.
Tap to row, layer by layer
| Layer | Decision |
|---|---|
| UI | Two button states, Follow and Following. A tap shows the new state immediately and the button stays tappable, so there is no separate spinner state. The profile payload carries viewer_follows so the first paint is right. Unfollow asks for confirmation only on private accounts or on a long press, never on a plain tap. |
| API | PUT /v1/users/{id}/follow and DELETE /v1/users/{id}/follow, no body, both answer 200 {"following": true, "follower_count": 201}. GET /v1/users/{id}/followers?limit=50&cursor=... lists followers. Following yourself returns 422. |
| Logic | One transaction: insert or delete the edge, then move the two counters by the number of rows that changed. |
| Data | follows edge table plus denormalised counters (a stored copy of a count, kept so profile reads do not run count(*)). |
The client logic is the same single-request-in-flight state machine used for a like button: taps while a request is pending only change what the user wants, one follow-up request goes out if the answer disagrees, and a failure restores the last confirmed state.
Schema and the write path
CREATE TABLE users (
id bigint PRIMARY KEY,
follower_count integer NOT NULL DEFAULT 0 CHECK (follower_count >= 0),
following_count integer NOT NULL DEFAULT 0 CHECK (following_count >= 0)
);
CREATE TABLE follows (
follower_id bigint NOT NULL REFERENCES users(id),
followee_id bigint NOT NULL REFERENCES users(id),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (follower_id, followee_id),
CHECK (follower_id <> followee_id)
);
CREATE INDEX follows_by_followee ON follows (followee_id, created_at DESC, follower_id);
CREATE FUNCTION set_follow(p_me bigint, p_target bigint, p_follow boolean)
RETURNS TABLE (out_following boolean, out_followers integer)
LANGUAGE plpgsql AS $$
DECLARE changed integer;
BEGIN
PERFORM 1 FROM users WHERE id IN (p_me, p_target) ORDER BY id FOR UPDATE;
IF p_follow THEN
INSERT INTO follows (follower_id, followee_id) VALUES (p_me, p_target) ON CONFLICT DO NOTHING;
ELSE
DELETE FROM follows WHERE follower_id = p_me AND followee_id = p_target;
END IF;
GET DIAGNOSTICS changed = ROW_COUNT;
UPDATE users SET follower_count = follower_count + CASE WHEN p_follow THEN changed ELSE -changed END WHERE id = p_target;
UPDATE users SET following_count = following_count + CASE WHEN p_follow THEN changed ELSE -changed END WHERE id = p_me;
RETURN QUERY SELECT p_follow, u.follower_count FROM users u WHERE u.id = p_target;
END $$;
INSERT INTO users SELECT g FROM generate_series(1, 300) g;
SELECT * FROM set_follow(1, 2, true); -- run twice
SELECT * FROM set_follow(1, 2, false); -- run twice
SELECT * FROM set_follow(5, 5, true);
- The
PERFORM ... ORDER BY id FOR UPDATEline locks both user rows in id order before anything else. Without it, user 1 following user 2 updates row 2 (the target) and then row 1, while user 2 following user 1 updates row 1 and then row 2 (the function updates the target's counter first and the follower's own counter second), and each can wait forever for the other (a deadlock; PostgreSQL aborts one of them). Locking in a fixed order removes that cycle. - Worked timeline of that deadlock with ids, using the unlocked order above: at time 1, A (user 1 follows user 2) locks row 2; at time 1, B (user 2 follows user 1) locks row 1; at time 2, A asks for row 1 and waits for B; at time 2, B asks for row 2 and waits for A. Each holds what the other needs, so neither can move. Sorting by
idmeans both A and B ask for row 1 first, so one simply waits for the other and then continues. ON CONFLICT DO NOTHINGskips the insert if the pair already exists, andGET DIAGNOSTICS changed = ROW_COUNTstores how many rows the insert or delete actually changed (1, or 0 for a repeat). The counters then move bychanged, so a repeat moves no counter.- The index on
(followee_id, created_at DESC, follower_id)serves the follower list, and the primary key serves "does the viewer follow this account?" with a single lookup.
Run in a postgres:16 container, the double tap prints follower counts t | 1, t | 1, f | 0, f | 0, and the self follow fails with violates check constraint "follows_check".
Double tap and simultaneous followers
Two taps from one user: the second INSERT waits for the first transaction, hits the primary key, does nothing, and returns the same answer. Two different users: their rows differ, so both inserts succeed, and the two UPDATE users statements queue on the target's row and each adds one to the latest value.
Checked with pgbench (PostgreSQL's load-testing tool; each client is one database session) in the same container. Three small script files: a.sql is SELECT set_follow(1,2,true);, b.sql is SELECT set_follow(2,1,true);, and f.sql is \set u :base + :client_id then SELECT set_follow(:u, 2, true);. Users 1 and 2 follow each other from 40 sessions at once, 50 transactions per session, each picking one of the two directions at random; then 200 different users follow user 2 in five waves of 40 simultaneous sessions. Deadlocks are read from the server's own counter, SELECT deadlocks FROM pg_stat_database WHERE datname = current_database(), before and after:
pgbench -n -c 40 -t 50 -f a.sql -f b.sql demo
for base in 3 43 83 123 163; do pgbench -n -c 40 -t 1 -D base=$base -f f.sql demo; done
counter_user2 | edges_user2 | counter_user1 | edges_user1
---------------+-------------+---------------+-------------
201 | 201 | 1 | 1
deadlocks during the run: 0
Reading the columns: counter_user2 is the stored follower count of user 2 and edges_user2 is a live count(*) of rows in follows pointing at user 2; they match at 201 (200 followers plus user 1), which shows no increment was lost. counter_user1 and edges_user1 are the same pair for user 1, who is followed by user 2 only, so both are 1. The repeated mutual follows in both directions are the deadlock trap, and the unchanged deadlock counter shows none occurred, because the fixed lock order removes the cycle. The check can fail: with the PERFORM ... FOR UPDATE line deleted from the function, the mutual-follow run made PostgreSQL abort transactions with deadlock errors. In one measured shorter run (-t 3, 3 transactions per session) the deadlock counter rose by about a hundred, and the full -t 50 run is slow because each deadlock waits out PostgreSQL's 1 second deadlock_timeout before one transaction is aborted; the exact count varies from run to run.
An account with millions of followers
Three things break first, in this order:
- The counter row becomes a queue. (Fan-out, used in point 3, means copying one event to many recipients, for example writing a new post into each follower's feed; a shard is one of several rows or partitions that share the work of one thing.) Every follow of that account updates the same
usersrow, and those updates run one after another. Find out whether it matters by watching lock wait time on that row (how long updates sit waiting for the lock); do not shard before measuring, since most accounts never need it. When it does matter, give the account several counter rows and add to a random one:
CREATE TABLE follower_shards (
user_id bigint NOT NULL, shard smallint NOT NULL, n bigint NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, shard)
);
CREATE FUNCTION bump_followers(p_user bigint) RETURNS void LANGUAGE sql AS $$
INSERT INTO follower_shards (user_id, shard, n)
VALUES (p_user, floor(random() * 16)::smallint, 1)
ON CONFLICT (user_id, shard) DO UPDATE SET n = follower_shards.n + 1;
$$;
SELECT bump_followers(99) FROM generate_series(1, 1000);
SELECT sum(n) AS follower_count, count(*) AS shard_rows, max(n) < 1000 AS spread_over_rows
FROM follower_shards WHERE user_id = 99;
Reading the code: floor(random() * 16)::smallint picks a shard number from 0 to 15 for each call; ON CONFLICT (user_id, shard) DO UPDATE SET n = follower_shards.n + 1 creates that shard's row with n = 1 the first time and otherwise adds 1 to it; the generate_series(1, 1000) call performs 1,000 follows. In the final query, sum(n) is the follower count, count(*) is how many shard rows exist, and max(n) < 1000 is true when no single row holds all 1,000, meaning the load was spread. Run in the same container this prints 1000 | 16 | t: the total is exact and the writes landed on 16 rows (each row holds about 1000/16, roughly 62, so the busiest row's queue is roughly a dozen times shorter than a single counter row's; the split among shards varies per run, the total does not). Reads sum 16 small rows, which is cheap, and the profile can cache the sum for a few seconds. The trade-off is that concurrent writers no longer wait for each other, at the price of an extra read step and a rule that only flagged hot accounts use shards.
- The follower list. Use keyset pagination (also called cursor-based), which means the cursor is the
(created_at, follower_id)of the last row shown and the next page asks for rows after it.OFFSET 5000000has to walk past five million rows; the keyset query jumps straight into the index. - Fan-out. It is tempting to push the new follow (or the followee's later posts) into every follower's stored feed at write time; for a million followers that is a million writes inside one tap. Following must not copy anything to the followee's followers. Whatever builds feeds reads the edge table later, outside this request.
Test, roll out, observe
- Tests: repeat and concurrent calls end with
follower_countequal to the number of edge rows (the check above), a mutual-follow stress test must produce zero deadlock errors, and a Playwright test with the route aborted must show the button reverting. - Roll out: ship the edge table and endpoints first, backfill counters (fill them in for existing data) from
count(*)per user, then switch the profile read, behind a flag. - Observe: lock wait on hot user rows, rate of
422and5xxon the follow endpoints, and a scheduled job that compares each sampled user's counter tocount(*)on the edge table.
Pitfalls
Do not make follow a toggle endpoint, do not read the follower count and then write it back from application code (two requests overwrite each other), and do not shard counters for every account because most accounts never need it.
Users of a social app can write a post with text and an image. Walk me through that feature from the compose screen to the database row: what the client does while they type and on submit, what the request looks like, what the server checks and stores, and what happens when the network drops mid-submit or the server rejects the post.
Sample Answer
Direct answer
The compose screen keeps the draft and uploads the image as soon as it is picked, so submit only has to send the text plus an image_id. Submit is a POST carrying a client-generated client_request_id, which the server stores under a unique constraint (a database rule that refuses a second row with the same value in the named columns): a retry after a dropped connection returns the original post instead of creating a second one. The server validates everything again (the client's checks are only for speed), writes the post and attaches the image in one transaction, and answers 201 with the post, or 422 with a list of field errors. The draft is cleared only after a success response.
The flow, step by step
| Step | Client | Server / storage |
|---|---|---|
| Typing | Draft saved to local storage on a short debounce (a wait that restarts on every keystroke), keyed by user. Counter shows characters left, counted in code points (one per Unicode code point: a simple emoji such as the grinning face counts 1, whereas JavaScript's plain .length counts it as 2; a family emoji or a flag is built from several code points, 5 and 2 respectively, so it counts more than 1, which is accepted because the unit only has to be the same on the client and the server), the same unit the server and PostgreSQL's char_length use. Submit disabled when empty or over 500. | nothing |
| Pick image | Preview appears at once; upload starts in the background with its own progress and its own error. Submit stays disabled until the image is uploaded or removed. | POST /v1/images returns an image_id and a short-lived upload URL; the bytes go straight to object storage (a service that stores files by key, such as Amazon S3), not through the API server |
| Submit | Button shows "Posting...", the text box is read-only, the draft is kept. | POST /v1/posts with {"body", "image_id", "client_request_id"} |
| Success | Clear the draft, close the composer, put the post at the top of the feed using the returned object. | 201 {"id": ...} |
| Rejected | Keep everything, put each message next to its field, focus the first invalid field. | 422 {"errors": [{"field": "body", "code": "too_long"}]} |
| Network drop | Retry automatically up to 3 times with the same client_request_id, then show "Couldn't post. Retry" with the draft intact. | a request that arrived is stored once |
What the server checks
- The user is signed in and under the rate limit (a cap on requests per user per time window; the server answers
429with aRetry-Afterheader saying how long to wait otherwise). body, after trimming, is 1 to 500 characters. The databaseCHECKrepeats the length limit, so no code path can store a body over 500 characters; it measures the stored text as it is, so a body of only spaces passes it, which is why the server trims and rejects an empty result before the insert.- If
image_idis present: it belongs to this user, its upload finished, the stored bytes really are an image of an allowed type (read the file's first bytes, never trust the declaredContent-Type, the label the uploader attached; a file renamed fromvirus.exetophoto.pngstill starts with the bytes of an executable, not of a PNG, and the client's own checks cannot be relied on because anyone can call the API directly without the app), and it is not already attached to another post. The attach is a conditional update inside the same transaction as the insert, so a failure rolls back both. - The
(author_id, client_request_id)pair: new means insert; seen before with the same payload means return the stored post with200; seen before with a different payload means409 idempotency_key_reused(409 Conflict: the request clashes with stored state). Idempotent means doing the request twice has the same effect as doing it once. The server keepspayload_hash, anmd5fingerprint of the body and image, so it can tell a true retry (same fingerprint, return the old post) from a reused id on different content (different fingerprint, refuse), instead of silently returning a post that does not match what was sent.
Storing it and replaying it
CREATE TABLE feed_posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author_id bigint NOT NULL,
body text NOT NULL CHECK (char_length(body) BETWEEN 1 AND 500),
image_id uuid,
client_request_id uuid NOT NULL,
payload_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (author_id, client_request_id)
);
CREATE FUNCTION create_post(p_author bigint, p_body text, p_image uuid, p_req uuid)
RETURNS TABLE (out_id bigint, out_replayed boolean)
LANGUAGE plpgsql AS $$
DECLARE h text := md5(coalesce(p_body,'') || '|' || coalesce(p_image::text,'')); new_id bigint; old_hash text; old_id bigint;
BEGIN
INSERT INTO feed_posts (author_id, body, image_id, client_request_id, payload_hash)
VALUES (p_author, p_body, p_image, p_req, h)
ON CONFLICT (author_id, client_request_id) DO NOTHING RETURNING id INTO new_id;
IF new_id IS NOT NULL THEN RETURN QUERY SELECT new_id, false; RETURN; END IF;
SELECT id, payload_hash INTO old_id, old_hash FROM feed_posts WHERE author_id = p_author AND client_request_id = p_req;
IF old_hash <> h THEN RAISE EXCEPTION 'idempotency_key_reused'; END IF;
RETURN QUERY SELECT old_id, true;
END $$;
SELECT * FROM create_post(7, 'hello world', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT * FROM create_post(7, 'hello world', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT * FROM create_post(7, 'hello EDITED', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT count(*) AS rows_stored FROM feed_posts;
SELECT * FROM create_post(7, repeat('x', 501), NULL, 'bbbbbbbb-0000-0000-0000-000000000002');
Run in a postgres:16 container, the three create_post calls print 1 | f, then 1 | t (the replay), then ERROR: idempotency_key_reused. The count query prints rows_stored = 1, and the 501-character body fails with violates check constraint "feed_posts_body_check". If two copies of the same request arrive at the same moment, the second INSERT waits for the first to commit, finds the key taken, and returns the existing row.
The client side of a retry
import { randomUUID } from 'node:crypto';
// ---- client ----
export const newDraft = () => ({ text: '', imageId: null, requestId: randomUUID() });
export const editDraft = (d, text) => ({ ...d, text, requestId: randomUUID() }); // new content = new request id
const NETWORK = Symbol('network');
export async function submit(draft, send, attempts = 3) {
for (let i = 1; i <= attempts; i++) {
try {
const r = await send({ body: draft.text, image_id: draft.imageId, client_request_id: draft.requestId });
if (r.status === 201 || r.status === 200) return { kind: 'posted', id: r.json.id, replayed: r.status === 200, attempts: i };
if (r.status === 422) return { kind: 'field_errors', errors: r.json.errors }; // keep the draft, show errors
if (r.status === 409) return { kind: 'conflict' };
if (r.status >= 500 && i < attempts) continue; // safe to repeat: same request id
return { kind: 'failed', status: r.status };
} catch (e) {
if (e === NETWORK && i < attempts) continue;
return { kind: 'failed_offline', attempts: i }; // draft stays; user taps Retry
}
}
}
// ---- fake server: stores by (author, request id) like the unique index does ----
const rows = new Map(); let nextId = 1;
function server(req, { dropResponseOnce } = {}) {
const trimmed = req.body.trim();
if ([...trimmed].length < 1 || [...trimmed].length > 500) return { status: 422, json: { errors: [{ field: 'body', code: [...trimmed].length ? 'too_long' : 'required' }] } };
const hash = trimmed + '|' + req.image_id;
const old = rows.get(req.client_request_id);
if (old) return old.hash === hash ? { status: 200, json: { id: old.id } } : { status: 409, json: { error: 'idempotency_key_reused' } };
const row = { id: nextId++, hash }; rows.set(req.client_request_id, row);
return { status: 201, json: { id: row.id } };
}
// ---- scenarios ----
let d = { ...newDraft(), text: 'hello world', imageId: 'img-1' };
let dropped = false;
const flaky = async (req) => { const res = server(req); if (!dropped) { dropped = true; throw NETWORK; } return res; };
console.log('1. response lost on the first attempt:', JSON.stringify(await submit(d, flaky)), '| rows stored:', rows.size);
console.log('2. user taps Retry later with same draft:', JSON.stringify(await submit(d, async (r) => server(r))), '| rows stored:', rows.size);
const edited = editDraft(d, 'hello world, edited');
console.log('3. user edits after a failure, new request id:', JSON.stringify(await submit(edited, async (r) => server(r))), '| rows stored:', rows.size);
console.log('4. same id, different text (a bug):', JSON.stringify(await submit({ ...d, text: 'other' }, async (r) => server(r))));
console.log('5. 501 characters:', JSON.stringify(await submit({ ...newDraft(), text: 'x'.repeat(501) }, async (r) => server(r))));
console.log('6. offline for every attempt:', JSON.stringify(await submit({ ...newDraft(), text: 'hi' }, async () => { throw NETWORK; })), '| rows stored:', rows.size);
Run in a node:22 container, it prints:
1. response lost on the first attempt: {"kind":"posted","id":1,"replayed":true,"attempts":2} | rows stored: 1
2. user taps Retry later with same draft: {"kind":"posted","id":1,"replayed":true,"attempts":1} | rows stored: 1
3. user edits after a failure, new request id: {"kind":"posted","id":2,"replayed":false,"attempts":1} | rows stored: 2
4. same id, different text (a bug): {"kind":"conflict"}
5. 501 characters: {"kind":"field_errors","errors":[{"field":"body","code":"too_long"}]}
6. offline for every attempt: {"kind":"failed_offline","attempts":3} | rows stored: 2
Scenario 1 is the case the question asks about. Walked through: attempt 1 reaches the server, which stores post 1 and answers 201, but the fake network throws the answer away, so the client sees a network failure. Attempt 2 sends the same client_request_id; the server finds the stored row and answers 200 with id 1; the client reports replayed: true, attempts: 2. The user experiences one successful post, and exactly one row is stored. Scenario 2 is the user tapping Retry later: same request id, same stored post, no new row. Scenario 4 reuses the request id with different text, which the server refuses with 409 because the fingerprint differs. Scenario 5 sends 501 characters, so the server answers 422 with too_long. Scenario 6 throws on every attempt: after 3 tries the client gives up, shows Retry with the draft intact, and nothing new is stored. Scenario 3 shows the rule that completes the design: when the user edits the text after a failure, the draft gets a new client_request_id, because reusing the old one with new text would be rejected as a conflict.
Failure cases to name
- Server rejects the post: keep the draft, show the message at the field. Never clear first and ask questions later.
- The image fails halfway: only the attachment shows an error, with Retry and Remove; the typed text is untouched.
- The tab closes mid-submit: the draft and its request id are in local storage, so reopening and pressing Post is a safe retry.
- A
5xxresponse: treated like a lost response and retried with the same id, which is why the endpoint must be idempotent.
Test, roll out, observe
Tests: the SQL checks above, a Playwright test (browser automation) that aborts the network route once and asserts exactly one post appears, and a test for each 422 field mapping. Roll out behind a flag with the old composer still deployable. Observe the share of submits that end in failed_offline, the 409 count (it should be near zero; a spike means a client is reusing ids after edits), and the time from tap to 201.
Trade-off
Uploading the image before submit makes the final request tiny and retries cheap, but leaves orphan uploads when users abandon the composer. Add an expiry job that deletes images not attached to a post within 24 hours. Sending the image inside the post request avoids orphans but makes every retry re-send megabytes.
On a support-ticket page, agents need to see a customer's new replies without refreshing. Walk me through how new replies reach the open page: which delivery option you would ship first (polling, server-sent events or WebSockets) and why, what the API and the client state look like, and how you make sure a reply that arrives while the connection is dropping is neither lost nor shown twice.
Sample Answer
Direct answer
Ship server-sent events (SSE: the browser opens one ordinary HTTP request that the server keeps open and writes small text messages into, one direction only, server to browser) first. Give every reply a per-ticket sequence number seq (1, 2, 3, ...) with no holes. The page remembers the highest seq it has shown; every message carries its seq as the event id; and the browser's built-in reconnect sends that id back, so the server replays everything after it. The page applies a reply only if its seq is the next one, ignores any seq it already has, and fetches the missing range if it sees a hole. That gives "not lost" (the database, not the connection, is the record, and replay starts from the last seq shown) and "not twice" (a seq can only be applied once) from one mechanism.
Why not the other two. Polling (the page asks every few seconds) is the simplest and always works, but it costs requests whether or not anything happened and delay is up to the interval. WebSockets (one long-lived two-way connection) pay for a second protocol, and this page needs nothing from the browser to the server except normal POSTs that already exist. SSE is plain HTTP, reconnects by itself, and carries an event id natively.
| Option | Requests for 2,000 open agent pages | Delay for a new reply | What it needs beyond HTTP |
|---|---|---|---|
| Polling every 5 s | 2,000 / 5 = 400 requests per second, nearly all returning nothing | 0 to 5 s, average 2.5 s | nothing |
| SSE | 2,000 open connections, one message per real reply | the time to write one message | proxies must not buffer the stream |
| WebSocket | 2,000 open connections | same as SSE | upgrade handshake, own message framing, own reconnect and resume logic |
The 2,000 pages is an assumed load for the arithmetic, not a measurement. What would flip the choice: if agents also need typing indicators or live cursors (frequent browser-to-server messages), use WebSockets; if the network between agents and the server strips long-lived responses and you cannot change it, ship polling behind the same API and keep the rest of the design unchanged.
Data model: a gapless sequence per ticket
CREATE TABLE tickets (
id bigint PRIMARY KEY,
last_seq integer NOT NULL DEFAULT 0
);
CREATE TABLE replies (
ticket_id bigint NOT NULL REFERENCES tickets(id),
seq integer NOT NULL,
author text NOT NULL,
body text NOT NULL CHECK (char_length(body) BETWEEN 1 AND 5000),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (ticket_id, seq)
);
INSERT INTO tickets (id) VALUES (1);
Three database terms first. A session is one open connection to the database. A transaction is a group of statements the database treats as one unit: other sessions see none of its changes until it commits (is finalized), and if it rolls back (is abandoned) none of them ever appear. A row lock is a hold the database puts on a row while a transaction changes it: any other transaction that wants to change the same row waits until the holder commits or rolls back.
Here is the failure with concrete steps, using a plain auto-increment id as the cursor (the cursor is "the highest id the page has seen; ask for everything after it"):
- Writer A starts a transaction and inserts a reply. The database hands it id 1. A has not committed, so nobody else can see reply 1.
- Writer B starts a transaction, inserts a reply, gets id 2, and commits. Reply 2 is visible.
- The page asks for "ids greater than 0" and receives only reply 2. Its cursor becomes 2.
- A commits; reply 1 is now visible. The page asks for "ids greater than 2" and receives nothing. Reply 1 is never delivered.
With a per-ticket seq, step 2 cannot happen: taking a number locks the ticket row, so B's request for a number waits until A commits.
The obvious choice, one global auto-increment id on replies and a cursor of "give me ids greater than the last one I saw", loses messages. The id is handed out when the INSERT runs, but a row becomes visible only when its transaction commits, and two transactions can commit in the opposite order. The seq here is taken by an UPDATE tickets SET last_seq = last_seq + 1, which locks the ticket row until the transaction ends, so two replies on one ticket cannot be in flight together, and they commit in seq order. Run in a postgres:16 container with two sessions and a third reading (gap-demo.mjs below), the two designs behave like this:
A. global id: poll after 0 sees [2] -> cursor = 2
A. then poll after 2 sees [] (reply 1 is never delivered)
B. A holds seq 1 ; B is waiting on a lock, and nothing of B is visible: []
B. after A commits, B gets seq 2 ; reader sees [1,2]
C. A took seq 3 then rolled back; the next writer gets seq 3 (no hole)
Line A prints steps 3 and 4 above (lines B and C are the fix, read next). In line A, a reader that saw only reply 2 moves its cursor to 2 and never sees reply 1, even though reply 1 commits afterwards. Lines B show the fix: session B really waits on a lock (pg_stat_activity, a built-in PostgreSQL view that lists every session and what it is currently waiting for, reports wait_event_type = 'Lock' for it) while A is open, so B cannot commit before A, and the reader never sees 2 without 1. Line C shows that a rolled-back reply gives its number back (the counter update is rolled back with it), so the sequence has no holes, which is what lets the client treat any jump as a missing message.
API
| Call | Purpose | Response |
|---|---|---|
GET /api/tickets/{id}/replies?after=N | catch-up: replies with seq greater than N, oldest first, at most 200 | 200 {"replies": [...]} |
GET /api/tickets/{id}/stream?after=N | the live stream | 200, Content-Type: text/event-stream, stays open |
POST /api/tickets/{id}/replies {author, body} | a customer or agent adds a reply | 201 with the saved reply, 404 unknown ticket, 422 invalid |
Each stream message looks like this (a blank line ends a message; id becomes the browser's last event id):
id: 4
event: reply
data: {"seq":4,"author":"customer","body":"reply 4","created_at":"..."}
The stream's starting point is the larger of the Last-Event-ID request header and the after query. On a reconnect the browser itself sends a request header (a named line sent along with the request) called Last-Event-ID carrying the last event id it received; the HTML specification says it sends the header only when that id is non-empty, so a connection that never received a message falls back to after. The server begins with retry: 500, the SSE field that sets the reconnect delay in milliseconds (the spec leaves the default to the browser, "a few seconds"). Lines starting with a colon are comments the browser ignores, so the server sends : keepalive periodically to stop idle-timeout rules in proxies from closing a quiet connection.
Backend: one code path for replay and live
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const HEARTBEAT_MS = Number(process.env.HEARTBEAT_MS ?? 25000);
const subs = new Map(); // ticket id (string) -> Set of open streams
let outage = false; // test hook: refuse new streams
const json = (res, status, data) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
};
const COLS = 'seq, author, body, created_at';
// Write every reply this stream has not yet received. The database is the source of truth,
// so replay after a reconnect and live delivery are the same code path.
async function flush(sub) {
if (sub.busy) { sub.again = true; return; }
sub.busy = true;
try {
do {
sub.again = false;
let rows;
do {
({ rows } = await pool.query(
`SELECT ${COLS} FROM replies WHERE ticket_id = $1 AND seq > $2 ORDER BY seq LIMIT 100`,
[sub.ticket, sub.last]));
for (const r of rows) sub.res.write(`id: ${r.seq}\nevent: reply\ndata: ${JSON.stringify(r)}\n\n`);
if (rows.length) sub.last = rows[rows.length - 1].seq;
} while (rows.length === 100);
} while (sub.again);
} catch (err) { sub.res.destroy(); }
finally { sub.busy = false; }
}
// One LISTEN connection wakes the streams. NOTIFY is only a wake-up, never the data.
const listener = new pg.Client({ connectionString: process.env.DATABASE_URL });
await listener.connect();
await listener.query('LISTEN ticket_replies');
listener.on('notification', (msg) => { for (const sub of subs.get(msg.payload) ?? []) flush(sub); });
function openStream(req, res, ticket, url) {
if (outage) return req.socket.destroy();
const fromHeader = Number(req.headers['last-event-id'] ?? 0) || 0;
const fromQuery = Number(url.searchParams.get('after') ?? 0) || 0;
res.writeHead(200, {
'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no',
});
res.write('retry: 500\n\n'); // reconnect delay in ms, set by the server
const sub = { ticket, res, last: Math.max(fromHeader, fromQuery), busy: false, again: false };
if (!subs.has(ticket)) subs.set(ticket, new Set());
subs.get(ticket).add(sub); // register BEFORE the first read, so nothing slips between
const beat = setInterval(() => res.write(': keepalive\n\n'), HEARTBEAT_MS);
req.on('close', () => { clearInterval(beat); subs.get(ticket).delete(sub); });
flush(sub);
}
async function readJson(req) {
let raw = '';
for await (const c of req) { raw += c; if (raw.length > 65536) throw Object.assign(new Error('too large'), { status: 413 }); }
try { return JSON.parse(raw); } catch { throw Object.assign(new Error('invalid JSON'), { status: 400 }); }
}
async function addReply(req, res, ticket) {
const input = await readJson(req);
const body = typeof input.body === 'string' ? input.body.trim() : '';
const author = typeof input.author === 'string' ? input.author.trim() : '';
if (!body || body.length > 5000 || !author) return json(res, 422, { errors: { body: 'A reply needs an author and 1 to 5000 characters.' } });
const db = await pool.connect();
try {
await db.query('BEGIN');
// Taking the next number locks the ticket row, so replies on one ticket commit in seq order.
const t = await db.query('UPDATE tickets SET last_seq = last_seq + 1 WHERE id = $1 RETURNING last_seq', [ticket]);
if (t.rowCount === 0) { await db.query('ROLLBACK'); return json(res, 404, { error: 'No such ticket' }); }
const { rows } = await db.query(
`INSERT INTO replies (ticket_id, seq, author, body) VALUES ($1, $2, $3, $4) RETURNING ${COLS}`,
[ticket, t.rows[0].last_seq, author, body]);
await db.query('SELECT pg_notify($1, $2)', ['ticket_replies', ticket]); // delivered when the transaction commits
await db.query('COMMIT');
json(res, 201, rows[0]);
} catch (err) { await db.query('ROLLBACK').catch(() => {}); throw err; }
finally { db.release(); }
}
http.createServer(async (req, res) => {
try {
const url = new URL(req.url, 'http://x');
const file = { '/': ['index.html', 'text/html; charset=utf-8'], '/client.js': ['client.js', 'text/javascript'], '/replies.js': ['replies.js', 'text/javascript'] }[url.pathname];
if (req.method === 'GET' && file) {
res.writeHead(200, { 'Content-Type': file[1] });
return res.end(await readFile(new URL(`./public/${file[0]}`, import.meta.url)));
}
if (process.env.TEST_HOOKS === '1' && url.pathname === '/test/outage') {
outage = url.searchParams.get('on') === '1';
if (outage) for (const set of subs.values()) for (const s of set) s.res.socket.destroy();
return json(res, 200, { outage });
}
const m = url.pathname.match(/^\/api\/tickets\/(\d{1,18})\/(replies|stream)$/);
if (!m) return json(res, 404, { error: 'Not found' });
const [, ticket, what] = m;
if (what === 'stream' && req.method === 'GET') return openStream(req, res, ticket, url);
if (what === 'replies' && req.method === 'GET') {
const after = Number(url.searchParams.get('after') ?? 0) || 0;
const { rows } = await pool.query(
`SELECT ${COLS} FROM replies WHERE ticket_id = $1 AND seq > $2 ORDER BY seq LIMIT 200`, [ticket, after]);
return json(res, 200, { replies: rows });
}
if (what === 'replies' && req.method === 'POST') return await addReply(req, res, ticket);
json(res, 405, { error: 'Method not allowed' });
} catch (err) {
if (err.status) return json(res, err.status, { error: err.message });
console.error(err); json(res, 500, { error: 'Server error' });
}
}).listen(3000, () => console.log('listening'));
LISTENandNOTIFYare PostgreSQL's built-in publish and subscribe: a connection that ranLISTEN ticket_repliesreceives a short message whenever any session runsNOTIFY(or the function form,pg_notify) on that channel. The server keeps one such dedicated listener connection open for the whole process.- A write takes the next
seq, inserts the row, and callspg_notifyin the same transaction. PostgreSQL delivers a notification only if the transaction commits, and delivers notifications from different transactions in commit order, so a rolled-back reply wakes nobody. - A notification is only a wake-up. Its payload is the ticket id; each open stream for that ticket then runs
flush, which queries "rows after what this stream last sent" and writes them. A reconnect runs the sameflushwithlasttaken fromLast-Event-ID. There is no separate "replay" and "live" logic to disagree. - No race at the start. The stream registers itself in
subsbefore its firstflush. A reply committed during the first read sets theagainflag and is picked up by the loop. A reply committed before registration is found by the query. There is no instant when a reply falls between the two. - Tracing
flushwith real values.busymeans "a flush for this stream is already running" andagainmeans "a wake-up arrived while it was running". Say a stream haslast = 2, the database holds replies 1 to 4, and reply 5 is committed while the first query is in flight. (1)flushstarts:busy = true,again = false. (2) The inner query asks forseq > 2and returns replies 3 and 4 (2 rows, fewer than the page size of 100, so the inner loop ends); they are written andlast = 4. (3) Meanwhile reply 5 committed and its notification calledflushagain; becausebusywas true that call only setagain = trueand returned. (4) The outerwhile (sub.again)seestrue, so the loop runs again:againis reset tofalse, the query asks forseq > 4, returns reply 5, andlast = 5. (5)againis stillfalse, so the function ends andbusybecomesfalse. Nothing can slip between step 5's check andbusy = false, because that part of the code has noawait, and JavaScript runs one piece of synchronous code to completion before any other callback runs. If a query ever returns exactly 100 rows, the innerwhile (rows.length === 100)repeats the query for the next page. - Because the notification travels through the database, this works with several server instances: each holds its own
LISTENconnection. The shipped listener has no reconnect handler: an unhandled error on that connection would end the process. A production version reconnects, re-runsLISTEN, and then runsflushfor every open stream, which repairs any missed wake-up because the data is never in the notification; the keepalive write notices dead sockets. - The
X-Accel-Buffering: noheader tells nginx (a widely used web server that is often placed in front of an application and forwards requests to it, which is what a reverse proxy does) not to buffer this response; nginx documents that header as turning response buffering off for one response, and buffering is on by default, which would hold messages back. outageand the/test/outageroute exist only so the test can force a dropped connection; they are inert unlessTEST_HOOKS=1.
Client state
The rules for the list live in a pure function with no DOM or network:
// Pure state for the reply list. No DOM, no network: easy to test.
export const initial = () => ({ last: 0, items: [] });
// Apply a batch of replies. Rules, per reply in seq order:
// seq <= last already shown (a replay or a duplicate): ignore
// seq === last + 1 the next one: append it
// seq > last + 1 a hole: stop, and tell the caller to fetch the missing range
export function apply(state, incoming) {
let { last, items } = state;
let gap = false, added = 0;
for (const r of [...incoming].sort((a, b) => a.seq - b.seq)) {
if (r.seq <= last) continue;
if (r.seq !== last + 1) { gap = true; break; }
items = [...items, r]; last = r.seq; added++;
}
return { state: { last, items }, gap, added };
}
The page wires it to the network:
import { initial, apply } from './replies.js';
const TICKET = 1;
let state = initial();
let es = null;
const setConn = (text) => { document.getElementById('conn').textContent = text; };
function render() {
const ol = document.getElementById('replies');
ol.replaceChildren(...state.items.map((r) => {
const li = document.createElement('li');
li.dataset.seq = r.seq;
li.textContent = `${r.author}: ${r.body}`;
return li;
}));
}
function ingest(list) {
const r = apply(state, list);
state = r.state;
if (r.added) render();
if (r.gap || list.length === 200) catchUp(); // a hole, or a full page that may have more behind it
}
async function catchUp() {
const res = await fetch(`/api/tickets/${TICKET}/replies?after=${state.last}`);
if (res.ok) ingest((await res.json()).replies);
}
function connect() {
es = new EventSource(`/api/tickets/${TICKET}/stream?after=${state.last}`);
es.onopen = () => setConn('Live');
es.addEventListener('reply', (e) => ingest([JSON.parse(e.data)]));
es.onerror = () => {
setConn('Reconnecting...');
if (es.readyState === EventSource.CLOSED) { es.close(); setTimeout(connect, 2000); } // the browser gave up (for example on a non-200 reply): retry ourselves
};
}
await catchUp(); // history first, so the stream starts from state.last
connect();
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Ticket 1</title></head>
<body>
<h1>Ticket 1</h1>
<p id="conn" role="status">Connecting...</p>
<ol id="replies"></ol>
<script type="module" src="/client.js"></script>
</body>
</html>
- The order at load matters: fetch history first, then open the stream with
after=state.last. Anything posted in between arrives on the stream, anything before is already in history. ingestis the only way a reply reaches the screen, whether it came from the stream, from a catch-up fetch, or from both at once. That single door is what prevents a double display.es.onerrorfires for every dropped connection.readyStateis the connection's state:CONNECTINGmeans the browser is trying (again) to connect,OPENmeans it is connected, andCLOSEDmeans it has stopped for good. WhilereadyStateisCONNECTINGthe browser is already retrying, so the code only updates the status text. If it isCLOSED, the browser has given up (the HTML specification fails the connection for any HTTP status other than 200, and a204is the way to tell the client to stop), so the code retries itself.- Rendering uses
textContent, so a reply containing markup shows as text. - Browsers limit simultaneous HTTP/1.1 connections per site; MDN gives 6 per browser for SSE, which agents with many tickets in tabs can hit. With HTTP/2, which carries many independent streams over one connection, the negotiated limit defaults to 100 streams (MDN), so serve the stream over HTTP/2.
The drop, walked through
The reducer on its own, then the server's starting-point rule, then the real page in Chromium with the connection killed while replies keep arriving:
import { chromium } from 'playwright';
import { initial, apply } from './public/replies.js';
const base = 'http://localhost:3000';
const post = (author, body) => fetch(`${base}/api/tickets/1/replies`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ author, body }) }).then((r) => r.json());
const seqs = (page) => page.$$eval('#replies li', (els) => els.map((e) => Number(e.dataset.seq)));
// 1. The reducer rules on their own
const r = (n) => ({ seq: n });
let s = initial();
const step = (label, batch) => { const o = apply(s, batch); s = o.state; console.log(label.padEnd(34), 'shown=' + JSON.stringify(s.items.map((x) => x.seq)), 'gap=' + o.gap); };
step('1, 2 arrive', [r(1), r(2)]);
step('2 again (duplicate)', [r(2)]);
step('1, 2, 3 replayed (overlap)', [r(1), r(2), r(3)]);
step('5 arrives, 4 missing', [r(5)]);
step('catch-up brings 4, 5', [r(4), r(5)]);
// 2. What the server does with Last-Event-ID and ?after
async function streamSeqs(url, headers, want) {
const ctl = new AbortController();
const res = await fetch(url, { headers, signal: ctl.signal });
const got = []; let buf = '';
for await (const chunk of res.body) {
buf += Buffer.from(chunk).toString();
for (const m of buf.matchAll(/^id: (\d+)$/gm)) if (!got.includes(+m[1])) got.push(+m[1]);
if (got.length >= want) break;
}
ctl.abort(); return got;
}
for (const n of [1, 2, 3]) await post('customer', `reply ${n}`);
console.log('after=0, no header ->', JSON.stringify(await streamSeqs(`${base}/api/tickets/1/stream?after=0`, {}, 3)));
console.log('after=0, Last-Event-ID: 2 ->', JSON.stringify(await streamSeqs(`${base}/api/tickets/1/stream?after=0`, { 'Last-Event-ID': '2' }, 1)));
// 3. The real page, with a dropped connection and replies posted during the outage
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(base);
await page.waitForFunction(() => document.getElementById('conn').textContent === 'Live');
console.log('loaded:', JSON.stringify(await seqs(page)));
await post('customer', 'reply 4');
await page.waitForSelector('li[data-seq="4"]');
console.log('live push:', JSON.stringify(await seqs(page)));
await fetch(`${base}/test/outage?on=1`);
await page.waitForFunction(() => document.getElementById('conn').textContent === 'Reconnecting...');
await post('customer', 'reply 5');
await post('customer', 'reply 6');
console.log('during outage the page shows:', JSON.stringify(await seqs(page)));
await fetch(`${base}/test/outage?on=0`);
await page.waitForSelector('li[data-seq="6"]');
await page.waitForFunction(() => document.getElementById('conn').textContent === 'Live');
console.log('after reconnect:', JSON.stringify(await seqs(page)));
await browser.close();
It prints (run in the Playwright image, Node 20.18, Chromium 130):
1, 2 arrive shown=[1,2] gap=false
2 again (duplicate) shown=[1,2] gap=false
1, 2, 3 replayed (overlap) shown=[1,2,3] gap=false
5 arrives, 4 missing shown=[1,2,3] gap=true
catch-up brings 4, 5 shown=[1,2,3,4,5] gap=false
after=0, no header -> [1,2,3]
after=0, Last-Event-ID: 2 -> [3]
loaded: [1,2,3]
live push: [1,2,3,4]
during outage the page shows: [1,2,3,4]
after reconnect: [1,2,3,4,5,6]
Reading the output: replaying 1, 2, 3 over a page that already shows 1, 2 adds only 3 (no double), and a jump to 5 is held back until the catch-up brings 4 (no loss, still in order). The stream started with after=0 and Last-Event-ID: 2 sends only 3, so the header wins when it is larger. In the page, the outage refuses every new stream, replies 5 and 6 are posted meanwhile, the page still shows [1,2,3,4], and a moment after the outage ends it shows [1,2,3,4,5,6], each once, in order. The whole run (server, test and the two-session demo) prints the same output every time, because every browser wait is on a condition, not a delay.
Failure modes and what to watch
Ordered by how many users a failure touches: a restart touches every page, a slow reader touches one stream, and the rest are checks that keep the system honest.
- Server restart or deploy: every stream drops and every page reconnects within the 500 ms hint at once. Add jitter (a random extra delay, so clients do not all act in the same instant) by sending a randomised
retryvalue, so a thousand pages do not arrive together. - Slow or stuck client:
res.writequeues in memory for a client that stopped reading. Handling this is called back-pressure: the sender notices the receiver cannot keep up and stops queueing for it. Production code checks the write result and closes streams that fall behind; the reconnect replays what it missed. - Authorization: the stream must check that this agent may see this ticket before registering; that check belongs in the same place as the one on the catch-up call.
- Observe: the number of open streams, reconnects per minute, the age of the oldest unsent reply per stream, and the count of
gapcatch-ups (a non-zero count in steady state means a bug or a dropped message path). - Tests to keep: the reducer cases above (pure), the two-session ordering demo against a real database, and the outage scenario in a real browser.
Running the code
docker network create tix-net
docker run -d --rm --name tix-pg --network tix-net -e POSTGRES_PASSWORD=pw postgres:16
sleep 5 # wait for Postgres to accept connections
docker exec tix-pg psql -U postgres -c "CREATE DATABASE tix"
docker exec -i tix-pg psql -U postgres -d tix < schema.sql
# in a folder holding schema.sql, server.mjs, test.mjs, gap-demo.mjs, public/ and package.json {"type":"module"}:
docker run --rm --network tix-net -v "$PWD":/w -w /w -e DATABASE_URL=postgres://postgres:pw@tix-pg:5432/tix \
-e TEST_HOOKS=1 -e HEARTBEAT_MS=300 mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i pg@8 playwright@1.48.2; node server.mjs & sleep 3; node test.mjs; node gap-demo.mjs'
gap-demo.mjs, the two-session program that printed the lines A, B and C above:
import pg from 'pg';
const url = process.env.DATABASE_URL;
const client = async () => { const c = new pg.Client({ connectionString: url }); await c.connect(); return c; };
const [a, b, reader] = [await client(), await client(), await client()];
const ids = async (sql, params) => (await reader.query(sql, params)).rows.map((r) => r.n);
await reader.query('CREATE TABLE naive (id bigserial PRIMARY KEY, body text)');
await a.query('BEGIN'); await a.query("INSERT INTO naive (body) VALUES ('from A')"); // A takes id 1
await b.query('BEGIN'); await b.query("INSERT INTO naive (body) VALUES ('from B')"); // B takes id 2
await b.query('COMMIT'); // B commits first
const first = await ids('SELECT id::int AS n FROM naive WHERE id > 0 ORDER BY id');
console.log('A. global id: poll after 0 sees', JSON.stringify(first), '-> cursor =', Math.max(...first));
await a.query('COMMIT'); // A commits late
console.log('A. then poll after', Math.max(...first), 'sees', JSON.stringify(await ids('SELECT id::int AS n FROM naive WHERE id > $1 ORDER BY id', [Math.max(...first)])), '(reply 1 is never delivered)');
await reader.query('CREATE TABLE tk (id int PRIMARY KEY, last_seq int NOT NULL DEFAULT 0)');
await reader.query('CREATE TABLE rp (ticket_id int, seq int, body text, PRIMARY KEY (ticket_id, seq))');
await reader.query('INSERT INTO tk VALUES (1, 0)');
const take = async (c, body) => { const { rows } = await c.query('UPDATE tk SET last_seq = last_seq + 1 WHERE id = 1 RETURNING last_seq'); await c.query('INSERT INTO rp VALUES (1, $1, $2)', [rows[0].last_seq, body]); return rows[0].last_seq; };
await a.query('BEGIN'); const seqA = await take(a, 'from A');
await b.query('BEGIN');
const pidB = (await b.query('SELECT pg_backend_pid() AS p')).rows[0].p;
const pendingB = take(b, 'from B'); // starts, then must wait for A
let waiting = false;
while (!waiting) {
waiting = (await reader.query("SELECT 1 FROM pg_stat_activity WHERE pid = $1 AND wait_event_type = 'Lock'", [pidB])).rowCount === 1;
if (!waiting) await new Promise((r) => setTimeout(r, 20));
}
console.log('B. A holds seq', seqA, '; B is waiting on a lock, and nothing of B is visible:', JSON.stringify(await ids('SELECT seq AS n FROM rp')));
await a.query('COMMIT');
const seqB = await pendingB; await b.query('COMMIT');
console.log('B. after A commits, B gets seq', seqB, '; reader sees', JSON.stringify(await ids('SELECT seq AS n FROM rp ORDER BY seq')));
await a.query('BEGIN'); const rolled = await take(a, 'will roll back'); await a.query('ROLLBACK');
await b.query('BEGIN'); const next = await take(b, 'next'); await b.query('COMMIT');
console.log('C. A took seq', rolled, 'then rolled back; the next writer gets seq', next, '(no hole)');
await reader.query('DROP TABLE naive, rp, tk');
await Promise.all([a.end(), b.end(), reader.end()]);
A cinema booking page lets users pick seats and then pay on the next screen (payment is handled by another team's service). Walk me through the seat-selection feature end to end so that two people can never end up with the same seat: what the seat map shows, the API calls, how a seat is held and released, and the database rule that makes a double booking impossible.
Sample Answer
Direct answer
The guarantee comes from the database, not from the screen or the API: one table with one row per seat per showing and a primary key on (showing_id, seat_id), so PostgreSQL itself refuses a second claim on the same seat, however many requests arrive at once. A seat moves through three states: free (no row, or an expired hold), held (a row with an expiry time, owned by one person's hold) and booked (the row, with the expiry cleared). The seat map is only advisory (a picture that helps the user choose, not a promise) and may be a few seconds stale; the hold call is the only thing that decides who gets a seat. Because payment belongs to another team's service, the booking is confirmed only by the payment result that arrives on the server, never by the browser saying "I paid".
The seat map (UI)
| Seat state | Looks like | Clickable |
|---|---|---|
| available | normal colour | yes |
| held by someone else | greyed, label "being selected" | no |
| booked | greyed with a different pattern (not colour alone, for colour-blind users) | no |
| yours | highlighted, with a countdown shown beside the "Continue to payment" button | yes, to deselect |
- Selecting seats is local until the user presses Continue; the browser then asks the server to hold all chosen seats in one call. This keeps seats from being locked by people who click around.
- Each seat has an accessible name and state ("Row F, seat 7, available"), is operable by keyboard, and a changed state is announced through a live region (a part of the page that screen readers read out when its text changes;
aria-live="polite"means "wait until the user is idle"). - The map refreshes by polling every 10 seconds while the tab is visible (a push channel such as Server-Sent Events, where the server keeps a connection open and sends updates, is an upgrade, not a requirement). A seat that turns grey while the user is hovering gets a message when clicked: "That seat was just taken. Pick another."
- The countdown starts from the
seconds_leftthe server returns, not from the user's clock, and re-syncs on every response. When it hits zero the page says the hold expired and takes the user back to the map with their selection cleared.
API calls
| Call | Meaning | Success | Failure |
|---|---|---|---|
GET /v1/showings/{id}/seats | seat states for the viewer, including seconds_left for their own hold | 200 | 404 unknown showing |
POST /v1/showings/{id}/holds with {"hold_id":"<uuid made by the client>","seats":["F7","F8"]} | hold every listed seat, or none | 201 {"hold_id","seats","seconds_left"} | 409 {"unavailable":["F8"]} and nothing is held; 422 more than 6 seats or an unknown seat id |
DELETE /v1/holds/{hold_id} | the user deselects or leaves | 204, also when already gone | |
POST /v1/holds/{hold_id}/checkout | start payment: extend the hold, call the payment service | 200 with the payment page or token | 409 the hold has already expired (the seats may already belong to someone else, or may still be free); the page sends the user back to the map to hold again |
POST /internal/payment-events (called by the payment service) | tells us a payment succeeded or failed | 200 |
- MDN defines
409 Conflictas a conflict with the current state of the target resource, which is exactly "that seat is no longer free".422 Unprocessable Contentmeans the request was understood but cannot be processed, which fits a request for seven seats when six is the limit. - The client makes the
hold_id(a random UUID). If the response to the hold call is lost and the browser retries, the samehold_idmakes the retry recognise its own hold instead of failing against it. A retry must not extend the hold, or a client could keep a seat forever by calling again; the SQL below keeps the old expiry in that case. - A hold lasts 8 minutes in the examples. That number is a product choice: long enough to find a card, short enough that an abandoned tab does not block a sold-out show for long.
The database rule and the operations
CREATE TABLE seat_claims (
showing_id bigint NOT NULL,
seat_id text NOT NULL,
status text NOT NULL CHECK (status IN ('held', 'booked')),
holder_id bigint NOT NULL,
hold_id uuid NOT NULL,
expires_at timestamptz,
CHECK ((status = 'held') = (expires_at IS NOT NULL)),
PRIMARY KEY (showing_id, seat_id)
);
CREATE FUNCTION try_hold(p_showing bigint, p_seat text, p_user bigint, p_hold uuid, p_ttl interval)
RETURNS boolean LANGUAGE sql AS $$
WITH r AS (
INSERT INTO seat_claims AS c (showing_id, seat_id, status, holder_id, hold_id, expires_at)
VALUES (p_showing, p_seat, 'held', p_user, p_hold, now() + p_ttl)
ON CONFLICT (showing_id, seat_id) DO UPDATE
SET holder_id = EXCLUDED.holder_id,
hold_id = EXCLUDED.hold_id,
expires_at = CASE WHEN c.hold_id = EXCLUDED.hold_id AND c.expires_at > now()
THEN c.expires_at ELSE EXCLUDED.expires_at END
WHERE c.status = 'held'
AND (c.expires_at <= now() OR c.hold_id = EXCLUDED.hold_id)
RETURNING 1)
SELECT EXISTS (SELECT 1 FROM r);
$$;
CREATE FUNCTION try_hold_many(p_showing bigint, p_seats text[], p_user bigint, p_hold uuid, p_ttl interval,
p_pause_s double precision DEFAULT 0)
RETURNS text[] LANGUAGE plpgsql AS $$
DECLARE s text; bad text[] := '{}';
BEGIN
FOR s IN SELECT x FROM unnest(p_seats) x ORDER BY x LOOP
IF NOT try_hold(p_showing, s, p_user, p_hold, p_ttl) THEN bad := bad || s; END IF;
PERFORM pg_sleep(p_pause_s); -- demo hook: widens the gap between two seats; 0 in real use
END LOOP;
RETURN bad;
END $$;
CREATE FUNCTION confirm_hold(p_hold uuid) RETURNS integer LANGUAGE sql AS $$
WITH u AS (
UPDATE seat_claims SET status = 'booked', expires_at = NULL
WHERE hold_id = p_hold AND status = 'held' RETURNING 1)
SELECT count(*)::int FROM u;
$$;
CREATE FUNCTION extend_hold(p_hold uuid, p_ttl interval) RETURNS integer LANGUAGE sql AS $$
WITH u AS (
UPDATE seat_claims SET expires_at = now() + p_ttl
WHERE hold_id = p_hold AND status = 'held' AND expires_at > now() RETURNING 1)
SELECT count(*)::int FROM u;
$$;
CREATE FUNCTION release_hold(p_hold uuid) RETURNS integer LANGUAGE sql AS $$
WITH d AS (DELETE FROM seat_claims WHERE hold_id = p_hold AND status = 'held' RETURNING 1)
SELECT count(*)::int FROM d;
$$;
CREATE FUNCTION seat_state(p_showing bigint, p_seat text, p_hold uuid) RETURNS text LANGUAGE sql STABLE AS $$
SELECT COALESCE((SELECT CASE WHEN c.status = 'booked' THEN 'booked'
WHEN c.expires_at <= now() THEN 'available'
WHEN c.hold_id = p_hold THEN 'yours'
ELSE 'held' END
FROM seat_claims c WHERE c.showing_id = p_showing AND c.seat_id = p_seat), 'available');
$$;
Terms used in that SQL: an upsert is an insert that turns into an update when the row already exists, which is what INSERT ... ON CONFLICT ... DO UPDATE does. Inside DO UPDATE, EXCLUDED is the row you tried to insert (the new claim) and c is the alias for the row already in the table (the existing claim). The CASE expression is an if/else that returns one value: here, "keep the old expiry if this is a retry of a live hold, otherwise use the new one". RETURNING 1 makes the statement hand back a row only when an insert or update really happened, and EXISTS (SELECT 1 FROM r) turns "a row came back" into true. plpgsql is PostgreSQL's built-in procedural language (loops and variables), used for try_hold_many; unnest turns an array into rows; ORDER BY x inside it puts the seats in one fixed order. pg_sleep(p_pause_s) pauses for that many seconds; it is a demo hook (the argument is 0 in real use) that lets the concurrency script below hold one seat for a while before the next one is taken. extend_hold pushes the expiry of a hold that is still live and touches nothing once the hold has expired.
How try_hold decides, step by step:
- It tries to
INSERTthe claim. If no row exists for that seat, the insert succeeds and the caller owns the seat. - If a row exists, the primary key raises a conflict, and
ON CONFLICT ... DO UPDATE ... WHEREruns instead. TheWHEREallows the update in exactly two cases: the existing hold has expired (expires_at <= now()), so the seat is up for grabs again; or it is the same hold asking again (a retry). A booked row hasstatus = 'booked', so it never matches. - If the
WHEREis false, no row is returned and the function answersfalse. TheCASEkeeps the old expiry for a retry of a live hold.
There is no background job in this design. Expiry is checked at the moment of the claim (expires_at <= now()) and by the seat map query, so correctness does not depend on a cleanup job running on time. A nightly job that deletes long-expired rows only keeps the table tidy.
Run in a postgres:16 container, this test file (seats_test.sql, with \set lines that name four hold ids) prints the following. Rows are claimed by user number; "payment arrives" calls confirm_hold.
\set h1 '''11111111-1111-1111-1111-111111111111'''
\set h2 '''22222222-2222-2222-2222-222222222222'''
\set h3 '''33333333-3333-3333-3333-333333333333'''
\set h4 '''44444444-4444-4444-4444-444444444444'''
SELECT '1 user 100 holds F7: ' || try_hold(1,'F7',100,:h1,'8 minutes');
SELECT '2 user 200 holds F7: ' || try_hold(1,'F7',200,:h2,'8 minutes');
SELECT '3 user 100 retries the same hold: ' || try_hold(1,'F7',100,:h1,'8 minutes');
UPDATE seat_claims SET expires_at = now() + interval '1 minute' WHERE seat_id = 'F7';
SELECT '3b retry on a hold with 1 minute left: ' || try_hold(1,'F7',100,:h1,'8 minutes');
SELECT '3c expiry still under 2 minutes: ' || (expires_at < now() + interval '2 minutes') FROM seat_claims WHERE seat_id = 'F7';
SELECT '4 map for user 100 / user 200 / F8 for user 200: ' || seat_state(1,'F7',:h1) || ' / ' || seat_state(1,'F7',:h2) || ' / ' || seat_state(1,'F8',:h2);
UPDATE seat_claims SET expires_at = now() - interval '1 second' WHERE seat_id = 'F7';
SELECT '5 map for user 200 after expiry: ' || seat_state(1,'F7',:h2);
SELECT '6 user 200 takes the expired seat: ' || try_hold(1,'F7',200,:h2,'8 minutes');
SELECT '7 user 100 payment arrives, rows booked: ' || confirm_hold(:h1);
SELECT '8 user 200 payment arrives, rows booked: ' || confirm_hold(:h2);
SELECT '9 user 300 tries the booked seat: ' || try_hold(1,'F7',300,:h3,'8 minutes');
SELECT '10 G1 held by user 100: ' || try_hold(1,'G1',100,:h1,'8 minutes');
UPDATE seat_claims SET expires_at = now() - interval '1 second' WHERE seat_id = 'G1';
SELECT '11 late payment, nobody took G1, rows booked: ' || confirm_hold(:h1);
BEGIN;
SELECT '12 user 400 asks for H2, H1, F7 -> unavailable: ' || array_to_string(try_hold_many(1, ARRAY['H2','H1','F7'], 400, :h3, '8 minutes'), ',');
SELECT '13 inside the transaction, user 400 rows: ' || count(*) FROM seat_claims WHERE hold_id = :h3;
ROLLBACK;
SELECT '14 after ROLLBACK, user 400 rows: ' || count(*) FROM seat_claims WHERE hold_id = :h3;
SELECT '15 hold J1, then release twice: ' || try_hold(1,'J1',500,:h3,'8 minutes') || ', ' || release_hold(:h3) || ' row, then ' || release_hold(:h3) || ' rows';
SELECT '16 hold K1, confirm twice: ' || try_hold(1,'K1',600,:h3,'8 minutes') || ', ' || confirm_hold(:h3) || ' row, then ' || confirm_hold(:h3) || ' rows';
SELECT '16b seats booked under that hold afterwards: ' || count(*) FROM seat_claims WHERE hold_id = :h3 AND status = 'booked';
SELECT '17 hold L1 for 1 minute, extend by 10: ' || try_hold(1,'L1',700,:h4,'1 minute') || ', ' || extend_hold(:h4,'10 minutes') || ' row';
SELECT '17b expiry now more than 9 minutes away: ' || (expires_at > now() + interval '9 minutes') FROM seat_claims WHERE seat_id = 'L1';
UPDATE seat_claims SET expires_at = now() - interval '1 second' WHERE seat_id = 'L1';
SELECT '17c extend after the hold expired: ' || extend_hold(:h4,'10 minutes') || ' rows';
1 user 100 holds F7: true
2 user 200 holds F7: false
3 user 100 retries the same hold: true
3b retry on a hold with 1 minute left: true
3c expiry still under 2 minutes: true
4 map for user 100 / user 200 / F8 for user 200: yours / held / available
5 map for user 200 after expiry: available
6 user 200 takes the expired seat: true
7 user 100 payment arrives, rows booked: 0
8 user 200 payment arrives, rows booked: 1
9 user 300 tries the booked seat: false
10 G1 held by user 100: true
11 late payment, nobody took G1, rows booked: 1
12 user 400 asks for H2, H1, F7 -> unavailable: F7
13 inside the transaction, user 400 rows: 2
14 after ROLLBACK, user 400 rows: 0
15 hold J1, then release twice: true, 1 row, then 0 rows
16 hold K1, confirm twice: true, 1 row, then 0 rows
16b seats booked under that hold afterwards: 1
17 hold L1 for 1 minute, extend by 10: true, 1 row
17b expiry now more than 9 minutes away: true
17c extend after the hold expired: 0 rows
Lines 7 and 11 are the payment edge ("rows booked" is how many seats the confirm call turned into bookings): when user 100's payment arrives after the hold expired, the outcome depends on one thing, whether anyone took the seat in between. In line 7 user 200 had, so user 100's confirm updates 0 rows. In line 11 nobody had, so the confirm still wins (1 row). confirm_hold is deliberately not conditioned on the expiry time. The reason: the customer has already paid, and rejecting a payment merely because the clock passed the hold time, when nobody else wants the seat, would charge them and give them nothing. The takeover and the confirm both change the same row, the database runs them one after the other (it serialises them: puts them in a single line, one at a time), and whichever commits first wins. If the takeover wins, the confirm updates 0 rows and the refund path below handles it.
Two people, one seat: what the database does
seat_claims has the primary key, and concurrent claims are the case that matters, so the script below starts real concurrent sessions in the same container (concurrency.sh; it assumes the SQL above is loaded and the container is named pg-demo).
C=pg-demo
psql_() { docker exec -i "$C" psql -U postgres -q -A -t "$@"; }
HA=aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa; HB=bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb
echo "== 1. two sessions, same seat; A takes 3 seconds to commit"
psql_ -c "TRUNCATE seat_claims"
psql_ -c "BEGIN; SELECT 'A holds F7: ' || try_hold(1,'F7',100,'$HA','8 minutes'); SELECT pg_sleep(3); COMMIT; SELECT 'A committed at ' || to_char(clock_timestamp(),'SS.MS');" &
sleep 1
psql_ -c "SELECT 'B starts at ' || to_char(clock_timestamp(),'SS.MS'); SELECT 'B holds F7: ' || try_hold(1,'F7',200,'$HB','8 minutes'); SELECT 'B returned at ' || to_char(clock_timestamp(),'SS.MS');"
wait
echo "== 2. 50 clients race for one seat"
psql_ -c "TRUNCATE seat_claims; CREATE TABLE IF NOT EXISTS attempts (client int, ok boolean); TRUNCATE attempts;"
echo "INSERT INTO attempts SELECT :client_id, try_hold(1,'F7',:client_id,gen_random_uuid(),'8 minutes');" > hold.sql
docker cp hold.sql "$C":/hold.sql
docker exec "$C" pgbench -U postgres -n -c 50 -j 4 -t 1 -f /hold.sql postgres > /dev/null 2>&1
psql_ -c "SELECT 'succeeded: ' || count(*) FILTER (WHERE ok) || ', refused: ' || count(*) FILTER (WHERE NOT ok) || ', claim rows: ' || (SELECT count(*) FROM seat_claims) FROM attempts"
echo "== 3. opposite order, one seat at a time (deadlock) "
psql_ -c "TRUNCATE seat_claims"
{ psql_ -c "BEGIN; SELECT try_hold(1,'F7',100,'$HA','8 minutes'); SELECT pg_sleep(2); SELECT try_hold(1,'F8',100,'$HA','8 minutes'); COMMIT;" 2>&1 | sed 's/^/A: /'; } &
sleep 0.5
{ psql_ -c "BEGIN; SELECT try_hold(1,'F8',200,'$HB','8 minutes'); SELECT pg_sleep(2); SELECT try_hold(1,'F7',200,'$HB','8 minutes'); COMMIT;" 2>&1 | sed 's/^/B: /'; } &
wait
echo "== 4. same two requests through try_hold_many (sorted), 2 seconds between seats"
psql_ -c "TRUNCATE seat_claims"
{ psql_ -c "BEGIN; SELECT 'A unavailable: {' || array_to_string(try_hold_many(1, ARRAY['F8','F7'], 100, '$HA', '8 minutes', 2), ',') || '}'; COMMIT;" 2>&1; } &
sleep 0.5
{ psql_ -c "BEGIN; SELECT 'B unavailable: {' || array_to_string(try_hold_many(1, ARRAY['F7','F8'], 200, '$HB', '8 minutes', 2), ',') || '}'; ROLLBACK;" 2>&1; } &
wait
psql_ -c "SELECT 'owners afterwards: ' || string_agg(seat_id || '=' || holder_id, ', ' ORDER BY seat_id) FROM seat_claims"
What it prints (one sample run; the seconds in the timestamps differ every run, which of the two deadlocked sessions is cancelled can vary, the order in which the A and B lines of run 3 appear can vary, and the process and transaction numbers differ):
== 1. two sessions, same seat; A takes 3 seconds to commit
A holds F7: true
A committed at 54.236
B starts at 52.239
B holds F7: false
B returned at 54.236
== 2. 50 clients race for one seat
succeeded: 1, refused: 49, claim rows: 1
== 3. opposite order, one seat at a time (deadlock)
A: t
A:
A: ERROR: deadlock detected
A: DETAIL: Process 420 waits for ShareLock on transaction 910; blocked by process 427.
A: Process 427 waits for ShareLock on transaction 909; blocked by process 420.
A: HINT: See server log for query details.
A: CONTEXT: while inserting index tuple (0,2) in relation "seat_claims"
A: SQL function "try_hold" statement 1
B: t
B:
B: t
== 4. same two requests through try_hold_many (sorted), 2 seconds between seats
A unavailable: {}
B unavailable: {F7,F8}
owners afterwards: F7=100, F8=100
- Run 1: B asked for the seat while A's transaction had inserted the row but not yet committed. B did not fail immediately; the database made B wait (it returned only when A committed, about two seconds after it started) and then answered
false, because the row now exists and is held. There is no moment at which both think they own the seat. (A's lines print together once its command finishes, which is why they appear above B's even though B started first.) - Run 2: 50 clients (
pgbench, PostgreSQL's load-testing tool) claimed the same seat at once; exactly one succeeded and 49 were refused, with one row in the table. - Reading run 3. With
-t -A,psqlprints the bare result of each statement:tistry_holdreturning true, and a blank line is the result ofpg_sleep(it returns nothing, so an empty row). The lines are prefixed with the session that printed them. Timeline: A claims F7 (A: t); half a second later B claims F8 (B: t); after A's sleep it asks for F8 and must wait, because B holds an uncommitted claim on it; B's sleep ends and it asks for F7 and must wait for A. Each now waits for the other, a cycle that would never end. The lineERROR: deadlock detectedis PostgreSQL noticing the cycle and cancelling one session (here A; it can be either):DETAILnames who waits for whom (aShareLockis the lock a session waits on while another session's uncommitted claim on the same key finishes). A's work is undone, so B's lasttry_holdon F7 returnstand B ends up with both seats.
| time | session A | session B |
|---|---|---|
| 0 s | claims F7 | |
| 0.5 s | claims F8 | |
| 2 s | asks for F8, waits for B | |
| 2.5 s | asks for F7, waits for A (cycle: deadlock) |
- Run 3 is why
try_hold_manysorts the seats. Two people who each want seats F7 and F8 but whose requests lock them in opposite orders can wait on each other forever. PostgreSQL detects this and cancels one of the two withdeadlock detected, which would surface as a 500. Taking seats in one fixed order (alphabetical here, any consistent order works) removes the cycle: in run 4 the second request simply waits for F7, then learns both seats are taken. The two-second pause between seats is what gives the unsorted version time to deadlock: withORDER BY xdeleted fromtry_hold_many, the same run 4 ends inERROR: deadlock detectedlike run 3. - All or nothing: line 12 to 14 of the test output show
try_hold_manyreturning the unavailable seats, and the application then rolls back, so the user does not end up holding half of what they asked for. The API answers409with that list.
Payment handed to another team's service
The booking rule stays the same; what changes is who tells us the money arrived.
- Checkout calls
extend_holdto stretch the hold to cover the payment window (say, 10 minutes from the moment the user presses Pay) so the countdown cannot release seats while a card is being charged; if it returns fewer rows than the seats held, the hold has already expired and the API answers409(line 17c above). It then asks the payment service to create a payment with an idempotency key (a unique id sent with the request so a repeat is recognised and does not charge twice) equal to thehold_id, and an amount computed on the server from the seats and showing, never taken from the browser. - Confirmation happens in the payment service's server-to-server notification, authenticated per their contract. The handler calls
confirm_hold(hold_id), then counts the seats now booked under that hold (not just the rows this call changed) and compares that count with the number of seats paid for. It is safe to receive twice: the second call updates 0 rows, but the count of booked seats is still complete, so nothing is refunded (lines 16 and 16b above). - If the payment succeeded but fewer seats are booked under the hold than were paid for (the payment landed after the hold expired and another person took a seat, line 7 above), the handler asks the payment service to refund that payment, using a refund request keyed by the payment id, and the user is told plainly. This is rare by design but must exist.
- No notification arrives (timeout, lost message): do not release the seats on a timer while a payment is unresolved. A periodic job asks the payment service for the status of every pending checkout and applies the same rules. While the answer is still "pending", the same job calls
extend_holdfor that hold, so it must run more often than the extension lasts (say every minute against a 10-minute extension):extend_holdrefuses a hold that has already expired, and an expired hold can be taken by the next customer, in which case the refund rule in step 3 applies.
Trade-offs and failure modes
- Why not lock rows with
SELECT ... FOR UPDATE(a query that locks the rows it reads until the transaction ends) and flags in the app? It works, but the rule then lives in application code that every future endpoint must remember. A primary key cannot be forgotten. - Why not hold seats in Redis with a TTL? It gives automatic expiry, but the booking must still be written to a durable database, so you end up with two systems that can disagree. Consider it only if hold traffic becomes a load problem (Redis is an in-memory store whose keys can carry a TTL, a time-to-live after which they vanish), and keep the database row as the final authority.
- Hot seats (a few seats everyone wants): a popular showing makes many clients fight for the same rows. That is acceptable (each loses quickly with a
409); the cost is the polling traffic on the seat map, which a short cache of the map (a few seconds) absorbs. - Common wrong turns: trusting the seat map when confirming; using the client clock for expiry; confirming on the browser's "payment done" redirect; releasing seats on a timer while a payment is still unresolved; and checking "is the seat free?" with one query and inserting with another, which leaves a gap for the second person.
Running the code
Save the table and function block as seats.sql, the test as seats_test.sql, and the script as concurrency.sh.
docker run -d --rm --name pg-demo -e POSTGRES_PASSWORD=x postgres:16
sleep 8
docker exec -i pg-demo psql -U postgres -v ON_ERROR_STOP=1 < seats.sql
docker exec -i pg-demo psql -U postgres -q -A -t < seats_test.sql
bash concurrency.sh
docker stop pg-demo
You built a "redeem a gift code" feature: a form, a POST endpoint, and a table of codes that can each be used once. Which tests would you write at each layer, what would each test mock and what would it run for real, and which single end-to-end test is worth its cost?
Sample Answer
Direct answer
Test each layer for the thing only that layer can get wrong, and mock only the boundary the layer sits on. A mock is a stand-in that returns a pre-written answer instead of doing the real work: a mocked database that always replies "row updated" never enforces anything, while a mocked fetch that replies 409 lets a form test run without a server. The single-use rule lives in the database, so it is tested against a real Postgres with 20 callers at once; a mock cannot catch a race condition (a bug that appears only when two requests overlap in time, because the outcome depends on who gets there first). The endpoint is tested with a real HTTP server and that real database, checking status codes and the exact fields of every response. The form is tested in a simulated browser (jsdom) with the network call faked, because the form's job is to turn each server answer into the right screen. One end-to-end test (a real browser, real server, real database) is worth its cost: redeem a code with a messy-looking input, then redeem it again. It catches the wiring that every other test mocks away, and it covers the success path and the "already used" path in one run.
What to write first
If time is short, write in this order: the database test with simultaneous callers (the only place the money rule is proved), then the API test (the contract), then the component test, then the unit test, and the single end-to-end test last. The order follows risk: a double credit costs real money, a wrong error message costs a support ticket.
What each layer tests, mocks, and runs for real
| Layer | What it proves | Runs for real | Mocked |
|---|---|---|---|
Unit: normalizeCode | " k7qm-2xd4 p9ta " becomes K7QM2XD4P9TA; wrong lengths and symbols give null | the function | nothing |
Database: redeem() | success credits and marks the code; second redeem is 409; unknown is 404; a failed credit puts the code back to unused; 20 simultaneous redeemers produce one winner | Postgres 16, real transactions, real constraints | nothing |
API: POST /v1/gift-codes/redeem | each status (200, 401, 404, 409, 422) is returned with exactly the documented fields | HTTP server, handler, Postgres | the session (a cookie stands in for the login system) |
Component: RedeemForm | success text, specific error text per server answer, empty input never calls the server, double click sends one request, network failure re-enables the button | React component in jsdom, user events | fetch (the network boundary), with fake responses built from the shared contract |
| End to end | the bundled form in Chromium reaches the real endpoint, the cookie travels, the database changes, the second try is refused | everything | nothing except seeding the data |
A seam is a point where one part of the system hands off to the next (browser to server, server to database). Bugs hide at seams, because each side's tests assume the other side behaves. A contract file is one shared description of what a response contains, used by both sides' tests.
Two choices carry most of the value. First, the database tests do not mock the database. The rule "a code can be used once" is enforced by one conditional UPDATE ... WHERE redeemed_at IS NULL inside a transaction (a group of statements that commit together or not at all), and a mock would return whatever the test author told it to. Second, the component tests and the API tests share one contract file, so the fake responses the component is tested against have the same fields as the responses the API test proves the server really sends. If the server renames balance_cents, the API test fails first. If the contract file is then updated to the new name, the component test fails until the form reads it, because the success response it is given comes from the same file.
Why exactly one of 20 simultaneous callers wins
The rule is UPDATE gift_codes SET redeemed_at = now(), ... WHERE code_hash = $2 AND redeemed_at IS NULL. Take two callers, A and B, arriving at the same instant:
- A and B each start a transaction and send the
UPDATE. Both find the one matching row, because both seeredeemed_atasNULL. - The database lets one of them lock that row first. Say A does. A writes
redeemed_atand holds the lock until its transaction commits. - B now wants the same row, so PostgreSQL makes B wait. It does not fail B and it does not let B write.
- A commits. The row now has a
redeemed_atvalue. - B wakes up and re-evaluates its
WHEREclause against the committed row. The PostgreSQL manual describes this for the default isolation level (Read Committed): the waiting updater re-checks the search condition on the updated version of the row and skips the row if it no longer matches.redeemed_at IS NULLis now false, so B updates zero rows. - Zero rows means B is not the winner, and
redeem()answers409. With 20 callers the same thing repeats: one holds the lock, the other 19 wait, re-check and match nothing.
That is the whole mechanism: the database serialises writers on the row, and the IS NULL test is repeated after the wait. The check and the write are one statement, so there is no gap between them. A race is exactly such a gap: code that looks first and writes afterwards leaves time in between for another request to change the answer.
The naive version leaves that gap. Two callers, A and B, with the 50 ms pause where other work happens:
| Time | Caller A | Caller B |
|---|---|---|
| t0 | SELECT: code is unused | SELECT: code is unused |
| t1 | (pause) | (pause) |
| t2 | UPDATE marks the code used, credits $25.00 | UPDATE marks the code used again, credits $25.00 |
Both decisions were made at t0 on information that stopped being true at t2. With 20 callers all 20 pass the check, which is the "20 winners" in the output below.
The feature under test
DROP TABLE IF EXISTS gift_codes, users;
CREATE TABLE users (
id integer PRIMARY KEY,
balance_cents integer NOT NULL DEFAULT 0 CHECK (balance_cents BETWEEN 0 AND 100000) -- wallet limit: $1,000.00
);
CREATE TABLE gift_codes (
code_hash text PRIMARY KEY, -- sha256 of the normalised code, never the code itself
value_cents integer NOT NULL CHECK (value_cents > 0),
redeemed_by integer REFERENCES users(id),
redeemed_at timestamptz,
CHECK ((redeemed_by IS NULL) = (redeemed_at IS NULL)) -- a code is either unused or fully recorded as used
);
Only a hash of each code is stored, so a leaked table does not leak usable codes. The wallet limit (BETWEEN 0 AND 100000) is $1,000.00 in cents. The CHECK that ties redeemed_by and redeemed_at together means a code can never be half recorded as used. The wallet limit on balance_cents gives the "crediting fails" test something real to trip.
// redeem.mjs
import crypto from 'node:crypto';
// "k7qm-2xd4 p9ta " -> "K7QM2XD4P9TA"; null when it cannot be a code (12 letters or digits).
export function normalizeCode(raw) {
if (typeof raw !== 'string') return null;
const code = raw.replace(/[\s-]/g, '').toUpperCase();
return /^[A-Z0-9]{12}$/.test(code) ? code : null;
}
const hash = (code) => crypto.createHash('sha256').update(code).digest('hex');
const outcome = (status, body) => ({ status, body });
export async function redeem(pool, userId, raw) {
const code = normalizeCode(raw);
if (!code) return outcome(422, { error: 'invalid_code_format' });
const client = await pool.connect();
try {
await client.query('BEGIN');
// The single-use rule lives here: only one caller can flip redeemed_at from NULL.
const used = await client.query(
`UPDATE gift_codes SET redeemed_by = $1, redeemed_at = now()
WHERE code_hash = $2 AND redeemed_at IS NULL RETURNING value_cents`, [userId, hash(code)]);
if (used.rowCount === 0) {
await client.query('ROLLBACK');
const known = await pool.query('SELECT 1 FROM gift_codes WHERE code_hash = $1', [hash(code)]);
return known.rowCount ? outcome(409, { error: 'code_already_redeemed' }) : outcome(404, { error: 'code_not_found' });
}
const credited = await client.query(
'UPDATE users SET balance_cents = balance_cents + $2 WHERE id = $1 RETURNING balance_cents',
[userId, used.rows[0].value_cents]);
await client.query('COMMIT');
return outcome(200, { added_cents: used.rows[0].value_cents, balance_cents: credited.rows[0].balance_cents });
} catch (err) {
await client.query('ROLLBACK').catch(() => {});
throw err;
} finally {
client.release();
}
}
// The tempting version: look first, then write. A pause between the two stands for
// "call the fraud service" or any other work that sits between the check and the write.
export async function redeemNaive(pool, userId, raw) {
const code = normalizeCode(raw);
if (!code) return outcome(422, { error: 'invalid_code_format' });
const { rows: [c] } = await pool.query('SELECT value_cents, redeemed_at FROM gift_codes WHERE code_hash = $1', [hash(code)]);
if (!c) return outcome(404, { error: 'code_not_found' });
if (c.redeemed_at) return outcome(409, { error: 'code_already_redeemed' });
await pool.query('SELECT pg_sleep(0.05)');
await pool.query('UPDATE gift_codes SET redeemed_by = $1, redeemed_at = now() WHERE code_hash = $2', [userId, hash(code)]);
const r = await pool.query('UPDATE users SET balance_cents = balance_cents + $2 WHERE id = $1 RETURNING balance_cents', [userId, c.value_cents]);
return outcome(200, { added_cents: c.value_cents, balance_cents: r.rows[0].balance_cents });
}
redeem() does one thing in one place: the first statement flips redeemed_at from NULL only for the caller that gets there first; the others match zero rows and are told 409 (code exists) or 404 (it does not). The credit is in the same transaction, so a failure there undoes the "used" mark. redeemNaive() is the tempting alternative (read the row, see it unused, then write); it is included only so the test can be shown failing.
// contract.mjs
// What the endpoint answers. The API test checks real responses against these key lists;
// the component test builds its fake responses from the same table.
export const CONTRACT = {
200: { keys: ['added_cents', 'balance_cents'], example: { added_cents: 2500, balance_cents: 4000 } },
401: { keys: ['error'], error: 'sign_in_required' },
404: { keys: ['error'], error: 'code_not_found' },
409: { keys: ['error'], error: 'code_already_redeemed' },
422: { keys: ['error'], error: 'invalid_code_format' },
};
// server.mjs
import http from 'node:http';
import fs from 'node:fs';
import { redeem } from './redeem.mjs';
export function makeServer(pool, { staticDir } = {}) {
return http.createServer(async (req, res) => {
const send = (status, body, type = 'application/json') => {
res.writeHead(status, { 'content-type': type });
res.end(typeof body === 'string' ? body : JSON.stringify(body));
};
if (staticDir && req.method === 'GET') {
const f = req.url === '/' ? 'index.html' : req.url.slice(1);
if (fs.existsSync(`${staticDir}/${f}`)) return send(200, fs.readFileSync(`${staticDir}/${f}`, 'utf8'), f.endsWith('.js') ? 'text/javascript' : 'text/html');
}
if (req.method !== 'POST' || req.url !== '/v1/gift-codes/redeem') return send(404, { error: 'not_found' });
const userId = Number(/demo_session=(\d+)/.exec(req.headers.cookie || '')?.[1]); // stands in for the real session lookup
if (!userId) return send(401, { error: 'sign_in_required' });
let raw = ''; for await (const c of req) raw += c;
let body; try { body = JSON.parse(raw); } catch { body = {}; }
try {
const r = await redeem(pool, userId, body.code);
send(r.status, r.body);
} catch { send(500, { error: 'server_error' }); }
});
}
// RedeemForm.jsx
import { useState } from 'react';
const MESSAGES = {
invalid_code_format: 'That does not look like a gift code. It has 12 letters and numbers.',
code_not_found: 'We could not find that code. Check it and try again.',
code_already_redeemed: 'This code has already been used.',
sign_in_required: 'Please sign in again to redeem a code.',
};
const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;
export function RedeemForm() {
const [code, setCode] = useState('');
const [view, setView] = useState({ kind: 'idle' }); // idle | submitting | success | error
async function submit(event) {
event.preventDefault();
if (!code.trim()) { setView({ kind: 'error', message: 'Enter the code from your gift card.' }); return; }
setView({ kind: 'submitting' });
try {
const res = await fetch('/v1/gift-codes/redeem', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }) });
const body = await res.json();
if (res.ok) { setView({ kind: 'success', added: body.added_cents, balance: body.balance_cents }); setCode(''); }
else setView({ kind: 'error', message: MESSAGES[body.error] ?? 'Something went wrong. Please try again.' });
} catch {
setView({ kind: 'error', message: 'We could not reach the server. Check your connection and try again.' });
}
}
return (
<form onSubmit={submit}>
<label htmlFor="code">Gift code</label>
<input id="code" value={code} onChange={(e) => setCode(e.target.value)} autoComplete="off" />
<button type="submit" disabled={view.kind === 'submitting'}>
{view.kind === 'submitting' ? 'Redeeming...' : 'Redeem'}
</button>
{view.kind === 'error' && <p role="alert">{view.message}</p>}
{view.kind === 'success' && <p role="status">Added {dollars(view.added)}. Your balance is {dollars(view.balance)}.</p>}
</form>
);
}
The tests
What the trickier tests set up, and what a failure would mean:
test.eachtable (API test). One test body runs four times, once per row[expected status, request body, session]. A failure names the row, so you see which status code broke. Each run also compares the response's field names to the contract list, which catches a renamed field.- Double-click test (component).
fetchis replaced byvi.fn(...), a spy function that records its calls (toHaveBeenCalledTimes(1)reads that record). It returns a promise that stays unresolved until the test callsrelease(). Holding the answer back keeps the form in its "submitting" state, so the test can double-click and prove the second click does nothing. If the button were not disabled,fetchwould be called twice and the test fails. Afterrelease()the test waits for the success message so nothing is left running. mockResolvedValueandmockRejectedValue. The first makes the fakefetchreturn a ready answer (a server reply); the second makes it throw (no network).findByRole/getByRole. They look elements up the way a user and a screen reader find them: astatusis a polite announcement (success text), analertis an urgent one (error text), and a button is found by its visible name.findBywaits for the element to appear;getByexpects it to be there already.- Crediting-fails test (database). It sets a balance of $990.00 so the $25.00 credit would pass the $1,000.00 wallet limit. The database rejects the credit, and the test checks the code is back to unused. If the code stayed marked used, a customer would lose a code and get nothing.
redeemNaiveandpg_sleep(0.05).pg_sleeppauses the database session for 50 ms; it stands in for work that sits between looking and writing.
Unit, with no setup:
// unit.test.mjs
import { test, expect } from 'vitest';
import { normalizeCode } from './redeem.mjs';
test('normalises case, spaces and hyphens', () => {
expect(normalizeCode(' k7qm-2xd4 p9ta ')).toBe('K7QM2XD4P9TA');
});
test('rejects wrong length, symbols and non-strings', () => {
for (const bad of ['', 'K7QM2XD4P9T', 'K7QM2XD4P9TAA', 'K7QM2XD4P9T!', null, 42]) expect(normalizeCode(bad)).toBeNull();
});
Database, against real Postgres, including the concurrency test:
// db.test.mjs
import { test, expect, beforeAll, beforeEach, afterAll } from 'vitest';
import pg from 'pg';
import fs from 'node:fs';
import crypto from 'node:crypto';
import * as impl from './redeem.mjs';
const redeem = process.env.IMPL === 'naive' ? impl.redeemNaive : impl.redeem;
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres', max: 30 });
const CODE = 'K7QM2XD4P9TA';
const h = crypto.createHash('sha256').update(CODE).digest('hex');
const state = async () => ({
code: (await pool.query('SELECT redeemed_by FROM gift_codes WHERE code_hash=$1', [h])).rows[0].redeemed_by,
credited: (await pool.query('SELECT coalesce(sum(balance_cents),0)::int AS s FROM users')).rows[0].s,
});
beforeAll(async () => { await pool.query(fs.readFileSync('schema.sql', 'utf8')); });
beforeEach(async () => {
await pool.query('TRUNCATE gift_codes, users CASCADE');
await pool.query('INSERT INTO users SELECT g, 0 FROM generate_series(1, 20) g');
await pool.query('INSERT INTO gift_codes (code_hash, value_cents) VALUES ($1, 2500)', [h]);
});
afterAll(() => pool.end());
test('redeeming credits the user and marks the code used', async () => {
const r = await redeem(pool, 1, 'k7qm-2xd4-p9ta');
expect(r).toEqual({ status: 200, body: { added_cents: 2500, balance_cents: 2500 } });
expect(await state()).toEqual({ code: 1, credited: 2500 });
});
test('a second redeem is 409 and credits nothing more', async () => {
await redeem(pool, 1, CODE);
expect((await redeem(pool, 2, CODE)).status).toBe(409);
expect(await state()).toEqual({ code: 1, credited: 2500 });
});
test('an unknown code is 404', async () => {
expect((await redeem(pool, 1, 'AAAAAAAAAAAA')).status).toBe(404);
});
test('if crediting fails, the code goes back to unused', async () => {
await pool.query('UPDATE users SET balance_cents = 99000 WHERE id = 20'); // 99000 + 2500 would pass the 100000 wallet limit
await expect(redeem(pool, 20, CODE)).rejects.toThrow('users_balance_cents_check');
expect(await state()).toEqual({ code: null, credited: 99000 });
});
test('20 users redeem the same code at once: exactly one wins and 2500 is credited once', async () => {
const results = await Promise.all(Array.from({ length: 20 }, (_, i) => redeem(pool, i + 1, CODE)));
const winners = results.filter((r) => r.status === 200).length;
expect(winners, `winners (expected 1)`).toBe(1);
expect(results.filter((r) => r.status === 409)).toHaveLength(19);
expect((await state()).credited).toBe(2500);
});
API, real server and database, checking the contract:
// api.test.mjs
import { test, expect, beforeAll, beforeEach, afterAll } from 'vitest';
import pg from 'pg';
import fs from 'node:fs';
import crypto from 'node:crypto';
import { makeServer } from './server.mjs';
import { CONTRACT } from './contract.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
const h = crypto.createHash('sha256').update('K7QM2XD4P9TA').digest('hex');
let srv, base;
const post = async (body, session = 7) => {
const r = await fetch(`${base}/v1/gift-codes/redeem`, { method: 'POST',
headers: { 'content-type': 'application/json', ...(session ? { cookie: `demo_session=${session}` } : {}) }, body: JSON.stringify(body) });
return { status: r.status, body: await r.json() };
};
beforeAll(async () => {
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
srv = makeServer(pool).listen(0); base = `http://127.0.0.1:${srv.address().port}`;
});
beforeEach(async () => {
await pool.query('TRUNCATE gift_codes, users CASCADE');
await pool.query('INSERT INTO users VALUES (7, 0)');
await pool.query('INSERT INTO gift_codes (code_hash, value_cents) VALUES ($1, 2500)', [h]);
});
afterAll(async () => { srv.close(); await pool.end(); });
test.each([
[200, { code: 'k7qm-2xd4-p9ta' }, 7],
[401, { code: 'K7QM2XD4P9TA' }, null],
[404, { code: 'AAAAAAAAAAAA' }, 7],
[422, { code: 'nope' }, 7],
])('%i response has exactly the documented fields', async (status, body, session) => {
const r = await post(body, session);
expect(r.status).toBe(status);
expect(Object.keys(r.body).sort()).toEqual(CONTRACT[status].keys);
if (CONTRACT[status].error) expect(r.body.error).toBe(CONTRACT[status].error);
});
test('409 after the code is used, with the documented fields', async () => {
await post({ code: 'K7QM2XD4P9TA' });
const r = await post({ code: 'K7QM2XD4P9TA' });
expect(r.status).toBe(409);
expect(Object.keys(r.body).sort()).toEqual(CONTRACT[409].keys);
});
Component, with only fetch faked:
// component.test.jsx
// @vitest-environment jsdom
import { test, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { RedeemForm } from './RedeemForm.jsx';
import { CONTRACT } from './contract.mjs';
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
const reply = (status, body) => vi.fn().mockResolvedValue({ ok: status < 300, status, json: async () => body });
const errorBody = (status) => ({ error: CONTRACT[status].error });
test('success shows the amount added and the new balance', async () => {
globalThis.fetch = reply(200, CONTRACT[200].example);
render(<RedeemForm />);
await userEvent.type(screen.getByLabelText('Gift code'), 'K7QM2XD4P9TA');
await userEvent.click(screen.getByRole('button', { name: 'Redeem' }));
expect((await screen.findByRole('status')).textContent).toBe('Added $25.00. Your balance is $40.00.');
});
test('an already used code shows a specific message', async () => {
globalThis.fetch = reply(409, errorBody(409));
render(<RedeemForm />);
await userEvent.type(screen.getByLabelText('Gift code'), 'K7QM2XD4P9TA');
await userEvent.click(screen.getByRole('button', { name: 'Redeem' }));
expect((await screen.findByRole('alert')).textContent).toBe('This code has already been used.');
});
test('an empty box never calls the server', async () => {
globalThis.fetch = vi.fn();
render(<RedeemForm />);
await userEvent.click(screen.getByRole('button', { name: 'Redeem' }));
expect((await screen.findByRole('alert')).textContent).toBe('Enter the code from your gift card.');
expect(globalThis.fetch).not.toHaveBeenCalled();
});
test('a double click sends one request and the button is disabled while it is pending', async () => {
let release;
globalThis.fetch = vi.fn(() => new Promise((ok) => { release = () => ok({ ok: true, status: 200, json: async () => CONTRACT[200].example }); }));
render(<RedeemForm />);
await userEvent.type(screen.getByLabelText('Gift code'), 'K7QM2XD4P9TA');
const button = screen.getByRole('button', { name: 'Redeem' });
await userEvent.dblClick(button);
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
expect(screen.getByRole('button', { name: 'Redeeming...' }).disabled).toBe(true);
release();
await screen.findByRole('status');
});
test('a network failure shows a retry message and re-enables the button', async () => {
globalThis.fetch = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'));
render(<RedeemForm />);
await userEvent.type(screen.getByLabelText('Gift code'), 'K7QM2XD4P9TA');
await userEvent.click(screen.getByRole('button', { name: 'Redeem' }));
expect((await screen.findByRole('alert')).textContent).toContain('could not reach the server');
expect(screen.getByRole('button', { name: 'Redeem' }).disabled).toBe(false);
});
Run with Vitest 2.1.8 in a node:22 container against postgres:16, the suite prints:
✓ component.test.jsx > success shows the amount added and the new balance
✓ component.test.jsx > an already used code shows a specific message
✓ component.test.jsx > an empty box never calls the server
✓ component.test.jsx > a double click sends one request and the button is disabled while it is pending
✓ component.test.jsx > a network failure shows a retry message and re-enables the button
✓ db.test.mjs > redeeming credits the user and marks the code used
✓ db.test.mjs > a second redeem is 409 and credits nothing more
✓ db.test.mjs > an unknown code is 404
✓ db.test.mjs > if crediting fails, the code goes back to unused
✓ db.test.mjs > 20 users redeem the same code at once: exactly one wins and 2500 is credited once
✓ api.test.mjs > 200 response has exactly the documented fields
✓ api.test.mjs > 401 response has exactly the documented fields
✓ api.test.mjs > 404 response has exactly the documented fields
✓ api.test.mjs > 422 response has exactly the documented fields
✓ api.test.mjs > 409 after the code is used, with the documented fields
✓ unit.test.mjs > normalises case, spaces and hyphens
✓ unit.test.mjs > rejects wrong length, symbols and non-strings
Test Files 4 passed (4)
Tests 17 passed (17)
The suite is deterministic: it passes 17 of 17 on repeated runs. A safety net should be seen failing once. Pointing the database tests at redeemNaive (IMPL=naive) gives, in one sample run (the number of winners varies with timing, but the pause in the naive version makes more than one winner the usual outcome):
× db.test.mjs > 20 users redeem the same code at once: exactly one wins and 2500 is credited once
→ winners (expected 1): expected 20 to be 1 // Object.is equality
All 20 callers were told "success", so 20 credits of $25.00 went out for one gift card. A test with a mocked database would have passed this code. (expected 20 to be 1 // Object.is equality is Vitest's way of saying the winners count was 20 and the test required exactly 1.) The same naive run also fails the "crediting fails" test, because the naive version has no transaction to undo.
Setup files the suite needs (save the JSON block below as package.json; JSON allows no comment line, so it has none). jsx: 'automatic' tells the build tool (esbuild) that JSX can be used without importing React in each file; fileParallelism: false makes Vitest run one test file at a time because the database tests share one database; jsdom is a simulated browser (a DOM, the page's element tree, running inside Node) so component tests need no real browser.
// vitest.config.mjs
export default {
esbuild: { jsx: 'automatic' }, // lets .jsx files use JSX without importing React
test: { fileParallelism: false }, // the DB tests share one database
};
{"type": "module", "devDependencies": {"vitest": "2.1.8", "jsdom": "25.0.1", "react": "18.3.1", "react-dom": "18.3.1", "@testing-library/react": "16.0.1", "@testing-library/dom": "10.4.0", "@testing-library/user-event": "14.5.2", "pg": "8.13.1", "playwright": "1.48.2", "esbuild": "0.24.0"}}
The one end-to-end test
// e2e.mjs
import pg from 'pg';
import fs from 'node:fs';
import crypto from 'node:crypto';
import { chromium } from 'playwright';
import { makeServer } from './server.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
await pool.query('INSERT INTO users VALUES (7, 1500)');
await pool.query('INSERT INTO gift_codes (code_hash, value_cents) VALUES ($1, 2500)', [crypto.createHash('sha256').update('K7QM2XD4P9TA').digest('hex')]);
const srv = makeServer(pool, { staticDir: 'static' }).listen(3300);
const balance = async () => (await pool.query('SELECT balance_cents FROM users WHERE id = 7')).rows[0].balance_cents;
const browser = await chromium.launch();
const ctx = await browser.newContext();
await ctx.addCookies([{ name: 'demo_session', value: '7', url: 'http://127.0.0.1:3300' }]);
const page = await ctx.newPage();
await page.goto('http://127.0.0.1:3300/');
await page.getByLabel('Gift code').fill('k7qm-2xd4-p9ta'); // typed the way a person copies it
await page.getByRole('button', { name: 'Redeem' }).click();
console.log('first try :', await page.getByRole('status').innerText(), '| database balance:', await balance());
await page.getByLabel('Gift code').fill('K7QM2XD4P9TA');
await page.getByRole('button', { name: 'Redeem' }).click();
console.log('second try:', await page.getByRole('alert').innerText(), '| database balance:', await balance());
await browser.close(); srv.close(); await pool.end();
// main.jsx
import { createRoot } from 'react-dom/client';
import { RedeemForm } from './RedeemForm.jsx';
createRoot(document.getElementById('root')).render(<RedeemForm />);
<!-- static/index.html -->
<!doctype html>
<meta charset="utf-8"><title>Redeem</title>
<div id="root"></div>
<script src="/app.js"></script>
Run in the Playwright 1.48.2 container (Chromium), it prints the same two lines on repeated runs:
first try : Added $25.00. Your balance is $40.00. | database balance: 4000
second try: This code has already been used. | database balance: 4000
The code is typed lowercase with hyphens, the way a person copies it from an email, so the test also confirms normalisation survives the browser and the real endpoint. The balance started at $15.00, so the $40.00 after one redemption and the unchanged database balance after the second try are two independent proofs that the refusal did not credit again.
Why this one and not more: it is the only test that crosses every seam at once (bundle, route, cookie, JSON, database, screen), and these seams are exactly what the unit tests mock out. Every extra browser test (expired code, wrong format) re-proves logic already covered more cheaply and faster lower down, while adding browser start-up, data seeding and flake risk (a flaky test passes on some runs and fails on others with no code change, which erodes trust in the whole suite). What would change the choice: if redemption moves money, add a post-deploy check that redeems a reserved test code in production.
Pitfalls
- Mocking the thing that enforces the rule. A database mock for the single-use rule tests your belief about the database, not the database.
- A concurrency test that cannot fail. One caller after another proves nothing about races; the test must fire simultaneous requests, and must be shown failing against a deliberately broken version.
- Fake responses invented by hand in the component test. They drift from the API. Build them from a shared contract and test the contract against the real server.
- Asserting on implementation. The component tests look for roles and visible text (
status,alert, button names), which is also what a user and a screen reader get. - Brute-force guessing of codes. Rate limiting belongs in front of this endpoint, and the tests above do not exercise it. A separate test would fire many wrong codes from one session and expect a
429once the limit is reached.
Running the code
cd work # every file above; index.html goes in work/static/
docker network create demo-net
docker run -d --rm --name demo-pg --network demo-net -e POSTGRES_PASSWORD=pw postgres:16
until docker exec demo-pg pg_isready -h 127.0.0.1 -q; do sleep 1; done # wait for the image's post-init restart
docker run --rm --network demo-net -v "$PWD":/w -w /w node:22 sh -c 'npm i --silent && npx vitest run --reporter=verbose'
# the failing naive run: add -e IMPL=naive and put db.test.mjs after "vitest run"
docker run --rm --ipc=host --network demo-net -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i --silent && npx esbuild main.jsx --bundle --jsx=automatic --outfile=static/app.js && node e2e.mjs'
Unlock Full Question Bank
Get access to all 20 End-to-End Feature Design and Development interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.