A public API receives bytes from strangers, and a mobile app or a script can send anything. Check the data once, at the edge, before any other code touches it.
The trust boundary is the line where data enters your process: a request body, a query string, a header, a message from a queue. Everything on the outside of that line is untrusted, including your own mobile app, because anyone can call the API without the app. Inside the line, your code may assume that data has the right shape. The check that makes this assumption true is called validation.
Without it, bad data travels deep before it fails. A missing customer becomes undefined in a SQL parameter and fails inside the database driver. A quantity sent as the text "2" turns qty + 1 into "21". An array with a million items costs memory and time before any business rule runs. An unexpected field such as admin: true gets copied into a record by a careless { ...req.body }. Each of these is a bug that a few lines at the edge would have stopped.
TypeScript does not help here. Types are erased when the code runs, and JSON.parse returns whatever the sender wrote. A schema is a runtime description of the shape you accept, and a validation library checks incoming data against it. This lesson uses zod 4, which also returns a cleaned copy of the data. The databases chapter checked a few fields by hand; a schema keeps the rules in one place and scales to nested data.
Describing an order with zod
The schema below describes the body of a new food order. Each rule is a method chained onto a type. The checks run in order, and trim() changes the value as well as testing it.
Read it from the outside in. The order is an object. customer is a string with spaces trimmed, one to sixty characters. items is an array of one to thirty entries, and each entry needs a sku in a fixed pattern and a whole qty from 1 to 20. coupon may be missing. The upper limits matter as much as the lower ones: they bound how much work one request can cause.
Two calls run a schema. schema.parse(data) returns the cleaned value or throws a ZodError. schema.safeParse(data) never throws; it returns an object with success: true and data, or success: false and error. At an HTTP edge you expect failures, so safeParse is the usual choice.
Animated sceneA bad payload stops at the edge0:17
Watch for the bad payload stopping at the schema check
Read it as steps
The validation step rejects the first request with a 400 and lets the second reach the database.
The scene shows the order of events. The schema check sits in front of the handler, so the handler and the database only ever see data that passed it. A rejected request costs one check and no database work.
Running good and bad payloads
This script parses one payload that has padding and an extra field, and one that breaks four rules.
js
import { NewOrder } from'./schema.mjs';
const good = {
customer: ' Meera ',
items: [{ sku: 'IDL-001', qty: 2 }],
admin: true,
};
const bad = {
customer: '',
items: [{ sku: 'idli', qty: 2.5 }, { sku: 'DOS-002', qty: 99 }],
};
const ok = NewOrder.safeParse(good);
console.log(ok.success, JSON.stringify(ok.data));
const no = NewOrder.safeParse(bad);
console.log(no.success);
for (const issue of no.error.issues) {
const where = issue.path.join('.');
console.log(`${where}: ${issue.message}`);
}
l1-parse.mjs
text
true {"customer":"Meera","items":[{"sku":"IDL-001","qty":2}]}
false
customer: Too small: expected string to have >=1 characters
items.0.sku: Invalid string: must match pattern /^[A-Z]{3}-\d{3}$/
items.0.qty: Invalid input: expected int, received number
items.1.qty: Too big: expected number to be <=20
Node 24.18.0, zod 4.6.7.
The good payload passed, and the result is not the input. The spaces around Meera are gone, and admin: true was dropped, because zod objects remove keys they do not declare. Hand the cleaned data to the rest of your code, never the original body.
The bad payload produced four issues. Each has a path that points to the field (items.0.qty means the first item's qty), a code, and a message. The next lesson turns that list into a response a client can read. Notice that the error for qty: 2.5 says it expected an integer: the schema reported every failure instead of stopping at the first.
Strict objects, coercion and dates
Strictness is a choice. If you would rather reject unknown fields than drop them, declare the object with z.strictObject. Zod does not convert types unless you ask: z.number() refuses the text "2". Conversion is available as z.coerce.number(), and it has traps of its own. The script below runs each of these, including a date that exists on no calendar.
Reading the lines in order: a strict object rejects admin; a plain number refuses "2"; coercion turns "2" into 2 and also turns an empty string into 0, so a blank form field silently becomes a zero. The last three lines are about dates. z.iso.datetime() rejected the 30th of February, but JavaScript's own Date accepted it and rolled it over to 2 March. A date check that works by calling new Date and seeing whether it throws would have let this through. Use the schema's check, or rebuild the date and compare its parts.
Check
What it proves
What it does not prove
Shape and types
fields exist and have the right type
that the values make business sense
Ranges and lengths
one request cannot be arbitrarily large
that the user is allowed to do it
Pattern on a sku
the text looks like a SKU
that such a product exists
Validation answers "is this a well-formed request". Whether the product exists, whether the coupon is valid and whether this user may place the order are separate questions, and later lessons keep them separate.
A client sends {"customer":"Ravi","items":[...],"admin":true} and your schema is a plain z.object. What reaches your handler?
The cleaned object without admin: zod objects drop undeclared keys by default. Use z.strictObject if you want the request rejected instead.
Why is z.coerce.number() risky for a quantity field?
It converts whatever it is given, so an empty string becomes 0 and a blank form field passes as a valid number. A plain z.number() with .int().min(1) rejects both.
Which result would you trust to hand to the next layer, the raw request body or result.data from safeParse?
result.data. It has been trimmed, stripped of unknown keys and checked against every rule. The raw body has none of that.
Part 2 · A consistent error shape: problem details
Why errors need a shape
Clients of an API, whether apps or other services, do more than display errors: they branch on them. A client that retries on a timeout, shows a form message for a bad field and logs out on an expired session must be able to tell those cases apart without reading English.
Teams that invent error bodies end up with several. One route returns { "error": "bad" }, another { "message": "...", "code": 12 }, and a crash returns the framework's HTML page. RFC 9457, "Problem Details for HTTP APIs", defines one JSON shape for all of them, with the media type application/problem+json. Using a published format means client libraries and your own colleagues already know how to read it.
Member
Meaning (from the RFC)
type
a URI reference that identifies the kind of problem; when absent it is taken to be about:blank, a generic problem
title
a short, human-readable summary of the problem type
status
the HTTP status code the origin server generated; advisory only
detail
an explanation specific to this occurrence
instance
a URI reference that identifies this specific occurrence
You may add your own members, called extensions. The RFC says clients must ignore extensions they do not recognise, so a new field never breaks an old client. It also says consumers should not parse detail to get information, so anything a program needs, such as the list of bad fields, belongs in an extension member and not in prose.
Building it in Express
The first helper sends a problem. The type values are addresses under example.com; they need not resolve, but a real API often puts a documentation page there. The instance is a fresh urn:uuid: value, which also gives support staff something to search the logs for.
js
import { randomUUID } from'node:crypto';
const BASE = 'https://api.example.com/problems/';
exportfunction problem(res, status, slug, title, extra = {}) {
res
.status(status)
.type('application/problem+json')
.json({
type: BASE + slug,
title,
status,
instance: `urn:uuid:${randomUUID()}`,
...extra,
});
}
problem.mjs, first half
The second helper is a middleware factory. Given a zod schema, it returns a middleware that checks the content type, validates req.body, replaces the body with the cleaned data, and calls next. On failure it turns zod's issues into an errors extension: each item has a JSON Pointer to the field (RFC 6901 syntax, /items/0/qty) and a message.
The 415 branch exists because express.json() quietly skips bodies whose content type is not JSON, which leaves req.body empty. Without the check, a form post would produce a confusing validation error about a missing object.
Errors that come from outside your routes
Not every failure passes through your validator. A body that is not valid JSON fails inside express.json() before your route runs, and a body past the size limit fails there too. Express hands those to the error-handling middleware, with a type field that says what happened. That final middleware is the one place that turns everything else into a problem as well.
js
app.use((req, res) =>
problem(res, 404, 'not-found', 'No such route'));
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return problem(res, 400, 'invalid-json', 'Body is not JSON');
}
if (err.type === 'entity.too.large') {
return problem(res, 413, 'too-large', 'Body is too large');
}
console.error('unhandled:', err.message);
problem(res, 500, 'internal', 'Something went wrong');
});
app.mjs, the last two middleware functions
The first function answers any route that nothing else matched. The second takes four arguments, which is how Express recognises an error handler. It maps the two body-parser errors, and for everything else it logs the real message on the server and sends a generic 500. The caller learns that something failed, and the log keeps the detail. Express 5 also sends a rejected promise from an async handler here, so you do not need a try/catch in every route; the databases chapter covers that.
Now the three failures in one run: invalid fields, broken JSON and a form post. The first response is printed in full.
--- bad fields: 400 application/problem+json; charset=utf-8
{
"type": "https://api.example.com/problems/validation",
"title": "The request body is invalid",
"status": 400,
"instance": "urn:uuid:a77fc50b-f9c3-4f7e-b946-6b99bd0aa7e2",
"detail": "2 problem(s) found",
"errors": [
{
"pointer": "/customer",
"message": "Too small: expected string to have >=1 characters"
},
{
"pointer": "/items/0/qty",
"message": "Too big: expected number to be <=20"
}
]
}
--- broken json: 400 application/problem+json; charset=utf-8
invalid-json | Body is not JSON
--- wrong type: 415 application/problem+json; charset=utf-8
unsupported-media | Send JSON
The `instance` value is random and differs on each run.
Every response has the same four core members and the same media type. The validation problem adds errors, and a client that does not know that extension still sees status and title. Pick one set of type values early and keep them stable, because clients will compare against them.
A client wants to show "Quantity must be 20 or less" under the right form field. Which member of the problem should it read?
The errors extension. Each entry has a pointer such as /items/0/qty and a message. The RFC advises against parsing detail, so field-level information belongs in an extension.
What does a client do with an extension member it does not recognise?
It ignores it. RFC 9457 requires consumers to ignore unknown extensions, which is what lets a server add members without breaking older clients.
Why does the final error handler send "Something went wrong" instead of err.message?
Messages from failures you did not anticipate can contain internal details such as connection strings or file paths. The handler logs them on the server and gives the caller only a generic problem.
Part 3 · Status codes that matter
Picking the code, and what each tells a client
A status code is the first thing a client reads and the only part every proxy, monitor and retry library understands. Choose it for what the client should do next: fix the request, sign in, wait, or try again later.
Code
Meaning
The client should
200 / 201 / 204
success; created (send Location); success with no body
carry on
400
the request is malformed or fails validation
fix it, do not retry unchanged
401
no valid credentials; must send WWW-Authenticate
sign in, then retry
403
authenticated, but not allowed
stop; signing in again will not help
404
no such resource
check the address
409
conflicts with the current state of the resource
refetch, resolve, resend
422
syntax is fine but the instructions cannot be processed
change the values
429
too many requests; may send Retry-After
wait, then retry
500
the server failed unexpectedly
retry later, maybe
503
temporarily unavailable; may send Retry-After
retry after the delay
These definitions come from RFC 9110, except 429, which is defined in RFC 6585. Two points in the RFCs are easy to miss. A 401 response must carry a WWW-Authenticate header with at least one challenge. And the 429 RFC says servers are not required to use that status at all: under attack, dropping connections may be the better response.
400 or 422, and 401 or 403
Two pairs cause most arguments. 400 or 422. RFC 9110 defines 422 as "the syntax of the request content is correct, but it was unable to process the contained instructions". By that reading, a body that is not valid JSON is a 400, and a well-formed body that breaks a business rule is a 422. This API goes one step further and uses 400 for anything that fails the schema, including a missing field, and 422 for a request that passes the schema but breaks a rule, such as an expired coupon. The RFC does not force that split: its own example of a validation problem uses 422, and many APIs use 422 for every schema failure. Pick one rule, write it down, and apply it everywhere.
401 or 403. Despite its name, 401 is about authentication: the server does not know who you are. 403 is about authorisation: it knows who you are and the answer is no. A client can fix a 401 by signing in. Repeating a 403 with the same identity changes nothing.
409. The RFC describes a conflict with the current state of the resource, where the user may be able to resolve it and resend. Cancelling an order that was already delivered fits, and so does creating a record whose unique key exists. 413 (Content Too Large) is the answer to a body over your size limit; the databases chapter set that limit.
One run through the codes
The routes live inside the createApp function of app.mjs. Its first lines hold the imports and the state they share. The second fragment shows the routes that produce 401, 403, 429 and 503. The 429 route is a toy counter that never resets; the caching chapter builds a real fixed-window limiter.
POST /orders 201 location: /orders/1
GET /orders/1200
GET /orders/99404
POST /orders 400
POST /orders 422
GET /admin/report 401 www-authenticate: Bearer
GET /admin/report 403
POST /orders/1/cancel 200
DELETE /orders/1204
GET /limited 200
GET /limited 200
GET /limited 200
GET /limited 429 retry-after: 30
GET /ready 503 retry-after: 5
unhandled: connection string is postgres://secret@db/prod
GET /boom 500
The `unhandled:` line is the server log, printed before the 500 line.
Read the output as a client would. The 201 carries Location. The two admin calls show the difference between no credentials (401 with a challenge) and the wrong credentials (403). The fourth call to /limited is a 429 with Retry-After: 30, which RFC 9110 defines as a number of seconds or an HTTP date. The 503 also carries Retry-After; it is what a service sends while it drains during a deploy. Last, the crash returned a 500, and the message with the connection string stayed in the server log, as the error handler promised in the previous lesson.
Retry rules follow from the codes. Retrying a 400, 403 or 422 without changing anything is pointless. Retrying a 429 or 503 is right, after the delay the server asked for. Retrying a 500 is a judgement, and it is only safe when the operation is idempotent, which is the subject of the lesson after next.
A request carries a valid session for Meera, who asks for an admin report. Which status is correct, and does a new login help?
403. The server knows who she is and refuses. Signing in again as the same user changes nothing; a 401 would be wrong because she is already authenticated.
A body is valid JSON and passes the schema, but the coupon in it expired yesterday. Which status does this API use?
422. The syntax is correct but the instruction cannot be carried out. A malformed or schema-invalid body would be a 400.
What must a server send with a 401 response?
A WWW-Authenticate header with at least one challenge, such as Bearer. RFC 9110 states this as a MUST.
Part 4 · Pagination, filtering and sorting
Why a list endpoint needs a limit
Every list endpoint that returns a whole table will fail one day, usually on the day the table gets large. Apps need pages: a bounded slice of results and a way to ask for the next slice.
SQL gives two ways to slice. Offset paging uses LIMIT 4 OFFSET 8: skip eight rows, return four. It is easy, and it lets a client jump to page 20. Keyset paging, also called cursor paging, remembers where the last page ended and asks for the rows after that point: WHERE id < 6 ORDER BY id DESC LIMIT 4. Both need an ORDER BY. The PostgreSQL manual says so plainly: without one you get "an unpredictable subset", and different LIMIT and OFFSET values can give inconsistent results.
Offset paging has two weaknesses. The manual notes that rows skipped by an OFFSET still have to be computed inside the server, so a large offset can be slow. And pages are positions, not bookmarks: if the data changes between two requests, positions shift. The next page shows the second weakness on a table that grows while a client is reading.
Drift, measured
The script starts with ten orders and pages newest first, four at a time. After reading page 1, three new orders arrive. Then it fetches page 2 two ways. The database is PGlite running in the same process: real PostgreSQL compiled to WebAssembly, with no server to start.
js
import { PGlite } from'@electric-sql/pglite';
const db = new PGlite();
await db.exec(`CREATETABLE orders (
id serial PRIMARY KEY, customer text NOT NULL)`);
const add = async (n) => {
for (let i = 0; i < n; i++) {
await db.query('INSERT INTO orders (customer) VALUES ($1)',
['cust']);
}
};
const ids = (r) => r.rows.map((x) => x.id).join(' ');
await add(10);
const off = (o) => db.query(
'SELECT id FROM orders ORDER BY id DESC LIMIT 4 OFFSET $1', [o]);
const key = (before) => db.query(
'SELECT id FROM orders WHERE id < $1 ORDER BY id DESC LIMIT 4',
[before]);
const p1 = await off(0);
const k1 = p1.rows.at(-1).id;
console.log('offset page 1:', ids(p1));
await add(3);
console.log('offset page 2:', ids(await off(4)));
console.log('keyset page 2:', ids(await key(k1)));
Page 1 returned orders 10, 9, 8 and 7. Three new orders (11, 12 and 13) then took the top positions, so offset 4 now starts three rows earlier in the list and page 2 shows 9, 8 and 7 again, with only 6 new. A client that appends pages to a list would display duplicates. If rows had been deleted instead, a row could be skipped without any sign. Keyset paging asked for "ids below 7" and returned 6, 5, 4 and 3. New rows at the top cannot disturb it, because it is anchored to a value, not to a position.
Keyset paging has costs. A client cannot jump to page 20, only walk forward from a cursor. And the sort must end in a unique column, or rows with equal sort values are lost or repeated at page boundaries.
Ties and the row comparison
Suppose orders are sorted by total, which has repeats. The fix is a tie-breaker: sort by total and then id, and compare both together. PostgreSQL supports a row comparison, (total, id) < ($1, $2), which means "total is less, or total is equal and id is less". The first parameter doubles as a check for the first page, where there is no cursor yet.
js
import { PGlite } from'@electric-sql/pglite';
const db = new PGlite();
await db.exec(`CREATETABLE orders (
id serial PRIMARY KEY, total int NOT NULL)`);
for (const t of [300, 500, 500, 500, 700, 200]) {
await db.query('INSERT INTO orders (total) VALUES ($1)', [t]);
}
const page = (after) => db.query(
`SELECT id, total FROM orders
WHERE ($1::int IS NULL OR (total, id) < ($1, $2))
ORDER BY total DESC, id DESC LIMIT 2`,
after ? [after.total, after.id] : [null, null]);
let after = null;
for (let n = 1; n <= 3; n++) {
const r = await page(after);
console.log('page', n, JSON.stringify(r.rows));
after = r.rows.at(-1);
}
The three orders worth 500 were split across pages 1 and 2 with none lost and none repeated. Because both columns sort in the same direction, one row comparison covers it; mixed directions need a more careful condition.
Cursors and sorting
Clients should not build cursors themselves. Send back an opaque string, and decode it on the way in. A cursor is untrusted input like any other: a client can edit it, so validate what comes out of it.
Encoding hides the structure but is not a secret, and the decoder returned null for both garbage and a forged object. Respond to a null cursor with a 400 problem.
Sorting and filtering come from query parameters, and they hit a limit of SQL. A placeholder stands for a value, never for a column name. The script below puts a parameter in ORDER BY and then uses an allowlist that maps each accepted key to a fixed fragment of SQL.
js
import { PGlite } from'@electric-sql/pglite';
const db = new PGlite();
await db.exec('CREATE TABLE orders (id int, total int)');
await db.exec('INSERT INTO orders VALUES (1, 300), (2, 100)');
const ids = (r) => r.rows.map((x) => x.id).join(' ');
const p = await db.query(
'SELECT id FROM orders ORDER BY $1', ['total']);
console.log('ORDER BY $1 gives:', ids(p));
const t = await db.query('SELECT id FROM orders ORDER BY total');
console.log('ORDER BY total gives:', ids(t));
const SORTS = { total: 'total', newest: 'id DESC' };
const pick = (key) => SORTS[key] ?? SORTS.newest;
for (const key of ['total', 'id; DROP TABLE orders']) {
const sql = `SELECT id FROM orders ORDER BY ${pick(key)}`;
const r = await db.query(sql);
console.log(JSON.stringify(key), '->', ids(r));
}
l4-sort.mjs
text
ORDER BY $1 gives: 12
ORDER BY total gives: 21"total" -> 21"id; DROP TABLE orders" -> 21
ORDER BY $1 did not sort by total: the parameter was treated as the constant text total, so the rows came back in table order, 1 then 2. The allowlist did work, and an unknown key such as id; DROP TABLE orders fell back to the default order and never reached the SQL text. Validate the sort key, the direction, and the page size (cap it, for example at 50), as you do any other input.
Page 1 of an offset-paged list was fetched, then 3 rows were added at the top. Why does page 2 repeat rows?
Offsets count positions from the top of the current list. Three new rows push older rows down three positions, so offset 4 starts earlier than where page 1 ended.
You sort by a column with many equal values and page by cursor. What goes wrong without a tie-breaker?
Rows with equal sort values straddle page boundaries, so some are skipped or repeated. Adding a unique column such as id to the sort and to the cursor makes the order total.
Can you write ORDER BY $1 and pass the column name as the parameter?
No. The parameter is sent as a value, so it acts as a constant and sorts nothing. Map the accepted keys to fixed SQL fragments in an allowlist.
Part 5 · Idempotency keys: retries that never charge twice
Why retries are dangerous
A phone on a weak network sends a payment request and the connection drops. The app cannot tell whether the server never saw the request, or processed it and lost the reply. Retrying is the only choice, and it may charge the customer twice.
An operation is idempotent when doing it many times has the same effect as doing it once. RFC 9110 lists PUT, DELETE and the safe methods as idempotent, so a client or proxy may retry them freely after a failure. POST is not on the list. Creating an order with POST twice creates two orders.
The usual fix is an idempotency key. The client generates a unique value for each logical operation, sends it in a header, and reuses it on every retry. The server remembers the keys it has seen and the result each produced. A repeat is not executed again; the stored result is sent back. An IETF Internet-Draft defines an Idempotency-Key request header for this. It is still a draft (the version read for this lesson was draft 09, active and due to expire in May 2027), so treat the details as likely to change. The draft says the value is a structured-field string, written in quotes on the wire as Idempotency-Key: "8e03978e-...", and recommends a UUID or similar random value. The demo below reads the bare text without quotes, which is a simplification. It says a server should answer 422 if a key arrives with a different payload, and 409 if the first request with that key is still running.
The mechanism
The server follows four steps. Claim the key by inserting a row, which a unique primary key makes atomic. If the insert succeeded, run the work. Save the response against the key. On a repeat, replay the saved response. The scene shows a retry after a lost reply.
Animated sceneA retry after a lost reply0:15
Watch for the retry reusing the stored result instead of charging again
Read it as steps
The second request with the same key gets the stored result and the gateway is not called again.
Three details make this correct. First, the fingerprint: the server stores a hash of the validated body with the key, so the same key with a different body is detected and rejected instead of replaying the wrong result. Hashing the cleaned body keeps the hash stable when the client orders its JSON keys differently. Second, the first request must write a marker before it does the work, so that a duplicate arriving while the first is still running finds the marker and gets a 409. Third, the key must be passed on to the payment gateway as well, because a crash between the gateway call and the database write would otherwise charge twice.
The store
The first fragment creates the database and three tables. The idempotency table holds the key, the fingerprint, and the saved status and body. claim inserts the row and reports whether this request created it, using ON CONFLICT DO NOTHING. lookup reads a row, and release deletes a marker when the work fails so that a retry can try again.
js
import { PGlite } from'@electric-sql/pglite';
exportconst db = new PGlite();
await db.exec(`
CREATETABLE orders (id serial PRIMARY KEY,
customer text, amount int);
CREATETABLE payments (id serial PRIMARY KEY,
order_id int, amount int);
CREATETABLE idempotency (key text PRIMARY KEY,
fingerprint text NOT NULL, status int, body jsonb)`);
store.mjs, the database and tables
js
exportasyncfunction claim(key, fp) {
const r = await db.query(
`INSERT INTO idempotency (key, fingerprint) VALUES ($1, $2)
ON CONFLICT (key) DO NOTHING RETURNING key`, [key, fp]);
return r.rows.length === 1;
}
exportasyncfunction lookup(key) {
const r = await db.query(
`SELECT fingerprint, status, body FROM idempotency
WHERE key = $1`, [key]);
return r.rows[0];
}
exportconst release = (key) =>
db.query('DELETE FROM idempotency WHERE key = $1', [key]);
store.mjs, three helpers
placeOrder does the database work in one transaction: the order, the payment row, and the saved response. They commit together or not at all.
The first fragment above is the top of the file: its imports and the Pay schema, the key pattern and the app. This script sends the cases and then counts the payment rows.
js
import { app } from'./idem-app.mjs';
import { db } from'./store.mjs';
const server = app.listen(55603, '127.0.0.1');
const post = async (key, amount) => {
const r = await fetch('http://127.0.0.1:55603/orders', {
method: 'POST',
headers: { 'content-type': 'application/json',
'idempotency-key': key },
body: JSON.stringify({ customer: 'Meera', amount }),
});
const body = await r.json();
const tag = r.headers.get('x-replayed') ? ' (replayed)' : '';
console.log(r.status + tag, body.orderId ?? body.title);
};
console.log('-- retry after a timeout');
await post('order-0001-meera', 450);
await post('order-0001-meera', 450);
console.log('-- same key, different amount');
await post('order-0001-meera', 900);
console.log('-- two at once');
await Promise.all([post('order-0002-meera', 300),
post('order-0002-meera', 300)]);
await post('order-0002-meera', 300);
const c = await db.query('SELECT count(*)::int AS n FROM payments');
console.log('payments charged:', c.rows[0].n);
server.close();
l5-run.mjs
text
-- retry after a timeout
2011201 (replayed) 1
-- same key, different amount
422 Key reused, new body
-- two at once
409 Still running
2012201 (replayed) 2
payments charged: 2
Node 24.18.0, PGlite 0.5.15 in the same process.
A retry with the same key returned the same order and was marked as replayed. The same key with a different amount was refused with a 422. When two identical requests arrived together, one ran and the other saw the marker and got a 409 problem; a client should wait and retry, and its next call received the stored 201. Two keys were used, and two payments were charged.
Two cautions remain, both stated from design and not from the run. If the process dies after the marker is written but before the work finishes, the key stays "in progress" until something clears it, so real systems store a creation time and treat old markers as abandoned. And a key should be scoped to the caller, with a unique constraint on the pair of user and key, so that one customer's key cannot collide with another's.
Why is POST retried with an idempotency key but DELETE is not?
RFC 9110 classes DELETE as idempotent, so a repeat has the same effect as one call. POST is not, so a repeat can create a second order or charge, and the key lets the server detect it.
A client reuses the key order-0001 with a different amount. What does the server do?
It compares the stored fingerprint with the new body, sees a mismatch, and refuses with a 422 problem. It does not replay the old result or run the new one.
Two identical requests with one key arrive at the same moment. How does exactly one of them run?
The key column is a primary key and the insert uses ON CONFLICT DO NOTHING, so only one insert succeeds. The other finds the unfinished marker and answers 409, and its retry later gets the stored result.
Part 6 · Fastify: schemas, plugins and hooks
What Fastify does differently
Fastify is a web framework built around schemas and plugins. Its routes carry JSON Schema for the body, query string, headers and response, and the framework validates and serialises with them.
JSON Schema is a standard vocabulary for describing JSON, written as JSON itself. Fastify checks each schema with Ajv, a validator. A route lists its schemas next to its handler, so the rules and the code that depends on them sit together. Compare that with the previous lessons, where a zod middleware was attached to an Express route. Both work. Fastify makes the schema part of the route definition.
The schemas for the route below are plain objects. additionalProperties: false says unknown keys are not allowed. The response schema lists the only fields that may leave the server.
The app registers a custom error handler that turns Fastify's validation errors into a problem. It builds the app in a function and does not call listen, which is what lets tests use the app without a port.
There are three routes: a POST that returns more than it should, an echo that returns the body unchanged, and a list that takes a limit query parameter. The script uses app.inject, which calls the app directly, without opening a port.
good 201 application/json
{"id":1,"customer":"Meera","status":"placed"}
extra 201 application/json
{"id":1,"customer":"Meera","status":"placed"}
echo 200 application/json
{"customer":"Meera","items":[{"sku":"IDL-001","qty":2}]}
bad 400 application/problem+json
/customer must NOT have fewer than 1 characters
q=5200 application/json
{"limit":5,"type":"number"}
q=abc 400 application/problem+json
/limit must be integer
q=none 200 application/json
{"limit":10,"type":"number"}
Node 24.18.0, Fastify 5.12.8.
Four things the run shows
Read the output closely, because each line is a Fastify default that differs from what many developers expect. The Fastify validation reference lists the defaults: coerceTypes is set to "array" (conversion is on), useDefaults is on, removeAdditional is on, and allErrors is off.
Extra properties were removed, not rejected. The extra payload carried admin: true and returned 201, and the echo route shows the handler received no admin. With removeAdditional on, additionalProperties: false strips the key silently. If you want a 400, change the Ajv options or add a check.
Only the first error was reported. The bad body broke three rules, and the response lists a single problem. With allErrors off, Ajv stops at the first failure. The docs warn that turning it on can open the door to a denial-of-service attack, so it stays off unless you bound the input.
Query values were coerced.limit=5 reached the handler as a number, a missing limit took the default 10, and limit=abc failed with "must be integer".
The response schema removed a field. The handler returned margin: "30%", and the client never saw it. A response schema is a safety net against leaking fields such as password hashes.
Notice what is not in the 400 body: the default Fastify validation error has statusCode, code, error and message (a run of the same route without a custom handler printed FST_ERR_VALIDATION as the code), and here a custom error handler turned the validation array into the problem format from the second lesson. The shape of your errors is your decision, not the framework's.
Plugins, encapsulation and hooks
A plugin is an async function that receives a Fastify instance and adds routes, hooks or decorators to it. A hook runs at a stage of the request, such as onRequest, before the handler. Plugins create encapsulation: according to the Fastify docs, what a plugin registers flows down to its child contexts and not up to its parents. A hook added inside a plugin guards only the routes in that plugin.
/menu is open and /staff/report is rejected without the header. Both are in one app, but the hook lives in the staff plugin, so /menu, registered outside it, is unaffected. The docs say that wrapping a plugin with fastify-plugin breaks this encapsulation on purpose, which is how shared things such as a database connection are made visible to the whole app.
A payload contains a key that the schema does not declare, and the schema says additionalProperties: false. Fastify with its defaults responds with what?
It succeeds. The default removeAdditional option strips the unknown key before the handler runs, so the request is not rejected. You must change the Ajv options to get a 400.
The handler returns an object with a field that the response schema omits. What does the client receive?
The object without that field. Fastify serialises with the response schema, so only declared properties leave the server.
A hook is added with addHook inside a plugin. Which routes does it affect?
Only the routes registered in that plugin and in plugins nested inside it. Routes in the parent or in sibling plugins are not affected, unless the plugin is wrapped with fastify-plugin.
Part 7 · Express or Fastify, versioning and OpenAPI
Choosing a framework
Both frameworks run production services, and the choice rests on how you want to work. This table lists differences that this chapter and the databases chapter showed in running code, not claims about speed.
Question
Express 5
Fastify 5
Validation
your choice of library, added as middleware (zod here)
JSON Schema on the route, checked by Ajv
Output filtering
you write it
a response schema drops undeclared fields
Async errors
a rejected promise from a handler reaches the error middleware
async handlers are native; errors reach the error handler
Structure
middleware order matters, one shared app
plugins with encapsulated contexts
Testing without a port
needs a listening server or an extra library
app.inject is built in
A team that already runs Express and knows its middleware has little reason to move in the middle of a project. A new service gains from Fastify's schema-first routes. The rest of this course uses whichever the lesson needs, and the ideas (validate at the edge, one error shape, idempotency) are the same in both.
Versioning an API
Once other people depend on your API, you cannot change it freely. Some changes are safe for existing clients: adding a new optional field to a response, or a new endpoint. Others break clients: removing or renaming a field, changing a type, or making an optional request field required. When you must make a breaking change, you publish it as a new version and keep the old one alive for a while.
There are two common ways to name a version. In the URL: /v1/orders/7 and /v2/orders/7. It is visible, easy to test with a browser, and each version can be its own plugin. In a header: the client sends Accept-Version: 2.x, and the address stays the same. Fastify supports this directly through route constraints. The docs say the header should follow semver, that a route without a matching version is not found, and that responses should set a Vary header naming the versioning header so that caches do not mix versions.
The fragment below is the rest of the file from the last lesson. The URL versions are two plugins with prefixes. The header versions are two routes with the same path and different version constraints.
200 /menu {"items":["idli","dosa"]}
401 /staff/report {"error":"staff only"}
200 /staff/report x-staff=1 {"orders":41}
200 /v1/orders/7 {"total":450}
200 /v2/orders/7 {"total":{"amount":450,"currency":"INR"}}
404 /items Not Found
200 /items accept-version=1.x {"shape":"v1: names only"}
200 /items accept-version=2.x {"shape":"v2: names and prices"}
404 /items accept-version=3.x Not Found
Node 24.18.0.
The /v2 route returns an object where /v1 returned a number, which is exactly the kind of change that needs a new version. For the header style, the run shows a request with no Accept-Version header got a 404, and so did a request for 3.x, which no route declares. Exact matching rules are in the Fastify routes reference. Whichever style you pick, run old versions until you know nobody calls them, and say in the response docs when a version will end.
Describing the API, and testing it
A written description of your API lets clients and tools generate code, documentation and tests. The OpenAPI Specification is the common format: a JSON or YAML document that lists paths, methods, parameters, request and response schemas, and security schemes. Fastify has plugins that build an OpenAPI document from the route schemas, for example @fastify/swagger; they are not run in this lesson. With zod, a similar conversion exists from schema to JSON Schema. Either way, keeping the description generated from the schemas you validate with prevents the document and the code from drifting apart.
Tests close the loop. Because buildApp returns an app without listening, a test can call inject directly. The file below checks two behaviours from this chapter: extra fields are hidden in the response, and a bad quantity produces a problem that points at the right field.
▶ POST /orders
✔ creates an order, hides extras (68.6034ms)
✔ rejects a quantity of 0 (3.7918ms)
✔ POST /orders (197.1124ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 430.8439
Node's built-in runner. Durations vary from run to run.
The after hook closes the app when the tests end, so the process can exit. The Fastify testing guide recommends this split between building the app and listening on a port, because tests then need no free port and no cleanup. The testing chapter later in this course goes further, with a database per test file.
To close the chapter, here is the order of defence for an incoming write. The schema stops malformed data. The handler applies business rules and returns a 422 when they fail. The idempotency key makes retries safe. The problem format tells the client which of these happened. Each layer answers a different question, and none replaces the others.
Term
Meaning
Trust boundary
the line where outside data enters your process
Problem details
the JSON error format of RFC 9457
Keyset paging
paging by a remembered sort value instead of a position
Idempotency key
a client-chosen value that lets the server detect a repeated request
Encapsulation
a Fastify plugin's hooks and decorators apply only to its own context
You rename a response field from total to amount. Is that a safe change for existing clients?
No. Removing or renaming a field breaks clients that read it. Publish it as a new version, or add amount and keep total until clients move.
Why does this chapter build the Fastify app in a function that does not call listen?
A test can then call app.inject without a port, and several tests can run at once without clashing over one.
What does an OpenAPI document describe?
The paths, methods, parameters, request and response schemas and security schemes of an HTTP API, in one JSON or YAML file that tools can read.