Chapter 10 — APIs as Contracts: REST, HTTP Semantics, Status Codes, Idempotency, Structured Errors
Part III · APIs as Contracts | Prerequisites: Ch 6 | Builds: Pulsely's resource model and contract
Parts I and II got you to the door marked handler on the spine. You can draw the request's journey from a thumb to a socket; you know the event loop that juggles ten thousand of those sockets at once; you can reason about a Node process the way you'd reason about any other long-lived program. What we never did was decide what the door itself promises. Every endpoint is a door in the trust boundary — but a door is only useful if both sides agree, in advance and without ever meeting, on what knocking means and what each kind of answer signifies. That agreement is the contract, and it is the actual product surface of a backend. Not the framework, not the language, not the database — the contract is the thing other people build against, and it outlives every implementation choice underneath it.
This chapter is about treating an HTTP API as a contract on purpose: designed from resources, governed by the semantics HTTP already ships with — safety, idempotency, status codes, caching, structured errors — so that clients you will never meet can be written, cached, retried, and evolved without coordinating with you. By the end you'll design Pulsely's resource model, status map, idempotency strategy, and a single error format, and you'll write the ADR that freezes those decisions. This is a heavy chapter on purpose: HTTP encodes thirty years of agreement, and the engineers who lose a weekend to a double-billed claim are almost always the ones who threw that agreement away and tried to re-invent it inside their JSON.
1. The problem: a network hiccup becomes a money bug
Let me start where it hurts.
A biller hits Submit on a finished claim. The client fires POST /claims, the server validates the claim, hands it to the clearinghouse, writes the claim record — and then, somewhere on the way back, a flaky link eats the response. The client waited four seconds, saw nothing, and did the most natural thing a client can do: it retried. Second POST /claims lands. The server, having no memory that it already did this, re-submits to the clearinghouse again, writes a second claim again. The payer now has two identical claims for one encounter — which means a duplicate payment that triggers a clawback and an audit, or a denial that ties up the money for weeks. Finance finds out the way finance always finds out — from the payer.
Nothing was hacked. No code threw. Every layer did exactly what it was told. The bug is that the contract said nothing about retries — and on a network, retries are not an edge case, they are the weather. A request whose response is lost is indistinguishable, from the client's side, from a request that never arrived. The client cannot know whether to retry, so it must be allowed to retry safely. The server didn't offer that safety, so an ordinary network hiccup turned into a money bug. (A duplicated e-prescription POST is the same failure with sharper teeth — the same script sent to the pharmacy twice.)
Now a second pain, quieter and more corrosive. A different team — the one wiring up the eligibility check against an older endpoint — discovers that every response comes back 200 OK — successes and failures alike — with the real outcome buried in the body: { "ok": false, "error": "member not eligible" }. Think about what that costs everyone downstream. The retry library can't branch, because every response looks successful at the transport layer. The load balancer's health check thinks the endpoint is fine while it's failing every call. The circuit breaker never trips. The alerting dashboard, which counts non-2xx responses, shows a flat green line through an outage. The team threw away the transport's own signaling channel — a typed return value the entire internet already understands — and re-implemented a worse version of it inside the payload, where no machine but theirs can read it.
And a third, the one that pages you at 2am. Someone renames encounter.author_id to encounter.provider_id because provider_id is "cleaner." It ships. It is a one-word diff. It silently breaks three downstream consumers in production — the billing service that reads the rendering provider off that field, and two more — because the field was load-bearing for clients the author had never heard of and could not redeploy. Nobody owned the contract, so nobody knew the rename was a breaking change, so the change went out as casually as a typo fix.
Three different failures, one root cause. The network sits between you and every caller, and the only thing the two of you share is the contract — not your code, not your intentions, not your assumptions. The contract is the product. And HTTP, the protocol you're already speaking, has spent three decades encoding agreement about exactly these problems: which operations are safe to repeat, how to signal an outcome, how to cache, how to describe an error. Ignore that, and you don't escape the problems — you just solve them again, badly, in a place no intermediary can help you.
🧭 A useful framing. An API is not a set of functions you expose; it is a promise you publish. The biller's screen, the clearinghouse integration, the patient app three versions out of date — none of them can call you up to ask what you meant. Everything they're allowed to rely on must be visible in the wire format itself. Good API design is the discipline of making promises you can keep to strangers, and making them legible enough that machines can hold you to them.
2. The mental model: a contract between strangers
Hold one sentence in your head for the rest of Part III: an API is a contract between strangers. You and the caller never coordinate a deploy. You ship on Tuesday; they shipped eighteen months ago to an app that's now on a nurse's cart on a ward. Every guarantee you want to offer has to be expressed in the wire format, because the wire is the only thing you both touch. Shared assumptions are not shared; only bytes are shared.
To design those bytes well, keep three layers strictly separate — beginners collapse them and pay for it forever:
RESOURCES REPRESENTATIONS TRANSFER SEMANTICS
the nouns/state the bytes on the wire what HTTP promises
─────────── ─────────────────── ───────────────────
"claim #42" {"id":42,"status":...} POST = may change state, not safe to repeat
"encounter #7" JSON today, maybe GET = safe + idempotent + cacheable
CBOR/Proto tomorrow 201 = "I created something, here's where"
ETag = "this is version X of that noun"
- Resources are the nouns your system is about: a patient, an encounter, an appointment slot, a claim. They have state and identity. They are not your functions and not your database tables — they're the conceptual things a caller wants to point at.
- Representations are the bytes that describe a resource at a moment in time. Today that's JSON. The resource "claim #42" is not its JSON; the JSON is one rendering of it, and you might serve a different rendering (a different shape, a different format) to a different caller without the resource changing.
- Transfer semantics are what the HTTP method, status, and headers promise about moving a representation across the wire — independent of what your handler actually contains.
That last layer is the one developers throw away, so let it sink in. Methods are promises about effects, not function names. GET, PUT, DELETE tell every intermediary on the path — proxies, CDNs, retry libraries, browser prefetchers — how they're allowed to behave without reading a line of your code. A retry library auto-retries a GET because the method promises repetition is safe. A CDN caches a GET because the method promises no side effect to cache around. None of those machines can see your handler; they trust the method's promise. Break the promise (a GET that deletes something) and you've lied to the entire internet at once.
Status codes are a typed return channel the whole internet already understands. Think of the status as the type tag and the body as the payload. 201 doesn't just mean "good," it means "I created a resource, and the Location header tells you where." 409 means "your request conflicts with current state." 404 means "no such resource." A client can branch on the status before it parses a single byte of body, and so can every machine in between. The body is data; the status is the type.
Errors are just another representation — a problem document, a noun with a stable shape — not a side-channel smuggled into a 200. "An error is data, with a schema." If your success responses are typed and your error responses are an improvised blob, half your contract is unspecified exactly when callers need it most.
Caching is trust delegated by contract. ETag and Cache-Control let you hand a correctness-preserving copy of a representation to a machine you'll never meet — a CDN edge node, a browser cache — and trust it to serve that copy without asking you, until your contract says the copy is stale. You're not losing control; you're encoding the rules under which control can be safely lent out.
🧭 Mental model. The durable shape of every well-designed HTTP API is one chain: a resource ⇒ uniform verbs act on it ⇒ each response is status-tagged ⇒ responses are optionally cacheable and conditional ⇒ errors are problem documents ⇒ and the whole thing is versioned so it can change without breaking the strangers who depend on it. Memorize that chain. Every section below is a zoom-in on one link, and every design argument in this chapter is "we did this so the link holds."
3. Theory & invariants
A model tells you how to picture an API. Invariants tell you what must stay true for the contract to be a contract at all.
First, let's define the word precisely, because "the API" gets used to mean everything and therefore nothing.
🔑 The contract invariant. A "contract" is exactly this set, and only this set: the URI shapes, the methods allowed on them, the request schema, the response schema, the status codes you emit, the headers that carry meaning, and the error types. Everything a consumer can observe and depend on lives in that set. Everything not in that set — your framework, your table layout, your variable names, your deployment topology — is implementation detail you may change freely, at 2am, without telling anyone. The discipline of API design is drawing this line sharply and then defending it: never let an implementation detail leak across it into something a caller can depend on, because the moment they depend on it, it's part of the contract whether you meant it to be or not.
REST as constraints, not a framework
REST is not a library you install; it is a set of architectural constraints, and each one buys a specific, nameable property. You're not "doing REST" because you return JSON from Express — you're doing REST to the degree you honor these:
- Client–server. The client owns presentation; the server owns state and rules. They evolve independently — the membrane you've already met between what the caller renders and what the backend guards.
- Statelessness. Each request carries everything needed to process it — identity, auth, context — in the request itself. The server keeps no per-client session in memory between requests. What this buys: any node can serve any request, so you scale horizontally and restart instances at will. What it forbids: server-side session affinity, "remember who I am between calls" in process memory. (This is the statelessness idea you saw earlier, now load-bearing.)
- Uniform interface. A small, fixed vocabulary of methods works the same way across every resource. A client that understands
GET/POST/PUT/DELETEon one resource understands them on all of them. What this buys: intermediaries and clients need no per-endpoint special-casing. - Resource orientation. You model the system as nouns with state transitions, not as a catalog of verbs. URIs identify resources; methods express the transition.
- Cacheability. Responses declare whether and how they can be cached, so reads can be absorbed before they reach you.
- Layered system. A client can't tell whether it's talking to your server, a CDN, or a gateway. Each layer can be inserted without the client's knowledge — because the uniform interface and cacheability hold.
🔑 The statelessness invariant. No per-session state in process memory — full stop. If request N needs to know something request N−1 established, that something travels in request N (a token, an ID) or lives in shared durable state (the database, Redis), never in a variable on the box that happened to handle N−1. This is what makes "the server" pluralizable. Violate it and your API works perfectly on one machine in development and breaks the instant a load balancer routes a user's second request to a second instance that has never heard of them. Earlier you saw the runtime reason this holds; here it becomes a contract obligation.
Resources, not RPC
The single most consequential design choice is resource orientation over RPC. RPC thinking gives you an endpoint per verb: POST /createClaim, POST /voidClaim, POST /getClaimStatus, POST /resubmitClaim. Resource thinking gives you a noun — /claims/{id} — and lets HTTP's uniform methods express the transitions: POST /claims creates, GET /claims/{id} reads, DELETE /claims/{id} voids a draft. The RPC catalog grows without bound and every entry is bespoke; the resource model is small, uniform, and predictable, and an intermediary can reason about all of it because the verbs mean the same thing everywhere.
The Richardson Maturity Model — a ladder, not a religion
A useful way to grade how far you've climbed toward resource orientation:
L3 Hypermedia (HATEOAS) responses carry links: "from here you can void/appeal"
▲ GET /claims/clm_42 → {..., "_links":{"void":"/claims/clm_42/void"}}
L2 HTTP verbs + status POST /claims → 201; GET /claims/clm_42 → 200; DELETE → 204
▲ the methods and codes carry meaning
L1 Resources /claims, /claims/clm_42 exist as addressable nouns
▲ ...but everything is still POST, status always 200
L0 Single endpoint / RPC POST /api {"op":"submitClaim", ...} (HTTP as a dumb tunnel)
L0 tunnels everything through one endpoint and one method — HTTP as a pipe, all semantics in the body. L1 introduces addressable resources but still ignores verbs and codes. L2 uses the methods and status codes as the contract — this is the realistic, correct target for almost every API you will build. L3 adds hypermedia: responses include links telling the client what transitions are available next, so clients can in principle follow links instead of hardcoding URIs.
Pin your target at a solid L2 and stay there. Full L3/HATEOAS is intellectually lovely and almost never pays back for a first-party API, because the client you control already knows your URI structure — it was written by the same org, deploys on a roughly similar cadence, and gains nothing from discovering links at runtime that it could just hardcode. The dynamic-discovery payoff only shows up for long-lived, third-party, public APIs with many independent consumers who genuinely benefit from not coupling to your URIs. We'll revisit this honestly in the tradeoffs.
Method guarantees: the truth table that runs the internet
Two properties, defined precisely, do an enormous amount of work:
- Safe = the request causes no observable state change.
GET,HEAD,OPTIONS. A crawler can hit it a million times and change nothing. - Idempotent = N identical requests have the same effect on state as 1.
GET,HEAD,OPTIONS,PUT,DELETE. The subtle part is that you may not get the same response each time. Delete encounter 7 once →204(done). Delete it again →404(already gone). Different status codes — but the world is in the same place both times: encounter 7 does not exist. Idempotent is a promise about the resulting state, not about getting an identical reply.
METHOD SAFE IDEMPOTENT CACHEABLE typical Pulsely use
────── ──── ────────── ───────── ───────────────────────────────
GET ✔ ✔ ✔ GET /encounters/enc_7, GET /claims/clm_42
HEAD ✔ ✔ ✔ existence/size probe on an encounter
OPTIONS ✔ ✔ ✗ CORS preflight
PUT ✗ ✔ ✗ PUT /encounters/enc_7 (full replace)
DELETE ✗ ✔ ✗ DELETE /appointments/9 (cancel)
POST ✗ ✗ ✗* POST /claims, POST /encounters (create)
PATCH ✗ ✗ ✗ PATCH /encounters/enc_7 (partial update)
What each guarantee licenses is the whole point. Safe licenses prefetching and caching — a browser may speculatively GET a link, a CDN may cache the answer. Idempotent licenses automatic retry — a client library can resend a PUT after a timeout without asking you, because the contract promises a duplicate is harmless. Neither (POST, PATCH) is exactly why our double-billed claim happened: the method explicitly does not promise that a retry is safe, so the burden of making it safe falls on you, by hand.
🔑 The idempotency-is-earned invariant. HTTP says
PUTandDELETEare idempotent. HTTP does not make them so. "PUT is idempotent" is a promise the spec asks your handler to keep — if yourPUT /encounters/enc_7handler appends a row instead of replacing one, you have broken the contract and HTTP cannot stop you. Idempotency is a property the server must guarantee in code; the method merely declares the promise that clients and intermediaries will rely on. Design your write handlers so the declared guarantee is actually true.
Status families as a contract vocabulary
The status code is your typed return channel; its families are the part clients branch on hardest:
- 2xx — success. It worked.
200(here's the result),201(created — andLocationsays where),202(accepted, will finish later),204(done, no body). - 3xx — redirection / conditional. "Look elsewhere" or "your cached copy is still good" (
304 Not Modified). - 4xx — the caller's fault. The request is wrong and will not succeed if retried unchanged.
400,401,403,404,409,422,429. - 5xx — the server's fault. Something broke on your side; the same request may succeed on retry with backoff.
500,502,503,504.
🔑 The 4xx/5xx invariant — the most load-bearing distinction in the whole chapter. The split between 4xx and 5xx is a contract about retries. A well-built client treats 4xx as "stop, fix the request, do not retry" and 5xx (plus
429) as "retry, with exponential backoff and jitter." This single rule is what keeps a struggling system from being hammered into the ground by its own clients. The corollary is a discipline you must enforce ruthlessly: never return 500 for a caller's mistake, and never return 4xx for your own bug. Mislabel a client error as 500 and well-behaved clients will retry-storm you into a self-inflicted outage; mislabel a server error as 4xx and clients give up on something that would have worked. The boundary between these two families is a promise about who should do what next.
Content negotiation, conditional requests, and structured errors
Three more invariants round out the vocabulary:
-
Content negotiation decouples resource from representation. The client states what it can accept (
Accept: application/json), the server states what it sent (Content-Type), and the server never guesses — it negotiates, or returns406 Not Acceptablewhen it can't satisfy the request. The resource is one thing; its representations are many; the headers pick between them. -
Conditional requests give you two superpowers from one primitive. A validator — an
ETagorLast-Modified, a short tag stamping which version of a representation you're holding — lets a client attach a precondition to its next request. There are two, and they're worth reading one at a time:If-None-Matchsays "only send the body if it changed." If your copy is current, the server answers304 Not Modifiedwith no body and you reuse what you already have — a pure bandwidth win.If-Matchsays "only apply my write if the resource is still the version I read." If someone edited it under you, the server answers412 Precondition Failedinstead of silently clobbering their change. This is optimistic concurrency control: let concurrent edits proceed and only reject the loser, rather than locking the row up front. If you've written an optimistic update in React Query, it's the same version guard — you say "apply my edit only if nobody has changed this record since I read it," and the server rejects you (412) if someone raced you.
Same validator, two distinct wins: cheaper reads and safe concurrent writes.
-
Errors have a standard schema: RFC 9457
application/problem+json(which obsoletes RFC 7807). A problem document is a typed, extensible noun:type(a stable URI naming the error class),title(human summary),status(the HTTP code, echoed),detail(this-occurrence specifics),instance(which request), plus any domain extensions you need. One schema, every error, across the whole surface.
Compatibility theory: the asymmetry that governs evolution
Finally, the rule that makes all of this survivable over time:
🔑 The evolution asymmetry. You control the server; you do not control the fleet of deployed clients. You can deploy a new server in a minute; you cannot deploy a new client into a workstation that's switched off in a back office. Therefore change is asymmetric. Backward-compatible changes — adding an optional field, adding a new endpoint, adding an enum value only if clients are built to tolerate unknowns — are safe because they don't invalidate what existing clients already do. Breaking changes — removing or renaming a field, tightening validation, changing a type, repurposing a status code — are unsafe because somewhere a client depends on the old behavior and you cannot reach them to fix it. This asymmetry is why the
author_idrename was a production incident and not a typo fix. Internalize it now; Chapter 11 turns it into an operational discipline (versioning, deprecation windows, expand/contract).
4. Under the hood
Let's kill the magic, the way we always do — by looking at the bytes and at the framework code, and showing that the framework is just a status/header/body emitter with no special powers.
A request and response on the wire
Every HTTP message has the same skeleton. The request:
POST /claims HTTP/1.1 ← request line: method, target, version
Host: api.pulsely.health ┐
Authorization: Bearer eyJh… │ headers
Content-Type: application/json │
Idempotency-Key: 4f1a…-9b22 ┘
← blank line separates headers from body
{"encounterId":"enc_88","payerId":"pyr_12"} ← body (the representation)
The response:
HTTP/1.1 201 Created ← status line: version, code, reason
Location: /claims/clm_42 ┐
Content-Type: application/json │ headers
ETag: "v1" ┘
{"id":"clm_42","status":"accepted", … } ← body
Now map every contract concept to its byte location: the method and target are the request line; the representation is the body; the status is the status line; caching/concurrency validators (ETag) and negotiation (Content-Type) and idempotency (Idempotency-Key) are all headers. There is nothing else. When you "design an API," you are deciding what goes in these slots.
The framework is just an emitter
Here is the same GET /encounters/:id in Express and NestJS. Notice that in both, all the framework does is parse the request into those byte-slots and let you set them on the way out:
// Express — imperative: you set status/headers/body on `res` yourself.
app.get('/encounters/:id', async (req, res) => {
const enc = await encounters.byId(req.params.id); // params = parsed target
if (!enc) return res.status(404).json(problem('encounter-not-found', req));
res.set('ETag', `"${enc.version}"`) // a header
.status(200) // the status line
.json(enc); // the body/representation
});
// NestJS — declarative: the decorators describe the route; the return value is the body.
@Controller('encounters')
class EncountersController {
@Get(':id')
async byId(@Param('id') id: string): Promise<EncounterDto> {
const enc = await this.encounters.byId(id);
if (!enc) throw new NotFoundException(); // mapped to a 404 by a filter (below)
return enc; // serialized to the body for you
}
}
req.params/req.query/req.body are the parsed representation. res.status().set().json() (or NestJS's return value plus an exception filter) is the typed response. There is no magic — the framework reads the byte-slots in and writes the byte-slots out. Everything in this chapter is which slots to set and why. This is also where a clinical service draws its boundary: an EncountersController owns encounters, a ClaimsController owns claims, and the contract between them is the same HTTP vocabulary you're publishing to the outside.
Routing mechanics and the resource hierarchy
A route is a (method + path template) pair. The template /encounters/:id matches GET /encounters/enc_7 and binds id = "enc_7". The split between a collection route (/encounters) and an item route (/encounters/:id) is how the URI encodes the resource hierarchy: the collection is "all encounters," the item is "this one encounter." Sub-resources express containment: /encounters/:id/observations is "the observations recorded in this encounter."
The one rule that saves you from regret: stop nesting at two levels. /encounters/enc_7/observations is fine. /patients/3/encounters/7/observations/9/amendments/2 is a brittle, un-shareable, impossible-to-cache mess, and the deep IDs are redundant — observation 9 has exactly one identity regardless of which encounter it hangs off. When you feel the urge to go deeper, promote the deep thing to a top-level resource and filter: /observations/9 for the item, /observations?encounterId=7 for the collection. Flat resources are addressable, cacheable, and shareable; deep ones are none of those.
Method dispatch and the cost of getting it wrong
The classic mistakes, and what each costs:
- Returning
200for a create instead of201 + Locationthrows away the "here's where the new thing lives" signal; clients have to fish the ID out of the body and guess its URL. GETwith a request body, or aGETthat mutates breaks the safe-and-cacheable promise — a crawler, a prefetcher, or a retry library will now change your data or cache a side effect.- Tunneling everything through
POST(the L0 trap) discards the entire status/method vocabulary; you're back to inventing it in the body, where no intermediary can read it.
ETag generation and the conditional paths
An ETag is a validator — an opaque tag identifying a representation's version. Strong validators ("v1") promise byte-for-byte equality — literally the same bytes. Weak ones (W/"v1") promise semantic equivalence — same meaning, maybe re-serialized: the same encounter re-encoded with a different JSON key ordering or some extra whitespace is weakly-equal but not strongly-equal. You don't need to hash the body to make one; the cheapest correct ETag is the resource's version column or updated_at timestamp combined with its id. Then HTTP gives you two short-circuits:
READ path (bandwidth saver):
client: GET /encounters/enc_7 If-None-Match: "v1"
server: is current version still "v1"?
├── yes → 304 Not Modified (no body — client reuses its copy)
└── no → 200 + new ETag (full body)
WRITE path (optimistic concurrency):
client: PUT /encounters/enc_7 If-Match: "v1" (I'm editing the version I read)
server: is current version still "v1"?
├── yes → apply write → 200 + new ETag
└── no → 412 Precondition Failed (someone edited it first; you must re-read)
The read path saves bandwidth and origin CPU; the write path prevents the lost-update problem — two clinicians clobbering each other's note edits — without a database lock held across the user's thinking time. One primitive, two wins.
Content negotiation mechanics
The server parses Accept and picks the best representation it can produce. The q-values in a header like Accept: application/json;q=1.0, text/html;q=0.5 are just the client ranking its preferences — JSON first (q=1.0), HTML as a fallback (q=0.5). The server then sets Content-Type to what it actually sent, and emits Vary: Accept. That last header tells any cache in the path "key this cached copy by the Accept header too" — without it, the cache might hand a JSON body to the next caller who asked for HTML. If the server can satisfy nothing the client will accept, it returns 406. Charset and compression negotiation (Accept-Encoding → gzip/br, with Vary: Accept-Encoding) are the same mechanism with different headers.
Idempotency keys, concretely
Now we fix the double-billed claim — and here I have to be careful about ownership.
📎 Borrowed on credit: idempotency. We are about to apply idempotency keys to make
POST /claimssafe to retry. We are not deriving the theory. The full machinery — why networks give you at-least-once delivery at best, why exactly-once is a myth you simulate rather than achieve, fencing tokens, dedup-store design, the deep delivery-semantics vocabulary — is owned by Chapter 25. Treat what follows as a contract-level pattern: "here is the header and the flow a client and server agree on so a retried unsafe write doesn't double-execute." When you need to reason rigorously about why the network forces this on you, or how dedup stores behave under partition and concurrency, that's Chapter 25's job, not this chapter's. I'm spending the credit here and paying it back there.
The contract: a client about to make an unsafe write generates a unique key and sends it.
1. client → POST /claims Idempotency-Key: 4f1a…-9b22 {encounterId, payerId}
2. server: look up key 4f1a… in the dedup store
├── miss → process the claim, then persist:
│ (key, request-fingerprint, stored-response, ttl)
│ → return 201 + the stored response
├── hit, same fingerprint, completed → replay the STORED response (no re-submit)
├── hit, still in-flight → 409 Conflict — "your earlier one is still running, retry shortly"
└── hit, DIFFERENT fingerprint → 422 — "you reused a key with a different body"
3. client times out, never saw step 1's response → retries with the SAME key
→ step 2 takes the "hit, completed" branch → one claim, replayed response
The dedup store is a small table:
idempotency_keys
─────────────────────────────────────────────────────────────
key varchar PRIMARY KEY -- the client's UUID
principal_id varchar -- WHO sent it (scope keys per caller!)
request_hash varchar -- fingerprint of method+path+body
response_status int -- the stored outcome
response_body jsonb -- the stored representation
state enum(in_flight, done)
created_at timestamptz -- for TTL cleanup
Two subtleties that separate a working implementation from a broken one. First, the request fingerprint (request_hash) exists so a client can't accidentally (or maliciously) reuse one key for two different claims and get the first one's response — a key bound to a body, not just a key. Second, scope keys to the authenticated principal; a global key namespace lets one client replay or collide with another's key. (Both of these, and the at-least-once reasoning under them, are Chapter 25's to fully justify.)
Wiring RFC 9457 in one place
Errors must have exactly one shape and exactly one place that produces them, or the shape drifts the moment two engineers touch it. A small helper, then a single chokepoint:
// One factory. Every error in Pulsely is born here, nowhere else.
function problem(type: string, status: number, detail: string, req: Request) {
return {
type: `https://errors.pulsely.health/${type}`, // stable, registered, namespaced
title: TITLES[type], // human summary, constant per type
status, // echo the HTTP code into the body
detail, // this-occurrence specifics
instance: req.id, // the correlation id (also in logs)
};
}
// Express: ONE terminal error middleware. Forbid ad-hoc res.json({error}) everywhere else.
app.use((err, req, res, next) => {
if (err instanceof DomainError) { // known, mapped → specific 4xx
return res
.status(err.status)
.type('application/problem+json')
.json(problem(err.type, err.status, err.message, req));
}
// unknown/uncaught → generic 500, NO stack trace in the body
logger.error({ err, reqId: req.id }); // details go to logs, keyed by correlation id
return res
.status(500)
.type('application/problem+json')
.json(problem('internal', 500, 'An unexpected error occurred.', req));
});
Two non-negotiables encoded above: set Content-Type: application/problem+json so machines know the body's shape, and never leak a stack trace or internal message as a 500 body — internals go to logs keyed by the correlation id; the client gets the id and a generic message. Unknown exceptions become a generic 500; known domain errors become specific 4xx. One chokepoint means the wire shape cannot drift, because there's only one place it's made.
JVM contrast, only where it teaches
(Skippable if you never touch the JVM — the transferable payoff is the last sentence, not the annotations.) Spring makes the same principle land differently, and the difference is instructive. Express is imperative — you mutate res. Spring's ResponseEntity<T> makes status and headers a typed return value: return ResponseEntity.status(201).header("Location", url).body(dto);. And Spring 6 / Boot 3 ships first-class RFC 9457 support — ProblemDetail is a built-in type, and @ControllerAdvice is the "one place to shape errors" chokepoint exactly like the Express middleware above. Here it maps the classic Pulsely conflict — two front-desk staff grabbing the same 9:00 slot — to a 409:
@ControllerAdvice
class ErrorHandler {
@ExceptionHandler(SlotUnavailableException.class)
ProblemDetail slotUnavailable(SlotUnavailableException e) {
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
pd.setType(URI.create("https://errors.pulsely.health/slot-unavailable"));
return pd; // Spring serializes it as application/problem+json
}
}
The transferable lesson is not the annotations — it's centralized, declarative status/error mapping. Whether you express it as Express middleware, a NestJS ExceptionFilter, or Spring's @ControllerAdvice, the principle is identical: one place owns the mapping from internal errors to wire-shaped responses, so the contract can't fray. The framework is, again, just an emitter; what matters is that exactly one piece of code does the emitting.
🛑 What we deliberately did not explain. Why the network forces at-least-once delivery and how dedup stores behave under concurrency and partition (Chapter 25 — we used the pattern, not the theory). How versioning, pagination, and deprecation windows actually operate over time (Chapter 11). How middleware ordering and error propagation work inside Express, and how NestJS's DI assembles the filters above (Chapters 13–14). How
ETag-driven caching plays with a real CDN at the edge, and the proxy mechanics underneath (Chapter 30 does the latency math). We located each on the map; we didn't open it here.
5. In production: the contract is a document, not a vibe
In a real org, "the API" is not whatever the handlers happen to do this week. It's an artifact, owned and enforced. Here's the shape of doing it well.
Write the contract first, as OpenAPI, and source-control it. Design-first beats code-first because the contract is the interface, and interfaces should be agreed before implementations exist. With an OpenAPI document checked in, reviewed in PRs, and linted in CI (Spectral catches "this endpoint has no error responses," "this 200 has no schema"), consumers and mock servers can start building against the contract before your server exists. Code-first — generating the spec from whatever the code does — inverts this: the code becomes the contract by accident, and "accidental contract" is how the author_id rename ships.
Generate, don't hand-write, the things that must not drift. Serve interactive docs from the same OpenAPI file. Generate typed clients and server stubs from it. The contract and the code can't silently diverge if one is generated from the other.
Publish a project-wide status-code policy table. Seventeen engineers will otherwise invent seventeen private conventions for "validation failed." Commit a table — per method × outcome → status — and enforce it in review:
OUTCOME STATUS notes
────────────────────────────────── ────── ─────────────────────────────
read success 200
create success 201 + Location header
accepted, async 202 for deferred work
success, nothing to return 204 DELETE, some PUTs
malformed syntax (bad JSON, …) 400
not authenticated 401 + WWW-Authenticate
authenticated but not allowed 403
resource doesn't exist 404 (see 404-vs-403 policy below)
state conflict (already signed/booked) 409
precondition (If-Match) failed 412
well-formed but semantically invalid 422 validation errors live here
rate limited 429 + Retry-After
our bug 500 generic problem doc, no internals
upstream/overloaded 503 + Retry-After
One error-emission chokepoint. As shown in §4: a single middleware/filter converts every thrown error into a problem+json with a stable type. Forbid ad-hoc res.json({ error }) in review — if errors can be born in twenty places, you have twenty error formats.
Idempotency keys are policy, not vibes. Decide which endpoints require them — every claim/payment/order-entry write — and make the server reject an unsafe write that arrives without one on those paths. Pick a TTL (24–48h is typical), run a cleanup job, and dashboard the duplicate-key hit rate: a rising number is a direct readout of client retry storms (and a leading indicator of a flaky network or a buggy client).
Validate at the edge. Schema-validate body/query/params before the handler runs, returning 422 (or 400 for malformed syntax) with field-level problem details, so your handler never sees malformed input. In practice this is where your PatientDto, EncounterDto, and ClaimDto earn their keep: a claim with an unknown CPT code or a missing payer fails loudly at the boundary, not three services deep. Echo a Request-Id in every response header and in every problem instance, so a user's screenshot of an error contains the exact key to the server logs.
Contract testing in CI is the guardrail tutorials never mention. A spec-conformance or consumer-driven contract test runs in your pipeline and fails the build when a change breaks the published contract without announcing it. This is what turns the evolution asymmetry from a 2am incident into a red check on a pull request.
🏭 Two production framings to carry forward. First, observability is part of the contract's operability: emit metrics labeled by route template + status family (not raw path —
/encounters/:id, not/encounters/enc_7, or you get a million distinct series). Then a 5xx spike and a 4xx-validation spike are separable on one dashboard — one is your bug, the other is a client's, and you page on them differently. (Chapter 34 builds this out.) Second, pagination/filtering/sorting and versioning are contract decisions made once and applied to every collection — we name them here as part of the surface and hand the full treatment to Chapter 11, because they're where the contract meets change over time.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Everything is 200; errors hide in the body. Signature: clients can't branch on outcome, retry logic misfires, dashboards stay green through an outage. Fix: use real status codes. Reserve 2xx for success; put the outcome in the status line, the data in the body. The status is the type tag the whole internet reads.
POST for reads, or GET with side effects.
Signature: a CDN caches a "read" that was actually a mutation, or a crawler/prefetcher changes your data by following links.
Fix: match the method to its safety/idempotency promise. Reads are GET (safe, cacheable); state changes are POST/PUT/PATCH/DELETE. The method is a promise to intermediaries — keep it.
Non-idempotent create with naive client retry.
Signature: duplicate claims/charges after a timeout-then-retry — exactly the double-billed claim.
Fix: Idempotency-Key + a dedup store keyed and fingerprinted; replay the stored response. Make the unsafe write replay-safe by contract.
404 vs 403 leakage. Signature: returning 404 for "exists but you're not allowed" (or 403 for "doesn't exist") leaks resource existence — in healthcare, even whether a given patient has a record is disclosure — or confuses clients. Fix: pick an explicit, documented policy. Often deliberately 404 for forbidden-and-private resources, to avoid letting attackers enumerate which IDs (or which patients) exist. Decide once, apply everywhere.
422 vs 400 vs 409 confusion.
Signature: the same class of problem returns different codes on different endpoints; clients can't write one handler.
Fix: standardize — 400 = malformed syntax (couldn't even parse it), 422 = well-formed but semantically invalid (parsed fine, failed business validation), 409 = conflicts with current state. Put it in the policy table.
Renaming or removing a field "quietly."
Signature: old clients you can't redeploy crash on the missing field at 2am — the author_id → provider_id rename all over again.
Fix: treat it as a breaking change (the evolution asymmetry). Add the new field, deprecate the old, never mutate in place.
Returning 500 for a client mistake. Signature: validation failures show up as 500s; error budgets bleed, on-call gets paged for a user's typo, and well-behaved clients retry-storm a request that will never succeed. Fix: audit the 4xx/5xx boundary relentlessly. A bad request is the client's fault → 4xx → don't retry. A bug is yours → 5xx → safe to retry.
Mutating ETag logic without invalidation, or strong/weak mismatch.
Signature: stale caches serve old data, or If-Match concurrency silently breaks.
Fix: define validator semantics explicitly (strong vs weak), tie the ETag to a real version/updated_at, and test the 304 and 412 paths as first-class behavior.
PATCH that isn't a patch.
Signature: a PATCH that actually full-replaces, or an unspecified patch format, so clients can't tell what a partial update does.
Fix: specify the patch semantics — JSON Merge Patch (RFC 7396) or JSON Patch (RFC 6902) — or don't offer PATCH and use PUT for full replacement. An ambiguous partial-update contract is no contract.
Stack traces in error bodies. Signature: a 500 body contains a Java/Node stack trace, a SQL fragment, an internal path — an information leak handed to anyone who can trigger an error. Fix: generic problem doc to the client, full detail to the logs, correlation id bridging the two. (Reinforced in §8.)
Over-nesting URIs.
Signature: /patients/{p}/encounters/{e}/observations/{o}/amendments/{a} — brittle, un-shareable, un-cacheable identifiers.
Fix: flatten to top-level resources with query filters; stop nesting at two levels. A resource has one identity regardless of how you reached it.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
REST/L2 ↔ gRPC ↔ GraphQL. REST's uniform interface buys you HTTP caching, intermediary-friendliness, and sheer ubiquity — every client, proxy, and CDN already speaks it. gRPC buys raw performance, streaming, and strict compile-time schemas. GraphQL buys client-shaped responses — the client asks for exactly the fields it wants — at the cost of HTTP caching and a heavier server. You stay on REST/L2 for public, first-party, cacheable surfaces (most of Pulsely's edge). You'd reverse toward gRPC for internal, high-throughput, low-latency service-to-service calls — the RPM ingestion pipe, say — where a strong typed contract and streaming matter more than browser reach. You'd reverse toward GraphQL when client-shape divergence is your dominant pain — many clients each wanting different field sets — not because it's modern. (This whole decision is Chapter 12's to develop; named here so the L2 default is a choice, not a blind spot.)
HATEOAS (L3) ↔ pragmatic L2. Hypermedia decouples clients from your URI structure — they follow links instead of hardcoding paths. The cost is real (every response carries link machinery, clients must be written to traverse it) and the payback, for a first-party client that ships from the same org and already knows your URIs, is essentially zero. Reverse toward L3 only for long-lived, third-party, public APIs where independent consumers genuinely benefit from runtime discovery and you genuinely want the freedom to move URIs under them.
URI versioning (/v1) ↔ media-type/header versioning.
Path versioning is blunt and "ugly," but it's trivially routable, trivially cacheable, and visible in every log line and every curl. Header/media-type versioning is "purer" REST but invisible in logs, harder to cache (you must Vary correctly or poison shared caches), and harder to test by hand. Most teams pick path versioning for sheer operability.
Idempotency-key store cost ↔ duplicate-safety.
A key store is an extra write, extra storage, and TTL management on every protected request. Weigh that against the cost of a double-submitted claim or a duplicated e-prescription. For claim/payment/order-entry paths it is never optional — the downside is real money, a compliance headache, and real patient-safety risk. For cheap, naturally-idempotent writes (a PUT that sets a value) it's debatable and often unnecessary.
Strong ↔ weak ETags, and cache-TTL aggressiveness.
More caching means less origin load but more staleness risk. Strong validators and short TTLs keep you correct but absorb fewer reads; weak validators and long TTLs absorb spikes but risk serving stale data. Conditional requests (revalidate every time, cheaply via 304) are the middle path: you cache and stay fresh, at the cost of a round trip per validation.
Strict ↔ tolerant input validation.
Rejecting unknown fields (.strict()) catches client bugs early — a typo'd field name fails loudly instead of being silently ignored. But strictness makes your own additive evolution harder: if you later send a new field, strict old clients reject it, and if clients reject unknowns, you can't add fields freely either. Tolerance (Postel's "be liberal in what you accept") eases evolution but hides client mistakes. Choose per surface and write it down: typically strict on writes you persist (a claim, a med order), tolerant on fields you merely read past.
Generic 404 (hide existence) ↔ precise 403. Returning 404 for forbidden-private resources is security-by-obscurity — it stops attackers enumerating valid IDs (or valid patients), at the cost of a client that can't tell "gone" from "not yours." Precise 403 is more debuggable and honest, at the cost of leaking existence. Pick by how sensitive existence itself is — and in healthcare, existence is often exactly the sensitive part.
Design-first OpenAPI ceremony ↔ code-first speed. Writing the contract before the code slows your first endpoint and feels like bureaucracy. It pays back across every consumer (who can start early), across every reviewer (who reviews an interface, not a diff), and across the entire life of the surface (the contract can't drift into something nobody decided). The more consumers and the longer the lifespan, the more lopsided this trade gets in favor of design-first.
🚫 A framing this book rejects. "Just return 200 with
{ success: false }and put the real status in the body — it's simpler, the frontend can handle it." It is not simpler; it is more complex, because you've thrown away a typed channel every machine on the path already understands and rebuilt a private, worse one inside the payload that only your code can read. Retry libraries, circuit breakers, load balancers, CDNs, and dashboards all reason about the status code and are blind to your body. A200-for-everything API is an API that has opted out of the entire internet's accumulated agreement about what an answer means — and then wonders why retries, caching, and alerting all misbehave.
8. Security & scale notes
Security and scale are properties of the contract itself, not features bolted on after.
Statelessness forces auth into every request — and out of the URI. Because no node holds a session, every request must carry its own auth context (Chapter 32 builds the mechanisms; here it's a contract obligation). The corollary is a rule violated constantly: credentials and tokens never go in the URL. A token in a query string leaks into access logs, proxy logs, browser history, the CDN cache key, and the Referer header sent to the next site the user visits. Auth lives in headers (Authorization), never in the path or query.
Status and error design is an information-disclosure surface. The 404-vs-403 distinction can leak which resources exist (enumeration) — and when the resource is a patient, that existence is itself PHI. Timing differences can leak the same thing even when the codes match. Verbose error bodies leak schema, SQL, stack traces, internal hostnames. The defense is the §4 chokepoint: generic problem documents to the client, full detail to the logs keyed by correlation id. The client gets enough to report the problem (the instance/request id); an attacker gets nothing to map your internals.
A GET is "safe" to HTTP but not silent to HIPAA. GET /patients/{id}/chart changes no state on the resource, so HTTP rightly calls it safe, idempotent, and cacheable. But under HIPAA the view itself is an event: every chart read must be written to an immutable, append-only audit log — who viewed which record, when, and under what justification. That is precisely why PHI reads are marked no-store rather than cached at a shared edge — you want every access to reach the origin so every access is logged. "Safe" means no change to the resource; it does not mean unobserved. This is a place where the healthcare contract carries an obligation the plain HTTP contract does not.
Idempotency keys are themselves an attack surface. An unbounded key store is a memory/storage DoS — flood it with unique keys and watch it grow without limit. Require a TTL, a size cap, and per-tenant quotas. And bind every key to the authenticated principal, so one caller can neither replay nor forge another's key — in a multi-tenant platform that boundary is per-clinic, and one org's keyspace must never touch another's. (The why-this-is-necessary delivery theory is Chapter 25; the security hardening of the store is here.)
Caching is a data-leak vector. A misconfigured CDN that caches an authenticated response can serve one patient's chart to the next clinician who asks — a reportable HIPAA breach, not a cosmetic bug. The rules: mark per-patient resources Cache-Control: private or no-store; Vary on any auth-relevant header so the cache key includes identity; and never cache a personalized 2xx in a shared/public cache. Correct caching is a scale lever (below); incorrect caching is a breach.
Disable method-override trickery unless you truly need it. Headers like X-HTTP-Method-Override let a client tunnel a DELETE through a POST, defeating any firewall or policy that reasons about methods. Turn it off unless a specific legacy client forces your hand.
Bound the payload at the edge. Reject oversized bodies and unexpected content types before they reach a handler — an unbounded body is a memory-exhaustion vector, and an unexpected media type is often a probe. Content-type allow-listing and a max body size are part of the contract's safety boundary.
Now scale, where correct contract design is itself the lever:
Cacheability absorbs read spikes before they reach you — but in healthcare you cache the non-PHI reads. Reference data is the safe, high-value target: a correct ETag + Cache-Control on the code-system lookups (ICD-10, CPT, LOINC, RxNorm), the provider directory, and public slot availability lets a CDN serve those hot reads at the edge, and conditional 304s cut bandwidth and origin CPU even on revalidation. A chart, by contrast, is no-store and never edge-cached — which, as above, is also what keeps every access loggable. A read-heavy reference endpoint with good caching survives a traffic spike that would flatten the same endpoint without it. The contract you designed is your first line of load defense.
🔑 4xx/5xx hygiene is a stability property under load. Clients must treat 4xx as "don't retry" and 5xx/429 as "retry with backoff and jitter." A server that mislabels client errors as 500 invites a retry storm: every client dutifully retries a request that can never succeed, multiplying load on an already-struggling system until it falls over — a self-amplifying outage you triggered by miscoding a status. Pair
429and503withRetry-Afterso clients back off on your schedule, not all at once. The retry contract, encoded in the status families, is one of the cheapest pieces of reliability engineering you will ever do — and Chapter 33 shows what it's worth.
9. Interview lens & exercises
Interview questions
"What's the difference between safe and idempotent? Is POST ever idempotent?"
- Junior answer: "GET is safe, it doesn't change anything." True and incomplete.
- Senior answer: distinguishes the two properties — safe = no observable state change, idempotent = N identical requests land the same state as 1 — notes that POST is neither by default but can be made idempotent via an idempotency key, and explains why a client cares: idempotency is what licenses a library to auto-retry after a timeout without risking a double effect. The "why a client cares" is the signal.
"A claim-submission request times out. What happens, and how do you prevent a double claim?"
- Junior: "check if the claim already exists before creating it." That's a race — two requests both check, both find nothing, both create.
- Senior: names the unknown-outcome problem (a lost response is indistinguishable from a lost request, so the client must retry), then prevents the double via a server-side
Idempotency-Key+ a dedup store that persists the response and a request fingerprint, with TTL and per-principal scoping — and notes the underlying delivery semantics (at-least-once) live in Chapter 25's territory, this is the applied contract.
"When do you use 400 vs 422 vs 409, and when 404 vs 403?"
- Junior: "400 for any bad request."
- Senior: maps each precisely — 400 malformed syntax, 422 well-formed but semantically invalid, 409 conflicts with current state (two staff booking the same slot) — and on 404-vs-403 explains the security tradeoff: returning 404 for a forbidden-private resource hides its existence from enumeration, at the cost of debuggability, and is a deliberate policy decision, not an accident. Ties it back to the 4xx/5xx retry contract.
"How do you evolve an API without breaking clients?"
- Junior: "bump it to /v2."
- Senior: leads with the evolution asymmetry (you control the server, not the deployed clients), so changes are additive-only — add fields and endpoints, deprecate but don't remove — and mentions deprecation/sunset headers, a versioning strategy with its operability tradeoff, and contract tests in CI that fail the build on an unannounced breaking change.
"Walk me through ETag and conditional requests."
- Junior: "it's for caching."
- Senior: covers validator generation (version/
updated_at, strong vs weak), then both paths from the one primitive —If-None-Match→304for bandwidth,If-Match→412for optimistic concurrency — and notes the cache-coherence and security implications (don't let a shared cache serve a personalized response).
Exercises & the Pulsely increment
Do these with the OpenAPI file open and a test runner ready. Fluency, not perfection.
-
Author Pulsely's contract. Write the OpenAPI document for
patients,encounters,appointment-slots, andclaims. For each resource define the collection (/encounters) and item (/encounters/{id}) URIs, the method × status matrix (which methods are allowed, which statuses each can return), pagination on collections, and run Spectral lint until it's clean. This is the Pulsely increment's spine. -
Make claim submission replay-safe. Implement
POST /claimswithIdempotency-Key: the dedup-store schema from §4, a request fingerprint, replay of the stored response on a duplicate key, and a test that fires two identical requests with the same key and asserts exactly one claim exists. (Reach for Chapter 25 when you want to understand why the network makes this mandatory.) -
Add conditional requests to encounters. Put an
ETagonGET /encounters/{id}and honorIf-None-Match(→304) andIf-MatchonPUT /encounters/{id}(→412) so two clinicians can't clobber each other's note edits. Write tests asserting a304on an unchanged GET and a412on a conditional update against a version someone else already changed. -
Build the one error chokepoint. Write a single Express middleware / NestJS
ExceptionFilteremittingapplication/problem+jsonwith a Pulselytyperegistry (https://errors.pulsely.health/...). Convert at least four domain errors —not-found,forbidden,validation,slot-unavailable— and assert the exact wire shape (type/title/status/detail/instance) for each. Then grep the codebase and delete every ad-hocres.json({ error }). -
Draw the four diagrams. (a) The method × property truth table (safe/idempotent/cacheable) with the Pulsely endpoint that lives in each cell. (b) The Richardson ladder L0→L3 with a concrete Pulsely claim request shown at each rung. (c) The idempotency-key sequence: client → timeout → retry → dedup store → single claim + replayed response. (d) The conditional-request flow with the
If-None-Match→304 andIf-Match→412/200 paths side by side. -
Write the ADR — "Resource model & error format." Record the four decisions and their rejected alternatives: (a) resource-oriented URIs over RPC-style (and why; what L2 target you chose); (b) the canonical status-code map (the policy table); (c) the idempotency-key mechanism for unsafe writes (header, dedup store, TTL, per-principal scoping); (d)
application/problem+jsonas the single error schema with a stabletyperegistry. An ADR that records why not the alternatives is worth ten that only record the choice.
Key takeaways
- An API is a contract between strangers: you and the caller never coordinate a deploy, so every guarantee must live in the wire format, not in shared assumptions. The contract — URIs, methods, request/response schemas, status codes, headers, error types — is the product surface and outlives every implementation.
- Keep three layers separate: resources (nouns/state), representations (the bytes), transfer semantics (what the method/status/headers promise).
- Methods are promises about effects; status codes are a typed return channel the whole internet already understands. The 4xx/5xx split is a retry contract — caller's fault, don't retry, vs server's fault, retry with backoff and jitter — and it's the single most load-bearing distinction here.
- Model resources, not RPC verbs; target a solid L2 on the Richardson ladder; reserve L3/HATEOAS for long-lived public APIs.
- Safe (no state change) and idempotent (N ≡ 1) are distinct properties that license caching, prefetch, and auto-retry. HTTP declares idempotency; your handler must earn it.
POSTis neither safe nor idempotent, so an unsafe write — a claim submission, an e-prescription — must be made replay-safe by contract: an idempotency key + dedup store + request fingerprint, scoped per principal. (The delivery theory under this is borrowed on credit from Chapter 25.)- One error shape, one chokepoint: RFC 9457
application/problem+jsonwith a stabletyperegistry, emitted from exactly one middleware/filter — generic to the client, full detail to the logs by correlation id. - Conditional requests (
ETag+If-None-Match/If-Match) give bandwidth savings and optimistic concurrency from one primitive. Correct caching absorbs read spikes on non-PHI reference data — and, done wrong, leaks a chart to the wrong clinician. - Design the contract first (OpenAPI, linted, contract-tested in CI). The evolution asymmetry — you control the server, not the deployed clients — makes additive-only change the law. (Operating that over time is Chapter 11.)
← Previous: Ch 9 — TypeScript & the JVM Contrast · Up: Part III overview · Master TOC · Next: Ch 11 — API Evolution at Scale →