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.
Users can attach videos of several GB to a post. Walk me through the upload feature end to end: what the user sees, how the bytes reach storage, how the backend learns the upload finished, and how you clean up when users abandon or fail halfway.
Sample Answer
Direct answer
Three ideas carry this design, and each can be said in one breath. First, the file is cut into numbered parts that go straight from the browser to object storage, so one dropped connection costs one part and not the whole file. Second, every status change on the upload row is a conditional update (an UPDATE whose WHERE clause names the status it expects, so only one of several racing callers changes the row). Third, cleanup has more than one layer, because no single layer catches every abandoned upload.
The video never passes through your API servers. The backend creates an Amazon S3 multipart upload (the object store splits one big file into numbered parts that can be sent in parallel, retried individually, and stitched together at the end), signs a short-lived URL for each part, and the browser sends the parts straight to object storage. A signed (presigned) URL is an ordinary storage URL with a time-limited signature in its query string, produced by the backend with its own credentials. Whoever holds it can perform exactly the one operation it was signed for (for example, PUT part 3 of this upload) until it expires, which is why a browser with no storage credentials is allowed to write to a private bucket. The client then calls complete; the backend asks storage to assemble the object, marks the upload processing, and a worker scans it and transcodes it (re-encodes the video into formats and sizes that browsers and phones play). Cleanup is layered: an explicit cancel, a database reaper (a scheduled job that finds expired rows and cleans them up) for expired uploads, and a bucket lifecycle rule (a storage-side setting that deletes or aborts things after a set age) as a backstop, meaning a last line of defence for what the others missed. Every state change is a conditional update, so the repeated complete calls and the repeated storage events that will happen cannot do the work twice.
What the user sees
- Pick the file. The page checks size (our product cap, 10 GiB) and type, shows the name and a progress bar. A post can be written while the upload runs.
- Uploading. A bar driven by bytes that storage has confirmed, a speed and time-left estimate, and Pause and Cancel. Closing the tab triggers a "leave page?" prompt only while parts are in flight.
- After a failure or reload. The upload id and the finished parts are kept in the browser's IndexedDB (browser-side database). The user reselects the same file; the page accepts it only if name, size and last-modified time match, asks the server which parts exist, and sends only the missing ones.
- Processing. "Processing your video" until the status is
ready. The author can submit the post once the bytes are safely stored, but other people see it only when the video isready.
One upload, traced
Take a 6 GiB file (GiB = 1,073,741,824 bytes; MiB = 1,048,576 bytes; the sizes below use these binary units). The server picks a 16 MiB part size, so the file becomes 384 parts. The browser slices the file: part 1 is bytes 0 to 16 MiB minus 1, part 2 is the next 16 MiB, and so on. For part 1 it asks the API for a signed URL, sends the bytes with PUT, and storage answers with an ETag header, a short fingerprint of that part. The browser keeps (1, etag1). It repeats this for parts 2 to 384, four at a time. After the last part it calls complete with the list of 384 (part number, ETag) pairs; storage checks each pair, joins the parts into one object, and the row moves on to processing. If the connection dies at part 200, parts 1 to 199 are already stored, so only part 200 onward is sent again.
API contract
| Call | Purpose | Response |
|---|---|---|
POST /v1/uploads {filename, size_bytes, content_type} | start; server creates the multipart upload and the row | 201 {upload_id, part_size, part_count, expires_at} |
GET /v1/uploads/{id}/parts?numbers=1,2,3,4 | sign the next few parts only (on demand, so a 640-part upload does not presign 640 URLs up front) | 200 {"urls": {"1": "...", ...}, "uploaded": [1,2]} |
POST /v1/uploads/{id}/complete {parts: [{n, etag}]} | assemble the object | 202 {status: "completing"}; repeating it returns the current status |
GET /v1/uploads/{id} | status for polling (every 2 s, backing off to 10 s) | 200 {status, attempts} |
DELETE /v1/uploads/{id} | user cancels | 200 {status: "abandoned"} |
How bytes reach storage: the browser sends each part with PUT to its signed URL. The signature is limited by the permissions of whoever signed it, and the URL expires, so a leaked URL is useless soon. The browser must record each part's ETag (a version tag the store returns per part) because the complete request needs the part number and ETag of every part. JavaScript can read that response header only if the bucket's CORS configuration lists it under ExposeHeaders. (CORS, cross-origin resource sharing, is the browser rule that stops a page on one site from reading responses from another origin unless that origin opts in; here the bucket is the other origin, and ExposeHeaders is its opt-in for specific response headers such as ETag.)
Storage limits that shape the plan, as documented for Amazon S3: at most 10,000 parts per upload, each part 5 MiB to 5 GiB (the last may be smaller), and a 48.8 TiB maximum object. ListParts (the storage call that lists which parts of an upload have already arrived) returns at most 1,000 parts per call, so resuming a large upload pages through it. Choosing the part size: the 10,000-part limit means a part must be at least size / 10,000, so the function rounds that up to a whole MiB, and never goes below 16 MiB so that a normal file is not split into thousands of tiny requests. Math.max picks the larger of the two, Math.ceil rounds up. With a 10 GiB cap the 16 MiB floor always wins (10 GiB / 10,000 is about 1 MiB); the size-based term only matters for files above 156.25 GiB.
const MiB = 1024 ** 2, GiB = 1024 ** 3, MAX_PARTS = 10000, MIN_PART = 5 * MiB;
// choose a part size: at least 16 MiB, and large enough that the file fits in 10,000 parts
export function partPlan(sizeBytes) {
const part = Math.max(16 * MiB, Math.ceil(sizeBytes / MAX_PARTS / MiB) * MiB);
return { partMiB: part / MiB, parts: Math.ceil(sizeBytes / part), lastPartMiB: (sizeBytes - (Math.ceil(sizeBytes / part) - 1) * part) / MiB };
}
for (const g of [0.5, 6, 10]) console.log(`${g} GiB ->`, JSON.stringify(partPlan(g * GiB)));
console.log('largest file 16 MiB parts allow:', (16 * MiB * MAX_PARTS) / GiB, 'GiB');
// time to re-send if the connection dies: whole file vs one part, at 10 Mbit/s upstream
const bytesPerSec = 10e6 / 8;
console.log('re-send whole 6 GiB at 10 Mbit/s (minutes):', (6 * GiB / bytesPerSec / 60).toFixed(1));
console.log('re-send one 16 MiB part (seconds):', (16 * MiB / bytesPerSec).toFixed(1));
Run in a node:22 container, it prints:
0.5 GiB -> {"partMiB":16,"parts":32,"lastPartMiB":16}
6 GiB -> {"partMiB":16,"parts":384,"lastPartMiB":16}
10 GiB -> {"partMiB":16,"parts":640,"lastPartMiB":16}
largest file 16 MiB parts allow: 156.25 GiB
re-send whole 6 GiB at 10 Mbit/s (minutes): 85.9
re-send one 16 MiB part (seconds): 13.4
That last pair is the reason for parts: a dropped connection costs one 16 MiB part (about 13 seconds at 10 Mbit/s) instead of the whole 6 GiB file (about 86 minutes). The client sends 4 parts at once and retries each part up to 3 times with exponential backoff and jitter (random extra delay so many clients do not retry in lockstep). It pauses on the browser's offline event.
Finish: how the backend learns the upload ended
Two paths lead to the same transition, and both are safe to repeat:
- The client calls
complete. The server moves the rowpendingtocompletingwith a conditional update, calls storage's complete operation with the part list, then moves it toprocessingand queues the job. Before assembling it can compare the part list withListParts, which is meant for verification. After assembly it checks the object size equals the declared size, and fails the upload if not. - A storage event. The bucket can notify a queue when an object is created. Amazon S3 documents event notifications as delivered at least once (a message may arrive twice, but is not silently dropped by design), so duplicates are normal. The handler uses the same conditional update, so a second delivery changes zero rows and does nothing. This path rescues the case where the server crashed after storage finished assembling but before the row was updated.
The state table and its guards
CREATE TABLE uploads (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id bigint NOT NULL,
s3_upload_id text NOT NULL,
object_key text NOT NULL,
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10 * 1024^3),
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','completing','processing','ready','failed','abandoned')),
attempts integer NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX uploads_open ON uploads (expires_at) WHERE status = 'pending';
INSERT INTO uploads (id, user_id, s3_upload_id, object_key, size_bytes, expires_at) VALUES
('00000000-0000-0000-0000-00000000000a', 7, 'mpu-a', 'raw/a', 6442450944, now() + interval '24 hours'),
('00000000-0000-0000-0000-00000000000b', 7, 'mpu-b', 'raw/b', 1000000, now() - interval '1 hour'),
('00000000-0000-0000-0000-00000000000c', 8, 'mpu-c', 'raw/c', 1000000, now() - interval '2 hours');
UPDATE uploads SET status = 'completing' WHERE id = '00000000-0000-0000-0000-00000000000a' AND status = 'pending' RETURNING id, status;
UPDATE uploads SET status = 'completing' WHERE id = '00000000-0000-0000-0000-00000000000a' AND status = 'pending' RETURNING id, status;
UPDATE uploads SET status = 'processing' WHERE id = '00000000-0000-0000-0000-00000000000a';
UPDATE uploads SET attempts = attempts + 1, status = CASE WHEN attempts + 1 >= 3 THEN 'failed' ELSE 'processing' END
WHERE id = '00000000-0000-0000-0000-00000000000a' RETURNING attempts, status;
UPDATE uploads SET attempts = attempts + 1, status = CASE WHEN attempts + 1 >= 3 THEN 'failed' ELSE 'processing' END
WHERE id = '00000000-0000-0000-0000-00000000000a' RETURNING attempts, status;
UPDATE uploads SET attempts = attempts + 1, status = CASE WHEN attempts + 1 >= 3 THEN 'failed' ELSE 'processing' END
WHERE id = '00000000-0000-0000-0000-00000000000a' RETURNING attempts, status;
WITH due AS (
SELECT id FROM uploads WHERE status = 'pending' AND expires_at < now()
ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED)
UPDATE uploads u SET status = 'abandoned' FROM due WHERE u.id = due.id
RETURNING u.id, u.s3_upload_id, u.status;
Reading the statements in order, with the table as set up by the INSERT: upload a is a live 6 GiB upload, b and c are pending uploads whose expires_at is already in the past.
- First guarded
UPDATE ... WHERE status = 'pending'ona: the condition holds, so one row changes tocompletingandRETURNINGprints it. - The identical statement again:
ais nowcompleting, theWHEREmatches nothing, and zero rows come back. This is a secondcompletecall, or a second copy of the storage event. - The unguarded
UPDATEtoprocessingprints nothing because it has noRETURNING; it stands for the assemble step finishing. - The three retry statements are the same text.
attempts = attempts + 1bumps the counter, andCASE WHEN attempts + 1 >= 3 THEN 'failed' ELSE 'processing' ENDsays: if this is the third failure, give up; otherwise stay inprocessingfor another try. In anUPDATE,attemptson the right side is the value before the update, henceattempts + 1. - The
WITH due AS (...)query is the reaper. It selects up to 100 pending rows past their expiry, oldest first, andUPDATE ... FROM duemarks themabandoned.
Run in a postgres:16 container, the guarded update returns one row the first time (completing) and (0 rows) the second, so only one caller proceeds. The three failure updates print 1 | processing, 2 | processing, 3 | failed: a processing job is retried until three attempts, then marked failed and the user is told. The reaper returns the two expired rows (mpu-c and mpu-b) as abandoned and leaves the live upload alone. FOR UPDATE SKIP LOCKED locks the rows the query selects and skips any row another transaction has already locked, so two reaper instances can run at once without claiming the same row.
Server-side processing at feature altitude
A worker takes the job from a queue (a list of pending jobs that workers pull from one at a time) and (1) scans the object for malware, (2) inspects the container to confirm it really is a video and within limits, (3) writes a thumbnail and web-friendly renditions (copies of the video at several resolutions and bitrates) into a separate processed/ prefix, and (4) sets ready. Retries use the attempt counter above with growing delays; a job that fails three times goes to failed. The raw bucket stays private. Web clients get the processed files through a CDN (content delivery network, a cache close to the viewer) with long cache lifetimes, since each rendition has a new key.
Cleaning up abandoned and failed uploads
Storage keeps uploaded parts, and bills for them, until the upload is completed or stopped. There are three layers:
| Layer | Trigger | Action |
|---|---|---|
| Cancel | user presses Cancel | DELETE marks abandoned and aborts the multipart upload |
| Reaper | every 15 minutes, rows still pending past expires_at (24 hours) | mark abandoned, call abort for each |
| Lifecycle rule | bucket-level rule AbortIncompleteMultipartUpload, whose DaysAfterInitiation setting is the number of days after an upload starts before storage aborts it (the AWS example uses 7) | storage stops uploads not completed in that time and deletes their parts |
Part uploads that were in flight when an abort arrived can still land afterwards, which is why the lifecycle rule exists as a sweep for anything the reaper missed. Failed processing keeps the raw object for a few days for investigation, then a retention rule deletes it.
Test, roll out, observe
Tests: the conditional-update SQL above, a Playwright test that kills the connection mid-part and asserts only that part is resent, a test that calls complete twice, and one that delivers the storage event twice. Roll out to staff first with a low size cap. Observe the share of uploads ending abandoned or failed, the age of the oldest pending row, queue depth (how many jobs are waiting for a worker; a rising number means workers cannot keep up), and bytes in incomplete multipart uploads (the leak the lifecycle rule guards).
Trade-offs
Direct-to-storage upload removes video bytes from your servers and gives resumability, and costs a more complex client and a second path to learn completion. For files under about 100 MB a single signed PUT is simpler; multipart pays off as sizes grow and networks worsen.
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.
Field technicians fill in an inspection checklist in a web app on tablets, often in basements with no signal. Walk me through how a submitted checklist reaches the server reliably: what the browser stores and where, how and when it retries, how the server avoids saving the same checklist twice, and what the technician sees at each step.
Sample Answer
Direct answer
Treat the tablet as the first place the checklist is saved and the server as the second. When the technician taps Submit, the app writes the finished checklist to the browser's own database (IndexedDB) together with an id generated on the tablet, tells the technician "Saved on this tablet", and only then tries the network. A small background loop (the outbox) sends queued checklists with PUT /v1/inspections/{id}, retries failures with a growing, randomised pause, and deletes the local copy only after the server has confirmed. The server stores each id at most once, so a retry after a lost reply is harmless. The screen never says "Submitted" until the server has answered with a success.
The id is the key to the whole design. Because the tablet picks it before the first attempt, every retry of the same checklist carries the same id, and the database can recognise a repeat. Without it, a lost response ("did it save or not?") forces a choice between losing data and saving twice.
What the technician sees at each step
| Moment | What happens underneath | What the screen says |
|---|---|---|
| Fills the form in the basement | answers held in the form; optionally draft-saved to IndexedDB every few seconds | normal form, a small "Offline" badge |
| Taps Submit | record written to IndexedDB (state: queued), button disabled so one tap makes one record | "Saved on this tablet. It will be sent when there is a signal." |
Send attempt fails (no signal, timeout, 5xx) | attempt counter goes up, next try scheduled after a random pause | "Saved on this tablet. Will retry automatically." plus a count of waiting checklists |
Signal returns, PUT answered 201 or 200 | local record deleted | "Sent. The office has your checklist." with the time |
Server answers 401 (signed out while offline) | record stays queued, no timer; retried after the technician signs in | "Please sign in again. Your checklist is safe on this tablet." |
Server answers 409 or 422 | record kept, marked needs_attention, never retried automatically | "This checklist was rejected. Tap to review it." |
| App closed and reopened with items waiting | outbox loop starts again on page load | "1 checklist waiting to be sent." |
Two wording rules follow from this. "Saved" and "Sent" are different words for different facts, and a technician who leaves the building after seeing "Saved" must understand the office does not have it yet. And a waiting count must stay visible on the home screen, because the main failure in the field is a technician who believes everything was sent.
What the browser stores, and where
- IndexedDB holds the outbox. (An origin is the site's address: scheme, host and port. Browser storage belongs to one origin, so another site cannot read it.) It is an asynchronous browser database that stores structured data, including files and blobs, so a checklist with photo attachments fits. A Blob is a chunk of binary data such as a photo.
localStorageholds only strings and suits small settings, not a queue of records with photos. - A service worker (a script the browser runs separately from the page, able to answer requests from a cache) keeps the app's own files, so the app opens in the basement on a cold start (opened fresh, with the browser not already holding the page). The demo below blocks only the API calls; the service worker is what makes the page files available offline.
- Eviction means the browser deleting stored data to free space. By default, browser storage is best effort: the browser may delete an origin's data under storage pressure, and MDN notes Safari deletes script-created data for an origin with no user interaction in seven days of browser use when cross-site tracking prevention is on.
navigator.storage.persist()asks the browser to keep the data until the user clears it; the browser may or may not agree (Firefox asks the user; Safari and Chromium decide from the user's history with the site). So request persistence at startup, treat afalseresult as normal, and keep the sync window short: the sooner a checklist reaches the server, the less it depends on the tablet's storage. - Photos are Blobs in IndexedDB uploaded as separate requests with their own client-generated ids, and the checklist references them. The checklist is marked sent only after the server confirms it, and its photos are confirmed separately.
When and how it retries
Triggers: right after Submit, when the page loads, when the browser fires the online event, when the app returns to the foreground (the tab becomes visible again; the browser fires a visibilitychange event), and on a timer after a failure. Do not wait for online alone: navigator.onLine can be true on a network that reaches no internet (MDN: a LAN connection counts as online), and MDN calls the property inherently unreliable, so use it as a hint and let a real request failure be the truth. The Background Synchronization API (a service worker sync event that fires when connectivity returns) fits this problem, but MDN lists it as limited availability and not Baseline, so it is an enhancement on top of the triggers above rather than the mechanism.
What to retry: network errors, timeouts, 408, 429 and 5xx. What not to retry automatically: other 4xx. A 401 is the exception that waits for a person: flush() stops, keeps the record queued and asks for sign-in, then the next trigger sends it. A 422 means the content is invalid and sending it again changes nothing; a 409 means the id exists with different content. Those go to needs_attention for a human.
The pause grows with each failed attempt and is randomised ("exponential backoff with full jitter"): wait a random time between 0 and min(cap, base * 2^attempt). The randomisation matters at scale: if a depot of tablets regains signal together after a power cut, fixed delays make them all retry in the same instant. Worked numbers for the code below (base 2 s, cap 300 s; the wait after failed attempt n is a random value between 0 and min(300 s, 2 s * 2^n)):
| Failed attempt n | Upper limit of the random wait |
|---|---|
| 1 | 4 s |
| 2 | 8 s |
| 3 | 16 s |
| 4 | 32 s |
| 5 | 64 s |
| 6 | 128 s |
| 7 | 256 s |
| 8 and later | 300 s (512 s would exceed the cap) |
Each actual wait is drawn at random inside its range, so two tablets that failed together will retry at different moments. Retry-After is a response header telling the client when to try again, written either as a number of seconds (Retry-After: 120) or as an HTTP date (Retry-After: Wed, 21 Oct 2015 07:28:00 GMT); honour it when the server sends one, and take the later of it and the backoff wait. The code below keeps to the backoff alone for brevity.
How the server avoids saving it twice
PUT /v1/inspections/{id} (an alternative is POST plus an Idempotency-Key header, a client-chosen token the server uses to recognise repeats) with the client-generated UUID (universally unique identifier, a random 128-bit id) in the path. MDN describes PUT as idempotent (calling it once is no different from calling it several times), and says the server answers 201 Created when it creates the resource and 200 or 204 when the resource already existed and was modified. Here the server uses 201 for the first save and 200 for a replay of identical content, and the client treats both as success.
DROP TABLE IF EXISTS inspections;
CREATE TABLE inspections (
id uuid PRIMARY KEY, -- generated on the tablet, the idempotency key
technician_id integer NOT NULL,
site text NOT NULL,
answers jsonb NOT NULL,
payload_hash text NOT NULL, -- fingerprint of the body, to tell a replay from a clash
completed_at timestamptz NOT NULL, -- when the technician finished (tablet clock)
received_at timestamptz NOT NULL DEFAULT now()
);
The primary key on id is what makes a duplicate impossible, even when two requests for the same id arrive at the same moment (a retry while the first attempt is still in flight). The insert uses ON CONFLICT (id) DO NOTHING (if a row with that primary key already exists, skip the insert instead of raising an error). The answers column is jsonb, PostgreSQL's binary JSON type. When the insert stores nothing, the server compares the stored payload_hash (a fingerprint of the body) and the technician id with the new request: same content from the same technician is a replay (200), anything else is a clash (409 Conflict, which MDN defines as a conflict with the current state of the target resource).
The code
How to read the browser code: IndexedDB works through events. tx() in outbox.js opens the database, starts a transaction (a group of reads and writes that complete together) on the outbox object store (IndexedDB's name for a table), runs the function passed in, and wraps the callbacks in a promise: oncomplete means the transaction has committed so the promise resolves, onerror rejects it. By default the browser may report a commit before it has verified the bytes on the storage medium (a power cut can still lose the last write); passing { durability: 'strict' } to db.transaction asks it to wait for persistent storage first, which is worth the small cost for a record the technician believes is saved (the code below leaves the default durability for brevity). Every outbox read and write goes through it, and save() awaits it before any network call, which is why a submitted checklist survives the page or app being closed or crashing. In the server, faults.loseResponses is a fault injector for the demo: when above zero the server saves the checklist and then cuts the connection without replying, which reproduces a lost response on demand.
The outbox (browser side), the page that uses it, the server, and the driver that exercises all of it in a real Chromium:
// outbox.js
const cfg = () => window.OUTBOX_RETRY || { base: 2000, cap: 300000 }; // ms
const open = () => new Promise((ok, no) => {
const r = indexedDB.open('inspections', 1);
r.onupgradeneeded = () => r.result.createObjectStore('outbox', { keyPath: 'id' });
r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error);
});
const tx = async (mode, fn) => {
const db = await open();
return new Promise((ok, no) => {
const t = db.transaction('outbox', mode); const out = fn(t.objectStore('outbox'));
t.oncomplete = () => { db.close(); ok(out.result); }; t.onerror = () => no(t.error);
});
};
export const requestPersistence = async () => (navigator.storage?.persist ? navigator.storage.persist() : false);
export const pending = () => tx('readonly', (s) => s.count());
export async function save({ site, answers }) {
const item = { id: crypto.randomUUID(), site, answers, completed_at: new Date().toISOString(), attempts: 0, state: 'queued' };
await tx('readwrite', (s) => s.put(item)); // durable on the tablet BEFORE any network call
return item.id;
}
let flushing = false, timer = null;
const say = (t) => window.dispatchEvent(new CustomEvent('outbox-state', { detail: t }));
export async function flush() {
if (flushing) return; flushing = true; clearTimeout(timer);
try {
const items = await tx('readonly', (s) => s.getAll());
for (const item of items.filter((i) => i.state === 'queued')) {
say('Sending...');
let res;
try {
res = await fetch(`/v1/inspections/${item.id}`, {
method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' },
body: JSON.stringify({ site: item.site, answers: item.answers, completed_at: item.completed_at }),
signal: AbortSignal.timeout(15000) });
} catch { res = null; } // no signal, timeout, or lost response
if (res && (res.status === 200 || res.status === 201)) {
await tx('readwrite', (s) => s.delete(item.id)); // delete locally only after the server confirmed
say('Sent. The office has your checklist.');
} else if (res && res.status === 401) { // signed out while offline: keep the record, ask for sign-in, no timer
say('Please sign in again. Your checklist is safe on this tablet.');
break;
} else if (res && res.status >= 400 && res.status < 500 && res.status !== 429 && res.status !== 408) {
await tx('readwrite', (s) => s.put({ ...item, state: 'needs_attention', status: res.status }));
say('This checklist was rejected. Tap to review it.');
} else { // retryable: network error, 5xx, 429, 408
const n = item.attempts + 1;
await tx('readwrite', (s) => s.put({ ...item, attempts: n }));
const { base, cap } = cfg();
const wait = Math.random() * Math.min(cap, base * 2 ** n); // exponential backoff with full jitter
say('Saved on this tablet. Will retry automatically.');
timer = setTimeout(flush, wait);
break;
}
}
} finally { flushing = false; }
}
<!-- index.html -->
<!doctype html>
<meta charset="utf-8">
<title>Inspection</title>
<form id="f">
<label>Site <input id="site" required></label>
<label><input type="checkbox" id="q1"> Fire exit clear</label>
<label><input type="checkbox" id="q2"> Extinguisher in date</label>
<button id="submit">Submit checklist</button>
</form>
<p id="status" role="status" aria-live="polite"></p>
<script type="module">
import { save, flush, pending, requestPersistence } from '/outbox.js';
const status = document.getElementById('status');
const show = (t) => { status.textContent = t; };
window.addEventListener('outbox-state', (e) => show(e.detail));
await requestPersistence();
document.getElementById('f').addEventListener('submit', async (ev) => {
ev.preventDefault();
document.getElementById('submit').disabled = true; // one tap makes one record
await save({ site: site.value, answers: { q1: q1.checked, q2: q2.checked } });
show('Saved on this tablet. It will be sent when there is a signal.');
flush();
});
if ((await pending()) > 0) { show('1 checklist waiting to be sent.'); flush(); }
window.addEventListener('online', flush);
document.addEventListener('visibilitychange', () => { if (!document.hidden) flush(); });
</script>
// server.mjs
import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
export function makeServer(pool, faults = { loseResponses: 0 }) {
const seen = new Map(); // id -> number of requests received
const srv = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
if (req.method === 'GET' && url.pathname === '/') { res.setHeader('content-type', 'text/html'); return res.end(fs.readFileSync('index.html')); }
if (req.method === 'GET' && url.pathname === '/outbox.js') { res.setHeader('content-type', 'text/javascript'); return res.end(fs.readFileSync('outbox.js')); }
const m = url.pathname.match(/^\/v1\/inspections\/([0-9a-f-]{36})$/);
if (!m || req.method !== 'PUT') { res.statusCode = 404; return res.end(); }
const tech = Number(req.headers['x-demo-user']);
if (!tech) { res.statusCode = 401; return res.end(); }
let raw = ''; for await (const c of req) raw += c;
let b; try { b = JSON.parse(raw); } catch { res.statusCode = 400; return res.end(); }
if (typeof b.site !== 'string' || !b.site || typeof b.answers !== 'object' || isNaN(Date.parse(b.completed_at))) {
res.statusCode = 422; return res.end(JSON.stringify({ error: 'invalid_checklist' }));
}
seen.set(m[1], (seen.get(m[1]) || 0) + 1);
const hash = crypto.createHash('sha256').update(JSON.stringify([b.site, b.answers, b.completed_at])).digest('hex');
const ins = await pool.query(
`INSERT INTO inspections (id, technician_id, site, answers, payload_hash, completed_at)
VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (id) DO NOTHING RETURNING id`,
[m[1], tech, b.site, b.answers, hash, b.completed_at]);
let status = 201;
if (ins.rowCount === 0) { // this id was saved before: replay or clash?
const { rows: [old] } = await pool.query('SELECT payload_hash, technician_id FROM inspections WHERE id=$1', [m[1]]);
status = old.payload_hash === hash && old.technician_id === tech ? 200 : 409;
}
if (faults.loseResponses > 0) { faults.loseResponses--; return req.socket.destroy(); } // saved, but the answer never arrives
res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ id: m[1] }));
});
srv.seen = seen; return srv;
}
// run.mjs
import pg from 'pg';
import fs from 'node:fs';
import { chromium } from 'playwright';
import { makeServer } from './server.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
const faults = { loseResponses: 1 };
const srv = makeServer(pool, faults).listen(3200);
const count = async () => (await pool.query('SELECT count(*)::int n FROM inspections')).rows[0].n;
const idb = (page) => page.evaluate(() => new Promise((ok) => {
const r = indexedDB.open('inspections', 1);
r.onsuccess = () => { const q = r.result.transaction('outbox').objectStore('outbox').getAll(); q.onsuccess = () => ok(q.result.map((i) => i.state + ':' + i.attempts)); };
}));
const text = (page) => page.locator('#status').innerText();
const browser = await chromium.launch();
const ctx = await browser.newContext();
await ctx.addInitScript(() => { window.OUTBOX_RETRY = { base: 40, cap: 200 }; });
const page = await ctx.newPage();
await page.goto('http://127.0.0.1:3200/');
// 1. Technician is in the basement: no signal
await page.route('**/v1/**', (r) => r.abort('internetdisconnected'));
await page.fill('#site', 'Plant room B2'); await page.check('#q1');
await page.click('#submit');
const shown = await (await page.waitForFunction(() => {
const t = document.getElementById('status').innerText;
return t.includes('retry automatically') ? t : false;
})).jsonValue();
console.log('1 offline submit | screen:', shown, '| server rows:', await count(), '| tablet outbox:', (await idb(page)).length);
// 2. Page is reloaded (or the app killed) while still offline: the checklist survives
await page.reload();
await page.waitForFunction(() => document.getElementById('status').innerText.length > 0);
console.log('2 reload offline | tablet outbox kept:', (await idb(page)).length === 1, '| server rows:', await count());
// 3. Signal returns, but the first success response is lost after the server saved it
await page.unroute('**/v1/**');
await page.waitForFunction(() => document.getElementById('status').innerText.startsWith('Sent'));
const id = [...srv.seen.keys()][0];
console.log('3 signal back | screen:', await text(page), '| server rows:', await count(), '| server received the same id more than once:', srv.seen.get(id) > 1, '| tablet outbox:', (await idb(page)).length);
// 4. Same id, different content is a clash, not a replay
const clash = await fetch(`http://127.0.0.1:3200/v1/inspections/${id}`, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' },
body: JSON.stringify({ site: 'Other site', answers: {}, completed_at: new Date().toISOString() }) });
const bad = await fetch(`http://127.0.0.1:3200/v1/inspections/${id}`, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' }, body: JSON.stringify({ site: '' }) });
console.log('4 same id, other body ->', clash.status, '| empty site ->', bad.status, '| server rows:', await count());
await browser.close(); srv.close(); await pool.end();
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy container against postgres:16, it prints:
1 offline submit | screen: Saved on this tablet. Will retry automatically. | server rows: 0 | tablet outbox: 1
2 reload offline | tablet outbox kept: true | server rows: 0
3 signal back | screen: Sent. The office has your checklist. | server rows: 1 | server received the same id more than once: true | tablet outbox: 0
4 same id, other body -> 409 | empty site -> 422 | server rows: 1
Reading it: in step 1 the API is blocked, the checklist is on the tablet (outbox 1) and not on the server (0 rows). Step 2 reloads the page while still blocked and the record survives. In step 3 the block is lifted, and the server is told to save the first request and then drop the connection before replying, so the tablet never learns it succeeded. The tablet retries the same id; the server received it more than once yet holds one row, and the screen ends on "Sent". Step 4 shows the two refusals: same id with different content gets 409, an empty site gets 422. The four lines are deterministic: they print the same way on repeated runs, because every step waits for a specific screen text or response rather than for a fixed delay, and step 1 prints the text it matched rather than re-reading the screen afterwards (the retry timer can already have changed the screen to "Sending..." by then). The driver overrides the retry delays to a base of 40 ms and a cap of 200 ms (window.OUTBOX_RETRY) so the demo finishes in seconds; the shipped defaults are the 2 s and 300 s of the table above.
The concurrent case, two requests for one id at the same instant, is shown with two database sessions (race.sh, executed inside the Postgres container as the last command of the Running the code section):
P="psql -U postgres -qAt"
$P -c "TRUNCATE inspections"
INS="INSERT INTO inspections (id, technician_id, site, answers, payload_hash, completed_at) VALUES ('11111111-1111-1111-1111-111111111111', 7, 'Plant room B2', '{}', 'h', now()) ON CONFLICT (id) DO NOTHING RETURNING 'inserted'"
TS="SELECT extract(epoch FROM clock_timestamp())"
printf "BEGIN;\n$INS;\nSELECT pg_sleep(1.5);\n$TS;\nCOMMIT;\n" | $P > a.out &
sleep 0.5
$P -c "$INS; $TS" > b.out
wait
echo "session A rows inserted: $(grep -c inserted a.out)"
echo "session B rows inserted: $(grep -c inserted b.out)"
echo "session B returned after A reached its commit: $(awk 'NR==FNR{ if ($1+0>1e9) a=$1; next } { if ($1+0>1e9) b=$1 } END { print (b>a) ? "true" : "false" }' a.out b.out)"
$P -c "SELECT 'rows in table: ' || count(*) FROM inspections"
session A rows inserted: 1
session B rows inserted: 0
session B returned after A reached its commit: true
rows in table: 1
How race.sh proves it, line by line: it empties the table, then starts session A, which opens a transaction, inserts the row, sleeps 1.5 s with pg_sleep and records a timestamp just before committing. Half a second later session B runs the same insert and records a timestamp when it returns. The shell then prints how many rows each session inserted, whether B's timestamp is later than A's (it can only be later if B waited for A's commit), and the row count. Session B's insert waited for session A to commit, then skipped, so the table holds one row. Without the unique key, nothing would make session B wait or skip, and both sessions could insert the same checklist.
Design choices and what would change them
- Client-generated id plus
PUT, versus anIdempotency-Keyheader onPOST. Either gives retries a stable identity; the path id makes the server record itself addressable and needs no key-expiry table. If the API must stayPOST /inspectionsfor other clients, keep a separate keys table with an expiry and store the first response to replay it. - Tablet clock.
completed_atcomes from the tablet and can be wrong;received_atis the server's. Show the technician the tablet time, sort and audit by the server time, and do not usecompleted_atfor anything where being wrong has consequences. - Large queues. Send oldest first and one at a time, so a slow connection finishes whole checklists rather than starting many.
- Authentication expiring while offline. The
401branch inflush()keeps the recordqueuedand prompts for sign-in; the run above does not trigger it. The demo's header user id stands in for a session.
Running the code
cd work # holds outbox.js index.html server.mjs run.mjs schema.sql race.sh
echo '{"type":"module","dependencies":{"pg":"8.13.1","playwright":"1.48.2"}}' > package.json
docker network create demo-net
docker run -d --rm --name demo-pg --network demo-net -e POSTGRES_PASSWORD=pw postgres:16
until docker exec demo-pg pg_isready -h 127.0.0.1 -q; do sleep 1; done
docker run --rm --ipc=host --network demo-net -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i --silent && node run.mjs'
docker cp race.sh demo-pg:/race.sh && docker exec -w /tmp demo-pg bash /race.sh
In a comments feature, people can edit and delete their own comments and moderators can delete anyone's. Walk me through where each permission check lives, from showing or hiding the buttons in the UI to the API handler and the database query, and what goes wrong if a check exists only in the UI.
Sample Answer
Direct answer
Write the rule once in words ("only the author can edit; the author or a moderator of that space can delete"), then enforce it in three places that each do a different job. The UI only decides which buttons to show, and it learns that from the server, never from its own copy of the rule. The API handler is the real gate: it identifies the caller (authentication, proving who you are) and then decides whether that caller may do this to this comment (authorization, deciding what you are allowed to do). The database statement repeats the rule inside its WHERE clause, so the check and the write happen in one atomic step (one indivisible step: no other request can slip in between the two halves) and cannot be separated by a race (a bug that appears only when two requests overlap in time) or a missing if.
A check that exists only in the UI is not a check. Anyone can send the HTTP request without the page (with curl, a browser console, or a script), so a hidden button protects nothing. The run below shows it: a server that trusts the UI let a stranger delete someone else's comment with a 204.
The rule and the data it needs
| Action | Who may do it |
|---|---|
| Edit a comment | its author only (a moderator cannot rewrite someone else's words) |
| Delete a comment | its author, or a moderator of the space the comment lives in |
Moderator is scoped to a space (a forum section, a project, a video page). A global "is_moderator" flag on the user would let a moderator of space 2 delete in space 1; the data model has to carry the scope.
DROP TABLE IF EXISTS comments, moderators;
CREATE TABLE moderators (
user_id integer NOT NULL,
space_id integer NOT NULL,
PRIMARY KEY (user_id, space_id)
);
CREATE TABLE comments (
id serial PRIMARY KEY,
space_id integer NOT NULL,
author_id integer NOT NULL,
body text NOT NULL CHECK (length(body) BETWEEN 1 AND 2000),
created_at timestamptz NOT NULL DEFAULT now(),
edited_at timestamptz,
deleted_at timestamptz,
deleted_by integer
);
author_id is set once at creation from the session and never accepted from a request body. deleted_at makes delete a soft delete (the row stays, marked as removed, so moderators can audit it and the action can be undone); deleted_by records who did it.
Layer 1: the UI shows what the server says is allowed
The list endpoint returns each comment with a permissions object, for example {"edit": false, "delete": true}. The component renders the Edit button only when permissions.edit is true and the Delete button only when permissions.delete is true. It contains no rule such as comment.authorId === currentUser.id || user.isModerator. If it did, there would be two copies of the rule in two languages, and the day the rule changes (say, moderators may now also edit within five minutes) the copies drift apart. The buttons are a courtesy so the user is not offered actions that will fail; they are not protection.
Two UI details matter. Permissions can go stale (the user was demoted while the page was open), so the UI must still handle a 403 on click: show "You no longer have permission to do this" and refresh the list. And hiding a button is not the same as removing the capability: the endpoint still exists.
Layer 2: the API handler decides, and answers precisely
The order inside this handler is: identify the caller, find the thing, check the input is well formed, then act through a statement that carries the permission rule.
- No session:
401. MDN describes 401 as the request lacking valid authentication credentials; signing in can fix it. - Comment does not exist (or is already deleted):
404. - Body invalid (empty, over 2,000 characters, wrong type):
422. MDN: the server understood the content type and the syntax was correct, but it was unable to process the contained instructions. This check runs before the database statement, so even a stranger who sends a malformed body sees422; that reveals nothing private here because the comment's existence is already public. - Signed in, body fine, but not allowed:
403. MDN describes 403 as the server understanding the request and refusing it, where authenticating or re-authenticating makes no difference. MDN also notes a server may answer404instead of403when acknowledging that a resource exists is unwanted. Comments here are public, so403is the more useful answer. In this handler the allow-or-refuse decision is made by theUPDATEstatement shown in Layer 3: zero rows changed means refuse. - Success:
200with the new body for an edit,204(no content) for a delete.
The handler also reads only the fields it expects. A PATCH that carries "author_id": 3 must not change the author: accepting whatever fields arrive is called mass assignment and is how ownership gets rewritten. The code below ignores everything except body.
// policy.mjs
// The one place the rule is written down in JavaScript.
// comment: { author_id, space_id, deleted_at } user: { id } | null
// modSpaces: Set of space ids the user moderates
export function can(action, user, comment, modSpaces) {
if (!user || comment.deleted_at) return false;
const isAuthor = comment.author_id === user.id;
const isModHere = modSpaces.has(comment.space_id);
if (action === 'edit') return isAuthor; // moderators cannot edit other people's words
if (action === 'delete') return isAuthor || isModHere;
return false;
}
can() is used by the list endpoint to compute the permissions flags. The write itself is guarded by the SQL, shown next.
Layer 3: the database statement repeats the rule
// server.mjs
import http from 'node:http';
import { can } from './policy.mjs';
export function makeServer(pool, { trustUi = false } = {}) {
const send = (res, status, body) => {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(body === undefined ? '' : JSON.stringify(body));
};
const readJson = (req) => new Promise((ok) => {
let s = ''; req.on('data', (c) => (s += c));
req.on('end', () => { try { ok(JSON.parse(s || '{}')); } catch { ok(null); } });
});
const modSpacesOf = async (userId) =>
new Set((await pool.query('SELECT space_id FROM moderators WHERE user_id = $1', [userId])).rows.map((r) => r.space_id));
return http.createServer(async (req, res) => {
// Stand-in for session lookup: header X-Demo-User holds the already authenticated user id.
const uid = Number(req.headers['x-demo-user']);
const user = uid ? { id: uid } : null;
const url = new URL(req.url, 'http://x');
const m = url.pathname.match(/^\/comments\/(\d+)$/);
if (req.method === 'GET' && url.pathname === '/spaces/1/comments') {
const mods = user ? await modSpacesOf(user.id) : new Set();
const { rows } = await pool.query(
'SELECT id, space_id, author_id, body, deleted_at FROM comments WHERE space_id = 1 AND deleted_at IS NULL ORDER BY id');
return send(res, 200, rows.map((c) => ({
id: c.id, body: c.body, author_id: c.author_id,
permissions: { edit: can('edit', user, c, mods), delete: can('delete', user, c, mods) },
})));
}
if (!m) return send(res, 404, { error: 'not_found' });
const id = Number(m[1]);
if (!trustUi && !user) return send(res, 401, { error: 'sign_in_required' });
const { rows: [c] } = await pool.query('SELECT * FROM comments WHERE id = $1', [id]);
if (!c || c.deleted_at) return send(res, 404, { error: 'comment_not_found' });
if (req.method === 'PATCH') {
const body = await readJson(req);
if (!body || typeof body.body !== 'string' || body.body.length < 1 || body.body.length > 2000)
return send(res, 422, { error: 'invalid_body' });
if (trustUi) { // the broken variant: the server trusts that the UI hid the button
await pool.query('UPDATE comments SET body = $2, edited_at = now() WHERE id = $1', [id, body.body]);
return send(res, 200, { id, body: body.body });
}
// Rule re-checked inside the statement: author only, and not already deleted.
const r = await pool.query(
`UPDATE comments SET body = $3, edited_at = now()
WHERE id = $1 AND author_id = $2 AND deleted_at IS NULL
RETURNING id, body`, [id, user.id, body.body]);
if (r.rowCount === 0) return send(res, 403, { error: 'not_your_comment' });
return send(res, 200, r.rows[0]);
}
if (req.method === 'DELETE') {
if (trustUi) {
await pool.query('UPDATE comments SET deleted_at = now() WHERE id = $1', [id]);
return send(res, 204);
}
const r = await pool.query(
`UPDATE comments SET deleted_at = now(), deleted_by = $2
WHERE id = $1 AND deleted_at IS NULL
AND (author_id = $2
OR EXISTS (SELECT 1 FROM moderators m WHERE m.user_id = $2 AND m.space_id = comments.space_id))`,
[id, user.id]);
if (r.rowCount === 0) return send(res, 403, { error: 'not_allowed' });
return send(res, 204);
}
return send(res, 404, { error: 'not_found' });
});
}
The PATCH and DELETE statements put the rule in the WHERE clause: author_id = $2 for edit, and author_id = $2 OR EXISTS (SELECT 1 FROM moderators ...) for delete, with the moderator lookup tied to the comment's own space_id. When rowCount is 0 nothing was written, and the handler answers 403 (the comment was loaded a moment earlier, so it exists). Read the delete statement in plain words: "mark comment $1 as deleted by user $2, but only if it is not already deleted, and only if user $2 is the author, or there exists a row in moderators saying user $2 moderates this comment's space." The EXISTS (SELECT 1 FROM moderators m WHERE ...) part is a yes/no question: does the inner query find at least one row? SELECT 1 just means "the row's contents do not matter, only whether one exists", and comments.space_id ties the question to the comment being deleted.
Here is the gap a separate check leaves. The two-step version runs SELECT (is the user allowed?) and then, later, UPDATE. At 10:00:00.000 the app reads "Dana is a moderator"; at 10:00:00.001 an admin removes Dana's moderator row; at 10:00:00.002 the app runs the delete, based on an answer that stopped being true. With the rule inside the UPDATE, the database decides while it writes. Doing it this way means the decision and the write are one statement: there is no gap between "I checked" and "I wrote" in which a forgotten branch or a second code path could skip the check. A second endpoint added next year that also deletes comments must go through the same statement shape, which is why many teams put it in one data-access function rather than inline.
An honest limit. A snapshot is the database's frozen view of all committed data, taken when a statement starts; in PostgreSQL's default mode each statement gets its own. Timeline: the admin's demotion is still uncommitted at 10:00:00.000, the delete statement starts at 10:00:00.001 and takes its snapshot, the demotion commits at 10:00:00.002, and the delete still treats Dana as a moderator. That window is one statement long, and a demotion that commits that close behind the delete is indistinguishable from the delete having run just before it. For stricter needs, use database row-level security (a feature where the database itself attaches a policy to every query on the table) as a second wall. Raising the transaction isolation level (the setting that decides how much one transaction is shielded from other transactions' concurrent changes) does not shrink this window, because every level still decides from a snapshot; it matters only when the check and the write are separate statements, where REPEATABLE READ keeps both on one snapshot instead of two.
Running it: what goes wrong with UI-only checks, and what the layers give you
The script starts the server in two modes. In trustUi mode the handler skips authorization (the UI "already hid the button"). Then it replays a table of callers against the layered server.
// run.mjs
import pg from 'pg';
import fs from 'node:fs';
import { makeServer } from './server.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
const ALICE = 1, BOB = 2, MALLORY = 3, MOD_ONE = 4, MOD_TWO = 5; // MOD_TWO moderates space 2 only
const reset = async () => {
await pool.query('TRUNCATE comments RESTART IDENTITY; TRUNCATE moderators');
await pool.query('INSERT INTO moderators VALUES ($1,1), ($2,2)', [MOD_ONE, MOD_TWO]);
await pool.query("INSERT INTO comments (space_id, author_id, body) VALUES (1, $1, 'alice says hi'), (1, $2, 'bob says hi')", [ALICE, BOB]);
};
const call = async (port, who, method, path, body) => {
const r = await fetch(`http://127.0.0.1:${port}${path}`, {
method, headers: { ...(who ? { 'x-demo-user': String(who) } : {}), 'content-type': 'application/json' },
body: body ? JSON.stringify(body) : undefined });
return r.status;
};
const alive = async (id) => (await pool.query('SELECT count(*)::int n FROM comments WHERE id=$1 AND deleted_at IS NULL', [id])).rows[0].n === 1;
// 1. A server that trusts the UI
await reset();
let s = makeServer(pool, { trustUi: true }).listen(3101);
const listMallory = await (await fetch('http://127.0.0.1:3101/spaces/1/comments', { headers: { 'x-demo-user': String(MALLORY) } })).json();
console.log('UI sees for Mallory on comment 1:', JSON.stringify(listMallory[0].permissions));
console.log('UI-only: Mallory DELETE comment 1 ->', await call(3101, MALLORY, 'DELETE', '/comments/1'), '| comment 1 still alive:', await alive(1));
s.close();
// 2. The layered server, full matrix
await reset();
s = makeServer(pool).listen(3102);
const rows = [];
const attempt = async (label, who, method, id, body) => {
await reset();
const st = await call(3102, who, method, `/comments/${id}`, body);
rows.push([label, `${method} comment ${id}`, st, method === 'DELETE' ? (await alive(id) ? 'kept' : 'deleted') : (await pool.query('SELECT body FROM comments WHERE id=$1', [id])).rows[0].body]);
};
await attempt('no session', null, 'DELETE', 1);
await attempt('Alice own', ALICE, 'PATCH', 1, { body: 'alice edited' });
await attempt('Mallory other', MALLORY, 'PATCH', 1, { body: 'hacked' });
await attempt('Mallory other', MALLORY, 'DELETE', 1);
await attempt('Alice own', ALICE, 'DELETE', 1);
await attempt('Moderator of space 1', MOD_ONE, 'DELETE', 2);
await attempt('Moderator of space 1', MOD_ONE, 'PATCH', 2, { body: 'mod rewrote bob' });
await attempt('Moderator of space 2', MOD_TWO, 'DELETE', 2);
await attempt('Alice, bad body', ALICE, 'PATCH', 1, { body: '' });
console.table(rows.map(([a,b,c,d]) => ({ caller: a, request: b, status: c, result: d })));
// Mass assignment: author_id in the body is ignored
await reset();
await call(3102, ALICE, 'PATCH', '/comments/1', { body: 'x', author_id: MALLORY });
console.log('author_id after PATCH carrying author_id=3:', (await pool.query('SELECT author_id FROM comments WHERE id=1')).rows[0].author_id);
// UI flags agree with what the server then allows
const l = await (await fetch('http://127.0.0.1:3102/spaces/1/comments', { headers: { 'x-demo-user': String(MOD_ONE) } })).json();
console.log('Moderator list flags:', JSON.stringify(l.map((c) => [c.id, c.permissions])));
s.close(); await pool.end();
Run in a node:22 container against postgres:16, it prints:
UI sees for Mallory on comment 1: {"edit":false,"delete":false}
UI-only: Mallory DELETE comment 1 -> 204 | comment 1 still alive: false
┌─────────┬────────────────────────┬────────────────────┬────────┬─────────────────┐
│ (index) │ caller │ request │ status │ result │
├─────────┼────────────────────────┼────────────────────┼────────┼─────────────────┤
│ 0 │ 'no session' │ 'DELETE comment 1' │ 401 │ 'kept' │
│ 1 │ 'Alice own' │ 'PATCH comment 1' │ 200 │ 'alice edited' │
│ 2 │ 'Mallory other' │ 'PATCH comment 1' │ 403 │ 'alice says hi' │
│ 3 │ 'Mallory other' │ 'DELETE comment 1' │ 403 │ 'kept' │
│ 4 │ 'Alice own' │ 'DELETE comment 1' │ 204 │ 'deleted' │
│ 5 │ 'Moderator of space 1' │ 'DELETE comment 2' │ 204 │ 'deleted' │
│ 6 │ 'Moderator of space 1' │ 'PATCH comment 2' │ 403 │ 'bob says hi' │
│ 7 │ 'Moderator of space 2' │ 'DELETE comment 2' │ 403 │ 'kept' │
│ 8 │ 'Alice, bad body' │ 'PATCH comment 1' │ 422 │ 'alice says hi' │
└─────────┴────────────────────────┴────────────────────┴────────┴─────────────────┘
author_id after PATCH carrying author_id=3: 1
Moderator list flags: [[1,{"edit":false,"delete":true}],[2,{"edit":false,"delete":true}]]
Reading the output:
- The page showed Mallory
{"edit":false,"delete":false}for Alice's comment, yet a directDELETEreturned204and the comment is gone. The UI was correct and still useless as a defence. - With the layers in place Mallory gets
403for both edit and delete, the row is untouched, and the unauthenticated call gets401. - Alice can edit and delete her own comment; the moderator of space 1 can delete Bob's comment but gets
403trying to edit it; the moderator of space 2 gets403on space 1's comment because moderator rights are scoped. - A body carrying
author_idchanges nothing: the author stays user 1. - The
permissionsflags the UI receives (delete: truefor the moderator on both comments,edit: false) match what the server then allows. A test that loops over the callers and compares the flag with the real status code keeps the JavaScript rule and the SQL rule from drifting apart.
Pitfalls that separate a careful answer
The first two matter most; the rest are quick checks.
- Most important: insecure direct object reference (IDOR): any endpoint that takes an id and trusts the caller to send only their own. Example:
DELETE /comments/2works for anyone because the server only checks the user is signed in. The fix is the ownership predicate in the query, not a clever or hidden id. - Most important: checking only on the write path: the list endpoint must not return data the caller may not see, and a "get one comment" endpoint needs its own check.
- Using the client's claim as input:
userId,roleorisModeratorin a request body or a hidden form field. Identity comes from the session; role comes from themoderatorstable. - Authorization in a UI framework's route guard only: a route guard is a client-side rule that decides which page renders, not who may call the API.
- Error leakage (an error message that reveals private data): a
403body should say "not allowed", not "this comment belongs to bob@example.com". - Audit trail (a record of who did what): log
deleted_byand the action so a moderator's deletion can be reviewed.
Running the code
cd work && echo '{"type":"module","dependencies":{"pg":"8.13.1"}}' > package.json
docker network create demo-net
docker run -d --rm --name demo-pg --network demo-net -e POSTGRES_PASSWORD=pw postgres:16
until docker exec demo-pg pg_isready -h 127.0.0.1 -q; do sleep 1; done
docker run --rm --network demo-net -v "$PWD":/w -w /w node:22 sh -c 'npm i --silent && node run.mjs'
Put schema.sql (the SQL listing), policy.mjs, server.mjs and run.mjs from the listings above in work/, and run the first line from the directory that contains work/. The pg_isready -h 127.0.0.1 line waits until the database accepts TCP connections, which happens only after the image's one-time initialisation restart; without it the script can fail with ECONNREFUSED. Stop the database afterwards with docker stop demo-pg.
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'
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.