Capstone: a paginated, filtered, transactional endpoint
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Combine validation, authorization, cursor pagination and an index in one endpoint.
- Use a transaction for the write path and idempotency for retries.
- Explain the query plan and the failure modes of the endpoint.
Overview
#This capstone assembles the course: a GET /articles list with cursor pagination and filters, and a POST /articles write that is validated, authorized, transactional and idempotent.
Cursor pagination
Offset pagination drifts when rows are inserted. Cursor pagination keys on the last seen sort value.
SELECT id, title, created_at
FROM articles
WHERE tenant_id = $1
AND status = $2
AND (created_at, id) < ($3, $4)
ORDER BY created_at DESC, id DESC
LIMIT 21;
Fetch one extra row to know whether a next page exists. The composite index (tenant_id, status, created_at DESC, id DESC) serves the filter and the order. The query above is the 'after cursor' form; for the first page there is no cursor, so omit the row-comparison predicate (or guard it with a NULL check, as the exercise does) to return the first page.
The write path
app.post('/articles', requireAuth, asyncHandler(async (req, res) => {
const { errors, value } = parseCreateArticle(req.body);
if (errors.length) return res.status(422).json({ error: { code: 'validation_error', details: errors } });
const key = req.header('Idempotency-Key');
const result = await createArticle({ tenantId: req.user.tenantId, value, key });
res.status(result.created ? 201 : 200).json(result.article);
}));
createArticle runs in a transaction: insert the article and the idempotency key together; on a unique-key conflict, return the stored article with created: false.
Failure modes to state
- A missing or expired cursor returns the first page.
- A duplicate idempotency key returns the original result, not an error.
- A cross-tenant id returns 404, never another tenant's data.
- A slow query is caught by the duration metric before it becomes an outage.
Common pitfalls
- Mixing offset and cursor pagination in one endpoint.
- Forgetting to bound
limitso a client can request everything. - Writing the article and the idempotency key in separate transactions, which allows a duplicate on retry.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Write the cursor pagination query for the first page and for the page after a cursor (created_at, id), returning one extra row to detect a next page.
starter.sql-- articles(id, tenant_id, status, title, created_at) -- params: tenantId, status, cursorCreatedAt, cursorIdReveal the reference answer
reference.sqlSELECT id, title, created_at FROM articles WHERE tenant_id = $1 AND status = $2 AND ($3::timestamptz IS NULL OR (created_at, id) < ($3, $4)) ORDER BY created_at DESC, id DESC LIMIT 21;Authored expected output: Up to 21 rows; if 21 are returned, the client has a next page and uses the 20th row as the next cursor.
A NULL cursor returns the first page. The row comparison (created_at, id) < (cursorCreatedAt, cursorId) continues after the last seen row without drift.
Exercise 2Test
List four assertions you would write for POST /articles covering validation, authorization, idempotency and conflict.
starter.text// describe the assertions, not the test runnerReveal the reference answer
reference.text1) A body with a two-character title returns 422 with a details entry for title. 2) A request without a valid session returns 401, and one from another tenant fetching an existing id returns 404. 3) Sending the same Idempotency-Key twice creates one row and returns the same article with 201 then 200. 4) A duplicate (tenant_id, slug) returns 409 rather than a 500.Authored expected output: Four assertions: validation 422, auth 401 and cross-tenant 404, idempotent replay, and duplicate conflict 409.
These assertions pin the contract at the boundaries where the endpoint is most likely to regress.
Common misconceptions
#- Cursor pagination is just offset with an id: it keys on the last sort value and does not drift on insert.
- An idempotency key is a client concern only: the server must store and check it to prevent duplicates.
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.