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.
Build the home feed for a small social app: it shows posts from the people the user follows, newest first, with infinite scroll. Walk me through the API contract, the query and indexes behind it, the client-side state, and what the user sees when new posts are published while they are scrolling.
Sample Answer
Direct answer
Page the feed with a keyset cursor (also called seek pagination: "give me the 20 posts older than this exact post", where the post is identified by its timestamp plus its id), never with OFFSET. Order by (created_at, id) newest first, back it with an index on the author, and return an opaque cursor with every page. On the client, keep the list in a small reducer (a pure function that takes the old state and an event and returns the new state) that appends pages, removes duplicates by post id, and holds posts published while the user scrolls in a separate "pending" list. A "3 new posts" pill moves them to the top only when the user clicks it, so the list never jumps under their thumb. This is fan-out-on-read (the feed is assembled when it is requested by joining follows to posts), which is the right choice at small scale; the section on trade-offs says what flips it.
API contract
| Call | Meaning | Success | Errors |
|---|---|---|---|
GET /v1/feed?limit=20 | first page | 200 {"items":[...],"next_cursor":"...","head":"..."} | 401 not signed in |
GET /v1/feed?limit=20&cursor=<next_cursor> | the next older page | 200, next_cursor is null on the last page | 400 for a cursor that does not decode |
GET /v1/feed?after=<head> | posts newer than the newest post the client has | 200 {"items":[...]} (up to 50, newest first) | 400 for a bad head |
limithas a server-side maximum (say 50); the client cannot ask for 10,000 rows.- The cursor is opaque (a value the client treats as a sealed token, never looks inside, and sends back unchanged); here it is a small JSON object (timestamp plus id) encoded as base64url (a way of writing arbitrary bytes using only letters, digits,
-and_, safe to put in a URL). That lets the server change its contents later without breaking clients. The server still validates it on every request, because a client can send anything: MDN describes400 Bad Requestas the server refusing a request it considers a client error, and notes that repeating it without modification will fail with the same error, so the client should not resend a400unchanged. headis a cursor pointing at the newest post in the first page. It is the anchor for "anything newer?".- A page of
Nitems is requested when the user is within a screen or two of the bottom. The usual trigger is a sentinel element (an empty marker placed under the last post) watched by anIntersectionObserver(a browser API that reports when a watched element enters the viewport). A visible "Load more" button stays available as the fallback for keyboard and screen-reader users, who cannot scroll a sentinel into view in the same way.
Data model and the query
Three facts are needed: who follows whom, the posts, and a stable sort order. The stable order matters most. If two posts carry the same timestamp, a sort on created_at alone has no defined order between them, and a page boundary can fall between them and lose one. Adding id as a tie-breaker makes the order total (every pair of posts has a defined before and after, with no ties left).
CREATE TABLE follows (
follower_id bigint NOT NULL,
followee_id bigint NOT NULL,
PRIMARY KEY (follower_id, followee_id)
);
CREATE TABLE posts (
id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
author_id bigint NOT NULL,
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX posts_author_time_idx ON posts (author_id, created_at DESC, id DESC);
-- user 1 follows authors 2 and 3; posts are one minute apart, two share a timestamp
INSERT INTO follows VALUES (1,2),(1,3);
INSERT INTO posts (author_id, body, created_at) VALUES
(2,'p1','2026-10-08 10:01+00'),(3,'p2','2026-10-08 10:02+00'),
(2,'p3','2026-10-08 10:03+00'),(3,'p4','2026-10-08 10:04+00'),
(2,'p5','2026-10-08 10:05+00'),(3,'p6','2026-10-08 10:05+00'),
(2,'p7','2026-10-08 10:06+00'),(3,'p8','2026-10-08 10:07+00'),
(4,'not-followed','2026-10-08 10:08+00');
The page query uses a row comparison, (created_at, id) < (cursor_time, cursor_id), which means "strictly before that post in the (created_at, id) order". Reading it with the two earlier posts that share 10:05: p6 (id 6) sorts before p5 (id 5) in descending order, so a cursor at p6 returns p5 next, and neither is lost or repeated.
-- page 1 (3 per page)
SELECT p.id, p.body FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1
ORDER BY p.created_at DESC, p.id DESC LIMIT 3;
-- page 2, cursor = last row of page 1 = (10:05, id 6)
SELECT p.id, p.body FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1 AND (p.created_at, p.id) < ('2026-10-08 10:05+00', 6)
ORDER BY p.created_at DESC, p.id DESC LIMIT 3;
What OFFSET does when a post is published in between
A reader fetches page 1, another user then publishes a post by author 2 at 10:09, and the reader fetches page 2 both ways. Each request is its own query and each statement commits on its own, so one script reproduces it exactly:
-- reader, page 1 by OFFSET
SELECT string_agg(body, ', ' ORDER BY created_at DESC, id DESC) AS offset_page1 FROM (
SELECT p.id, p.body, p.created_at FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1 ORDER BY p.created_at DESC, p.id DESC LIMIT 3 OFFSET 0) page;
-- another user publishes
INSERT INTO posts (author_id, body, created_at) VALUES (2, 'NEW', '2026-10-08 10:09+00');
-- reader, page 2 by OFFSET
SELECT string_agg(body, ', ' ORDER BY created_at DESC, id DESC) AS offset_page2 FROM (
SELECT p.id, p.body, p.created_at FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1 ORDER BY p.created_at DESC, p.id DESC LIMIT 3 OFFSET 3) page;
-- reader, page 2 by keyset (cursor = last row of page 1 = 10:05, id 6)
SELECT string_agg(body, ', ' ORDER BY created_at DESC, id DESC) AS keyset_page2 FROM (
SELECT p.id, p.body, p.created_at FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1 AND (p.created_at, p.id) < ('2026-10-08 10:05+00', 6)
ORDER BY p.created_at DESC, p.id DESC LIMIT 3) page;
Run against the seed above, the three queries print:
| page 1 | page 2 after the new post | |
|---|---|---|
OFFSET | p8, p7, p6 | p6, p5, p4 (p6 appears twice) |
| keyset | p8, p7, p6 | p5, p4, p3 |
The new post pushes every older post one position down, so OFFSET 3 lands on a row the reader already saw. In the other direction (a post deleted while scrolling) OFFSET would silently skip one. Keyset paging anchors on a post, not a position, so insertions above the cursor change nothing below it.
Keep the full timestamp in the cursor
The cursor must carry the timestamp exactly as the database stores it. PostgreSQL keeps microseconds, but a JavaScript Date keeps milliseconds. Take three posts:
| post | id | created_at |
|---|---|---|
| a | 1 | 10:00:00.123456 |
| b | 2 | 10:00:00.123789 |
| c | 3 | 10:00:00.123100 |
Newest first the order is b, a, c (b has the latest microseconds). Page 1 has size 1 and returns b, so the cursor is (10:00:00.123789, 2). Page 2 should return a and c.
- Cursor built through a
Date(milliseconds only):(10:00:00.123, 2). The comparison(created_at, id) < (10:00:00.123, 2)asks for rows before.123000, but a (.123456) and c (.123100) are both after.123000, so it returns zero rows and both vanish. - Cursor with the full text:
(10:00:00.123789, 2). Now a and c are both before it, and the query returnsaandc.
TRUNCATE posts RESTART IDENTITY;
INSERT INTO posts (author_id, body, created_at) VALUES
(2, 'a', '2026-10-08 10:00:00.123456+00'),
(2, 'b', '2026-10-08 10:00:00.123789+00'),
(2, 'c', '2026-10-08 10:00:00.123100+00');
-- page 2 with a cursor rebuilt through a JavaScript Date (milliseconds only)
SELECT body FROM posts WHERE (created_at, id) < ('2026-10-08 10:00:00.123+00', 2) ORDER BY created_at DESC, id DESC;
-- page 2 with the full timestamp text
SELECT body FROM posts WHERE (created_at, id) < ('2026-10-08 10:00:00.123789+00', 2) ORDER BY created_at DESC, id DESC;
Run in postgres:16, the first query prints no rows and the second prints a then c. So the server prints the timestamp as text, base64url-encodes it with the id, and never routes it through a Date. The cursor helpers at the top of the next code block do exactly that (they run on the server).
What the index buys, and where it stops
With this data generator (400,000 posts spread over 5,000 authors, user 1 following 200 of them) and the query below, whose cursor is newer than every row so it behaves like a first page:
TRUNCATE posts, follows RESTART IDENTITY;
INSERT INTO follows SELECT 1, g FROM generate_series(2, 201) g;
INSERT INTO posts (author_id, body, created_at)
SELECT 2 + (g % 5000), 'x', timestamptz '2026-01-01 00:00+00' + (g || ' seconds')::interval
FROM generate_series(1, 400000) g;
ANALYZE;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT p.id, p.created_at FROM posts p JOIN follows f ON f.followee_id = p.author_id
WHERE f.follower_id = 1 AND (p.created_at, p.id) < ('2026-02-01 00:00+00', 300000)
ORDER BY p.created_at DESC, p.id DESC LIMIT 20;
It prints this plan (read from the bottom of the tree upwards; actual rows is what each step really produced):
Limit (actual rows=20 loops=1)
-> Sort (actual rows=20 loops=1)
Sort Key: p.created_at DESC, p.id DESC
Sort Method: top-N heapsort Memory: 25kB
-> Merge Join (actual rows=16000 loops=1)
Merge Cond: (p.author_id = f.followee_id)
-> Index Only Scan using posts_author_time_idx on posts p (actual rows=16001 loops=1)
Index Cond: (ROW(created_at, id) < ROW('2026-02-01 00:00:00+00'::timestamp with time zone, 300000))
Heap Fetches: 16001
-> Index Only Scan using follows_pkey on follows f (actual rows=200 loops=1)
Index Cond: (follower_id = 1)
Heap Fetches: 200
What the nodes mean: an index-only scan answers from an index (here posts_author_time_idx, then the primary key of follows) without opening the table, but only for rows the table's visibility map (a per-page note that every row on the page is visible to all transactions) marks as safe; Heap Fetches counts the rows for which it still had to open the table to check. The data in this demo was bulk-loaded and not yet vacuumed, so every row needed that check (Heap Fetches: 16001); after a VACUUM the same query reports Heap Fetches: 0 with the same row counts. The merge join walks the two sorted inputs (posts by author, followees by id) side by side and pairs up equal authors. The top-N heapsort keeps only the 20 best rows seen so far while the 16,000 flow past it. Limit then returns those 20. The arithmetic: 400,000 posts over 5,000 authors is 80 posts per author; user 1 follows 200 authors, so 200 x 80 = 16,000 posts, and because the cursor is newer than every row, all 16,000 match (the plan shows actual rows=16000; the one extra row in the index scan, 16001, is most likely the join reading one row past the last matching author to know it is finished). The signal is the gap: 16,000 rows produced to return 20, and that gap grows with posts per followee, not with the page size. In plain words: this query's cost grows with how much the followed authors have posted, not with the page size. At a few hundred followees and modest posting rates that is fine; for a user following thousands of prolific accounts it is not. Two mitigations come before changing the architecture: add a recency window to the query (for example only posts from the last 30 days), and cache the first page for a few seconds.
Client state and what the user sees
The code block below opens with the server-side cursor helpers; the reducer that follows is the client's whole behaviour. Its tests also check that a cursor with a valid timestamp but a non-numeric id is rejected, and that a numeric id with an invalid timestamp is rejected, so each validation line is exercised on its own. Reading the reducer's events: PAGE_OK appends a page (first page or "load more"); POLL_OK stores newly published posts in pending and does not touch items; SHOW_PENDING runs when the user clicks the pill; PAGE_FAIL keeps everything already on screen and records an error so a "Try again" button can appear.
import test from 'node:test';
import assert from 'node:assert/strict';
export const encodeCursor = (createdAt, id) =>
Buffer.from(JSON.stringify({ t: createdAt, id: String(id) })).toString('base64url');
export function decodeCursor(raw) {
try {
const { t, id } = JSON.parse(Buffer.from(raw, 'base64url').toString());
if (typeof t !== 'string' || !/^\d+$/.test(id) || Number.isNaN(Date.parse(t))) return null;
return { t, id };
} catch { return null; }
}
export const initial = { items: [], seen: new Set(), next: null, head: null, loading: false, error: null, pending: [] };
export function reduce(s, ev) {
switch (ev.type) {
case 'PAGE_START': return { ...s, loading: true, error: null };
case 'PAGE_OK': {
const fresh = ev.items.filter((p) => !s.seen.has(p.id));
return { ...s, loading: false, items: [...s.items, ...fresh],
seen: new Set([...s.seen, ...fresh.map((p) => p.id)]),
next: ev.next, head: s.head ?? ev.head };
}
case 'PAGE_FAIL': return { ...s, loading: false, error: 'Could not load more posts.' };
case 'POLL_OK': {
const known = new Set([...s.seen, ...s.pending.map((p) => p.id)]);
const fresh = ev.items.filter((p) => !known.has(p.id));
return { ...s, pending: [...fresh, ...s.pending] };
}
case 'SHOW_PENDING': {
const ids = s.pending.map((p) => p.id);
return { ...s, items: [...s.pending, ...s.items], seen: new Set([...s.seen, ...ids]),
pending: [], head: ev.head ?? s.head };
}
}
return s;
}
const post = (id) => ({ id: String(id), body: `p${id}` });
test('cursor round trip and tamper rejection', () => {
const c = encodeCursor('2026-10-08 10:05:00.123456+00', 6);
assert.deepEqual(decodeCursor(c), { t: '2026-10-08 10:05:00.123456+00', id: '6' });
assert.equal(decodeCursor('not-a-cursor'), null);
const enc = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
assert.equal(decodeCursor(enc({ t: '2026-10-08 10:05:00+00', id: '1; DROP' })), null);
assert.equal(decodeCursor(enc({ t: 'x', id: '1' })), null);
});
test('new posts wait in pending and do not move the list', () => {
let s = reduce(initial, { type: 'PAGE_OK', items: [post(8), post(7), post(6)], next: 'c1', head: 'h8' });
s = reduce(s, { type: 'POLL_OK', items: [post(9)] });
assert.deepEqual(s.items.map((p) => p.id), ['8', '7', '6']);
assert.equal(s.pending.length, 1);
s = reduce(s, { type: 'SHOW_PENDING', head: 'h9' });
assert.deepEqual(s.items.map((p) => p.id), ['9', '8', '7', '6']);
});
test('overlap between polls and pages never duplicates a post', () => {
let s = reduce(initial, { type: 'PAGE_OK', items: [post(8), post(7)], next: 'c1', head: 'h8' });
s = reduce(s, { type: 'POLL_OK', items: [post(9), post(8)] });
s = reduce(s, { type: 'POLL_OK', items: [post(9)] });
assert.deepEqual(s.pending.map((p) => p.id), ['9']);
s = reduce(s, { type: 'PAGE_OK', items: [post(7), post(6)], next: null });
assert.deepEqual(s.items.map((p) => p.id), ['8', '7', '6']);
});
test('a failed page keeps what is on screen and offers retry', () => {
let s = reduce(initial, { type: 'PAGE_OK', items: [post(3)], next: 'c1', head: 'h3' });
s = reduce(reduce(s, { type: 'PAGE_START' }), { type: 'PAGE_FAIL' });
assert.equal(s.items.length, 1);
assert.equal(s.loading, false);
assert.ok(s.error);
});
Run with node --test, the four tests pass (# pass 4, # fail 0).
A traced example with concrete ids (steps 0, 1, 2 and 4 are the second test; step 3 adds the overlap case from the third test):
| step | event | items | pending |
|---|---|---|---|
| 0 | start | empty | empty |
| 1 | PAGE_OK with posts 8, 7, 6 | 8, 7, 6 | empty |
| 2 | POLL_OK with post 9 (published meanwhile) | 8, 7, 6 (unchanged) | 9 |
| 3 | POLL_OK again with posts 9, 8 | 8, 7, 6 | 9 (8 is already shown, 9 already waiting, so neither is added) |
| 4 | user clicks the pill: SHOW_PENDING | 9, 8, 7, 6 | empty |
What the user sees, state by state:
| Situation | UI |
|---|---|
| First load | A few skeleton cards (grey placeholders the shape of a post), not a spinner on a blank page |
| Follows nobody, or followed accounts have posted nothing | An empty state that says so and links to finding people |
| Scrolling near the bottom | The next page is requested early; a small "Loading" row sits under the last post |
| Page request fails | Posts already shown stay; the bottom row says "Could not load more posts" with a "Try again" button |
| Last page reached | "You're all caught up", and no more requests |
| New posts published meanwhile | The list does not move. A pill at the top reads "3 new posts"; it is announced politely to screen readers (aria-live="polite"); clicking it prepends the posts and scrolls to the top |
Polling for the pill: every 30 to 60 seconds while the tab is visible, call GET /v1/feed?after=<head>. Stop polling when the tab is hidden (document.visibilityState). If a poll returns the full 50 items there may be more than fit, so the pill reads "50+ new posts" and clicking it reloads the first page instead of prepending; prepending only the newest 50 and then moving head forward would silently skip the older posts in between.
The commit-order gap, and the overlap that closes it
A post's created_at is set by now() when its transaction starts, not when it commits. This script, run with the schema above loaded, starts two psql sessions and shows the consequence:
C=pg-demo
psql_() { docker exec -i "$C" psql -U postgres -q -A -t "$@"; }
psql_ -c "TRUNCATE posts, follows RESTART IDENTITY; INSERT INTO follows VALUES (1,2),(1,3);"
# session A: the transaction starts (and now() is fixed), inserts, then commits 4 seconds later
psql_ -c "BEGIN; INSERT INTO posts (author_id, body) VALUES (2, 'from-A'); SELECT pg_sleep(4); COMMIT;" > /dev/null &
sleep 1
# session B: inserts and commits at once
psql_ -c "INSERT INTO posts (author_id, body) VALUES (3, 'from-B')" > /dev/null
echo "poll while A is open:"; psql_ -c "SELECT body FROM posts ORDER BY created_at DESC, id DESC"
wait
echo "newer than head (B) after A commits:"
psql_ -c "SELECT count(*) FROM posts WHERE (created_at, id) > (SELECT created_at, id FROM posts WHERE body = 'from-B')"
echo "newer than head by id instead of by time:"
psql_ -c "SELECT count(*) FROM posts WHERE id > (SELECT id FROM posts WHERE body = 'from-B')"
echo "with a 60 second overlap before head:"
psql_ -c "SELECT body FROM posts WHERE created_at > (SELECT created_at FROM posts WHERE body = 'from-B') - interval '60 seconds' ORDER BY created_at DESC, id DESC"
Session A begins a transaction, inserts from-A, and sleeps 4 seconds before committing. Meanwhile session B inserts from-B and commits at once, and the reader's poll sees only from-B and takes it as the newest post. The script prints from-B for the poll, 0 for "newer than from-B" after A commits, 0 again when "newer" is judged by id instead of time, and with the 60 second overlap from-B then from-A. As a timeline:
| time | session A | session B | what the reader sees |
|---|---|---|---|
| 0 s | begins, inserts from-A (gets created_at t0 and id 1) | nothing yet (A has not committed) | |
| 1 s | still open | inserts from-B (t0 + 1 s, id 2) and commits | from-B, which becomes the head |
| 4 s | commits | from-A is now visible but older than the head |
Because session A commits last, from-A has the older timestamp, so the check "anything newer than from-B?" returns 0 even though a fresh first page lists both. Left alone, the pill would never mention from-A.
The fix is an overlap: the server answers after=<head> with every post newer than a point 60 seconds before the head's timestamp, and the client discards ids it has already seen (the reducer's seen set and pending list do exactly that, and its third test sends overlapping ids). A transaction that stays open longer than the overlap can still slip through, so a full refresh on pull-to-refresh or tab return is the backstop. Ordering by id instead does not escape this: the database hands out an identity value when the row is inserted, not when it commits, so a lower id can commit later than a higher one. Here from-A has id 1 and commits after from-B (id 2), and the script's id > check also returns 0.
Trade-offs and what would change the design
- Fan-out-on-read (this design) versus fan-out-on-write. "Fan-out" means spreading one post to many readers. On read (this design) the feed is assembled when requested. On write, publishing a post copies a row into each follower's own feed table (a materialised feed: a stored, precomputed result instead of one computed on request); reading is then a single indexed range scan on one user. It pays off when feed reads vastly outnumber writes and the query above gets slow, but a celebrity with a million followers turns one publish into a million inserts. Stay on read until the
EXPLAINrow counts or the page latency say otherwise, and when that happens the usual compromise is to write feeds for ordinary accounts and merge in the posts of very popular accounts at read time. - Unfollow and delete take effect immediately here, because the query joins the current
followstable. A materialised feed table (the precomputed one described above) would need cleanup jobs. - Long sessions: a list that only grows holds thousands of DOM nodes. Virtualisation (rendering only the rows near the viewport) is the answer when scrolling gets heavy; it changes the rendering layer, not this contract.
- Common wrong turns:
OFFSET, a cursor that is just a timestamp (ties lose posts), a cursor that is milliseconds only, and auto-inserting new posts at the top while the user is reading.
Running the code
Save each SQL block, in the order shown, as feed.sql (schema and seed), pages.sql (the two page queries), offset.sql, micro.sql and plan.sql (the data generator and EXPLAIN); save the shell block as gap.sh with C=pg-demo matching the container name below, and the JavaScript block as feed.mjs.
docker run -d --rm --name pg-demo -e POSTGRES_PASSWORD=x postgres:16
sleep 8
for f in feed.sql pages.sql offset.sql micro.sql plan.sql; do docker exec -i pg-demo psql -U postgres -v ON_ERROR_STOP=1 < $f; done
bash gap.sh
docker stop pg-demo
docker run --rm -v "$PWD":/w -w /w node:22 node --test feed.mjs
You are shipping an "order history" page that lists a user's past orders with a date filter. Walk me through every state the page can be in, from the first load to a backend timeout, what the API returns in each case, and which numbers you would watch after launch to know the feature actually works for real users.
Sample Answer
Direct answer
The page is a small state machine (code that is always in exactly one named state and moves to another on a defined event) with eleven views, and each one maps to one API outcome, so the UI never has to guess. The API answers 200 with a list (possibly empty) for everything that worked, 422 for a bad filter, 401 for an expired session, and 503 with a Retry-After header when the backend cannot answer in time. The client adds the cases the server cannot report: it gives up after its own timeout, it can be offline, and it must ignore an old response that arrives after a newer request. After launch, the numbers worth watching are the share of page views that end in a good view (list or a legitimate empty) within a time limit (for example 3 seconds; an illustrative target, to be replaced by one set from the first week of real traffic), the rate of each error view, the latency of the first page of orders, and the empty-result rate with a date filter, because a sudden jump in that last one is how a time zone or filter bug shows up.
The eleven views and what the API returns
The three kinds of view to be able to name first are loaded (views 2 and 3), empty (views 5 and 6) and the retryable error (view 9); the other six are variations on those.
| # | View | When | API response | What the user sees |
|---|---|---|---|---|
| 1 | Loading | first request, nothing to show yet | (pending) | skeleton rows (grey placeholder bars shaped like rows) the height of real rows, so nothing jumps when data arrives |
| 2 | Loaded | orders returned, no further page | 200 {orders:[...], next_cursor:null} | the list, newest first |
| 3 | Loaded, more pages | next_cursor is not null | 200 {orders:[...], next_cursor:"..."} | the list plus a "Load more" button |
| 4 | Refreshing | the filter changed while rows are on screen | (pending) | previous rows dimmed and marked busy, not a blank page |
| 5 | Empty, no orders ever | no filter, zero orders | 200 {orders:[], next_cursor:null} | "You have not placed any orders yet" and a link to browse |
| 6 | Empty, filter matched nothing | filter set, zero orders | 200 {orders:[], ...} | "No orders between these dates" and a Clear filter button |
| 7 | Invalid filter | from date after to date, malformed date | 422 {error:"invalid_filter"} | the field is flagged; the previous list stays |
| 8 | Signed out | session expired | 401 {error:"sign_in_required"} | sign-in prompt that returns to this page |
| 9 | Backend slow or down | database timeout, upstream error, rate limit, or the client gave up | 503 with Retry-After, or 504, or no response before the client timeout (a 429 rate-limit answer would map here too; the demo server never sends one) | "We could not load your orders" with a Try again button |
| 10 | Offline | the request never reached any server | none (fetch fails) | "You appear to be offline" and a retry that works when the connection returns |
| 11 | Load more failed | the next-page request failed | same as 9, for page 2 | the existing list stays; an inline "Could not load more. Try again" under it |
The key design decisions:
- Empty is a success, not an error. An empty list is a normal
200with[]. A404would make every client special-case "no data" as a failure, and monitoring would count normal new customers as errors. Empty with a filter (view 6) and empty with no filter (view 5) need different words and different actions, which is why the client tracks whether a filter is active. - Never show a blank page while refreshing. View 4 keeps the old rows visible, which avoids layout jumping (CLS, cumulative layout shift) and makes the page feel fast.
- An error that happens on page 2 must not wipe page 1. View 11 is separate from view 9 for that reason.
- Do not retry blindly. Views 7 and 8 are not retryable as they stand (same request, same answer), so they have no automatic retry. View 9 is retryable.
API contract
GET /v1/orders?from=2026-06-01&to=2026-06-30&tz=America/New_York&limit=20&cursor=...
fromandtoare calendar dates in the user's time zone, both inclusive. The server turns them into the half-open range "from 00:00 onfrom, up to but not including 00:00 on the day afterto", in the zonetz. Treating the dates as UTC puts late-evening orders on the wrong day. In the run below, an order placed at 23:30 in New York on March 31 (03:30 UTC on April 1) is found by a March 31 filter and not by an April 1 filter in New York, while an April 1 filter read as UTC wrongly finds it.- Paging uses a cursor (an opaque token marking where the last page ended) over
(placed_at, id), notOFFSET. With an offset, a new order arriving while the user reads shifts every row down and page 2 repeats a row from page 1; the cursor says "after this exact row". Theidis the tie-break for two orders in the same instant. 401: MDN describes it as the request lacking valid authentication credentials.422: syntax fine, instructions could not be processed (MDN adds that repeating the same request unchanged fails again).503: the server is not ready to handle the request; MDN says to use it for temporary conditions withRetry-Aftercarrying the estimated recovery time. The header's value is either a non-negative whole number of seconds (used here) or an HTTP date.504: a gateway or proxy did not get a response in time from the server behind it.
Backend: the timeout is a feature
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
id bigserial PRIMARY KEY,
user_id integer NOT NULL,
placed_at timestamptz NOT NULL,
total_cents integer NOT NULL,
status text NOT NULL
);
-- one user's orders, newest first, with a stable tie-break: serves the list and the "next page" cursor
CREATE INDEX orders_user_recent ON orders (user_id, placed_at DESC, id DESC);
-- user 1: an order every 3 days for 45 orders, ending 2026-06-30 12:00 UTC
INSERT INTO orders (user_id, placed_at, total_cents, status)
SELECT 1, timestamptz '2026-06-30 12:00+00' - (n * interval '3 days'), 1000 + n, 'delivered'
FROM generate_series(0, 44) n;
-- user 2: no orders at all. user 3: one order at 23:30 on March 31 in New York (03:30 UTC on April 1)
INSERT INTO orders (user_id, placed_at, total_cents, status) VALUES (3, timestamptz '2026-04-01 03:30+00', 4200, 'delivered');
-- user 4: three orders inside one millisecond (microsecond timestamps, as now() produces)
INSERT INTO orders (user_id, placed_at, total_cents, status) VALUES
(4, timestamptz '2026-07-01 10:00:00.123900+00', 1, 'delivered'),
(4, timestamptz '2026-07-01 10:00:00.123500+00', 2, 'delivered'),
(4, timestamptz '2026-07-01 10:00:00.123100+00', 3, 'delivered');
In plain words, the filter lines do this. Take user 3 in New York with an order placed at 23:30 on March 31, which is 03:30 UTC on April 1. ($2::date)::timestamp AT TIME ZONE $4 turns the text date into a midnight on that calendar day and says "that midnight is in the user's time zone" (::date and ::timestamp are casts, type conversions). For from = 2026-04-01 in New York that midnight is 04:00 UTC, so the order at 03:30 UTC is before it and is excluded. For to = 2026-03-31, the upper bound is ($3::date + 1) = April 1 midnight in New York = 04:00 UTC, and the comparison is < (the range is half-open: includes its start, excludes its end), so the 03:30 UTC order is included. The (placed_at, id) < ($5, $6) line compares two columns as a pair: a row qualifies if its time is earlier, or the times are equal and its id is smaller, which is "after the last row of the previous page" in the list's sort order. The query asks for limit + 1 rows; if the extra row exists there is another page, and the handler returns only limit rows. The cursor is a small JSON array [placed_at, id] of the last row shown, encoded with base64url (a way to write bytes as URL-safe text), so it is opaque to the client but easy to decode on the server. The placed_at inside it is the exact database value written out as text with microseconds (to_char(... US) in the query), not a JavaScript Date: a Date keeps only milliseconds, and a rounded cursor would silently skip orders placed in the same millisecond as the last row shown. pg_sleep(1) pauses the database session for one second and is only the demo's stand-in for a slow query.
The index matches the query's WHERE user_id = ... ORDER BY placed_at DESC, id DESC, so a page is a short walk down one user's rows instead of a sort.
// server.mjs
import http from 'node:http';
const isDate = (s) => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && !isNaN(Date.parse(s));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export function makeServer(pool) {
return http.createServer(async (req, res) => {
const send = (status, body, headers = {}) => { res.writeHead(status, { 'content-type': 'application/json', ...headers }); res.end(JSON.stringify(body)); };
const url = new URL(req.url, 'http://x');
if (req.method !== 'GET' || url.pathname !== '/v1/orders') return send(404, { error: 'not_found' });
const userId = Number(/demo_session=(\d+)/.exec(req.headers.cookie || '')?.[1]); // stands in for the session lookup
if (!userId) return send(401, { error: 'sign_in_required' });
const from = url.searchParams.get('from'), to = url.searchParams.get('to');
const tz = url.searchParams.get('tz') || 'UTC';
const limit = Math.min(Number(url.searchParams.get('limit') || 20), 50);
if ((from && !isDate(from)) || (to && !isDate(to)) || (from && to && from > to) || !(limit >= 1))
return send(422, { error: 'invalid_filter' });
let after = [null, null];
if (url.searchParams.get('cursor')) {
try { after = JSON.parse(Buffer.from(url.searchParams.get('cursor'), 'base64url').toString()); }
catch { return send(422, { error: 'invalid_cursor' }); }
}
// demo-only hooks so the page's slow and stuck paths can be reproduced on demand
if (req.headers['x-demo-delay-ms']) await sleep(Number(req.headers['x-demo-delay-ms']));
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('SET LOCAL statement_timeout = 300'); // the database gives up before the user does
if (req.headers['x-demo-slow-query']) await client.query('SELECT pg_sleep(1)');
// The user's own local days: [from 00:00, to + 1 day 00:00) in their time zone, half-open.
const { rows } = await client.query(
`SELECT id, placed_at, total_cents, status,
to_char(placed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS cursor_at FROM orders
WHERE user_id = $1
AND ($2::date IS NULL OR placed_at >= ($2::date)::timestamp AT TIME ZONE $4)
AND ($3::date IS NULL OR placed_at < (($3::date + 1))::timestamp AT TIME ZONE $4)
AND ($5::timestamptz IS NULL OR (placed_at, id) < ($5::timestamptz, $6::bigint))
ORDER BY placed_at DESC, id DESC LIMIT $7`,
[userId, from, to, tz, after[0], after[1], limit + 1]);
await client.query('COMMIT');
const page = rows.slice(0, limit);
const last = page[page.length - 1];
send(200, {
orders: page.map((o) => ({ id: Number(o.id), placed_at: o.placed_at.toISOString(), total_cents: o.total_cents, status: o.status })),
next_cursor: rows.length > limit ? Buffer.from(JSON.stringify([last.cursor_at, Number(last.id)])).toString('base64url') : null,
});
} catch (err) {
await client.query('ROLLBACK').catch(() => {});
if (err.code === '57014') return send(503, { error: 'temporarily_unavailable' }, { 'retry-after': '5' }); // statement_timeout hit
if (err.code === '22023') return send(422, { error: 'invalid_filter' }); // unknown time zone name
send(500, { error: 'server_error' });
} finally { client.release(); }
});
}
Four time limits have to nest, shortest inside. Illustrative values: database statement limit 300 ms (the demo's value), then the handler's own limit about 2 s, then the gateway in front of the service about 5 s (it would return 504), then the client's 8 s. SET LOCAL statement_timeout = 300 tells PostgreSQL to abort any statement in the current transaction that runs longer than 300 ms, and the setting ends with the transaction. In the shipped code only the database limit and the client limit exist; the handler and gateway limits belong to the hosting setup, so the numbers in between are examples of how they should be ordered. The demo uses 300 ms for the statement only so the slow path is quick to reproduce; the real value comes from the measured slow end of that query. If an outer limit is shorter than an inner one, the user gets a client-side "gave up" while the server keeps working on an abandoned request. The statement timeout surfaces as PostgreSQL error 57014 (query_canceled), which the handler turns into 503 plus Retry-After: 5; an unknown time zone name raises 22023 (invalid_parameter_value) and becomes 422.
Client: one function from outcome to view
// client.mjs
// The page's data layer: one function turns every possible outcome into one named view state.
export function viewFromResponse(status, body, retryAfter, hasFilter) {
if (status === 200) {
if (body.orders.length > 0) return { kind: 'loaded', orders: body.orders, next: body.next_cursor };
return { kind: hasFilter ? 'empty_filtered' : 'empty_no_orders', orders: [], next: null };
}
if (status === 401) return { kind: 'error_auth' };
if (status === 422) return { kind: 'error_validation' };
if (status === 429 || status >= 500) return { kind: 'error_retryable', retryAfterSeconds: retryAfter ? Number(retryAfter) : null };
return { kind: 'error_other' };
}
export function createOrdersClient({ base, cookie, timeoutMs = 8000, onEvent = () => {} }) {
let latest = 0;
let state = { kind: 'idle', orders: [], next: null };
async function load(filter = {}, extraHeaders = {}) {
const id = ++latest; // only the newest request may change the screen
const hasFilter = Boolean(filter.from || filter.to);
state = { ...state, kind: state.orders.length ? 'refreshing' : 'loading' };
const qs = new URLSearchParams({ ...(filter.from && { from: filter.from }), ...(filter.to && { to: filter.to }), tz: filter.tz || 'UTC' });
const t0 = performance.now();
let next, status = null;
try {
const res = await fetch(`${base}/v1/orders?${qs}`, { headers: { cookie, ...extraHeaders }, signal: AbortSignal.timeout(timeoutMs) });
status = res.status;
next = viewFromResponse(status, await res.json(), res.headers.get('retry-after'), hasFilter);
} catch (e) {
next = e.name === 'TimeoutError' ? { kind: 'error_retryable', reason: 'client_timeout' } : { kind: 'offline' };
}
if (id !== latest) { onEvent({ event: 'orders_response_ignored_stale' }); return state; }
state = next;
onEvent({ event: 'orders_view', view: next.kind, http_status: status, has_filter: hasFilter, duration_ms: Math.round(performance.now() - t0) });
return state;
}
return { load, get state() { return state; } };
}
viewFromResponse is a pure mapping (same inputs, same output, no side effects), so it is easy to test. The client does three things beyond the mapping. It gives the request a deadline with AbortSignal.timeout, which aborts with a TimeoutError. It numbers each request and lets only the newest one write to the screen (a stale response: an old answer arriving after a newer request, which would otherwise replace the right list with the wrong one). And it emits one event per finished load, which feeds the launch numbers below.
Running every state
// run.mjs
import pg from 'pg';
import fs from 'node:fs';
import { makeServer } from './server.mjs';
import { createOrdersClient } from './client.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
const srv = makeServer(pool).listen(3400);
const base = 'http://127.0.0.1:3400';
const events = [];
const as = (uid, opts = {}) => createOrdersClient({ base, cookie: uid ? `demo_session=${uid}` : '', onEvent: (e) => events.push(e), ...opts });
const rows = [];
const scenario = async (name, client, filter, headers) => {
events.length = 0;
const s = await client.load(filter, headers);
const e = events.find((x) => x.event === 'orders_view');
rows.push({ scenario: name, http: e.http_status ?? '(none)', view: s.kind, orders: s.orders?.length ?? 0, next_page: Boolean(s.next), extra: s.retryAfterSeconds ? `retry in ${s.retryAfterSeconds}s` : s.reason ?? '' });
};
await scenario('first visit, 45 orders on record', as(1), {});
await scenario('filter 2026-06-01..2026-06-30', as(1), { from: '2026-06-01', to: '2026-06-30' });
await scenario('filter with no matches', as(1), { from: '2025-01-01', to: '2025-01-31' });
await scenario('new customer, no orders ever', as(2), {});
await scenario('from after to', as(1), { from: '2026-06-30', to: '2026-06-01' });
await scenario('session expired', as(null), {});
await scenario('database too slow', as(1), {}, { 'x-demo-slow-query': '1' });
await scenario('server stuck, client gives up', as(1, { timeoutMs: 200 }), {}, { 'x-demo-delay-ms': '1000' });
await scenario('no network at all', createOrdersClient({ base: 'http://127.0.0.1:1', cookie: '', onEvent: (e) => events.push(e) }), {});
console.table(rows);
// two quick filter changes; the first answer arrives last and must not win
events.length = 0;
const racer = as(1);
const slow = racer.load({ from: '2026-06-01', to: '2026-06-30' }, { 'x-demo-delay-ms': '400' });
const fast = racer.load({});
await Promise.all([slow, fast]);
console.log('race: events =', events.map((e) => e.event === 'orders_view' ? `view:${e.has_filter ? 'filtered' : 'unfiltered'}` : e.event).join(', '), '| screen shows unfiltered list:', racer.state.orders.length === 20);
// paging: follow next_cursor to the end; every order must appear exactly once
const walk = async (uid, limit) => {
let cur = null, n = 0; const seen = new Set();
do {
const r = await (await fetch(`${base}/v1/orders?limit=${limit}${cur ? `&cursor=${cur}` : ''}`, { headers: { cookie: `demo_session=${uid}` } })).json();
r.orders.forEach((o) => seen.add(o.id)); n += r.orders.length; cur = r.next_cursor;
} while (cur);
return `${n} rows, ${seen.size} distinct`;
};
console.log('paging | user 1, 45 orders, 20 per page:', await walk(1, 20), '| user 4, 3 orders in one millisecond, 1 per page:', await walk(4, 1));
// time zones: user 3's only order is 2026-03-31 23:30 in New York (2026-04-01 03:30 UTC)
const tzCount = async (day, tz) => (await as(3).load({ from: day, to: day, tz })).orders.length;
console.log('order at 23:30 New York time, Mar 31 | filter Mar 31 in New York:', await tzCount('2026-03-31', 'America/New_York'),
'| filter Apr 1 in New York:', await tzCount('2026-04-01', 'America/New_York'),
'| filter Apr 1 read as UTC:', await tzCount('2026-04-01', 'UTC'));
await new Promise((r) => setTimeout(r, 1200)); // let the abandoned slow request finish before closing
srv.close(); await pool.end();
Run in a node:22 container against postgres:16 (the run covers views 2, 3, 5, 6, 7, 8, 9 and 10 plus the stale-response guard and cursor paging, and does not exercise views 1, 4 or 11), it prints:
┌─────────┬────────────────────────────────────┬──────────┬────────────────────┬────────┬───────────┬──────────────────┐
│ (index) │ scenario │ http │ view │ orders │ next_page │ extra │
├─────────┼────────────────────────────────────┼──────────┼────────────────────┼────────┼───────────┼──────────────────┤
│ 0 │ 'first visit, 45 orders on record' │ 200 │ 'loaded' │ 20 │ true │ '' │
│ 1 │ 'filter 2026-06-01..2026-06-30' │ 200 │ 'loaded' │ 10 │ false │ '' │
│ 2 │ 'filter with no matches' │ 200 │ 'empty_filtered' │ 0 │ false │ '' │
│ 3 │ 'new customer, no orders ever' │ 200 │ 'empty_no_orders' │ 0 │ false │ '' │
│ 4 │ 'from after to' │ 422 │ 'error_validation' │ 0 │ false │ '' │
│ 5 │ 'session expired' │ 401 │ 'error_auth' │ 0 │ false │ '' │
│ 6 │ 'database too slow' │ 503 │ 'error_retryable' │ 0 │ false │ 'retry in 5s' │
│ 7 │ 'server stuck, client gives up' │ '(none)' │ 'error_retryable' │ 0 │ false │ 'client_timeout' │
│ 8 │ 'no network at all' │ '(none)' │ 'offline' │ 0 │ false │ '' │
└─────────┴────────────────────────────────────┴──────────┴────────────────────┴────────┴───────────┴──────────────────┘
race: events = view:unfiltered, orders_response_ignored_stale | screen shows unfiltered list: true
paging | user 1, 45 orders, 20 per page: 45 rows, 45 distinct | user 4, 3 orders in one millisecond, 1 per page: 3 rows, 3 distinct
order at 23:30 New York time, Mar 31 | filter Mar 31 in New York: 1 | filter Apr 1 in New York: 0 | filter Apr 1 read as UTC: 1
Reading the output: row 0 is view 3 (20 orders and a next page), row 1 is view 2 (10 orders in June, no next page), row 2 is view 6, row 3 is view 5, row 4 is view 7, row 5 is view 8, rows 6 and 7 are view 9 (a 503 with Retry-After: 5 from the database timeout, and a client that gave up with no response at all), and row 8 is view 10. The race line shows the slow filtered request finishing after the fast unfiltered one and being discarded, so the screen keeps the list matching the current filter. The paging line follows next_cursor to the end: 45 orders at 20 per page come back as 45 distinct rows, and the three orders placed within one millisecond come back one per page without losing any, which is what the microsecond cursor and the id tie-break are for. Views 1 and 4 are the loading and refreshing values the client sets while a request is in flight; they are visible only while waiting, so the run does not print them. View 11 is not coded in the run: it would send the same request with the cursor parameter added and feed the answer through the same mapping, with the difference that success appends rows under the list and failure shows an inline message under it.
What to watch after launch
Define "works for real users" as a number before launch, then watch these:
Example targets (illustrative, to be replaced by the first week's real baseline): good-view rate (a good view arriving within 3 seconds) at or above 99 percent of page views over a day, and a page of orders in 2 seconds or less at the 95th percentile.
| Signal | How it is measured | What a bad movement means |
|---|---|---|
| Good-view rate | orders_view events with view loaded or empty_* and duration_ms within the time limit (3 seconds in the example above), divided by all orders_view events | falls when errors or slow loads rise; the headline number |
| Error-view mix | share of error_retryable, offline, error_auth, error_validation | a rise in error_validation points at a front-end date bug; in error_auth, session handling; in error_retryable, the backend |
| First-page latency | duration_ms from the client event (p50 and p95, i.e. the median and the 95th percentile), next to the server's own request duration | the gap between the two is network and client time; a climbing p95 predicts the timeouts |
Backend 5xx and statement-timeout rate | server logs and database metrics for the orders query | a slow query before users complain; compare against an alert threshold set from the first week's baseline |
| Empty rate with a filter | empty_filtered divided by loads with a filter | a sudden jump suggests the time-zone or range logic is wrong |
| Retry and Try again clicks | click events on the error button | users hitting retry repeatedly means the error is persistent, not blips |
| Load-more usage and cursor errors | click rate and invalid_cursor responses | cursors breaking after a deploy |
| Page experience | Core Web Vitals field data (real-user measurements): LCP (largest contentful paint, when the main content appears) 2.5 s or less, INP (interaction to next paint, how quickly the page responds to taps and clicks) 200 ms or less, CLS (cumulative layout shift, how much the layout jumps) 0.1 or less, at the 75th percentile (web.dev) | the page loaded but felt slow or jumpy |
Two cautions. Alert on the good-view rate over a window of real traffic (for example, page someone if it stays below 95 percent for 15 minutes; create a ticket below 99 percent over a day), not on a single failed request. And segment (split the numbers into groups) by time zone, device and session age, because an overall average can hide a bug that only hits users east of UTC.
Pitfalls
- A skeleton or spinner with no timeout: the user waits forever. Every wait needs an end state.
OFFSETpagination on a list that changes.- Showing "You have no orders" on an error because the error handler fell through to the empty branch.
- Logging only server-side: the client's timeout and offline views never reach the server, so only a client event sees them.
Running the code
cd work # schema.sql server.mjs client.mjs run.mjs
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 # wait for the image's post-init restart
docker run --rm --network demo-net -v "$PWD":/w -w /w node:22 sh -c 'npm i --silent && node run.mjs'
In a 45-minute coding round you are asked to build a minimal notes feature: list notes, add a note, and edit a note. Write the table, the HTTP handlers and the browser code that calls them, then tell me what you would add first if you had one more hour.
Sample Answer
Direct answer
Build it in this order, and say the order out loud so the interviewer can follow: (1) agree the contract, three calls on one resource, (2) the table, (3) the handlers, (4) the browser code with its loading, empty and error states, (5) run it end to end. Then name what you would add next. A contract is the agreed shape of each request and response between the browser and the server; writing it first keeps the two halves from drifting apart.
The design is deliberately small: one notes table, GET and POST on the collection, PATCH on one note. The server validates and returns the saved row, so the browser never guesses a field the server owns (the id, the timestamps). With one more hour, the first thing to add is ownership: a user_id on every note and on every query, because as built, anyone who can reach the server can read and change everyone's notes. Pagination, search and delete are real but harmless by comparison; ownership is the gap that leaks data.
The contract
| Call | Meaning | Success | Failures |
|---|---|---|---|
GET /api/notes | list the 100 most recently changed notes | 200 {"notes": [...]} | 500 |
POST /api/notes {"body": "..."} | create a note | 201 plus a Location header and the saved note | 400 bad JSON, 413 too large, 422 invalid body |
PATCH /api/notes/{id} {"body": "..."} | replace the text of one note | 200 and the saved note | 400, 413, 422, 404 no such note |
201 Createdmeans a new resource now exists; MDN says it must be locatable by the request URL or by aLocationheader, so the handler sendsLocation: /api/notes/{id}as well as the body.400 Bad Requestis for a request the server cannot parse (broken JSON).422 Unprocessable Contentis for a request that parses but whose content is unacceptable (an empty note). The split matters to the browser: a422carries per-field messages to show next to the form, a400is a bug in the client.PATCHchanges part of a resource; here the only editable part isbody, so the request carries just that.- ids travel as strings. The id column is a 64-bit integer and JavaScript numbers are only exact up to 9007199254740991 (2^53 - 1), so the SQL casts with
id::text.
Data model
CREATE TABLE notes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL CHECK (char_length(body) BETWEEN 1 AND 5000),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX notes_recent ON notes (updated_at DESC, id DESC);
GENERATED ALWAYS AS IDENTITYmakes the database assign ids, andALWAYSrefuses a client-supplied id.- The
CHECKconstraint is the last line of defence: whatever a future code path forgets to validate, the database refuses an empty or over-long body. Inserting an empty string directly fails withnew row for relation "notes" violates check constraint "notes_body_check"(run in apostgres:16container). notes_recentmatches the list query'sORDER BY updated_at DESC, id DESC. An index is a sorted side-structure the database keeps next to the table; an index scan walks it in order, so the first 100 rows in the wanted order are found without sorting every row.idis the tiebreaker (the second sort key that decides between rows whose first key is equal), so two notes saved in the same instant keep a stable order.EXPLAINasks Postgres to print the plan it would use without running the query. With 20,000 rows loaded by this script:
INSERT INTO notes (body, updated_at)
SELECT 'note ' || g, now() - g * interval '1 second' FROM generate_series(1, 20000) g;
ANALYZE notes;
EXPLAIN SELECT id, body FROM notes ORDER BY updated_at DESC, id DESC LIMIT 100;
it prints (run in a postgres:16 container after schema.sql):
INSERT 0 20000
ANALYZE
QUERY PLAN
----------------------------------------------------------------------------------------
Limit (cost=0.29..5.31 rows=100 width=26)
-> Index Scan using notes_recent on notes (cost=0.29..1004.16 rows=20000 width=26)
(2 rows)
Read it from the inside out: the inner line says Postgres would read notes through Index Scan using notes_recent, and the outer Limit line says it stops after rows=100. There is no Sort line, which is the point: a plan with a Sort over every row would get slower as the table grows. The cost numbers are the planner's own unit-less estimates, not milliseconds.
Backend: the handlers
This is a plain Node http server and the pg driver, so there is no framework to explain. A handler is the function that runs for one route: parse the request, validate, talk to the database, send a response.
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 COLS = 'id::text AS id, body, created_at, updated_at';
const send = (res, status, data, headers = {}) => {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(data === undefined ? '' : JSON.stringify(data));
};
async function readJson(req) {
let size = 0; const chunks = [];
for await (const c of req) {
size += c.length;
if (size > 65536) throw Object.assign(new Error('too large'), { status: 413 });
chunks.push(c);
}
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
catch { throw Object.assign(new Error('invalid JSON'), { status: 400 }); }
}
function validate(input) {
const body = typeof input?.body === 'string' ? input.body.trim() : '';
if (body.length === 0) return { errors: { body: 'Write something first.' } };
if (body.length > 5000) return { errors: { body: 'Keep it under 5000 characters.' } };
return { value: body };
}
const handlers = {
async list(req, res) {
const { rows } = await pool.query(`SELECT ${COLS} FROM notes ORDER BY updated_at DESC, id DESC LIMIT 100`);
send(res, 200, { notes: rows });
},
async create(req, res) {
const v = validate(await readJson(req));
if (v.errors) return send(res, 422, { errors: v.errors });
const { rows } = await pool.query(`INSERT INTO notes (body) VALUES ($1) RETURNING ${COLS}`, [v.value]);
send(res, 201, rows[0], { Location: `/api/notes/${rows[0].id}` });
},
async update(req, res, id) {
const v = validate(await readJson(req));
if (v.errors) return send(res, 422, { errors: v.errors });
const { rows } = await pool.query(
`UPDATE notes SET body = $1, updated_at = now() WHERE id = $2 RETURNING ${COLS}`, [v.value, id]);
if (rows.length === 0) return send(res, 404, { error: 'Note not found' });
send(res, 200, rows[0]);
},
};
const server = http.createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://x');
if (req.method === 'GET' && pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(await readFile(new URL('./public/index.html', import.meta.url)));
}
if (req.method === 'GET' && pathname === '/app.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' });
return res.end(await readFile(new URL('./public/app.js', import.meta.url)));
}
if (pathname === '/api/notes' && req.method === 'GET') return await handlers.list(req, res);
if (pathname === '/api/notes' && req.method === 'POST') return await handlers.create(req, res);
const m = pathname.match(/^\/api\/notes\/(\d{1,18})$/);
if (m && req.method === 'PATCH') return await handlers.update(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' });
}
});
server.listen(Number(process.env.PORT ?? 3000), () => console.log('listening'));
- Every query is parameterized (
$1,$2): the driver sends the SQL text and the values separately, so a note containing'; DROP TABLE notes; --is just text. That is the whole defence against SQL injection. validatetrims first, so a note of spaces counts as empty, and returns the same shape of error for create and update. Two handlers share one rule instead of two copies that drift.readJsoncaps the body at 64 KiB and answers413beyond it, so one client cannot make the server buffer an unbounded upload.- The
UPDATE ... WHERE id = $2 ... RETURNINGruns as one statement; zero rows back means the note does not exist, which is the404. There is no separate "does it exist" query to race with. - Anything unexpected becomes a
500with a generic message; the detail goes to the server log, never to the client. - Routing, read line by line.
pathname.match(/^\/api\/notes\/(\d{1,18})$/)means: the path must start with/api/notes/, then 1 to 18 digits (captured as the id), then end./api/notes/7matches with id7;/api/notes/abcand/api/notes/7/extrado not match and fall through to the404. Eighteen digits is the longest number that always fits thebigintcolumn. Thetry/catcharound the whole function does one job: an error carrying astatusproperty (the400and413thrown byreadJson) is sent back as that status, and any other error is logged and becomes the500.
Browser code
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Notes</title></head>
<body>
<h1>Notes</h1>
<form id="add">
<label for="new-body">New note</label>
<textarea id="new-body" rows="3"></textarea>
<p id="add-error" role="alert"></p>
<button type="submit">Add note</button>
</form>
<p id="status" role="status"></p>
<ul id="list"></ul>
<script src="/app.js"></script>
</body>
</html>
const $ = (id) => document.getElementById(id);
let notes = [];
async function api(method, path, body) {
const res = await fetch(path, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw Object.assign(new Error(data.error ?? 'Request failed'), { status: res.status, errors: data.errors });
return data;
}
function render() {
const list = $('list');
list.replaceChildren();
$('status').textContent = notes.length === 0 ? 'No notes yet. Add your first one above.' : '';
for (const note of notes) {
const li = document.createElement('li');
li.dataset.id = note.id;
const text = document.createElement('p');
text.textContent = note.body; // textContent, never innerHTML: notes are user input
const edit = document.createElement('button');
edit.textContent = 'Edit';
edit.addEventListener('click', () => startEdit(li, note));
li.append(text, edit);
list.append(li);
}
}
function startEdit(li, note) {
const area = document.createElement('textarea');
area.value = note.body;
const save = document.createElement('button');
save.textContent = 'Save';
const cancel = document.createElement('button');
cancel.textContent = 'Cancel';
const err = document.createElement('p');
err.setAttribute('role', 'alert');
li.replaceChildren(area, save, cancel, err);
cancel.addEventListener('click', render);
save.addEventListener('click', async () => {
save.disabled = true; // stop double submits while the request is out
try {
const updated = await api('PATCH', `/api/notes/${note.id}`, { body: area.value });
notes = [updated, ...notes.filter((n) => n.id !== updated.id)]; // edited note moves to the top
render();
} catch (e) {
err.textContent = e.errors?.body ?? 'Could not save. Your text is still here, try again.';
save.disabled = false; // keep the draft in the textarea
}
});
}
$('add').addEventListener('submit', async (ev) => {
ev.preventDefault();
const button = ev.target.querySelector('button');
button.disabled = true;
$('add-error').textContent = '';
try {
const created = await api('POST', '/api/notes', { body: $('new-body').value });
notes = [created, ...notes];
$('new-body').value = '';
render();
} catch (e) {
$('add-error').textContent = e.errors?.body ?? 'Could not add the note. Try again.';
} finally {
button.disabled = false;
}
});
async function load() {
$('status').textContent = 'Loading...';
try {
notes = (await api('GET', '/api/notes')).notes;
render();
} catch {
$('status').textContent = 'Could not load notes.';
const retry = document.createElement('button');
retry.textContent = 'Retry';
retry.addEventListener('click', load);
$('status').append(' ', retry);
}
}
load();
- State is one array,
notes, andrender()rebuilds the list from it. After every successful call the code stores what the server returned (created,updated), so the screen shows the server's truth, including its timestamps and the trimmed text. - Loading, empty, error are all handled: "Loading..." while the first request is out, a sentence that tells a new user what to do when the list is empty, and a message with a Retry button when the load fails.
- Note text is written with
textContent, neverinnerHTML. If a note is<b>second</b> note, the page shows those characters instead of running them as markup, which is how a stored cross-site scripting (XSS, attacker-supplied script running in other users' pages) hole is avoided in one line. - While a save is in flight its button is disabled, so a double click does not send two requests. On failure the button comes back and the textarea keeps the draft: a failed save must never throw away what the user typed.
- Edited notes move to the top, which matches the server's
ORDER BY updated_at DESC, so a reload shows the same order the screen already showed.
Proof that it runs
The server and a postgres:16 container share a Docker network, and a Playwright script (a browser-automation library that drives real Chromium) first calls the API, then drives the page: add a note containing HTML, submit an empty one, edit a note while the network route is aborted to force a failure, retry, and reload.
import { chromium } from 'playwright';
const base = 'http://localhost:3000';
const log = (...a) => console.log(...a);
// 1. API contract with curl-style calls
const call = async (method, path, body, raw) => {
const r = await fetch(base + path, { method, headers: { 'Content-Type': 'application/json' }, body: raw ?? (body && JSON.stringify(body)) });
return `${method} ${path} -> ${r.status}${r.headers.get('location') ? ' Location: ' + r.headers.get('location') : ''} ${await r.text()}`.replace(/"(created|updated)_at":"[^"]+"/g, '"$1_at":"..."');
};
log(await call('POST', '/api/notes', { body: ' buy milk ' }));
log(await call('POST', '/api/notes', { body: ' ' }));
log(await call('POST', '/api/notes', null, '{oops'));
log(await call('PATCH', '/api/notes/1', { body: 'buy oat milk' }));
log(await call('PATCH', '/api/notes/999', { body: 'x' }));
log(await call('GET', '/api/notes'));
// 2. Browser behaviour
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(base);
await page.locator('#list li').first().waitFor();
log('after load, items:', await page.locator('#list li').count());
await page.fill('#new-body', '<b>second</b> note');
await page.click('#add button');
await page.waitForFunction(() => document.querySelectorAll('#list li').length === 2);
log('top item text (rendered as text, not HTML):', await page.locator('#list li p').first().textContent());
await page.click('#add button');
await page.waitForFunction(() => document.getElementById('add-error').textContent !== '');
log('empty submit message:', await page.textContent('#add-error'));
await page.locator('#list li').first().getByRole('button', { name: 'Edit' }).click();
await page.locator('#list li textarea').fill('second note, edited');
await page.route('**/api/notes/*', (route) => route.abort());
await page.locator('#list li').first().getByRole('button', { name: 'Save' }).click();
await page.waitForFunction(() => document.querySelector('#list li [role=alert]').textContent !== '');
log('failed save message:', await page.locator('#list li [role=alert]').textContent());
log('draft kept:', await page.locator('#list li textarea').inputValue());
await page.unroute('**/api/notes/*');
await page.locator('#list li').first().getByRole('button', { name: 'Save' }).click();
await page.waitForFunction(() => document.querySelector('#list li textarea') === null);
await page.reload();
await page.locator('#list li').first().waitFor();
log('after reload:', JSON.stringify(await page.locator('#list li p').allTextContents()));
await browser.close();
Run in the Playwright image (Node 20.18, Chromium 130), it prints:
listening
POST /api/notes -> 201 Location: /api/notes/1 {"id":"1","body":"buy milk","created_at":"...","updated_at":"..."}
POST /api/notes -> 422 {"errors":{"body":"Write something first."}}
POST /api/notes -> 400 {"error":"invalid JSON"}
PATCH /api/notes/1 -> 200 {"id":"1","body":"buy oat milk","created_at":"...","updated_at":"..."}
PATCH /api/notes/999 -> 404 {"error":"Note not found"}
GET /api/notes -> 200 {"notes":[{"id":"1","body":"buy oat milk","created_at":"...","updated_at":"..."}]}
after load, items: 1
top item text (rendered as text, not HTML): <b>second</b> note
empty submit message: Write something first.
failed save message: Could not save. Your text is still here, try again.
draft kept: second note, edited
after reload: ["second note, edited","buy oat milk"]
How to read the script: page.route('**/api/notes/*', route => route.abort()) intercepts every matching request the page makes and makes it fail like a dropped network connection, which is how the failed save is forced; unroute removes it so the retry reaches the server. waitFor and waitForFunction pause until a condition on the page is true (an item exists, a message is non-empty) instead of sleeping for a guessed time, which is what keeps the run from being flaky.
Reading the output: the first POST returns 201 with a Location header and the trimmed text buy milk; the whitespace-only body gets 422; the broken JSON gets 400; a PATCH to a missing id gets 404. In the browser, the HTML note shows as literal text, the empty submit shows the validation message, the aborted save keeps the draft, and after the retry and reload the edited note is on top. The output is deterministic: every wait is on a condition (waitForFunction, locator.waitFor) rather than a fixed delay.
Complexity and edge cases: each request does one indexed query, and the list is capped at 100 rows, so response size is bounded. The cases covered above are an empty or whitespace body, a body past 5000 characters (422), malformed JSON (400), an oversized request (413), an unknown id (404), HTML in a note, and a failed network call.
A 45-minute plan
| Minutes | Work | Output you can show |
|---|---|---|
| 0 to 5 | say the contract (the three calls) and write the table | schema.sql |
| 5 to 15 | list, create and update handlers with validation | the three curl-style calls returning the statuses in the table |
| 15 to 30 | page: load, add, edit, with loading, empty and error states | the page working against the server |
| 30 to 40 | run it end to end, including one forced failure | the output above |
| 40 to 45 | say what the build leaves out and what you would add first | the next section |
The version that must exist at minute 30 is: table, three handlers that return the saved row, and a page that renders the server's answer. The guards in this answer (the CHECK constraint, the 64 KiB body cap, the Location header) are each one or two lines added to that version once it works, so type the happy path first and add them in the time that remains.
What to add first with one more hour: ownership
- Add
user_id bigint NOT NULLtonotesand change the index to(user_id, updated_at DESC, id DESC). - Take the user id from the authenticated session (a signed cookie or token checked in a shared step before the handlers), never from the request body. A client that can choose its own
user_idhas ownership in name only. - Add
AND user_id = $nto the list query and to theUPDATE ... WHERE. A note that belongs to someone else then simply matches zero rows and returns404, not403, so the response does not reveal that the id exists. - Write the test that proves it: user A creates a note, user B tries to
PATCHit and gets404, and A's text is unchanged.
Why this and not something else: every other gap (pagination past 100, search, delete) is a missing feature, while this one is a data leak, and it changes the table, every query and the tests, so it is the cheapest to do before more code builds on the old shape. After that, in order:
- A version check. Add an integer
versioncolumn that goes up by one on every save. Example: two tabs both load note 1 at version 3. Tab one saves and the note becomes version 4. Tab two then sends itsPATCHwith the headerIf-Match: "3"(a precondition: "apply this only if the note is still at version 3"); the server finds version 4, answers412 Precondition Failed, and tab one's text is not overwritten. - An idempotency key on
POST. An operation is idempotent when doing it twice has the same effect as doing it once;POSTis not, so a retry after a lost response can create a duplicate note. The browser makes a random string for each click on Add and sends it in anIdempotency-Keyheader. The server stores the key with the new note, and a second request carrying the same key returns the note that already exists instead of inserting another. - Cursor pagination, then delete. Instead of "page 3", the browser sends the
updated_atandidof the last note it holds, and the server returns the next 100 after that pair. Unlike skipping rows by a count (OFFSET), it neither skips nor repeats notes when new ones arrive between requests.
What would change this order: if the notes are public by design (a shared scratchpad), ownership drops and the version check moves first.
Running the code
docker network create notes-net
docker run -d --rm --name notes-pg --network notes-net -e POSTGRES_PASSWORD=pw postgres:16
sleep 5 # wait for Postgres to accept connections
docker exec notes-pg psql -U postgres -c "CREATE DATABASE notes"
docker exec -i notes-pg psql -U postgres -d notes < schema.sql
# in a folder with server.mjs, test.mjs, public/, and package.json {"type":"module"}:
docker run --rm --network notes-net -v "$PWD":/w -w /w -e DATABASE_URL=postgres://postgres:pw@notes-pg:5432/notes \
mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i pg@8 playwright@1.48.2; node server.mjs & sleep 3; node test.mjs'
Users of a social app can write a post with text and an image. Walk me through that feature from the compose screen to the database row: what the client does while they type and on submit, what the request looks like, what the server checks and stores, and what happens when the network drops mid-submit or the server rejects the post.
Sample Answer
Direct answer
The compose screen keeps the draft and uploads the image as soon as it is picked, so submit only has to send the text plus an image_id. Submit is a POST carrying a client-generated client_request_id, which the server stores under a unique constraint (a database rule that refuses a second row with the same value in the named columns): a retry after a dropped connection returns the original post instead of creating a second one. The server validates everything again (the client's checks are only for speed), writes the post and attaches the image in one transaction, and answers 201 with the post, or 422 with a list of field errors. The draft is cleared only after a success response.
The flow, step by step
| Step | Client | Server / storage |
|---|---|---|
| Typing | Draft saved to local storage on a short debounce (a wait that restarts on every keystroke), keyed by user. Counter shows characters left, counted in code points (one per Unicode code point: a simple emoji such as the grinning face counts 1, whereas JavaScript's plain .length counts it as 2; a family emoji or a flag is built from several code points, 5 and 2 respectively, so it counts more than 1, which is accepted because the unit only has to be the same on the client and the server), the same unit the server and PostgreSQL's char_length use. Submit disabled when empty or over 500. | nothing |
| Pick image | Preview appears at once; upload starts in the background with its own progress and its own error. Submit stays disabled until the image is uploaded or removed. | POST /v1/images returns an image_id and a short-lived upload URL; the bytes go straight to object storage (a service that stores files by key, such as Amazon S3), not through the API server |
| Submit | Button shows "Posting...", the text box is read-only, the draft is kept. | POST /v1/posts with {"body", "image_id", "client_request_id"} |
| Success | Clear the draft, close the composer, put the post at the top of the feed using the returned object. | 201 {"id": ...} |
| Rejected | Keep everything, put each message next to its field, focus the first invalid field. | 422 {"errors": [{"field": "body", "code": "too_long"}]} |
| Network drop | Retry automatically up to 3 times with the same client_request_id, then show "Couldn't post. Retry" with the draft intact. | a request that arrived is stored once |
What the server checks
- The user is signed in and under the rate limit (a cap on requests per user per time window; the server answers
429with aRetry-Afterheader saying how long to wait otherwise). body, after trimming, is 1 to 500 characters. The databaseCHECKrepeats the length limit, so no code path can store a body over 500 characters; it measures the stored text as it is, so a body of only spaces passes it, which is why the server trims and rejects an empty result before the insert.- If
image_idis present: it belongs to this user, its upload finished, the stored bytes really are an image of an allowed type (read the file's first bytes, never trust the declaredContent-Type, the label the uploader attached; a file renamed fromvirus.exetophoto.pngstill starts with the bytes of an executable, not of a PNG, and the client's own checks cannot be relied on because anyone can call the API directly without the app), and it is not already attached to another post. The attach is a conditional update inside the same transaction as the insert, so a failure rolls back both. - The
(author_id, client_request_id)pair: new means insert; seen before with the same payload means return the stored post with200; seen before with a different payload means409 idempotency_key_reused(409 Conflict: the request clashes with stored state). Idempotent means doing the request twice has the same effect as doing it once. The server keepspayload_hash, anmd5fingerprint of the body and image, so it can tell a true retry (same fingerprint, return the old post) from a reused id on different content (different fingerprint, refuse), instead of silently returning a post that does not match what was sent.
Storing it and replaying it
CREATE TABLE feed_posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author_id bigint NOT NULL,
body text NOT NULL CHECK (char_length(body) BETWEEN 1 AND 500),
image_id uuid,
client_request_id uuid NOT NULL,
payload_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (author_id, client_request_id)
);
CREATE FUNCTION create_post(p_author bigint, p_body text, p_image uuid, p_req uuid)
RETURNS TABLE (out_id bigint, out_replayed boolean)
LANGUAGE plpgsql AS $$
DECLARE h text := md5(coalesce(p_body,'') || '|' || coalesce(p_image::text,'')); new_id bigint; old_hash text; old_id bigint;
BEGIN
INSERT INTO feed_posts (author_id, body, image_id, client_request_id, payload_hash)
VALUES (p_author, p_body, p_image, p_req, h)
ON CONFLICT (author_id, client_request_id) DO NOTHING RETURNING id INTO new_id;
IF new_id IS NOT NULL THEN RETURN QUERY SELECT new_id, false; RETURN; END IF;
SELECT id, payload_hash INTO old_id, old_hash FROM feed_posts WHERE author_id = p_author AND client_request_id = p_req;
IF old_hash <> h THEN RAISE EXCEPTION 'idempotency_key_reused'; END IF;
RETURN QUERY SELECT old_id, true;
END $$;
SELECT * FROM create_post(7, 'hello world', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT * FROM create_post(7, 'hello world', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT * FROM create_post(7, 'hello EDITED', 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000001');
SELECT count(*) AS rows_stored FROM feed_posts;
SELECT * FROM create_post(7, repeat('x', 501), NULL, 'bbbbbbbb-0000-0000-0000-000000000002');
Run in a postgres:16 container, the three create_post calls print 1 | f, then 1 | t (the replay), then ERROR: idempotency_key_reused. The count query prints rows_stored = 1, and the 501-character body fails with violates check constraint "feed_posts_body_check". If two copies of the same request arrive at the same moment, the second INSERT waits for the first to commit, finds the key taken, and returns the existing row.
The client side of a retry
import { randomUUID } from 'node:crypto';
// ---- client ----
export const newDraft = () => ({ text: '', imageId: null, requestId: randomUUID() });
export const editDraft = (d, text) => ({ ...d, text, requestId: randomUUID() }); // new content = new request id
const NETWORK = Symbol('network');
export async function submit(draft, send, attempts = 3) {
for (let i = 1; i <= attempts; i++) {
try {
const r = await send({ body: draft.text, image_id: draft.imageId, client_request_id: draft.requestId });
if (r.status === 201 || r.status === 200) return { kind: 'posted', id: r.json.id, replayed: r.status === 200, attempts: i };
if (r.status === 422) return { kind: 'field_errors', errors: r.json.errors }; // keep the draft, show errors
if (r.status === 409) return { kind: 'conflict' };
if (r.status >= 500 && i < attempts) continue; // safe to repeat: same request id
return { kind: 'failed', status: r.status };
} catch (e) {
if (e === NETWORK && i < attempts) continue;
return { kind: 'failed_offline', attempts: i }; // draft stays; user taps Retry
}
}
}
// ---- fake server: stores by (author, request id) like the unique index does ----
const rows = new Map(); let nextId = 1;
function server(req, { dropResponseOnce } = {}) {
const trimmed = req.body.trim();
if ([...trimmed].length < 1 || [...trimmed].length > 500) return { status: 422, json: { errors: [{ field: 'body', code: [...trimmed].length ? 'too_long' : 'required' }] } };
const hash = trimmed + '|' + req.image_id;
const old = rows.get(req.client_request_id);
if (old) return old.hash === hash ? { status: 200, json: { id: old.id } } : { status: 409, json: { error: 'idempotency_key_reused' } };
const row = { id: nextId++, hash }; rows.set(req.client_request_id, row);
return { status: 201, json: { id: row.id } };
}
// ---- scenarios ----
let d = { ...newDraft(), text: 'hello world', imageId: 'img-1' };
let dropped = false;
const flaky = async (req) => { const res = server(req); if (!dropped) { dropped = true; throw NETWORK; } return res; };
console.log('1. response lost on the first attempt:', JSON.stringify(await submit(d, flaky)), '| rows stored:', rows.size);
console.log('2. user taps Retry later with same draft:', JSON.stringify(await submit(d, async (r) => server(r))), '| rows stored:', rows.size);
const edited = editDraft(d, 'hello world, edited');
console.log('3. user edits after a failure, new request id:', JSON.stringify(await submit(edited, async (r) => server(r))), '| rows stored:', rows.size);
console.log('4. same id, different text (a bug):', JSON.stringify(await submit({ ...d, text: 'other' }, async (r) => server(r))));
console.log('5. 501 characters:', JSON.stringify(await submit({ ...newDraft(), text: 'x'.repeat(501) }, async (r) => server(r))));
console.log('6. offline for every attempt:', JSON.stringify(await submit({ ...newDraft(), text: 'hi' }, async () => { throw NETWORK; })), '| rows stored:', rows.size);
Run in a node:22 container, it prints:
1. response lost on the first attempt: {"kind":"posted","id":1,"replayed":true,"attempts":2} | rows stored: 1
2. user taps Retry later with same draft: {"kind":"posted","id":1,"replayed":true,"attempts":1} | rows stored: 1
3. user edits after a failure, new request id: {"kind":"posted","id":2,"replayed":false,"attempts":1} | rows stored: 2
4. same id, different text (a bug): {"kind":"conflict"}
5. 501 characters: {"kind":"field_errors","errors":[{"field":"body","code":"too_long"}]}
6. offline for every attempt: {"kind":"failed_offline","attempts":3} | rows stored: 2
Scenario 1 is the case the question asks about. Walked through: attempt 1 reaches the server, which stores post 1 and answers 201, but the fake network throws the answer away, so the client sees a network failure. Attempt 2 sends the same client_request_id; the server finds the stored row and answers 200 with id 1; the client reports replayed: true, attempts: 2. The user experiences one successful post, and exactly one row is stored. Scenario 2 is the user tapping Retry later: same request id, same stored post, no new row. Scenario 4 reuses the request id with different text, which the server refuses with 409 because the fingerprint differs. Scenario 5 sends 501 characters, so the server answers 422 with too_long. Scenario 6 throws on every attempt: after 3 tries the client gives up, shows Retry with the draft intact, and nothing new is stored. Scenario 3 shows the rule that completes the design: when the user edits the text after a failure, the draft gets a new client_request_id, because reusing the old one with new text would be rejected as a conflict.
Failure cases to name
- Server rejects the post: keep the draft, show the message at the field. Never clear first and ask questions later.
- The image fails halfway: only the attachment shows an error, with Retry and Remove; the typed text is untouched.
- The tab closes mid-submit: the draft and its request id are in local storage, so reopening and pressing Post is a safe retry.
- A
5xxresponse: treated like a lost response and retried with the same id, which is why the endpoint must be idempotent.
Test, roll out, observe
Tests: the SQL checks above, a Playwright test (browser automation) that aborts the network route once and asserts exactly one post appears, and a test for each 422 field mapping. Roll out behind a flag with the old composer still deployable. Observe the share of submits that end in failed_offline, the 409 count (it should be near zero; a spike means a client is reusing ids after edits), and the time from tap to 201.
Trade-off
Uploading the image before submit makes the final request tiny and retries cheap, but leaves orphan uploads when users abandon the composer. Add an expiry job that deletes images not attached to a post within 24 hours. Sending the image inside the post request avoids orphans but makes every retry re-send megabytes.
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 20 End-to-End Feature Design and Development interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.