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.
Tell me about a feature you owned across the frontend, the backend and the data layer. What contract did you agree between the layers, what changed after launch, and what would you design differently now?
Sample Answer
Direct answer
A strong answer here is one feature told in four beats: what I owned and why it crossed layers, the contract I wrote down between the layers before building, what launch taught us that the contract had not covered, and the specific things I would do differently now. The example below is a model story for a CSV invoice export; the same shape works for a checkout step, a notification setting or a search filter. Replace its facts with your own, because an interviewer will ask follow-ups that only your real details survive.
The model story
Situation. Customers of our billing product could view invoices but not download them, and finance teams were asking support for spreadsheets by hand. I was the one engineer on the feature end to end: the React page, the API, the background job that builds the file, and the table that tracks it. I had a designer for the layout and a second engineer who reviewed my pull requests.
The decision that shaped everything. Small accounts could be exported in under a second, but a few large accounts had years of invoices. A single request that waits for the file would time out for exactly the customers who wanted the feature most. So I made export an asynchronous job (work that runs in the background after the request has already been answered): the browser asks for an export, the server answers that it has been accepted, a worker builds the file, and the page shows progress until a download link appears.
The contract I agreed before writing code. I wrote it as a short document and reviewed it with the other engineer and the designer, because each layer depended on a different part of it:
| Part | Agreement | Why it was written down |
|---|---|---|
| Create | POST /v1/exports with {from, to} as calendar dates, and a client-generated request_key; answers 202 Accepted with {id, status} | MDN defines 202 as accepted for processing, with processing not completed or not even started, and with no later protocol-level message about the outcome. So the outcome has to be found by polling. |
| Poll | GET /v1/exports/{id} returns {status, created_at, row_count?, download_url?, error_code?} | the frontend polls (asks again and again) this every few seconds, backing off (waiting longer between each poll, for example 2 s, then 4 s, then 8 s) |
| Status values | queued, running, ready, failed; the last two never change again once reached (a terminal state) | the page has one screen per status |
| Repeat requests | same request_key returns the same export instead of starting a second one | a double click or a retry after a lost response must not build two files |
| The file | UTF-8 CSV; one row per invoice; columns in a fixed order; money as whole cents plus a currency column; dates in ISO 8601 (the international 2026-06-30 format) | finance would import it, and a column change would break their spreadsheets |
| Errors | 422 for a bad range (to before from, or more than five years), 409 if the account already has two exports running, 401 if signed out | the form shows a specific message for each |
| Data layer | an export_jobs row with status, the account, the range, the request key (unique per account) and timestamps; the file in object storage (a cloud file store that holds whole files by name, separate from the database) | the key's unique constraint is what makes repeats safe |
What each layer owned under this contract: the frontend never computed anything about the data and only drew the four statuses and the error messages; the API validated, created the row and returned quickly; the worker moved the row through the statuses and wrote the file; the database guaranteed one row per request key. The agreement lived in a machine-readable file describing every endpoint and response (an OpenAPI file; a shared TypeScript type would do the same job). I also wrote a contract test, a test that calls the real endpoint and checks every response against that file's field names and types, so a rename in the API would fail in the pull request, not in the browser.
What I did, specifically. I wrote the contract and the contract test, built the endpoint and the export_jobs table with its unique key, built the worker, and then built the page's states myself so I could see the whole path on one machine: the empty state, the in-progress panel, the failure message and the download. The other engineer reviewed; I did not hand any layer off.
What changed after launch. Three things, found in the first weeks by watching real use rather than guessing:
- Exports stuck on "running". For the largest accounts the worker was killed partway by a platform time limit. The row stayed
runningforever, and the page showed a spinner forever. I added a heartbeat (a timestamp column the worker refreshes every ten seconds or so while it works) and a sweep (a scheduled job that runs every few minutes and looks for stale rows). Timeline of a job that dies: the worker starts a big export and refreshes the heartbeat; the platform kills it at minute 15; the heartbeat stops moving; at the next sweep the row isrunningwith a heartbeat older than the limit, so the sweep marks itfailedwith anerror_code. The page now showed "This export did not finish. Try a smaller date range." - Download links dying. Files were deleted from storage after a day, as planned, but people opened the link the next morning and got an unreadable error page. I added an
expiredstatus and anexpires_atfield to the response. This broke the first contract's rule thatreadynever changes: areadyexport now becomesexpiredwhen its file is deleted, so the rule became "the build is finished, but areadyrecord can still move toexpired". Adding a status value is a contract change, and our first client treated any status it did not know as "keep spinning". I shipped a client fix first (an unknown status shows "Refresh the page and try again" and stops polling), then the backend change, in that order, so the old client never met the new value. - The file itself. Finance users opened the CSV in a spreadsheet that guessed types and mangled long invoice numbers. A data-layer detail I had not considered became a support topic, so we kept the cents column untouched and added a text-quoted invoice number column, agreed with two real customers by sending them a sample.
A disagreement I had to settle. The other engineer wanted a single download_url field filled in for every status to keep the page simple; I wanted it present only when the status is ready, because a link to a half-built file is a bug waiting to happen. We resolved it by writing both versions as example responses in the contract document and asking which one the page code would be simpler with; the ready-only version won because the page already switched on status.
The result. I measured it the way I had said I would before launch: the weekly count of support tickets tagged "export", and the share of export jobs ending in ready rather than failed. Manual export requests to support dropped out of the weekly support review as a recurring item, and the number of jobs stuck in running fell to zero once the heartbeat sweep went in. To show the shape of a believable figure (illustrative numbers, not a real measurement): "support tickets tagged export went from about eight a week to about one a week over the six weeks after launch, and jobs stuck in running for more than 20 minutes went from about 3 percent of export jobs to none, both read from our weekly support review and the job table." The share ending in ready did not rise, and it should not: the sweep turns a stuck job into an honest failed with a message, it does not make the job succeed. A good answer says which number a change can move and which it cannot. Use your own figures, and say honestly which part you could not measure (for example, whether customers who never contacted support were happy). It took us about two days after launch to notice the stuck jobs, because a user wrote in; the sweep and a dashboard of jobs by status are what would have shown it in minutes.
What I would design differently now.
- Put the unknown-value rule in the contract on day one. "Clients must treat an unknown status as 'something changed, refresh'" costs one sentence and would have saved the ordered rollout.
- Add a heartbeat and a terminal state for every job from the start. Any asynchronous job needs a way to say it has stopped, otherwise silence looks like progress.
- Estimate size before queueing. Count the rows first; small exports can answer immediately and skip the whole polling path for most users.
- Sample the output with real users before building the writer. The CSV conversation took one afternoon and would have been cheaper before launch.
How to build your own version
Pick a feature where you wrote or approved the contract, not one where you only did your layer. Bring these seven facts, and have a one-line answer to each ready:
- Which three layers the feature crossed, and what each owned.
- The contract artefact (a written document, an OpenAPI file that lists every endpoint in a form a tool can read, or a shared type definition that both sides import) and who signed off.
- One decision you made that cost something (here: async instead of a simple request).
- What broke or surprised you after launch, found by which signal.
- The order in which you shipped the fix and why that order.
- The measure you chose before launch, and its direction after.
- Two things you would change, each tied to something that actually happened.
Say "I" for what you did and "we" only for what the team decided. If you cannot name the surprise, the story reads as rehearsed; real features always have one.
Pitfalls
- A story with no contract. "The frontend and backend teams just talked" gives the interviewer nothing to probe. A written agreement does.
- All success, no change. The question asks what changed after launch; a feature that needed nothing after launch reads as one nobody watched.
- Invented precision. A number you cannot source from your own dashboard will not survive the next question. Use a measure you actually tracked, or say what you would track.
- Blaming a layer. "The backend should have..." is weaker than "the contract did not say, so I added it".
- Listing technologies. Name the decision and its trade-off, not the framework.
A like button on a post has to feel instant even on a slow connection. Walk me through how the UI, the API and the backend cooperate so that a failed or repeated request never leaves the heart or the count wrong.
Sample Answer
Direct answer
Flip the heart on the screen the instant the user taps (an optimistic update: showing the result you expect before the server confirms it). Send the server a request that says "this user's like state is ON", not "toggle". Store one row per (user, post) so a repeat cannot create a second like, and have the server answer with the canonical state {liked, like_count}. The client keeps at most one request in flight (sent and not yet answered) per post, replaces its guess with the server's answer when it arrives, and rolls back to the last confirmed state if the request fails. The canonical state is the server's own record of the truth, here the pair of the user's like and the post's total.
The contract
| Call | Meaning | Success response |
|---|---|---|
PUT /v1/posts/{id}/like | make my like state ON | 200 {"liked": true, "like_count": 42} |
DELETE /v1/posts/{id}/like | make my like state OFF | 200 {"liked": false, "like_count": 41} |
- Neither call has a request body: the method and path carry the whole intent.
- Idempotent means doing it twice leaves the same result as doing it once.
PUTON twice is still ON.DELETEon a like that does not exist returns200withliked: false, not404, so a retry after a lost response is harmless. - A
POST /toggleendpoint is the wrong shape: if the response is lost and the client retries, the retry flips the state back and the heart is wrong. - Errors:
401(not signed in),404(post deleted),429with aRetry-Afterheader (rate limit). The client retries network failures, timeouts and5xxup to two times with a short backoff (a growing pause between attempts, for example 200 ms then 400 ms) because the calls are safe to repeat. It does not retry other4xxanswers, and honoursRetry-Afteron429(a response header giving the number of seconds to wait before trying again).
Backend: the edge row decides, the count follows
An edge row is the row in likes that links one user to one post (the user and the post are the two ends of the edge). If that row exists, the user likes the post; the like_count on posts is only a stored total kept for fast reads. The function below runs in PL/pgSQL, PostgreSQL's built-in procedural language, and a transaction is a group of statements that commit together or not at all.
CREATE TABLE posts (
id bigint PRIMARY KEY,
like_count integer NOT NULL DEFAULT 0 CHECK (like_count >= 0)
);
CREATE TABLE likes (
user_id bigint NOT NULL,
post_id bigint NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, post_id)
);
CREATE FUNCTION set_like(p_user bigint, p_post bigint, p_liked boolean)
RETURNS TABLE (out_liked boolean, out_count integer)
LANGUAGE plpgsql AS $$
DECLARE changed integer;
BEGIN
IF p_liked THEN
INSERT INTO likes (user_id, post_id) VALUES (p_user, p_post) ON CONFLICT DO NOTHING;
ELSE
DELETE FROM likes WHERE user_id = p_user AND post_id = p_post;
END IF;
GET DIAGNOSTICS changed = ROW_COUNT; -- 1 if the edge changed, 0 if it was a repeat
UPDATE posts p
SET like_count = p.like_count + CASE WHEN p_liked THEN changed ELSE -changed END
WHERE p.id = p_post;
RETURN QUERY SELECT p_liked, p.like_count FROM posts p WHERE p.id = p_post;
END $$;
INSERT INTO posts VALUES (1, 0);
SELECT * FROM set_like(7, 1, true); -- run three times
SELECT * FROM set_like(7, 1, false); -- run twice
Line by line: ON CONFLICT DO NOTHING skips the insert quietly if the row already exists. GET DIAGNOSTICS changed = ROW_COUNT copies the number of rows the previous statement actually inserted or deleted into changed: 1 for a real change, 0 for a repeat. The UPDATE then adds +changed for a like or -changed for an unlike, and the last line returns the new state. Walking the calls: the first true inserts the row (changed = 1, count 0 to 1); the second and third find the row, change nothing (changed = 0), count stays 1; the first false deletes the row (count 1 to 0); the second false deletes nothing (count stays 0).
The primary key (user_id, post_id) is what makes a duplicate impossible: the database refuses a second row no matter how many requests race. The counter moves only by the number of rows that actually changed (ROW_COUNT), so a repeat adds 0. The edge change and the counter update sit in one transaction, so they commit or fail together. Run in a postgres:16 container, the three true calls each print t | 1, and the two false calls each print f | 0.
Two different users liking at the same moment is safe too: both update the same posts row, the database makes the second wait for the first, and each increment is applied to the latest value. Run in the same container with pgbench (PostgreSQL's load-testing tool, which opens many database sessions at once), 20 users each sending the like twice at the same instant (40 sessions), then 10 of them each sending the unlike twice (20 sessions). The two script files and commands are:
-- like.sql -- unlike.sql
\set u 1 + (:client_id % 20) \set u 1 + (:client_id % 10)
SELECT set_like(:u, 1, true); SELECT set_like(:u, 1, false);
pgbench -n -c 40 -t 1 -f like.sql demo -- 40 clients, two per user id
pgbench -n -c 20 -t 1 -f unlike.sql demo -- 20 clients, two per user id 1..10
SELECT p.like_count AS counter, (SELECT count(*) FROM likes) AS edge_rows FROM posts p WHERE id = 1;
After each run the final query prints:
counter | edge_rows counter | edge_rows
---------+----------- ---------+-----------
20 | 20 10 | 10
Client: the state machine
A state machine is code whose behaviour depends on a current state plus an incoming event. reduce(state, event) is a reducer: a pure function (same inputs always give the same output, and it changes nothing outside itself) that takes the old state and an event and returns the new state plus a list of effects, things the caller must then do, such as sending a request.
export const initial = (liked, count) => ({ confirmed: { liked, count }, desired: null, inflight: false, error: null });
export const view = (s) => {
const liked = s.desired ?? s.confirmed.liked;
return { liked, count: s.confirmed.count + (Number(liked) - Number(s.confirmed.liked)), error: s.error };
};
export function reduce(s, ev) {
switch (ev.type) {
case 'TAP': {
const desired = !view(s).liked;
const next = { ...s, desired, error: null };
return s.inflight ? { state: next, effects: [] }
: { state: { ...next, inflight: true }, effects: [{ send: desired }] };
}
case 'RESPONSE_OK': {
const confirmed = { liked: ev.liked, count: ev.count };
if (s.desired !== null && s.desired !== ev.liked)
return { state: { ...s, confirmed, inflight: true }, effects: [{ send: s.desired }] };
return { state: { ...s, confirmed, desired: null, inflight: false }, effects: [] };
}
case 'RESPONSE_FAIL':
return { state: { ...s, desired: null, inflight: false, error: 'Could not update. Try again.' }, effects: [] };
case 'SNAPSHOT': {
if (s.inflight || s.desired !== null) return { state: s, effects: [] };
if (ev.liked !== s.confirmed.liked) return { state: s, effects: [{ refetchLater: true }] };
return { state: { ...s, confirmed: { liked: ev.liked, count: ev.count } }, effects: [] };
}
}
}
- Read the non-obvious lines this way. In
view,count: s.confirmed.count + (Number(liked) - Number(s.confirmed.liked))converts the booleans to 1 or 0: if the screen shows liked but the server last said not liked, the difference is 1 - 0 = +1; if it shows not liked while the server said liked, it is 0 - 1 = -1; if they agree, it is 0. InRESPONSE_OK, theifhandles a user who tapped again while the request was in flight: the answer saysliked: truebutdesiredis nowfalse, so the state staysinflight: trueand a second request{send: false}goes out. confirmedis the last thing the server told us.desiredis what the user last asked for. The screen showsdesiredif there is one, and the displayed count is the confirmed count plus the local change (+1 or -1).- One request in flight per post. Taps during a request only change
desired. When the response lands, ifdesiredstill differs from what the server now says, one more request goes out. Two requests for the same post can therefore never overtake each other, so there is no "older answer arrives last" problem between taps. - The pending marker. A
SNAPSHOTis any other read of the post (a refocus refetch, a poll, a list reload). While a request is in flight ordesiredis set, snapshots are ignored, because they were produced before the server saw the tap and would flash the old count over the new one. After the action settles, a snapshot that disagrees about the user's own like state is treated as stale and re-requested later instead of applied. The reducer shows only that first step: a production version also counts refetches, because a disagreement that survives a refetch is real (for example the user unliked on another device) and must then be applied, or the heart would never converge. - A failure discards
desired, so the heart and count fall back toconfirmedtogether, and the error text appears.
The reducer has no network in it, so a driver feeds it the events a response would produce. Saved as like-machine.mjs (the reducer above) next to this driver:
import { initial, view, reduce } from './like-machine.mjs';
function run(title, s, events) {
console.log(title);
for (const ev of events) {
const r = reduce(s, ev); s = r.state; const v = view(s);
console.log(ev.type.padEnd(13), '-> heart=' + (v.liked ? 'on ' : 'off'), 'count=' + v.count,
'inflight=' + s.inflight, 'sends=' + JSON.stringify(r.effects) + (v.error ? ` error="${v.error}"` : ''));
}
console.log();
}
const T = { type: 'TAP' };
run('A. three quick taps (on, off, on) while the first request is in flight', initial(false, 41),
[T, T, T, { type: 'RESPONSE_OK', liked: true, count: 42 }]);
run('B. two taps (on, off): the second state differs from the request in flight', initial(false, 41),
[T, T, { type: 'RESPONSE_OK', liked: true, count: 42 }, { type: 'RESPONSE_OK', liked: false, count: 41 }]);
run('C. server error after one tap', initial(false, 41), [T, { type: 'RESPONSE_FAIL' }]);
run('D. a snapshot mid-request, a stale one after settling, a fresh one', initial(false, 41),
[T, { type: 'SNAPSHOT', liked: false, count: 41 }, { type: 'RESPONSE_OK', liked: true, count: 42 },
{ type: 'SNAPSHOT', liked: false, count: 41 }, { type: 'SNAPSHOT', liked: true, count: 44 }]);
Run in a node:22 container (the post starts unliked with a count of 41), it prints the trace for four situations:
A. three quick taps (on, off, on) while the first request is in flight
TAP -> heart=on count=42 inflight=true sends=[{"send":true}]
TAP -> heart=off count=41 inflight=true sends=[]
TAP -> heart=on count=42 inflight=true sends=[]
RESPONSE_OK -> heart=on count=42 inflight=false sends=[]
B. two taps (on, off): the second state differs from the request in flight
TAP -> heart=on count=42 inflight=true sends=[{"send":true}]
TAP -> heart=off count=41 inflight=true sends=[]
RESPONSE_OK -> heart=off count=41 inflight=true sends=[{"send":false}]
RESPONSE_OK -> heart=off count=41 inflight=false sends=[]
C. server error after one tap
TAP -> heart=on count=42 inflight=true sends=[{"send":true}]
RESPONSE_FAIL -> heart=off count=41 inflight=false sends=[] error="Could not update. Try again."
D. a snapshot mid-request, a stale one after settling, a fresh one
TAP -> heart=on count=42 inflight=true sends=[{"send":true}]
SNAPSHOT -> heart=on count=42 inflight=true sends=[]
RESPONSE_OK -> heart=on count=42 inflight=false sends=[]
SNAPSHOT -> heart=on count=42 inflight=false sends=[{"refetchLater":true}]
SNAPSHOT -> heart=on count=44 inflight=false sends=[]
Case A sends one request for three taps. Case B sends two, in order. In case D the post starts unliked with a count of 41, and the three snapshots carry (liked false, count 41) during the request, (liked false, count 41) after the response, and (liked true, count 44). The first is ignored because inflight is true. The second arrives after the like was confirmed (confirmed.liked is true) but says false, so it was produced before the server saw the tap: it is not applied and a later refetch is requested instead. The third agrees with the confirmed like state, so it is trusted, and its count of 44 replaces 42 because other people liked the post in the meantime.
Test, roll out, observe
- Unit: the reducer above is a pure function, so the four traces are the tests. Database: repeat and concurrent calls must leave
like_countequal tocount(*)of the edge rows. End to end: a Playwright test (a browser-automation test tool) aborts the network route and asserts the heart rolls back with the error text, and a throttled-connection test asserts the heart changes before the response is fulfilled. - Roll out behind a feature flag by percentage of users (the new code runs for, say, 5% of users first, then more, and a switch turns it off instantly), with the old endpoint still served until the flag reaches 100%.
- Observe: the share of like calls that end in
RESPONSE_FAIL, p95 latency of the endpoint (the time that 95% of calls beat, so it exposes slow outliers that an average hides), and a scheduled drift check that compareslike_counttocount(*)oflikesfor a sample of posts. Drift above zero means some code path writes the counter or the edge without the other.
Trade-offs and pitfalls
- The stored counter makes reads cheap but concentrates writes on one row per post. For an ordinary post that is fine; for a viral post, spread the counter over several rows (a random one of, say, 16 per like, summed on read) or accept a slightly delayed count. For example, 1,000 likes might land as roughly 62 on each of 16 rows, and the page shows their sum, 1,000. Most posts never need this, so add it only when measurements show waiting on that one row.
- Never compute "count + 1" on the client and keep it forever: it drifts as soon as another user likes the post. Always replace it with the server's number.
- Rolling back silently confuses users, so show the failure.
Two staff members open the same product description in an internal admin tool, both edit it, and both press Save. Today the second save silently overwrites the first. Walk me through fixing this across the UI, the API and the database so that a conflicting save is detected, and the second editor can see what changed and decide what to keep.
Sample Answer
Direct answer
Use optimistic concurrency control: assume conflicts are rare, let both editors work without locks, and make the save itself check that nothing changed. Concretely: the product row gets a version number; the API sends it to the browser as an ETag, the browser sends it back in an If-Match header when saving, and the database only applies the update WHERE version = <that number>. If a conflicting save got in first, the update changes zero rows, the API answers 412 Precondition Failed with the current text and the text both editors started from, and the UI shows the second editor a diff of what changed and three choices: keep mine, use theirs, or edit by hand. Every saved version is also kept in a history table, so choosing "keep mine" never destroys the other person's text.
Three pieces carry the correctness: the version column, the If-Match header, and WHERE version = N in the update. The history table and the diff screen are what let the second editor decide with full information.
Terms used below. A lost update is when two people read the same data, both change it, and the second write silently replaces the first. An ETag (entity tag) is an opaque version label a server attaches to a resource. If-Match is a request header meaning "only do this if the resource's current ETag equals this one". A three-way comparison looks at three texts: the base (what both editors started from), mine and theirs; comparing each side against the base shows what each person changed, which comparing mine against theirs cannot.
Why this and not the alternatives
| Approach | What happens | Verdict |
|---|---|---|
| Last write wins (today) | the second save replaces the first, nobody is told | the bug |
| Lock the record while someone edits (pessimistic locking) | one editor blocks the others; a closed tab leaves a lock behind | a database row lock cannot span several HTTP requests and minutes of typing, so you would build lock leases (a lock that expires on its own after a set time), heartbeats (the page pinging the server to say "I am still here", so a dead tab's lock can be released) and an admin "break lock" button |
| Version check on save (optimistic) | both edit; the second save is refused and resolved by a person | cheap, stateless, and the conflict is shown at the moment it matters |
| Merge automatically | text edits combine without asking | safe only for edits in different parts; a product description that two people rewrite needs a human decision |
A soft presence banner ("Priya is editing this") can sit on top as a courtesy, but the version check is what guarantees correctness, since a banner is only a hint.
Data model
CREATE TABLE products (
id bigint PRIMARY KEY,
name text NOT NULL,
description text NOT NULL CHECK (char_length(description) BETWEEN 1 AND 5000),
version integer NOT NULL DEFAULT 1,
updated_by text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE product_revisions (
product_id bigint NOT NULL REFERENCES products(id),
version integer NOT NULL,
description text NOT NULL,
edited_by text NOT NULL,
edited_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (product_id, version)
);
INSERT INTO products (id, name, description, updated_by) VALUES (1, 'Trail Mug', 'Enamel mug, 350 ml.', 'seed');
INSERT INTO product_revisions (product_id, version, description, edited_by) VALUES (1, 1, 'Enamel mug, 350 ml.', 'seed');
versionincrements on every successful save; it is the value behind the ETag.product_revisionsstores each version's text, author and time. It is what lets the conflict response contain the base text even if the second editor reloaded the page, and it gives an audit trail and an "undo to version N" for free. The row for a version is written in the same statement as the update (below), so history and current state cannot disagree.- If the
versioncolumn is added to an existing table,ADD COLUMN version integer NOT NULL DEFAULT 1fills every row, and the first revision row can be backfilled from the current text.
API
| Call | Success | Failure |
|---|---|---|
GET /api/products/{id} | 200, body plus ETag: "3" | 404 |
PATCH /api/products/{id} with If-Match: "3" and {"description": "..."} | 200, new body, ETag: "4" | 428 no If-Match; 412 version moved on; 422 invalid text; 404 |
412 Precondition Failed: MDN describes it as returned for a conditional request on a method other thanGETorHEADwhen the condition inIf-MatchorIf-Unmodified-Sinceis not fulfilled, and its "Avoiding mid-air collisions" example is this case: the stored ETag no longer matches, so the document was edited in between and a412comes back. What the client does next is left to the application; here it is the panel described below, which re-fetches nothing extra because the412body already carries the latest text, shows the difference, and retries with the new version. That is exactly the conflict case, so it is the status to use.409 Conflict("a request conflict with the current state of the target resource") is the other common choice when the version travels in the body rather than a header; withIf-Matchin play,412is the standard answer and a generic HTTP client or proxy understands it.428 Precondition Required(RFC 6585) tells a client that sent noIf-Matchthat the server requires one. Without it, an old client that omits the header would silently get last-write-wins back.- The ETag is strong (
"3", noW/prefix). A strong tag means "byte-for-byte the same content"; a weak tag (W/"3") means only "equivalent in meaning". MDN statesIf-Matchuses the strong comparison, so a weak tag never matches; the raw check in the test below sendsW/"1"and gets412. - The
412body carriescurrent(the latest text, who saved it and when) andbase(the text of the version the caller started from, from the history table), so the browser can render the diff without a second request.
Backend: one statement does the check, the change and the history
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 PRODUCT = 'id::text AS id, name, description, version, updated_by, updated_at';
const send = (res, status, data, headers = {}) => {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(JSON.stringify(data));
};
const etag = (version) => `"${version}"`; // a strong ETag: quotes, no W/ prefix
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 getProduct(res, id) {
const { rows } = await pool.query(`SELECT ${PRODUCT} FROM products WHERE id = $1`, [id]);
if (!rows.length) return send(res, 404, { error: 'No such product' });
send(res, 200, rows[0], { ETag: etag(rows[0].version) });
}
async function patchProduct(req, res, id) {
if (!req.headers['if-match']) return send(res, 428, { error: 'If-Match is required' });
const match = /^"(\d{1,9})"$/.exec(req.headers['if-match']);
const baseVersion = match ? Number(match[1]) : -1; // anything but a strong ETag we issued (W/"2", *, junk) matches nothing
const input = await readJson(req);
const description = typeof input.description === 'string' ? input.description.trim() : '';
if (!description || description.length > 5000) return send(res, 422, { errors: { description: 'Use 1 to 5000 characters.' } });
const editor = req.headers['x-user'] || 'unknown'; // stands in for the signed-in user
// One statement: the version check, the change, and the history row succeed or fail together.
const { rows } = await pool.query(
`WITH upd AS (
UPDATE products SET description = $1, version = version + 1, updated_by = $2, updated_at = now()
WHERE id = $3 AND version = $4
RETURNING ${PRODUCT}),
rev AS (
INSERT INTO product_revisions (product_id, version, description, edited_by)
SELECT id::bigint, version, description, updated_by FROM upd)
SELECT * FROM upd`, [description, editor, id, baseVersion]);
if (rows.length) return send(res, 200, rows[0], { ETag: etag(rows[0].version) });
// Zero rows: no such product, or the version moved on. Tell the caller which, with enough to resolve it.
const cur = await pool.query(`SELECT ${PRODUCT} FROM products WHERE id = $1`, [id]);
if (!cur.rows.length) return send(res, 404, { error: 'No such product' });
const base = await pool.query(
'SELECT version, description, edited_by, edited_at FROM product_revisions WHERE product_id = $1 AND version = $2', [id, baseVersion]);
send(res, 412, { error: 'The description changed since you opened it.', current: cur.rows[0], base: base.rows[0] ?? null },
{ ETag: etag(cur.rows[0].version) });
}
http.createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://x');
const files = { '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript'], '/diff.js': ['diff.js', 'text/javascript'] };
if (req.method === 'GET' && files[pathname]) {
res.writeHead(200, { 'Content-Type': files[pathname][1] });
return res.end(await readFile(new URL(`./public/${files[pathname][0]}`, import.meta.url)));
}
const m = pathname.match(/^\/api\/products\/(\d{1,18})$/);
if (m && req.method === 'GET') return await getProduct(res, m[1]);
if (m && req.method === 'PATCH') return await patchProduct(req, res, m[1]);
send(res, 404, { error: 'Not found' });
} catch (err) {
if (err.status) return send(res, err.status, { error: err.message });
console.error(err); send(res, 500, { error: 'Server error' });
}
}).listen(3000, () => console.log('listening'));
The core is the WITH statement, read in three steps: upd runs the UPDATE and its RETURNING clause hands back the changed row; rev inserts the history row by selecting from upd (so it is inserted only if upd changed a row, and it copies the new version number); the final SELECT * FROM upd returns the row to the caller. id::bigint and id::text are PostgreSQL casts (:: converts a value to another type): the id travels as text so JavaScript cannot round it, and goes back to a number for the history table. A data-modifying WITH runs as one statement, so the version check, the new text and the history row commit together or not at all. Zero rows back from upd means the WHERE ... AND version = $4 did not match: either the row does not exist (404) or someone else got there first (412). The follow-up reads can be slightly stale by the time they run, which is harmless: they only decide what to show, and the next save re-checks everything.
Why the WHERE version = N check is safe against two saves at the very same instant. Read Committed is PostgreSQL's default isolation level (the rule for what one transaction may see of another's work): each statement sees only data that was committed when the statement began. Re-evaluated means the database checks the WHERE condition again against the newest committed version of the row. As a timeline, with both sessions having loaded version 1:
- A starts a transaction and updates the row where
version = 1: the row becomes version 2 inside A's transaction, and A holds the row lock. - B runs the same update where
version = 1. It finds the row, sees it is locked by A, and waits. - A commits. Version 2 is now the committed truth.
- B wakes up and re-checks its
WHEREagainst the new row:version = 1is false because the row now says 2, so B changes 0 rows.
PostgreSQL's documentation for this level says that when a row was changed by a concurrent transaction that is still open, the second updater waits for it, and if it commits the WHERE clause is re-evaluated against the updated row. Run in a postgres:16 container with three sessions, the program below reproduces the cases: no check (the bug), the check applied one after the other, and the check applied concurrently, where session B is observed waiting on a lock (wait_event_type = 'Lock' in pg_stat_activity) until session A commits:
import pg from 'pg';
const url = process.env.DATABASE_URL;
const connect = async () => { const c = new pg.Client({ connectionString: url }); await c.connect(); return c; };
const [a, b, watcher] = [await connect(), await connect(), await connect()];
await watcher.query('CREATE TABLE mugs (id int PRIMARY KEY, description text NOT NULL, version int NOT NULL)');
await watcher.query("INSERT INTO mugs VALUES (1, 'Enamel mug, 350 ml.', 1)");
const reset = () => watcher.query("UPDATE mugs SET description = 'Enamel mug, 350 ml.', version = 1 WHERE id = 1");
const state = async () => (await watcher.query('SELECT version, description FROM mugs WHERE id = 1')).rows[0];
const show = async (label) => console.log(label.padEnd(44), JSON.stringify(await state()));
// 1. No version check: both writers think they succeeded, and the first edit is gone.
await reset();
await a.query("UPDATE mugs SET description = 'A: dishwasher safe', version = version + 1 WHERE id = 1");
await b.query("UPDATE mugs SET description = 'B: camping mug', version = version + 1 WHERE id = 1");
await show('1. no check, A then B:');
// 2. Version check, one after the other: B matches zero rows.
await reset();
const upd = "UPDATE mugs SET description = $1, version = version + 1 WHERE id = 1 AND version = 1";
const r1 = await a.query(upd, ['A: dishwasher safe']);
const r2 = await b.query(upd, ['B: camping mug']);
console.log('2. with check, A then B: rows changed', r1.rowCount, 'and', r2.rowCount);
await show(' state:');
// 3. Version check, truly at the same time: A has changed the row but not committed.
await reset();
await a.query('BEGIN');
await a.query(upd, ['A: dishwasher safe']);
const pidB = (await b.query('SELECT pg_backend_pid() AS pid')).rows[0].pid;
const pendingB = b.query(upd, ['B: camping mug']); // starts now and has to wait for A
let waiting = false;
while (!waiting) {
waiting = (await watcher.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('3. A has not committed; B is waiting on a lock:', waiting);
await a.query('COMMIT');
const rB = await pendingB;
console.log(' after A commits, B changed', rB.rowCount, 'rows');
await show(' state:');
await watcher.query('DROP TABLE mugs');
await Promise.all([a.end(), b.end(), watcher.end()]);
1. no check, A then B: {"version":3,"description":"B: camping mug"}
2. with check, A then B: rows changed 1 and 0
state: {"version":2,"description":"A: dishwasher safe"}
3. A has not committed; B is waiting on a lock: true
after A commits, B changed 0 rows
state: {"version":2,"description":"A: dishwasher safe"}
Line 1 is the bug: version 3, B's text, A's edit gone, and nobody was told. Lines 2 and 3 are the fix: B's update changes zero rows both when it runs after A and when it runs while A is mid-transaction, and the final text is A's.
UI: show what changed and let the person decide
The diff is computed in the browser by comparing words with a longest-common-subsequence algorithm (LCS: the standard way to find the longest run of words, not necessarily adjacent, that two texts share in the same order; everything outside that run is an insertion or deletion):
// Word-level diff by longest common subsequence. Returns [{ type: 'same' | 'del' | 'ins', text }].
export function wordDiff(a, b) {
const x = a.split(/(\s+)/).filter(Boolean), y = b.split(/(\s+)/).filter(Boolean);
const lcs = Array.from({ length: x.length + 1 }, () => new Array(y.length + 1).fill(0));
for (let i = x.length - 1; i >= 0; i--)
for (let j = y.length - 1; j >= 0; j--)
lcs[i][j] = x[i] === y[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
const ops = [];
const push = (type, text) => (ops.at(-1)?.type === type ? (ops.at(-1).text += text) : ops.push({ type, text }));
let i = 0, j = 0;
while (i < x.length && j < y.length) {
if (x[i] === y[j]) { push('same', x[i]); i++; j++; }
else if (lcs[i + 1][j] >= lcs[i][j + 1]) push('del', x[i++]);
else push('ins', y[j++]);
}
while (i < x.length) push('del', x[i++]);
while (j < y.length) push('ins', y[j++]);
return ops;
}
Called on two pairs (the original text against Priya's added sentence, then against Sam's added word), saved as diff-demo.mjs and run with node diff-demo.mjs:
import { wordDiff } from './public/diff.js';
console.log(JSON.stringify(wordDiff('Enamel mug, 350 ml.', 'Enamel mug, 350 ml. Dishwasher safe.')));
console.log(JSON.stringify(wordDiff('Enamel mug, 350 ml.', 'Enamel camping mug, 350 ml.')));
It prints:
[{"type":"same","text":"Enamel mug, 350 ml."},{"type":"ins","text":" Dishwasher safe."}]
[{"type":"same","text":"Enamel "},{"type":"ins","text":"camping "},{"type":"same","text":"mug, 350 ml."}]
A trace on the second line of output, Enamel mug, 350 ml. against Enamel camping mug, 350 ml.. The texts split into tokens (words and the spaces between them): the old text has 7, ["Enamel"," ","mug,"," ","350"," ","ml."], the new text has 9, with " ", "camping" inserted after the first space. The table lcs[i][j] holds the length of the longest shared run of the old tokens from position i on and the new tokens from position j on; it is filled from the end backwards, and lcs[0][0] is 7 here because all 7 old tokens appear in the new text in order. The walk then starts at i = 0, j = 0: "Enamel" equals "Enamel" and " " equals " ", so both are emitted as same. At i = 2, j = 2 the tokens differ ("mug," against "camping"), so the code compares lcs[3][2], the value after skipping the old token (4), with lcs[2][3], the value after skipping the new token (5). The comparison lcs[i+1][j] >= lcs[i][j+1] is 4 >= 5, false, so it emits ins "camping" and advances only j. The same comparison at i = 2, j = 3 (4 against 5 again) emits ins " ". After that, "mug," matches "mug," and the rest matches, so everything else is same, and the merged result is the three operations in the output: same Enamel , insert camping , same mug, 350 ml.. A del is chosen when skipping the old token keeps at least as much shared text as skipping the new one.
The page keeps the version it loaded, sends it as If-Match, and on 412 opens a panel instead of discarding anything. It uses <ins> and <del> elements filled with textContent (so text is shown, never run as markup), moves focus to the panel's heading (tabindex="-1" lets a heading receive focus from code without joining the Tab order) so keyboard users and screen-reader users (people who hear the page read aloud by assistive software) land on the explanation, and leaves the person's text in the box.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Edit product</title></head>
<body>
<h1 id="name"></h1>
<label for="desc">Description</label>
<textarea id="desc" rows="5" cols="60"></textarea>
<button id="save">Save</button>
<p id="msg" role="status"></p>
<section id="conflict" hidden aria-labelledby="conflict-title">
<h2 id="conflict-title" tabindex="-1"></h2>
<h3>Their change</h3><p id="theirs-diff"></p>
<h3>Your change</h3><p id="mine-diff"></p>
<button id="keep-mine">Keep my version</button>
<button id="use-theirs">Use their version</button>
<button id="edit-by-hand">Edit by hand</button>
</section>
<script type="module" src="/app.js"></script>
</body>
</html>
import { wordDiff } from './diff.js';
const $ = (id) => document.getElementById(id);
const user = new URLSearchParams(location.search).get('user') ?? 'anonymous';
let base = null; // what this editor started from: { version, description }
let conflict = null; // the server's 412 body while the dialog is open
const renderDiff = (el, from, to) => {
el.replaceChildren(...wordDiff(from, to).map(({ type, text }) => {
const node = document.createElement(type === 'ins' ? 'ins' : type === 'del' ? 'del' : 'span');
node.textContent = text;
return node;
}));
};
async function load() {
const res = await fetch('/api/products/1');
const p = await res.json();
base = { version: p.version, description: p.description };
$('name').textContent = p.name;
$('desc').value = p.description;
}
async function save(baseVersion) {
$('save').disabled = true;
try {
const res = await fetch('/api/products/1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', 'If-Match': `"${baseVersion}"`, 'X-User': user },
body: JSON.stringify({ description: $('desc').value }),
});
const data = await res.json();
if (res.status === 200) {
base = { version: data.version, description: data.description };
$('desc').value = data.description;
$('conflict').hidden = true;
$('msg').textContent = `Saved as version ${data.version}.`;
} else if (res.status === 412) {
showConflict(data);
} else {
$('msg').textContent = data.errors?.description ?? 'Could not save. Your text is still here, try again.';
}
} catch {
$('msg').textContent = 'Could not save. Your text is still here, try again.';
} finally {
$('save').disabled = false;
}
}
function showConflict(data) {
conflict = data;
const baseText = data.base?.description ?? base.description; // what both editors started from
$('conflict-title').textContent = `${data.current.updated_by} saved version ${data.current.version} while you were editing`;
renderDiff($('theirs-diff'), baseText, data.current.description);
renderDiff($('mine-diff'), baseText, $('desc').value);
$('msg').textContent = 'Your changes are not saved yet.';
$('conflict').hidden = false;
$('conflict-title').focus();
}
$('save').addEventListener('click', () => save(base.version));
$('keep-mine').addEventListener('click', () => save(conflict.current.version)); // knowingly overwrite, but only version N
$('use-theirs').addEventListener('click', () => {
base = { version: conflict.current.version, description: conflict.current.description };
$('desc').value = conflict.current.description;
$('conflict').hidden = true;
$('msg').textContent = 'Showing their version.';
});
$('edit-by-hand').addEventListener('click', () => {
base = { version: conflict.current.version, description: conflict.current.description };
$('desc').value = conflict.current.description; // start from theirs; the "Your change" panel stays on screen to copy from
$('msg').textContent = 'Their version is loaded. Re-apply your change, then save.';
$('desc').focus();
});
await load();
The three buttons:
- Keep my version saves the text in the box with
If-Matchset to the latest version. It deliberately overwrites, but only version N: if a third person saved in between, the server answers412again and the panel reopens with the newer diff. The overwritten text stays inproduct_revisions. - Use their version discards the local edit and loads theirs as the new base.
- Edit by hand loads their text into the box and keeps the "Your change" panel on screen to copy from, then saves against their version. This is the real merge path for two rewrites of the same sentence.
Proof that it works
Raw HTTP checks first, then two separate browser contexts (two users with their own sessions) editing the same product, with the whole flow printed:
import { chromium } from 'playwright';
const base = 'http://localhost:3000';
const patch = (headers) => fetch(`${base}/api/products/1`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify({ description: 'x' }) });
const get = await fetch(`${base}/api/products/1`);
console.log('GET ->', get.status, 'ETag:', get.headers.get('etag'));
console.log('PATCH without If-Match ->', (await patch({})).status);
const weak = await patch({ 'If-Match': 'W/"1"' });
console.log('PATCH with weak W/"1" ->', weak.status, 'ETag:', weak.headers.get('etag'));
const stale = await patch({ 'If-Match': '"7"' });
console.log('PATCH with stale "7" ->', stale.status, JSON.stringify(Object.keys(await stale.json())));
const browser = await chromium.launch();
const open = async (user) => {
const page = await (await browser.newContext()).newPage();
await page.goto(`${base}/?user=${user}`);
await page.waitForFunction(() => document.getElementById('desc').value !== '');
return page;
};
const msg = (page) => page.textContent('#msg');
const saveAndWait = async (page, text) => { await page.locator('#msg').evaluate((e) => (e.textContent = '')); await page.click('#save'); await page.waitForFunction((t) => document.getElementById('msg').textContent.startsWith(t), text); };
const priya = await open('Priya'), sam = await open('Sam');
await priya.fill('#desc', 'Enamel mug, 350 ml. Dishwasher safe.');
await sam.fill('#desc', 'Enamel camping mug, 350 ml.');
await saveAndWait(priya, 'Saved');
console.log('Priya:', await msg(priya));
await sam.click('#save');
await sam.locator('#conflict').waitFor();
console.log('Sam sees title :', await sam.textContent('#conflict-title'));
console.log('Sam sees message:', await msg(sam));
console.log('Their change ins:', JSON.stringify(await sam.locator('#theirs-diff ins').allTextContents()), 'del:', JSON.stringify(await sam.locator('#theirs-diff del').allTextContents()));
console.log('Your change ins:', JSON.stringify(await sam.locator('#mine-diff ins').allTextContents()), 'del:', JSON.stringify(await sam.locator('#mine-diff del').allTextContents()));
await sam.click('#edit-by-hand');
console.log('Editor now holds Priya\'s text:', await sam.inputValue('#desc'));
await sam.fill('#desc', 'Enamel camping mug, 350 ml. Dishwasher safe.');
await saveAndWait(sam, 'Saved');
console.log('Sam after merge:', await msg(sam), '| conflict panel hidden:', await sam.locator('#conflict').isHidden());
// Round two: Priya edits again from version 3 while Sam, still on version 3, edits too; Sam chooses "Keep my version".
await priya.reload(); await priya.waitForFunction(() => document.getElementById('desc').value.includes('camping'));
await priya.fill('#desc', 'Enamel camping mug, 350 ml. Dishwasher safe. Ships in 2 days.');
await sam.fill('#desc', 'Enamel camping mug, 350 ml. Dishwasher safe. Pack of two.');
await saveAndWait(priya, 'Saved');
await sam.click('#save');
await sam.locator('#conflict').waitFor();
await sam.click('#keep-mine');
await sam.waitForFunction(() => document.getElementById('msg').textContent.startsWith('Saved'));
console.log('Sam keeps his version:', await msg(sam));
await browser.close();
const rows = await (await fetch(`${base}/api/products/1`)).json();
console.log('Final:', rows.version, '|', rows.description, '|', rows.updated_by);
GET -> 200 ETag: "1"
PATCH without If-Match -> 428
PATCH with weak W/"1" -> 412 ETag: "1"
PATCH with stale "7" -> 412 ["error","current","base"]
Priya: Saved as version 2.
Sam sees title : Priya saved version 2 while you were editing
Sam sees message: Your changes are not saved yet.
Their change ins: [" Dishwasher safe."] del: []
Your change ins: ["camping "] del: []
Editor now holds Priya's text: Enamel mug, 350 ml. Dishwasher safe.
Sam after merge: Saved as version 3. | conflict panel hidden: true
Sam keeps his version: Saved as version 5.
Final: 5 | Enamel camping mug, 350 ml. Dishwasher safe. Pack of two. | Sam
The history table after that run:
version | description | edited_by
---------+---------------------------------------------------------------+-----------
1 | Enamel mug, 350 ml. | seed
2 | Enamel mug, 350 ml. Dishwasher safe. | Priya
3 | Enamel camping mug, 350 ml. Dishwasher safe. | Sam
4 | Enamel camping mug, 350 ml. Dishwasher safe. Ships in 2 days. | Priya
5 | Enamel camping mug, 350 ml. Dishwasher safe. Pack of two. | Sam
(5 rows)
Reading it: Priya and Sam both loaded version 1. Priya's save made version 2. Sam's save got 412; his panel showed Priya's insertion (" Dishwasher safe.") and his own (the word "camping "), his "Edit by hand" box started from Priya's text, and his combined save became version 3. In round two Sam chose "Keep my version" over Priya's version 4, producing version 5; Priya's text is still row 4 in the history. The output is deterministic because each browser wait is on a condition, not a delay.
Rolling it out and what can go wrong
- Ship in three steps so no existing client breaks. Step one: deploy the
versioncolumn and history table, and have the server accept a missingIf-Matchwhile logging it. Step two: ship the UI that sends it. Step three, after the log shows no more header-less writes, return428for them. Requiring the header on day one would fail every save from an old page that is still open in someone's browser, since it was loaded before the new script existed. - A retry after a lost response. If a save succeeded but the response never arrived, the retry carries the old version and gets
412. The panel would then show the person a "conflict" with their own change; the client should treat a412whosecurrent.descriptionequals what it sent as already saved. - Conflict rate is the health signal. Count
412per day against saves. A rising ratio means editors really do collide, which is the point where a presence banner, or real-time collaborative editing for that one field, starts to pay for itself. - Other writers. Imports and scripts that update the same row must send a version too, or they bypass the protection.
Running the code
docker network create shop-net
docker run -d --rm --name shop-pg --network shop-net -e POSTGRES_PASSWORD=pw postgres:16
sleep 5 # wait for Postgres to accept connections
docker exec shop-pg psql -U postgres -c "CREATE DATABASE shop"
docker exec -i shop-pg psql -U postgres -d shop < schema.sql
# in a folder holding schema.sql, server.mjs, race-demo.mjs, diff-demo.mjs, test.mjs, public/ and package.json {"type":"module"}:
docker run --rm --network shop-net -v "$PWD":/w -w /w -e DATABASE_URL=postgres://postgres:pw@shop-pg:5432/shop \
mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i pg@8 playwright@1.48.2; node diff-demo.mjs; node race-demo.mjs; node server.mjs & sleep 3; node test.mjs'
docker exec shop-pg psql -U postgres -d shop -c "SELECT version, description, edited_by FROM product_revisions ORDER BY version"
In a comments feature, people can edit and delete their own comments and moderators can delete anyone's. Walk me through where each permission check lives, from showing or hiding the buttons in the UI to the API handler and the database query, and what goes wrong if a check exists only in the UI.
Sample Answer
Direct answer
Write the rule once in words ("only the author can edit; the author or a moderator of that space can delete"), then enforce it in three places that each do a different job. The UI only decides which buttons to show, and it learns that from the server, never from its own copy of the rule. The API handler is the real gate: it identifies the caller (authentication, proving who you are) and then decides whether that caller may do this to this comment (authorization, deciding what you are allowed to do). The database statement repeats the rule inside its WHERE clause, so the check and the write happen in one atomic step (one indivisible step: no other request can slip in between the two halves) and cannot be separated by a race (a bug that appears only when two requests overlap in time) or a missing if.
A check that exists only in the UI is not a check. Anyone can send the HTTP request without the page (with curl, a browser console, or a script), so a hidden button protects nothing. The run below shows it: a server that trusts the UI let a stranger delete someone else's comment with a 204.
The rule and the data it needs
| Action | Who may do it |
|---|---|
| Edit a comment | its author only (a moderator cannot rewrite someone else's words) |
| Delete a comment | its author, or a moderator of the space the comment lives in |
Moderator is scoped to a space (a forum section, a project, a video page). A global "is_moderator" flag on the user would let a moderator of space 2 delete in space 1; the data model has to carry the scope.
DROP TABLE IF EXISTS comments, moderators;
CREATE TABLE moderators (
user_id integer NOT NULL,
space_id integer NOT NULL,
PRIMARY KEY (user_id, space_id)
);
CREATE TABLE comments (
id serial PRIMARY KEY,
space_id integer NOT NULL,
author_id integer NOT NULL,
body text NOT NULL CHECK (length(body) BETWEEN 1 AND 2000),
created_at timestamptz NOT NULL DEFAULT now(),
edited_at timestamptz,
deleted_at timestamptz,
deleted_by integer
);
author_id is set once at creation from the session and never accepted from a request body. deleted_at makes delete a soft delete (the row stays, marked as removed, so moderators can audit it and the action can be undone); deleted_by records who did it.
Layer 1: the UI shows what the server says is allowed
The list endpoint returns each comment with a permissions object, for example {"edit": false, "delete": true}. The component renders the Edit button only when permissions.edit is true and the Delete button only when permissions.delete is true. It contains no rule such as comment.authorId === currentUser.id || user.isModerator. If it did, there would be two copies of the rule in two languages, and the day the rule changes (say, moderators may now also edit within five minutes) the copies drift apart. The buttons are a courtesy so the user is not offered actions that will fail; they are not protection.
Two UI details matter. Permissions can go stale (the user was demoted while the page was open), so the UI must still handle a 403 on click: show "You no longer have permission to do this" and refresh the list. And hiding a button is not the same as removing the capability: the endpoint still exists.
Layer 2: the API handler decides, and answers precisely
The order inside this handler is: identify the caller, find the thing, check the input is well formed, then act through a statement that carries the permission rule.
- No session:
401. MDN describes 401 as the request lacking valid authentication credentials; signing in can fix it. - Comment does not exist (or is already deleted):
404. - Body invalid (empty, over 2,000 characters, wrong type):
422. MDN: the server understood the content type and the syntax was correct, but it was unable to process the contained instructions. This check runs before the database statement, so even a stranger who sends a malformed body sees422; that reveals nothing private here because the comment's existence is already public. - Signed in, body fine, but not allowed:
403. MDN describes 403 as the server understanding the request and refusing it, where authenticating or re-authenticating makes no difference. MDN also notes a server may answer404instead of403when acknowledging that a resource exists is unwanted. Comments here are public, so403is the more useful answer. In this handler the allow-or-refuse decision is made by theUPDATEstatement shown in Layer 3: zero rows changed means refuse. - Success:
200with the new body for an edit,204(no content) for a delete.
The handler also reads only the fields it expects. A PATCH that carries "author_id": 3 must not change the author: accepting whatever fields arrive is called mass assignment and is how ownership gets rewritten. The code below ignores everything except body.
// policy.mjs
// The one place the rule is written down in JavaScript.
// comment: { author_id, space_id, deleted_at } user: { id } | null
// modSpaces: Set of space ids the user moderates
export function can(action, user, comment, modSpaces) {
if (!user || comment.deleted_at) return false;
const isAuthor = comment.author_id === user.id;
const isModHere = modSpaces.has(comment.space_id);
if (action === 'edit') return isAuthor; // moderators cannot edit other people's words
if (action === 'delete') return isAuthor || isModHere;
return false;
}
can() is used by the list endpoint to compute the permissions flags. The write itself is guarded by the SQL, shown next.
Layer 3: the database statement repeats the rule
// server.mjs
import http from 'node:http';
import { can } from './policy.mjs';
export function makeServer(pool, { trustUi = false } = {}) {
const send = (res, status, body) => {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(body === undefined ? '' : JSON.stringify(body));
};
const readJson = (req) => new Promise((ok) => {
let s = ''; req.on('data', (c) => (s += c));
req.on('end', () => { try { ok(JSON.parse(s || '{}')); } catch { ok(null); } });
});
const modSpacesOf = async (userId) =>
new Set((await pool.query('SELECT space_id FROM moderators WHERE user_id = $1', [userId])).rows.map((r) => r.space_id));
return http.createServer(async (req, res) => {
// Stand-in for session lookup: header X-Demo-User holds the already authenticated user id.
const uid = Number(req.headers['x-demo-user']);
const user = uid ? { id: uid } : null;
const url = new URL(req.url, 'http://x');
const m = url.pathname.match(/^\/comments\/(\d+)$/);
if (req.method === 'GET' && url.pathname === '/spaces/1/comments') {
const mods = user ? await modSpacesOf(user.id) : new Set();
const { rows } = await pool.query(
'SELECT id, space_id, author_id, body, deleted_at FROM comments WHERE space_id = 1 AND deleted_at IS NULL ORDER BY id');
return send(res, 200, rows.map((c) => ({
id: c.id, body: c.body, author_id: c.author_id,
permissions: { edit: can('edit', user, c, mods), delete: can('delete', user, c, mods) },
})));
}
if (!m) return send(res, 404, { error: 'not_found' });
const id = Number(m[1]);
if (!trustUi && !user) return send(res, 401, { error: 'sign_in_required' });
const { rows: [c] } = await pool.query('SELECT * FROM comments WHERE id = $1', [id]);
if (!c || c.deleted_at) return send(res, 404, { error: 'comment_not_found' });
if (req.method === 'PATCH') {
const body = await readJson(req);
if (!body || typeof body.body !== 'string' || body.body.length < 1 || body.body.length > 2000)
return send(res, 422, { error: 'invalid_body' });
if (trustUi) { // the broken variant: the server trusts that the UI hid the button
await pool.query('UPDATE comments SET body = $2, edited_at = now() WHERE id = $1', [id, body.body]);
return send(res, 200, { id, body: body.body });
}
// Rule re-checked inside the statement: author only, and not already deleted.
const r = await pool.query(
`UPDATE comments SET body = $3, edited_at = now()
WHERE id = $1 AND author_id = $2 AND deleted_at IS NULL
RETURNING id, body`, [id, user.id, body.body]);
if (r.rowCount === 0) return send(res, 403, { error: 'not_your_comment' });
return send(res, 200, r.rows[0]);
}
if (req.method === 'DELETE') {
if (trustUi) {
await pool.query('UPDATE comments SET deleted_at = now() WHERE id = $1', [id]);
return send(res, 204);
}
const r = await pool.query(
`UPDATE comments SET deleted_at = now(), deleted_by = $2
WHERE id = $1 AND deleted_at IS NULL
AND (author_id = $2
OR EXISTS (SELECT 1 FROM moderators m WHERE m.user_id = $2 AND m.space_id = comments.space_id))`,
[id, user.id]);
if (r.rowCount === 0) return send(res, 403, { error: 'not_allowed' });
return send(res, 204);
}
return send(res, 404, { error: 'not_found' });
});
}
The PATCH and DELETE statements put the rule in the WHERE clause: author_id = $2 for edit, and author_id = $2 OR EXISTS (SELECT 1 FROM moderators ...) for delete, with the moderator lookup tied to the comment's own space_id. When rowCount is 0 nothing was written, and the handler answers 403 (the comment was loaded a moment earlier, so it exists). Read the delete statement in plain words: "mark comment $1 as deleted by user $2, but only if it is not already deleted, and only if user $2 is the author, or there exists a row in moderators saying user $2 moderates this comment's space." The EXISTS (SELECT 1 FROM moderators m WHERE ...) part is a yes/no question: does the inner query find at least one row? SELECT 1 just means "the row's contents do not matter, only whether one exists", and comments.space_id ties the question to the comment being deleted.
Here is the gap a separate check leaves. The two-step version runs SELECT (is the user allowed?) and then, later, UPDATE. At 10:00:00.000 the app reads "Dana is a moderator"; at 10:00:00.001 an admin removes Dana's moderator row; at 10:00:00.002 the app runs the delete, based on an answer that stopped being true. With the rule inside the UPDATE, the database decides while it writes. Doing it this way means the decision and the write are one statement: there is no gap between "I checked" and "I wrote" in which a forgotten branch or a second code path could skip the check. A second endpoint added next year that also deletes comments must go through the same statement shape, which is why many teams put it in one data-access function rather than inline.
An honest limit. A snapshot is the database's frozen view of all committed data, taken when a statement starts; in PostgreSQL's default mode each statement gets its own. Timeline: the admin's demotion is still uncommitted at 10:00:00.000, the delete statement starts at 10:00:00.001 and takes its snapshot, the demotion commits at 10:00:00.002, and the delete still treats Dana as a moderator. That window is one statement long, and a demotion that commits that close behind the delete is indistinguishable from the delete having run just before it. For stricter needs, use database row-level security (a feature where the database itself attaches a policy to every query on the table) as a second wall. Raising the transaction isolation level (the setting that decides how much one transaction is shielded from other transactions' concurrent changes) does not shrink this window, because every level still decides from a snapshot; it matters only when the check and the write are separate statements, where REPEATABLE READ keeps both on one snapshot instead of two.
Running it: what goes wrong with UI-only checks, and what the layers give you
The script starts the server in two modes. In trustUi mode the handler skips authorization (the UI "already hid the button"). Then it replays a table of callers against the layered server.
// run.mjs
import pg from 'pg';
import fs from 'node:fs';
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'));
const ALICE = 1, BOB = 2, MALLORY = 3, MOD_ONE = 4, MOD_TWO = 5; // MOD_TWO moderates space 2 only
const reset = async () => {
await pool.query('TRUNCATE comments RESTART IDENTITY; TRUNCATE moderators');
await pool.query('INSERT INTO moderators VALUES ($1,1), ($2,2)', [MOD_ONE, MOD_TWO]);
await pool.query("INSERT INTO comments (space_id, author_id, body) VALUES (1, $1, 'alice says hi'), (1, $2, 'bob says hi')", [ALICE, BOB]);
};
const call = async (port, who, method, path, body) => {
const r = await fetch(`http://127.0.0.1:${port}${path}`, {
method, headers: { ...(who ? { 'x-demo-user': String(who) } : {}), 'content-type': 'application/json' },
body: body ? JSON.stringify(body) : undefined });
return r.status;
};
const alive = async (id) => (await pool.query('SELECT count(*)::int n FROM comments WHERE id=$1 AND deleted_at IS NULL', [id])).rows[0].n === 1;
// 1. A server that trusts the UI
await reset();
let s = makeServer(pool, { trustUi: true }).listen(3101);
const listMallory = await (await fetch('http://127.0.0.1:3101/spaces/1/comments', { headers: { 'x-demo-user': String(MALLORY) } })).json();
console.log('UI sees for Mallory on comment 1:', JSON.stringify(listMallory[0].permissions));
console.log('UI-only: Mallory DELETE comment 1 ->', await call(3101, MALLORY, 'DELETE', '/comments/1'), '| comment 1 still alive:', await alive(1));
s.close();
// 2. The layered server, full matrix
await reset();
s = makeServer(pool).listen(3102);
const rows = [];
const attempt = async (label, who, method, id, body) => {
await reset();
const st = await call(3102, who, method, `/comments/${id}`, body);
rows.push([label, `${method} comment ${id}`, st, method === 'DELETE' ? (await alive(id) ? 'kept' : 'deleted') : (await pool.query('SELECT body FROM comments WHERE id=$1', [id])).rows[0].body]);
};
await attempt('no session', null, 'DELETE', 1);
await attempt('Alice own', ALICE, 'PATCH', 1, { body: 'alice edited' });
await attempt('Mallory other', MALLORY, 'PATCH', 1, { body: 'hacked' });
await attempt('Mallory other', MALLORY, 'DELETE', 1);
await attempt('Alice own', ALICE, 'DELETE', 1);
await attempt('Moderator of space 1', MOD_ONE, 'DELETE', 2);
await attempt('Moderator of space 1', MOD_ONE, 'PATCH', 2, { body: 'mod rewrote bob' });
await attempt('Moderator of space 2', MOD_TWO, 'DELETE', 2);
await attempt('Alice, bad body', ALICE, 'PATCH', 1, { body: '' });
console.table(rows.map(([a,b,c,d]) => ({ caller: a, request: b, status: c, result: d })));
// Mass assignment: author_id in the body is ignored
await reset();
await call(3102, ALICE, 'PATCH', '/comments/1', { body: 'x', author_id: MALLORY });
console.log('author_id after PATCH carrying author_id=3:', (await pool.query('SELECT author_id FROM comments WHERE id=1')).rows[0].author_id);
// UI flags agree with what the server then allows
const l = await (await fetch('http://127.0.0.1:3102/spaces/1/comments', { headers: { 'x-demo-user': String(MOD_ONE) } })).json();
console.log('Moderator list flags:', JSON.stringify(l.map((c) => [c.id, c.permissions])));
s.close(); await pool.end();
Run in a node:22 container against postgres:16, it prints:
UI sees for Mallory on comment 1: {"edit":false,"delete":false}
UI-only: Mallory DELETE comment 1 -> 204 | comment 1 still alive: false
┌─────────┬────────────────────────┬────────────────────┬────────┬─────────────────┐
│ (index) │ caller │ request │ status │ result │
├─────────┼────────────────────────┼────────────────────┼────────┼─────────────────┤
│ 0 │ 'no session' │ 'DELETE comment 1' │ 401 │ 'kept' │
│ 1 │ 'Alice own' │ 'PATCH comment 1' │ 200 │ 'alice edited' │
│ 2 │ 'Mallory other' │ 'PATCH comment 1' │ 403 │ 'alice says hi' │
│ 3 │ 'Mallory other' │ 'DELETE comment 1' │ 403 │ 'kept' │
│ 4 │ 'Alice own' │ 'DELETE comment 1' │ 204 │ 'deleted' │
│ 5 │ 'Moderator of space 1' │ 'DELETE comment 2' │ 204 │ 'deleted' │
│ 6 │ 'Moderator of space 1' │ 'PATCH comment 2' │ 403 │ 'bob says hi' │
│ 7 │ 'Moderator of space 2' │ 'DELETE comment 2' │ 403 │ 'kept' │
│ 8 │ 'Alice, bad body' │ 'PATCH comment 1' │ 422 │ 'alice says hi' │
└─────────┴────────────────────────┴────────────────────┴────────┴─────────────────┘
author_id after PATCH carrying author_id=3: 1
Moderator list flags: [[1,{"edit":false,"delete":true}],[2,{"edit":false,"delete":true}]]
Reading the output:
- The page showed Mallory
{"edit":false,"delete":false}for Alice's comment, yet a directDELETEreturned204and the comment is gone. The UI was correct and still useless as a defence. - With the layers in place Mallory gets
403for both edit and delete, the row is untouched, and the unauthenticated call gets401. - Alice can edit and delete her own comment; the moderator of space 1 can delete Bob's comment but gets
403trying to edit it; the moderator of space 2 gets403on space 1's comment because moderator rights are scoped. - A body carrying
author_idchanges nothing: the author stays user 1. - The
permissionsflags the UI receives (delete: truefor the moderator on both comments,edit: false) match what the server then allows. A test that loops over the callers and compares the flag with the real status code keeps the JavaScript rule and the SQL rule from drifting apart.
Pitfalls that separate a careful answer
The first two matter most; the rest are quick checks.
- Most important: insecure direct object reference (IDOR): any endpoint that takes an id and trusts the caller to send only their own. Example:
DELETE /comments/2works for anyone because the server only checks the user is signed in. The fix is the ownership predicate in the query, not a clever or hidden id. - Most important: checking only on the write path: the list endpoint must not return data the caller may not see, and a "get one comment" endpoint needs its own check.
- Using the client's claim as input:
userId,roleorisModeratorin a request body or a hidden form field. Identity comes from the session; role comes from themoderatorstable. - Authorization in a UI framework's route guard only: a route guard is a client-side rule that decides which page renders, not who may call the API.
- Error leakage (an error message that reveals private data): a
403body should say "not allowed", not "this comment belongs to bob@example.com". - Audit trail (a record of who did what): log
deleted_byand the action so a moderator's deletion can be reviewed.
Running the code
cd work && echo '{"type":"module","dependencies":{"pg":"8.13.1"}}' > package.json
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
docker run --rm --network demo-net -v "$PWD":/w -w /w node:22 sh -c 'npm i --silent && node run.mjs'
Put schema.sql (the SQL listing), policy.mjs, server.mjs and run.mjs from the listings above in work/, and run the first line from the directory that contains work/. The pg_isready -h 127.0.0.1 line waits until the database accepts TCP connections, which happens only after the image's one-time initialisation restart; without it the script can fail with ECONNREFUSED. Stop the database afterwards with docker stop demo-pg.
After a backend release, the "update shipping address" form on an online store shows "Something went wrong" for some users but not others. The API logs show a spike in 400 responses, and the frontend team says they changed nothing. Walk me through how you find out whether the client and the API now disagree on the contract, how you fix it for users right away, and what you change so it cannot happen silently again.
Sample Answer
Direct answer
Treat it as a contract question until the data says otherwise, in this order: (1) prove the 400s start at the backend release and not at some other event, (2) find the exact field the two sides disagree on by slicing the failures and replaying one real failing request, (3) restore service first with the fastest safe move, a rollback or a one-line backend fix that makes the server accept what it used to accept, and only then (4) add the guard that makes the same mistake fail in the pull request instead of in production. Here the evidence points at a single mechanism: the release made the optional line2 field (address line 2) stricter, so a request carrying "line2": null now gets 400, while requests that omit it or carry text still pass. That is why only some users fail, and why the frontend team changed nothing: the form sends back whatever the profile API returned, and the profile API has always returned null for users who never entered a second line.
That is the hypothesis the evidence below confirms, not a given: the first two sections show how you would arrive at it without knowing it in advance. The profile API's response for such a user looks like {"line1": "1 Main St", "line2": null, "city": "Austin", ...}: the field is present with the value null, and the form puts exactly that value back into its PUT.
A contract here means the agreed shape of the request: field names, types, which fields may be missing and which may be null. A 400 Bad Request is the server saying it considers the request itself wrong. Note that "missing" and "null" are different things in JSON, and many validation libraries accept one and reject the other.
1. Is it the release? (minutes)
| Check | Where | What the answer tells you |
|---|---|---|
| 400 rate per minute with deploy markers (vertical lines on a chart at the moment each release shipped) on the same chart | API metrics dashboard | A step at the deploy minute means the release; a slow climb means data or traffic, not the release |
| Same chart for 500s and for other endpoints | same | Only this endpoint's 400s moved: a rule on this endpoint changed. Everything moved: a shared layer (gateway, auth) changed |
| Which client build sent the failing requests | a client-version header, or the bundle hash (the fingerprint in a JavaScript file's name that changes whenever its content changes), in the access log (one line per request the server handled) | If the failing share is the same on every build, the client did not change the outcome; if it is one build only, suspect a stale cached bundle (an old JavaScript file the browser kept instead of fetching the new one) |
| Which validation rule rejected them | the validation-failure log line | The field name is the whole investigation if the log has it; log the field names, never the submitted values (addresses are personal data) |
If the API does not log the failing field, add that log line to the fix below; for now get the payload another way: ask one affected user for a HAR file (HTTP Archive, a saved record of the browser's network requests, exported from DevTools' Network tab) or reproduce the failure yourself with the same profile data. In the browser's DevTools Network tab, select the failed request and read two things: the request payload (does it hold "line2": null?) and the response body (which field does the server name?). The same panel can export the capture as a HAR file, and a request can be copied as a runnable curl command so you can replay it against a staging copy of each release.
2. Find the disagreement
Slice the failures by every dimension you can name and keep the dimension that separates failures from successes. Slicing means grouping the failing requests by one field at a time and counting. A real access-log row is one line of structured data; the generated log below has rows of this shape (two of the 600 are shown: row 300 is the first request after the release, row 301 the next):
{ release: 'v42', client: 'web-118', country: 'US', line2: 'null', status: 400 }
{ release: 'v42', client: 'web-118', country: 'CA', line2: 'text', status: 200 }
The generator and the grouping are short enough to read in full. Each count in the output below is by(failing, field): keep only the rows with status 400, then count how many rows have each value of that field.
// A generated, deterministic request log: 300 requests before the release (v41), 300 after (v42).
const countries = ['US', 'CA', 'GB', 'DE'];
const log = Array.from({ length: 600 }, (_, i) => {
const release = i < 300 ? 'v41' : 'v42';
const line2 = ['null', 'text', 'missing'][i % 3];
return { release, client: 'web-118', country: countries[i % 4], line2, status: release === 'v42' && line2 === 'null' ? 400 : 200 };
});
const failing = log.filter((r) => r.status === 400);
const by = (rows, key) => Object.entries(rows.reduce((m, r) => ((m[r[key]] = (m[r[key]] ?? 0) + 1), m), {})).map(([k, n]) => `${k}=${n}`).join(' ');
console.log('400s by server release :', by(failing, 'release'), ' (requests per release: 300 each)');
console.log('400s by client build :', by(failing, 'client'));
console.log('400s by country :', by(failing, 'country'));
console.log('400s by line2 sent :', by(failing, 'line2'));
console.log('v42 requests with line2=null:', log.filter((r) => r.release === 'v42' && r.line2 === 'null').length, ', of which rejected:', failing.length);
Running it (600 requests: 300 before the release, 300 after) shows what a clean separation looks like:
400s by server release : v42=100 (requests per release: 300 each)
400s by client build : web-118=100
400s by country : US=25 DE=25 GB=25 CA=25
400s by line2 sent : null=100
v42 requests with line2=null: 100 , of which rejected: 100
The 100 failures sit entirely after the release (v42), they are spread evenly over countries and over the one client build (so neither explains them), and they correspond one to one to requests with line2 sent as null. Country is the dimension people reach for first (postal code formats differ by country), and the table is how you rule it out instead of assuming.
Then replay the three shapes of the field against all three releases of the validator, using the same client function the form uses:
// Three releases of the same rule set for PUT /api/address.
const text = (v, max) => typeof v === 'string' && v.length <= max;
function check(a, { line2Rule }) {
const errors = [];
if (!(text(a.line1, 100) && a.line1.length > 0)) errors.push({ field: 'line1', message: 'is required (1 to 100 characters)' });
if (line2Rule === 'strict') {
if (a.line2 !== undefined && !text(a.line2, 100)) errors.push({ field: 'line2', message: 'must be a string' });
} else if (a.line2 !== undefined && a.line2 !== null && !text(a.line2, 100)) {
errors.push({ field: 'line2', message: 'must be text of at most 100 characters, or empty' });
}
if (!(text(a.city, 80) && a.city.length > 0)) errors.push({ field: 'city', message: 'is required' });
if (!(text(a.postal_code, 12) && a.postal_code.length > 0)) errors.push({ field: 'postal_code', message: 'is required (up to 12 characters)' });
if (!(typeof a.country === 'string' && /^[A-Z]{2}$/.test(a.country))) errors.push({ field: 'country', message: 'must be a 2-letter country code' });
return errors;
}
export const releases = {
v41: (a) => check(a, { line2Rule: 'lenient' }), // before: line2 may be missing, null or text
v42: (a) => check(a, { line2Rule: 'strict' }), // the release that broke it: line2 must be text when present
v43: (a) => check(a, { line2Rule: 'lenient' }), // the fix: null means "no second line" again
};
import http from 'node:http';
import { releases } from './validators.mjs';
const validate = releases[process.env.RELEASE];
let saved = null;
http.createServer(async (req, res) => {
if (req.method !== 'PUT' || req.url !== '/api/address') { res.writeHead(404); return res.end(); }
let raw = ''; for await (const c of req) raw += c;
let input; try { input = JSON.parse(raw); } catch { input = null; }
const errors = input && typeof input === 'object' ? validate(input) : [{ field: '', message: 'body must be a JSON object' }];
if (errors.length) {
console.error(`validation failed ${JSON.stringify(errors.map((e) => e.field))}`); // field names only, never the values
res.writeHead(400, { 'Content-Type': 'application/problem+json' });
return res.end(JSON.stringify({ type: 'about:blank', title: 'Invalid address', status: 400, errors }));
}
saved = input;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(saved));
}).listen(Number(process.env.PORT), () => console.log(`${process.env.RELEASE} listening`));
// What the form code does with a response. `base` is the API origin.
export function describeError(status, problem) {
if (status === 400 && Array.isArray(problem?.errors) && problem.errors.length > 0) {
return problem.errors.map((e) => `${e.field}: ${e.message}`).join('; '); // one line per field in the real form
}
return 'Something went wrong';
}
export async function saveAddress(base, address) {
const res = await fetch(`${base}/api/address`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(address) });
const problem = res.ok ? null : await res.json().catch(() => null);
return { status: res.status, message: res.ok ? 'Saved' : describeError(res.status, problem) };
}
import { saveAddress } from './client.mjs';
const base = { line1: '1 Main St', city: 'Austin', postal_code: '78701', country: 'US' };
const cases = { 'line2 = "Apt 4"': { ...base, line2: 'Apt 4' }, 'line2 = null ': { ...base, line2: null }, 'line2 missing ': base };
for (const [release, port] of [['v41', 3041], ['v42', 3042], ['v43', 3043]]) {
for (const [label, body] of Object.entries(cases)) {
const r = await saveAddress(`http://localhost:${port}`, body);
console.log(release, label, '->', r.status, r.message);
}
}
import { describeError } from './client.mjs';
console.log('400 with no problem body (for example an HTML error page from a gateway) ->', describeError(400, undefined));
Three servers run side by side in a node:22 container (v41 before, v42 the broken release, v43 the fix); the demo prints:
v41 line2 = "Apt 4" -> 200 Saved
v41 line2 = null -> 200 Saved
v41 line2 missing -> 200 Saved
v42 line2 = "Apt 4" -> 200 Saved
v42 line2 = null -> 400 line2: must be a string
v42 line2 missing -> 200 Saved
v43 line2 = "Apt 4" -> 200 Saved
v43 line2 = null -> 200 Saved
v43 line2 missing -> 200 Saved
400 with no problem body (for example an HTML error page from a gateway) -> Something went wrong
Reading the validator in words: check collects errors instead of stopping at the first. For line2, the strict rule (release v42) reads a.line2 !== undefined && !text(a.line2, 100): if the field is present at all, it must be text, and null is present but is not text, so it fails with "must be a string". The lenient rule (releases v41 and v43) reads a.line2 !== undefined && a.line2 !== null && !text(...): the field is checked only when it is neither missing nor null, so both of those mean "no second line" and pass. One extra clause, a.line2 !== null, is the whole difference between the releases.
v42 rejects only the null row, and the server log for it holds one line, validation failed ["line2"]. A rule that went from "missing, null or text" to "missing or text" is a tightened request schema: a breaking change for any client that was legal yesterday, even though no endpoint, field name or status code changed. This is also why the frontend team is right that they changed nothing: the form code is untouched. The API team did change something, a validation rule, without intending to change the contract.
The last demo line shows the second defect. The form maps every failure to "Something went wrong" unless the response carries a structured body, so the user, support and the frontend team all lost the one fact that named the field. Error bodies in the application/problem+json format (defined by RFC 9457, which obsoletes RFC 7807) carry type, title, status, detail and instance, and the format allows extension members (extra fields beyond those five, which clients that do not know them ignore); this API adds an errors list of {field, message} pairs, and describeError shows it.
3. Fix it for users right now
Decide in this order:
- Roll the release back (or switch its feature flag off) if the release is one deployable unit and the previous version can still read the data the new one wrote. It is the fastest action that does not require anyone to be right about the cause. The 400s should fall to the pre-release level within a few minutes; confirm on the same chart that showed the step.
- Otherwise fix forward on the server, not the client. The server is the side that changed, and a server deploy fixes every user at once, while a client fix waits for bundles to reload. The fix is the
v43rule: treatnullas "no second line" again. This is the tolerant-reader principle (be liberal in what you accept): for an optional field,nulland missing mean the same thing, so accept both. A feature flag is a configuration switch that turns a piece of code on or off without a new deploy; if the release was behind one, flipping it is the rollback. - Do not "fix" it by changing the client to strip nulls as the only action: users with a cached old bundle, and other clients such as a mobile app, still send
null.
After either, check the outcome with a metric, not with a single manual save: the 400 rate on this endpoint back to its pre-release level, and the count of line2 validation failures at zero. Then look for users who gave up: they will have retried a few times and left, so support tickets and form abandonment for the window are the cleanup list.
4. Make it impossible to ship silently
If you can name only one guard, name the first, the replay of real request shapes: it is the one shown below failing on this exact bug. The other four add layers around it.
- A contract check in CI (continuous integration, the automated build that runs on every pull request) over real request shapes. Keep a corpus of anonymised request bodies that real clients have sent (one per distinct shape: filled,
null, missing, empty string), and fail the pull request if the new rules reject a body the previous release accepted. The script below (contract-check.mjs) replays the corpus that follows it against an old and a candidate release; its output for the broken and then the fixed rules is shown after the corpus.
// Replays recorded request bodies against the old and the candidate release.
// Fails if the candidate rejects a body that the old release accepted.
import { readFileSync } from 'node:fs';
import { releases } from './validators.mjs';
const [oldName, candidateName] = process.argv.slice(2);
const corpus = JSON.parse(readFileSync(new URL('./corpus.json', import.meta.url)));
let regressions = 0;
for (const { name, body } of corpus) {
const before = releases[oldName](body), after = releases[candidateName](body);
const verdict = before.length === 0 && after.length > 0 ? 'REGRESSION' : 'ok';
if (verdict === 'REGRESSION') regressions++;
console.log(`${verdict.padEnd(10)} ${name}${after.length ? ' -> ' + after.map((e) => e.field + ' ' + e.message).join(', ') : ''}`);
}
console.log(`${regressions} regression(s) between ${oldName} and ${candidateName}`);
process.exit(regressions > 0 ? 1 : 0);
[
{ "name": "US, second line filled", "body": { "line1": "1 Main St", "line2": "Apt 4", "city": "Austin", "postal_code": "78701", "country": "US" } },
{ "name": "US, second line null (profile never had one)", "body": { "line1": "1 Main St", "line2": null, "city": "Austin", "postal_code": "78701", "country": "US" } },
{ "name": "CA, second line key missing", "body": { "line1": "9 King St", "city": "Ottawa", "postal_code": "K1A 0B1", "country": "CA" } },
{ "name": "GB, second line empty string", "body": { "line1": "2 High Rd", "line2": "", "city": "Leeds", "postal_code": "LS1 4AP", "country": "GB" } }
]
## contract-check v41 -> v42
ok US, second line filled
REGRESSION US, second line null (profile never had one) -> line2 must be a string
ok CA, second line key missing
ok GB, second line empty string
1 regression(s) between v41 and v42
exit code 1
## contract-check v41 -> v43
ok US, second line filled
ok US, second line null (profile never had one)
ok CA, second line key missing
ok GB, second line empty string
0 regression(s) between v41 and v43
exit code 0
The check fails on v42 (exit code 1, which fails the pipeline step) and passes on v43 (exit code 0), so it demonstrably catches this exact bug. A check that has never been seen failing proves nothing.
- Put the contract in one machine-readable place (a file a program can read, not a wiki page). An OpenAPI document (a standard format that describes an HTTP API) or a shared schema that the server validates against and the client types are generated from means a stricter field changes a file in the diff. A schema-diff tool such as
oasdiffcompares two OpenAPI documents and reports changes that break existing clients, which turns "did a request field get stricter?" into a failing build step instead of a reviewer's memory. - Roll out tighter validation in two steps. First ship the new rules in log-only mode (validate, record violations, still accept), watch the violation count for a day, then enforce. The breaking data shows up in a log line instead of in a user's failed save.
- Release canary with a 400 guard. A canary release sends the new version to a small share of traffic first; alert on the 400 rate of mutating endpoints by version. Teams often alert on 5xx only, because 4xx is "the client's fault"; this incident is a 4xx that was the server's fault.
- Client error handling. Show the field message when the response is a problem document, keep the generic message for anything else, and include a request id in the generic message so support can find the server log line.
What to say about validation status codes: this API answers 400 for field errors, as in the stem. MDN describes 422 Unprocessable Content for requests that are well formed but cannot be processed, and either is defensible; what matters here is that the body names the field and that the choice is the same on every endpoint.
Running the code
# folder with validators.mjs, server.mjs, client.mjs, demo.mjs, triage.mjs, contract-check.mjs, corpus.json
docker run --rm -v "$PWD":/w -w /w node:22 sh -c '
for r in 41 42 43; do RELEASE=v$r PORT=30$r node server.mjs >/dev/null 2>/tmp/err$r.txt & done
sleep 2; node triage.mjs; node demo.mjs; sort /tmp/err42.txt | uniq -c
echo "## contract-check v41 -> v42"; node contract-check.mjs v41 v42; echo "exit code $?"
echo "## contract-check v41 -> v43"; node contract-check.mjs v41 v43; echo "exit code $?"'
The files, in the order they appear above: triage.mjs (the generated log and the grouping), validators.mjs (the three rule sets), server.mjs (the PUT endpoint), client.mjs (the form's save and error code), demo.mjs (the nine-case replay), contract-check.mjs and corpus.json (the CI check).
No package.json is needed: the files use only Node built-ins and the .mjs extension. The three servers stop when the container exits, and the two ## contract-check header lines in the last output come from the echo commands above. The output is the same on every run.
Unlock Full Question Bank
Get access to all 16 End-to-End Feature Design and Development interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.