Chapter 11 — API Evolution at Scale: Versioning, Pagination, Validation, Rate Limiting
Part III · APIs as Contracts | Prerequisites: Ch 10 | Builds: versioning, keyset pagination, validation, and rate limiting for Pulsely
Earlier you learned to treat an API as a contract — resources, verbs, status codes, idempotency, structured errors — and you froze that contract in an OpenAPI document. But a contract you signed yesterday has to survive tomorrow: more data, more clients you can't redeploy, more traffic from callers who don't care about your capacity. That clean design was the contract at rest. This chapter is the contract under load and over time. It is where APIs that demoed beautifully start timing out at 3 a.m., where a one-line field rename blanks out three versions of a patient-facing app, and where a single misbehaving partner starves everyone else.
Four disciplines keep a published contract honest as data, clients, and traffic all grow: evolving compatibly (you add, you don't mutate), paginating with a stable cursor (not a fixed grid over a moving stream), validating at the boundary (parse untrusted bytes into typed values before they touch your domain), and rate limiting fairly (allocate scarce capacity as a budget, not a wall). We'll build all four into Pulsely. This is a heavy, code-dense chapter on purpose — these are the four mistakes that most reliably turn a working API into an incident.
1. The problem: the contract under load and over time
It's 3 a.m. and PagerDuty is screaming. Pulsely's /encounters timeline — the chart-activity feed a clinician scrolls to see everything that's happened to a patient — is timing out, but only sometimes, and only for certain patients. You pull the slow-query log and there it is:
SELECT * FROM encounters ORDER BY created_at DESC LIMIT 20 OFFSET 84000;
A caller — a reporting integration syncing a long-history patient's chart — is paging through the timeline with ?page=4200&limit=20. To serve page 4200, Postgres doesn't skip 84,000 rows for free — it walks the index, materializes and then throws away 84,000 rows, and finally returns the 20 you asked for. The cost of a page is proportional to how deep it is. Page 1 is instant; page 4200 is an eight-second table-walk. And because that query holds a connection from the pool for those eight seconds, and the pool is finite (the stateless server borrows from a shared, bounded pool of DB connections), the slow deep-paginators drain connections, queue piles up behind them, and unrelated endpoints start timing out. One cheap-looking request became a chain-wide saturation event — exactly the backpressure mechanic you already know: in a chain of finite-capacity stages, the slowest stage sets the pace, and the queue grows behind it.
That's the latency pain. There's a correctness pain hiding in the same design. A clinician is scrolling a patient's chart timeline. They read page 1 (the 20 newest chart entries — notes, vitals, results), then a nurse records a new vital, then they request page 2. But "page 2" now means "rows 21–40 of the current ordering" — and the new reading pushed everything down by one. So the entry that was row 20 on page 1 is now row 21, and the clinician sees it again on page 2. Worse, if an entry is retracted between requests — say, a result that posted to the wrong patient and gets pulled — page 2 starts at what is now row 21, silently skipping a chart entry the clinician will never see. Offset pagination over a mutable, time-ordered set is inherently inconsistent: a page number is a coordinate in a snapshot that no longer exists.
Now the evolution pain. Pulsely's product team wants to rename note.body to note.content — cleaner, more consistent with addendum.content. In a monolith you'd do it in one commit. But this field is consumed by a patient-portal iOS app, three versions of which are installed on phones you will never touch. Version 4.2, downloaded by a patient who turned off auto-update, does note.body.substring(0, 200) to render a note preview in their visit summary. The day body disappears from the response, that app throws on undefined.substring and the summary renders blank for every patient still on 4.2. You cannot force-upgrade the fleet. The old field can therefore never simply disappear.
Two more, quickly. A single integration partner writes a buggy sync loop that calls GET /orders five hundred times a second. There's no limit, so that one tenant consumes capacity meant for everyone — a self-inflicted denial of service. And a client sends ?limit=10000000 or ?sort=ssn; the boundary trusts it, passes it to the query layer, and now the client's bug (or attack) is your outage or your PHI leak.
🧭 The framing. An API is a contract held over time with clients you don't control and can't redeploy. Everything before this designed the contract; this chapter keeps it honest as three things grow independently: the dataset (pagination), the client fleet (versioning), and the traffic (rate limiting) — with validation as the boundary that keeps all three from being poisoned by untrusted input. Tutorials skip these because they demo with ten rows, one client, and no adversary. Production has none of those luxuries — and in healthcare, "poisoned by untrusted input" can mean a leaked chart or a mis-attributed result.
2. The mental model: additive change, stable cursors, typed boundaries, fair budgets
Hold four pictures, one per discipline. They're independent, but they share a single spine: the client is untrusted and uncoordinated, and the system grows underneath a contract you've already published.
The API as a published contract, not a function call. A function you can change because you recompile every caller. An API you cannot, because the callers are out there, compiled, on phones and partner servers. The instant a field is consumed by a client you can't redeploy, it is load-bearing forever. So the only safe move is additive: you add new fields and endpoints; you don't mutate or remove existing ones without a deliberate, gated migration. This flips your instinct. In application code, renaming is hygiene. In a public contract, renaming is a breaking change in disguise.
Compatibility is directional. Two distinct properties hide under "compatible." Backward compatible means a new server tolerates an old client — the server you just deployed still answers requests shaped the way last year's app sends them. Forward compatible means an old client tolerates a new server — last year's app doesn't choke when this year's server adds a field it's never heard of. You design for both. Backward compatibility is on you (don't remove what old clients need); forward compatibility is a property you require of clients — the tolerant reader: clients must ignore unknown fields, not crash on them. State this in your client SDK and your docs, because you're depending on it.
Pagination as a stable cursor through a moving stream, not a fixed grid. The wrong mental image is a spreadsheet: page = rows (n × p) to (n × p + n). That image assumes the grid is frozen. The right image is a bookmark in a river: "give me what comes immediately after this exact point." A page number is a position in a snapshot that no longer exists by the time you ask for the next one. A cursor is a position in the data itself — "the last thing you saw was the entry created at T with id X; here's what's older than that" — and it stays correct no matter how many entries are inserted or retracted around it.
OFFSET model (a grid over a snapshot that's already gone):
page 1: [ 1 2 3 4 5 ] ← insert happens here
page 2: [ 5 6 7 8 9 ] ← "5" repeats; nothing guarantees no skips either
KEYSET model (a bookmark in the live stream):
"after (T_5, id_5)" → [ 6 7 8 9 10 ] ← stable across inserts/deletes
The boundary as a customs checkpoint. Untyped, untrusted bytes arrive from the network. Nothing crosses into your domain until it's been inspected and stamped into a known shape. The discipline here is "parse, don't validate": don't run a gauntlet of if checks and then pass the same loose any through — produce a new, typed value that, by its existence, proves the checks passed. After the boundary, your handler receives CreateOrderInput, not req.body: any. The domain layer becomes unreachable by unvalidated data, which means a whole class of bugs simply cannot be written.
Rate limiting as a fairness-and-protection valve. You're not only blocking abuse. You're allocating a scarce shared resource — your finite capacity — across many tenants so that no single caller can starve the rest. It's a budget, not a wall: each key gets an allowance, replenished over time, and when they exceed it you shed them cheaply (a fast 429) rather than letting them sink the shared connection pool.
🧭 Mental model. One line ties the four together: additive change, stable cursors, typed boundaries, fair budgets. Each is the discipline that lets one axis of growth — clients, data, input, traffic — scale without breaking the contract the others depend on.
3. Theory & invariants
A model tells you how to picture things; invariants tell you what must stay true. Here are the load-bearing rules for all four disciplines.
Compatibility: the contract algebra
There's a small algebra of what you may and may not do to a published contract.
Safe (backward-compatible) changes: add an optional field to a response; add a new endpoint; add a new optional request field; add a new enum value only if clients are documented to tolerate unknowns; widen inputs (accept more than before) and narrow outputs (the server promises at least as much as before, never less of what was promised).
Breaking changes: remove or rename a field; make an optional field required; tighten a constraint (maxLength from 500 to 200); change a field's type (string → number); change the semantics of an existing field (same name, new meaning — the cruelest break, because nothing fails loudly); change an error's shape or a status code's meaning.
🔑 The append-only invariant. A published contract is append-only. You may add to it; you may not subtract from or redefine what's already there — not without a new version and a migration window. The asymmetry that forces this: you control the server; you do not control the fleet of deployed clients. You can deploy a fix in seconds. They upgrade on their own schedule, or never. The contract is the only thing you both touch, so it can only grow.
🔑 The tolerant-reader invariant. Clients must ignore fields they don't recognize and must not break on new ones. This is the dual of append-only: it's what makes additive change safe. If even one important client crashes on an unknown field, then adding a field is a breaking change for you, and you've lost the ability to evolve at all. So you require tolerant reading explicitly — in the SDK, in the docs — and you treat any client that violates it as a bug on their side, not a constraint on yours.
Versioning vocabulary
A version names a frozen contract. Major versions are breaking (v1 → v2); minor/additive changes happen within a major version without a version bump (that's what append-only buys you). The invariant: a published major version's responses are append-only until a formal sunset. You don't quietly change v1 because v2 exists; v1 keeps its promises until you've announced its death, watched its traffic fall to zero, and removed it deliberately.
Pagination invariants
Two properties define correct pagination under concurrent mutation:
- Stability: an item appears at most once across all pages, absent edits to that item. (No duplicates like the repeated row 5.)
- Completeness: no item that existed before and after your scan is silently skipped. (No gaps from the retracted-row case.)
Offset pagination violates both the moment the underlying set mutates. Keyset preserves both — given a total order.
🔑 The total-order invariant for keyset. The sort key must be unique and stable, or made unique with a tiebreaker.
created_atalone is not unique — two entries can share a millisecond — so a cursor oncreated_atwill skip or duplicate the tied rows. The fix is a composite key with a guaranteed-unique tiebreaker:(created_at, id). The cursor encodes the full tuple of the last row seen, and the query asks for everything strictly after that tuple in the total order. Without a total order, "the next page" is literally undefined — and so is the correctness of pagination itself.
A corollary worth stating: without an explicit, deterministic ORDER BY, pagination is meaningless. "Page 2" assumes a stable sequence; an unordered query returns rows in whatever order the executor felt like today, so page 2 has no defined relationship to page 1.
Validation as a total function
🔑 The boundary invariant. A validator is a total function from
unknowntoResult<Typed, Errors>. Total function is just a precise name for a contract you already know from the frontend: it is defined for every possible input and never throws — hand it anything the client sent, garbage included, and it returns either clean typed data or a structured list of errors, exactly the way a well-written form validator behaves, never an exception that blows up the caller. It accepts any input and always returns either a typed value or a structured error, never throwing past the boundary and never letting unvalidated data through. The domain must be unreachable by untyped input. And it must whitelist, not blacklist: enumerate what's allowed and reject everything else, because you can't enumerate every malicious input but you can enumerate every valid one.
Rate-limit semantics
Four parameters define any limit: limit (capacity — how many units), window (the period over which capacity refills or resets), cost (units consumed per request — usually 1, but an expensive search might cost 5), and key (the dimension you count by — user, API key, IP). Two correctness properties: limits must be enforced consistently across all instances (a per-instance counter behind a load balancer is a lie — see §4), and the algorithm must not permit boundary bursts — the "double-window" flaw where a client fires a full window's worth at the end of one window and another full window's worth at the start of the next, doing 2× the intended rate across the seam.
4. Under the hood: the mechanics that make it work
Let's get concrete. Each discipline has a precise mechanism, and the mechanism is where the correctness lives.
Offset vs keyset SQL, side by side
Here is the whole pagination argument in two queries.
-- OFFSET: O(offset). Postgres walks the index from the top, counts past
-- 84,000 rows, materializes and DISCARDS them, then returns 20.
SELECT * FROM encounters
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 84000;
-- KEYSET: O(log N + n). An index range scan jumps STRAIGHT to the cursor
-- position via the B-tree, then reads 20 rows forward. Deep pages cost
-- the same as page 1.
SELECT * FROM encounters
WHERE (created_at, id) < ($cursor_ts, $cursor_id) -- row-value comparison
ORDER BY created_at DESC, id DESC
LIMIT 20;
The WHERE (created_at, id) < ($ts, $id) is a row-value comparison: Postgres treats (created_at, id) as one combined key and compares it the way a dictionary orders words — first by the first column, and only when those tie does it look at the second. (That word-by-word ordering is what lexicographically means, and it exactly matches the (created_at DESC, id DESC) sort.) Here's why that's fast. The index is physically stored in that exact order, so the database can jump straight to your cursor position — a seek — instead of reading everything from the top and throwing away what comes before the cursor — a scan-then-filter. For the seek to happen at all, you need a composite index whose columns and their directions match the ORDER BY exactly; if a direction disagrees, Postgres can't walk the index in one clean sweep and falls back to reading-then-discarding:
CREATE INDEX idx_encounters_timeline ON encounters (created_at DESC, id DESC);
OFFSET 84000 KEYSET WHERE (ts,id) < cursor
┌─────────────────────────┐ ┌─────────────────────────┐
│ ███████ scan + discard │ │ · │
│ ███████ 84,000 rows │ │ index seek ─┐ │
│ ███████ (work thrown │ │ ▼ │
│ ███████ away) │ │ ▓▓ read 20 │
│ ▓▓ read 20 (kept) │ │ (kept) │
└─────────────────────────┘ └─────────────────────────┘
cost ∝ page depth cost ∝ page size (flat)
The keyset cost is flat in page depth — page 5000 is as cheap as page 1 — which is the entire point. The tradeoff (you give up arbitrary jump-to-page) we'll handle in §7.
Cursor encoding
The cursor is the sort tuple of the last row, but you must not expose it raw. Encode it as opaque, signed bytes:
import { createHmac, timingSafeEqual } from 'node:crypto';
type Cursor = { ts: string; id: string };
const SECRET = process.env.CURSOR_SECRET!; // server-only
function encodeCursor(c: Cursor): string {
const payload = Buffer.from(JSON.stringify(c)).toString('base64url');
const sig = createHmac('sha256', SECRET).update(payload).digest('base64url');
return `${payload}.${sig}`;
}
function decodeCursor(raw: string): Cursor {
const [payload, sig] = raw.split('.');
const expected = createHmac('sha256', SECRET).update(payload ?? '').digest('base64url');
const a = Buffer.from(sig ?? '', 'base64url');
const b = Buffer.from(expected, 'base64url');
// constant-time compare; reject tampered or hand-crafted cursors
if (a.length !== b.length || !timingSafeEqual(a, b)) {
throw new BadCursorError('cursor signature invalid');
}
return JSON.parse(Buffer.from(payload!, 'base64url').toString());
}
Two reasons for this. Opacity (base64url of an internal structure) means the cursor is yours to change — swap created_at for a sequence number later and no client notices, because they only ever echo back the blob you gave them. Signing (HMAC) means a client can't hand-craft a cursor to probe WHERE (ts, id) < (anything I want) and iterate slices of a chart they shouldn't reach; a tampered cursor fails the constant-time signature check and is rejected. (Use timingSafeEqual, not ===. A normal === stops at the very first byte that differs — so a forged cursor that gets the first few bytes of the signature right returns very slightly slower than one that's wrong immediately, and an attacker who can measure that timing can reconstruct the signature one byte at a time. timingSafeEqual always takes the same amount of time regardless of where the mismatch is, closing that side channel — the same constant-time discipline that protects token comparison; the cryptographic why is Chapter 31.)
The validation pipeline with zod
Validation sits in middleware that runs before any handler. It parses body, query, and params, attaches a typed result to the request, and short-circuits with a structured 400 if parsing fails — so handlers are guaranteed clean input.
import { z } from 'zod';
import type { RequestHandler } from 'express';
// One schema → both the runtime check AND the TypeScript type. They cannot drift.
const EncounterQuery = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20), // query strings are strings
cursor: z.string().optional(),
sort: z.enum(['new', 'oldest']).default('new'), // allow-list, not free text
}).strict(); // reject unknown keys
type EncounterQuery = z.infer<typeof EncounterQuery>; // inferred, never hand-written
function validate<S extends z.ZodTypeAny>(where: 'body' | 'query' | 'params', schema: S): RequestHandler {
return (req, res, next) => {
const result = schema.safeParse(req[where]);
if (!result.success) {
// RFC 9457 problem+json with field-level detail
return res.status(400).type('application/problem+json').json({
type: 'https://errors.pulsely.health/validation',
title: 'Invalid request',
status: 400,
errors: result.error.issues.map(i => ({
field: i.path.join('.'),
code: i.code,
message: i.message,
})),
});
}
(req as any).validated = { ...(req as any).validated, [where]: result.data };
next();
};
}
// usage — the handler now receives a fully typed, trusted value:
app.get('/v1/encounters', validate('query', EncounterQuery), async (req, res) => {
const q = (req as any).validated.query as EncounterQuery; // typed; bounds already enforced
res.json(await encounterService.page(req.user.id, q));
});
The load-bearing details: z.coerce.number() because every query-string value arrives as a string; .strict() so an unexpected key (a client typo, or a mass-assignment probe) becomes a loud 400 instead of a silent ignore; z.infer so the DTO type and the runtime validator are the same source and can never drift; and refinements for cross-field rules (e.g., reject a request that sends both cursor and page — pick one paging mode):
const ListQuery = z.object({ cursor: z.string().optional(), page: z.coerce.number().optional() })
.refine(q => !(q.cursor && q.page), { message: 'cursor and page are mutually exclusive' });
This same boundary is where a patient, encounter, or claim DTO earns its keep. A CreateEncounter body carries a patient reference, an encounter type, and a state that must be one of a fixed clinical set (scheduled | arrived | in-progress | signed | billed); a claim DTO carries a charge_amount_cents, a payer, and diagnosis/procedure codes that must be real ICD-10 / CPT values. Each of these is exactly the enum/range/shape check zod is built for — and each one caught at the boundary is a malformed encounter or a rejected claim that never reaches your domain in the first place.
Rate-limit algorithms: token bucket vs sliding window
Three algorithms, in order of sophistication.
Fixed window is the naive one: count requests per calendar minute, reset to zero at the top of the minute. It's simple and it's wrong at the edges — a client can send the full limit in the last second of 10:00 and the full limit again in the first second of 10:01, doing 2× the rate across the boundary.
Token bucket models a bucket of capacity C that refills at rate r tokens/sec. Each request costs one token; if a token's available, allow and decrement; if empty, reject. It permits controlled bursts up to C (good for spiky-but-legit clients) while bounding the steady-state rate to r.
// In-process token bucket — correct for ONE instance only (see the caveat below).
type Bucket = { tokens: number; lastRefill: number };
const buckets = new Map<string, Bucket>();
function allow(key: string, capacity = 100, refillPerSec = 10, cost = 1): boolean {
const now = Date.now();
const b = buckets.get(key) ?? { tokens: capacity, lastRefill: now };
// refill proportionally to elapsed time, capped at capacity
const elapsedSec = (now - b.lastRefill) / 1000;
b.tokens = Math.min(capacity, b.tokens + elapsedSec * refillPerSec);
b.lastRefill = now;
if (b.tokens >= cost) {
b.tokens -= cost;
buckets.set(key, b);
return true;
}
buckets.set(key, b);
return false;
}
Sliding-window counter approximates a true sliding window by blending the current fixed window's count with a weighted fraction of the previous window's, based on how far into the current window you are. It's the common production pick: smoother than fixed window, far cheaper than a sliding-window log (which stores every request timestamp — exact but memory-heavy).
Sliding-window counter at time t, 40% into the current minute:
estimate = current_count + previous_count * (1 - 0.40)
It "remembers" 60% of the prior window's load, killing the boundary burst
without storing individual timestamps.
The 429 response carries the contract for when to come back:
function reject429(res: Response, retryAfterSec: number, limit: number, remaining: number, resetEpoch: number) {
res.set('Retry-After', String(retryAfterSec)); // the load-bearing one
res.set('RateLimit-Limit', String(limit));
res.set('RateLimit-Remaining', String(remaining));
res.set('RateLimit-Reset', String(resetEpoch));
res.status(429).type('application/problem+json').json({
type: 'https://errors.pulsely.health/rate-limited',
title: 'Too Many Requests', status: 429,
detail: `Retry after ${retryAfterSec}s`,
});
}
Why the in-process limiter is a lie behind a load balancer
That Map-based bucket is correct for one process. But earlier you saw that "the server" is plural — N identical instances behind a load balancer. Each instance has its own buckets map, so a limit of "100/min per user" becomes "100/min per instance," i.e. 100 × N/min globally. A client whose requests fan out across 10 instances gets 1000/min. The counter doesn't enforce the limit; it under-counts by a factor of N.
The correct fix is a single shared store that all instances atomically read-modify-write. The naive attempt — INCR the counter, then EXPIRE it — is a bug. Those are two separate round trips to Redis:
- In between them, a second request from the same user can slip in — that's a race, two operations interleaving in an order you didn't intend.
- Or the process can crash after the
INCRbut before theEXPIRE, leaving a counter that was incremented but never given an expiry.
Because nothing will ever clear that counter, it is now immortal and that user is locked out of the key forever. The fix is to do the increment-and-set-expiry as one indivisible step so nothing can slip in between. The real implementation does the whole read-modify-write in a single atomic operation: a Redis Lua script that refills the bucket, checks it, decrements it, and sets the TTL in one round trip with no interleaving.
📎 Borrowed on credit: distributed rate limiting → Ch 21. The algorithms (token bucket, sliding window) and the contract (
429+Retry-After+RateLimit-*headers) are this chapter's to own, and the in-process limiter above is complete and correct for a single instance. But the production-grade distributed limiter — a Redis-backed token bucket with an atomic Lua script that enforces one global limit across N app servers without races — belongs to Redis. Why it lands there: it's fundamentally a Redis atomicity and data-structure problem (single-threaded execution, Lua scripting,EXPIREsemantics), not an API-design problem. For now, absorb the shape: one shared atomic store, or your limit is a per-instance fiction.
Versioning routing mechanics
Three places to carry the version, three routing consequences:
URI path: GET /v2/encounters → routed by path; visible in logs, trivially cacheable
Header: GET /encounters Accept-Version: 2 → invisible in URL; needs Vary: Accept-Version
Media-type: GET /encounters Accept: application/vnd.pulsely.v2+json
→ content-negotiated; "REST-pure"; cache-hostile if Vary mishandled
URI versioning resolves at the router (app.use('/v2', v2Router)) and the version is right there in the access log and the CDN cache key. Header/media-type versioning resolves in a middleware that inspects the header and dispatches, and it must set Vary on that header or a shared cache will serve a v1 response to a v2 request (or vice versa) — a subtle, ugly bug.
JVM contrast, where it teaches
(Skippable if you don't do Java — the transferable payoff is in the last line of each.)
- Bean Validation (JSR-380):
@Valid @RequestBody CreateEncounter dtowith@NotNull,@Max,@Sizeannotations on the DTO is declarative boundary validation — the same "reject at the edge" idea as zod, but the check is attached to the type rather than producing the type. zod'ssafeParsereturns a freshly-typed value (parse-don't-validate); Bean Validation checks an already-deserialized object. Both centralize the boundary; the philosophies differ. Pageable/Page<T>: Spring Data's pagination abstraction is ergonomic —repository.findAll(pageable)— but it defaults to offset (OFFSET/LIMITunder the hood) and even computes atotal_countwith a secondCOUNT(*)query. It quietly carries both the offset cost and the count cost we're trying to escape. The lesson: a convenient abstraction can hide an expensive default; keyset there means dropping to explicit queries.- Bucket4j / resilience4j: token-bucket rate limiters in the JVM ecosystem. Same algorithm, different runtime — proof that the principle (token bucket, refill rate, burst capacity) is portable and the libraries are interchangeable detail.
5. In production: operating the four disciplines
Mechanisms are necessary; an operable policy is what survives a real org of seventeen engineers who'll each invent their own convention if you let them.
A versioning policy you actually run
Pick one scheme and write it down. For public APIs the pragmatic default is URI versioning — /v1, /v2 — because it's visible in logs, trivial to route, easy to cache, and obvious to a human debugging at 3 a.m. Then operate a deprecation lifecycle, not a guillotine:
announce ──▶ emit Deprecation + Sunset headers ──▶ watch old-version traffic metric ──▶ hard sunset (only when usage ≈ 0)
HTTP/1.1 200 OK
Deprecation: true
Sunset: Sat, 31 Oct 2026 23:59:59 GMT
Link: <https://docs.pulsely.health/v2-migration>; rel="deprecation"
You never delete a version because the calendar says so; you delete it because the dashboard says no one is using it.
Expand/contract (parallel change) for field renames
This is how you rename note.body → note.content without a single client crash. Never a big-bang rename — instead, three phases:
EXPAND ─▶ MIGRATE ─▶ CONTRACT
emit BOTH switch readers remove old field
body AND content to content; ONLY when the
(dual-write/emit) old clients still "reads of body"
read body metric hits zero
- Expand: the response includes both
bodyandcontent, identical values. Old clients readbody; new clients readcontent. Nothing breaks because nothing was removed — it's a purely additive change. - Migrate: ship new client versions that read
content. Instrument reads of the old field (or proxy it via version analytics) so you can see the old field's usage fall. - Contract: only when the metric shows ≈ zero consumers of
bodydo you remove it — and that removal is itself announced viaDeprecation/Sunset. The removal gate is a metric, not a date.
This matters more in healthcare than almost anywhere, because a chunk of your fleet is patient-facing apps on personal phones that patients rarely update — the un-upgradable client is the norm, not the exception.
Pagination response envelope
Standardize the shape across every collection (/encounters, /orders, /search):
{
"data": [ /* ...the page of items... */ ],
"page_info": {
"next_cursor": "eyJ0cyI6...", // null when there's no next page
"has_next": true
}
}
And a firm rule: do not return total_count on large, mutable sets. Computing it is the exact expensive full scan you adopted keyset to avoid — a COUNT(*) over the whole table on every page. If product genuinely needs a count, make it a separate, optional, cached or estimated endpoint (Postgres's reltuples estimate is often good enough), never a field on the hot paging path.
Filtering and sorting as an allow-list
A filter or sort parameter is a client-controlled fragment of your SQL. Treat it like one. Map a fixed set of client-facing names to vetted, indexed columns and operators; reject anything off the list:
const SORT_COLUMNS: Record<string, string> = {
new: 'created_at', // backed by idx_encounters_timeline
amount: 'charge_amount_cents', // backed by idx_claims_amount
};
const FILTER_OPS: Record<string, (v: unknown) => string> = {
status: () => 'status = $1',
min_amount: () => 'charge_amount_cents >= $1',
};
// sort=ssn or filter=diagnosis_free_text → not in the map → 400. No exceptions.
Two non-negotiables: every sortable/filterable column must be backed by an index, or it's a latent table scan waiting to be triggered by a single request; and limit has a hard cap (e.g., 100) and a sane default — never an unbounded value the client supplies (back to the ?limit=10000000 pain).
Rate-limit operations
Real limiters are tiered and cost-weighted:
- Tiers by principal: anonymous < authenticated user < paid integration partner. The same endpoint allows more for a trusted, contracted partner key (say, a lab or clearinghouse) than for an anonymous caller.
- Separate read and write budgets: a write storm is more dangerous than a read storm; don't let cheap reads consume the budget that protects expensive writes.
- Cost-weighting: an expensive patient search costs 5 tokens, a cheap
GET /encounters/{id}costs 1. The bucket drains in proportion to the work, not the request count. - The
RateLimit-*headers on every response (not just429), so well-behaved clients can self-throttle before they hit the wall.
And one decision you must make explicitly and document: fail-open vs fail-closed when the limiter store (Redis) is down. Fail-open (allow everything) risks an outage-driven stampede sinking your DB; fail-closed (reject everything) turns a Redis blip into a full API outage. There's no universal answer — choose per endpoint by blast radius: fail-open on read paths, fail-closed on /login and money writes like claim submission.
Observability
Make the failure modes visible as first-class metrics, labeled by route template (not raw path):
- pagination latency per endpoint (catch a keyset regression);
- cursor-decode failures (a spike means client bugs or tampering probes);
- validation-rejection rate (a spike on a normally-clean route means a client shipped a bug or an attacker is fuzzing);
429rate per key — a rising429rate on a normally-quiet key is one of the earliest abuse/incident signals you have.
🏭 The instinct to build. Every one of these disciplines has a number on a dashboard that tells you it's working or failing before a human notices. Keyset keeps pagination p99 flat — so a rising deep-page latency means someone reintroduced offset. Validation rejections should be a low, steady hum — so a spike is a client bug or a fuzzer.
429s per key should be near zero for legitimate tenants — so a climbing line is an integration partner gone rogue or an attack starting. You don't "add metrics later"; the metric is how you operate the thing. (The full observability discipline is Chapter 34.)
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Page 2 shows a chart entry already seen on page 1. Signature: clinicians report duplicates (or quietly miss entries) while scrolling a live chart timeline; it's intermittent and "can't be reproduced" because it only happens when someone inserts or retracts an entry during paging. Fix: stop using offset over mutable, time-ordered data. Switch to keyset with a unique tiebreaker; the cursor is a position in the data, immune to inserts/deletes around it.
/encounters?page=1 is instant, ?page=5000 takes 8 seconds.
Signature: latency that scales with page depth; deep pages drain the connection pool and stall unrelated endpoints.
Fix: that's the O(offset) discard cost. Keyset makes every page as cheap as page 1 (index range scan, flat cost). Bound limit too.
Keyset still skips or duplicates rows.
Signature: you moved to keyset but the bug persists at exactly the rows where timestamps tie.
Fix: your sort key isn't unique. ORDER BY created_at alone breaks on millisecond ties. Add id to both the ORDER BY and the cursor tuple, and make the composite index match ((created_at DESC, id DESC)).
Clients hand-craft cursors and probe other slices of a chart.
Signature: a curious or hostile client decodes your base64 cursor, edits the embedded id, and iterates chart rows they shouldn't reach.
Fix: cursors must be opaque and signed (HMAC). Verify the signature with a constant-time compare on the way in; reject any tampered cursor with a 400.
The rate limiter works locally, leaks in prod. Signature: load tests pass on one box; in production the global rate is N× the configured limit and abuse gets through. Fix: an in-process counter behind a load balancer counts per instance. Move to a single shared atomic store (Redis Lua — Ch 21). One global counter, or your limit is fiction.
Bursty traffic passes the limit at window edges (2× in one second). Signature: a client sends a full window's worth at 10:00:59 and again at 10:01:00 and your fixed-window limiter allows both. Fix: the fixed-window boundary flaw. Use a sliding-window counter or a token bucket, both of which smooth across the seam.
A renamed field crashes old mobile clients. Signature: the visit summary renders blank for patients on an old app version the morning after a "harmless cleanup" rename. Fix: expand/contract. Dual-emit the old and new field through a deprecation window; remove the old field only when its usage metric hits zero. Never mutate a published field in place.
?sort= lets a caller order by an unindexed or sensitive column.
Signature: ?sort=ssn returns rows ordered in a way that leaks information, or ?sort=some_unindexed_col triggers a full table scan on demand.
Fix: allow-list sort (and filter) names mapped to vetted, indexed columns; reject everything off the list with a 400. The client never names a column directly.
Validation passes but extra keys are silently ignored.
Signature: a client sends { contnet: "..." } (typo), your schema ignores the unknown key, the real field is empty, and nobody notices for a week.
Fix: .strict() schemas reject unknown keys with a clear 400, turning silent client typos and mass-assignment probes into loud, early failures.
429 returned, but the client hammers immediately.
Signature: a throttled client retries in a tight loop, making the overload worse, not better.
Fix: always include Retry-After on the 429, and document that clients must back off with jitter. A 429 without a Retry-After is a wall with no sign on it.
7. Tradeoffs
Each discipline is a decision with a spectrum. Senior judgment is naming the spectrum and saying why you stand where you stand — and when you'd reverse.
URI vs header vs media-type versioning. URI (/v1) is visible, cache-friendly, trivial to route, and obvious in logs — at the cost of being "ugly" and coupling the version to the path. Media-type (application/vnd.pulsely.v2+json) is REST-pure and content-negotiated, but it's invisible in URLs, harder to test and debug, and cache-hostile if Vary is mishandled. Default to URI for public APIs because operability beats purity at 3 a.m. Reverse toward media-type only when you have sophisticated clients and strong caching infrastructure that can handle content negotiation correctly.
Keyset vs offset. Offset wins for jump-to-arbitrary-page UIs — admin tables with "go to page 47," small fixed datasets, anything where random page access is a hard product requirement — and it's trivial to implement. Keyset wins for large, mutable, infinite-scroll sets where correctness and flat latency matter, but it cannot do "jump to page 500" (there's no page number, only "after this cursor"). Default keyset for chart timelines and worklists; reverse toward offset when the dataset is small and mostly static and random page access is genuinely required.
Token bucket vs sliding-window counter. Token bucket allows controlled bursts (good UX for spiky-but-legitimate clients — the patient-portal app that wakes up and fires five requests at once). Sliding window is smoother and simpler to reason about for strict, flat caps. Choose by a single question: are bursts a feature or a threat? Feature → token bucket. Threat → sliding window.
Per-IP vs per-user vs per-API-key limiting. IP is the only key available pre-auth — but it's shared and NAT-prone, so it unfairly penalizes mobile carriers and hospital networks where thousands of users share one egress IP. User/key is fair and precise but only available post-auth. Real systems layer both: coarse per-IP at the edge (to survive a flood before auth even runs) and precise per-key at the app (for fairness among authenticated tenants — providers, clinics, integration partners).
Validation strictness. .strict() (reject unknown fields) catches client bugs early — but it breaks forward compatibility if clients start sending new fields you haven't modeled yet, making their additive change your breaking change. Passthrough (tolerant reader) eases evolution but hides typos. The resolution is directional: strict on writes you persist (you must know exactly what you're storing to a chart or a claim — mass-assignment defense), tolerant on fields you merely ignore (so clients can evolve without your permission).
Fail-open vs fail-closed rate limiting when the limiter store is down. Fail-open risks an outage-driven stampede flattening your database; fail-closed risks turning a Redis hiccup into a total API outage. Pick per endpoint by blast radius: fail-open on idempotent reads (a brief over-allow is survivable), fail-closed on /login and money writes like claim submission (where an over-allow is a security or correctness disaster).
🚫 A framing this book rejects. "We'll add pagination/versioning/rate-limiting later, once we have scale — it's premature optimization now." This conflates tuning (premature) with contract shape (not). Once a client consumes your
?page=API or your un-versioned field, those shapes are load-bearing forever — and retrofitting keyset or a version scheme means breaking the very clients you were trying to protect. The contract's shape is a day-one decision precisely because you can't change it cheaply later. Tune the implementation whenever; choose the contract once, up front.
8. Security & scale notes
These four disciplines are also four security controls. Each defends a specific attack and shapes behavior under load.
Offset is a DoS amplifier. An unbounded limit/offset lets a cheap request (?page=999999) trigger an expensive scan that drains the connection pool. Bound both — hard limit cap, and prefer keyset so depth is free — and rate-limit expensive read paths with higher cost weights so a single caller can't conjure unbounded work.
Cursors leak and iterate data if guessable. An unsigned cursor that encodes raw ids is an open invitation to enumerate another patient's slice — increment the id, fetch the next chunk, repeat. Sign cursors (HMAC), verify with a constant-time compare, and scope them to the authenticated requester so one principal's cursor can't address another's data. In a PHI system that enumeration isn't just a bug — it's a reportable breach.
Validation is your first injection and mass-assignment defense. It isn't only shape-checking. Allow-listed filters/sorts prevent ORDER-BY and predicate injection (the client never names a raw column). .strict() blocks mass assignment — a client setting { "role": "admin" } or { "is_signed": true } on a field you never meant them to touch (marking a clinical note attested when they had no authority to sign it) is rejected at the boundary, not silently persisted. "Whitelist, not blacklist" is a security stance before it's a code-quality one. (Authorization — who may do what once the input is valid, including minimum-necessary access to PHI — is Chapter 32.)
Rate limiting is a security control. It throttles credential-stuffing, scraping, and account enumeration. So apply stricter, separate limits to /login, signup, password-reset, and write endpoints than to general reads — those are the paths attackers hammer, and they deserve a tighter, fail-closed budget.
Behavior under load. Keyset keeps p99 flat as the table grows from thousands to billions of rows — constant-cost deep pagination is a reliability property, not just a performance one. And the limiter sheds load predictably: a 429 is fast and cheap to return, so when traffic exceeds capacity you reject at the edge, cheaply, instead of letting requests pile into the connection pool and collapse the database. Load shedding at the edge protects the shared pool from the saturation cascade — you fail a few requests cleanly rather than failing all of them by timeout. (Tail-latency mechanics: Chapter 30. Load-shedding as a reliability pattern: Chapter 33.)
Versioning is a scale tax. Every live major version multiplies your test matrix, your operational surface, and your cache fragmentation — each version is a tax you pay continuously. So sunset aggressively: the cheapest version to operate is the one you've removed. And header/media-type versioning can poison shared caches if Vary is mishandled (a v1 response served to a v2 client) — another operability point for URI versioning.
429 storms re-synchronize load. If every throttled client retries at the same Retry-After, you've created a thundering herd that re-hits you in a synchronized wave — the cure becomes a second outage. Always recommend (and, in your own SDK, implement) jittered backoff so retries spread out instead of stacking up.
🛑 What we deliberately did not explain. The atomic distributed rate limiter — Redis single-threaded execution, Lua scripting,
EXPIRErace-freedom — is named and motivated here but built in Chapter 21. The cryptographic why of HMAC and constant-time comparison (whytimingSafeEqualand not===, how the signature actually proves integrity) is Chapter 31. The index mechanics that make a keyset range scan O(log N) — B-tree structure, why the index direction must match theORDER BY— are Chapter 19. We used all three as tools here; we open their hoods elsewhere.
9. Interview lens & exercises
Interview questions
Each separates levels by the quality of reasoning, not the recital of a keyword.
"Design pagination for a patient's chart timeline (or a provider worklist) with millions of rows and constant inserts."
- Junior answer: reaches for
LIMIT/OFFSETand?page=numbers; doesn't mention what happens during concurrent inserts. - Senior answer: leads with keyset on a unique-tiebreaker total order
(created_at, id), an opaque signed cursor, nototal_counton the hot path, and a matching composite index. Names the two invariants explicitly — stability (no duplicates) and completeness (no skips) under mutation — and explains why offset violates both and why deep-page latency stays flat with keyset.
"How do you rename a field in a public API used by un-upgradable mobile clients?"
- Junior: "bump the version and rename it."
- Senior: expand/contract — dual-emit old and new during a deprecation window, ship readers on the new field, gate removal on a usage metric (not a date), and signal the deprecation with
Deprecation/Sunsetheaders. Notes that you control the server but not the fleet — and that in healthcare a big chunk of that fleet is patient-facing apps nobody updates — so the published field is append-only until usage is provably zero.
"Where do you put validation and what does it return?"
- Junior: scattered
ifchecks inside the handler, or trusts the client. - Senior: at the boundary as parse-to-typed-DTO (parse, don't validate), in middleware that runs before any handler, returning structured RFC 9457
problem+jsonwith field-level detail; strict on persisted writes (a patient, encounter, or claim DTO), tolerant on ignored fields; and ties it to injection and mass-assignment defense (allow-listed sorts,.strict()rejecting unknown keys).
"Token bucket vs sliding window — which and why?"
- Junior: "just count requests per minute" (the fixed-window trap).
- Senior: frames it as bursts-as-feature vs bursts-as-threat — token bucket for controlled bursts, sliding window for strict flat caps — calls out the fixed-window boundary flaw (2× across the seam), and notes that any real limiter needs distributed atomicity (one shared store, atomic read-modify-write) because per-instance counters lie behind a load balancer.
"Per-IP or per-user rate limits?"
- Junior: picks one, usually IP.
- Senior: layered — coarse per-IP at the edge (the only key available pre-auth) plus precise per-key at the app (fair among authenticated tenants) — and flags the NAT/shared-IP fairness problem (hospital networks behind one egress IP) and stricter, separate limits on auth and write paths.
Exercises & the Pulsely increment
The Pulsely increment for this chapter: replace the naive ?page=&limit= endpoints with keyset pagination, add a zod validation layer at every boundary, allow-list filtering/sorting, version the surface, and add per-user/per-key rate limiting with 429 + Retry-After.
-
Convert
/encounters,/orders, and/searchto keyset pagination. Add a composite(created_at, id)index. Encode an opaque, HMAC-signed cursor. Return the{ data, page_info: { next_cursor, has_next } }envelope. Then benchmark: measure page-1 vs page-5000 latency against the old offset version and chart the two curves. You should see offset's curve climb linearly with depth while keyset's stays flat — that chart is the ADR's evidence. -
Add a zod validation middleware to every Pulsely route. Attach a typed
req.validated; use.strict()on write schemas (theCreateEncounterand claim-submission bodies); allow-list filter and sort names mapped to indexed columns; caplimitat a hard maximum; emit RFC 9457 error bodies. Write a test proving?limit=99999and?sort=ssnare both rejected with400and a field-level error, and that an unknown body key on a write is rejected by.strict(). -
Implement token-bucket rate limiting with tiered limits (anon / user / partner), cost-weighted search (search costs 5, a point read costs 1), and
429+Retry-After+RateLimit-*headers. Build the in-process version here and prove it correct on one instance; then demonstrate the leak by load-testing two instances behind a load balancer and showing the global rate is 2× the configured limit — the motivation for the Chapter 21 Redis-backed atomic limiter. Decide and document fail-open vs fail-closed per endpoint (fail-closed on claim submission and/login). -
Run the expand/contract drill. Take the
note.body→note.contentrename. Implement the dual-emit (expand) phase, add a metric that counts reads of the old field, and write the contract test that fails the build if the old field is removed while the metric is non-zero. This is the automated guardrail that turns "never mutate a published field" from a hope into an enforced rule — and the field is read by a patient-portal app you can't force-upgrade. -
Write ADR-011. Record two decisions with their rejected alternatives: (a) Why keyset over offset for the encounter timeline / order list / search — the latency-under-depth curve, the stability/completeness invariants, the total-order requirement, and the cost (no jump-to-page), with offset's "admin table" niche acknowledged as the rejected default. (b) The rate-limit policy — algorithm (token bucket vs sliding window), limit tiers, key dimension (user vs API key vs IP, layered), storage (in-process now → Redis later), and fail-open/closed per endpoint — with fixed-window and per-IP-only named as the rejected alternatives.
Key takeaways
- An API is a contract held over time with clients you can't redeploy. Four disciplines keep it honest as data, clients, input, and traffic grow: additive change, stable cursors, typed boundaries, fair budgets.
- Append-only + tolerant reader are the twin invariants of evolution: you may add to a published contract but never subtract or redefine; clients must ignore unknown fields. Rename via expand/contract, gated on a usage metric, not a date — doubly true when the fleet includes patient-facing apps nobody updates.
- Keyset beats offset at scale. Offset is O(depth) and inconsistent under mutation (duplicates and skips); keyset is O(log N + n) and stable — given a unique total order like
(created_at, id)with a matching composite index and an opaque, signed cursor. Offset's only remaining niche is jump-to-arbitrary-page on small static sets. - Validate at the boundary by parsing, not checking: a total function from
unknown→ typed DTO (a patient, encounter, or claim), in middleware before any handler, whitelisting (not blacklisting), strict on writes and tolerant on ignored fields. It's your first injection and mass-assignment defense. - Rate limit as a budget: know your limit / window / cost / key; prefer token bucket (bursts) or sliding-window counter (strict caps) over fixed windows (boundary-burst flaw); always return
429+Retry-Afterand recommend jittered backoff. Layer per-IP (edge) with per-key (app). - An in-process limiter lies behind a load balancer — it counts per instance. One shared atomic store is required for a real global limit; the distributed Redis/Lua implementation is Chapter 21's to build.
- All four are security controls and reliability controls too: bounded pagination and edge load-shedding protect the connection pool from the saturation cascade; signed cursors stop enumeration (a PHI breach if unsigned); allow-lists stop injection; rate limits stop credential-stuffing and scraping.
← Previous: Ch 10 — APIs as Contracts · Up: Part III overview · Master TOC · Next: Ch 12 — Beyond REST →