Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·45

HTTP API Design

Companion to Volume 3, chapter 45: how resources, HTTP semantics, collections and change over time connect; new angles (a response's caching headers as instructions on a parcel, a proxy as a translator who speaks an older dialect, a contract diff as a building inspector); what the chapter simplifies, measured with nginx 1.24 in front of the build's stage 46: a default proxy that speaks HTTP/1.0 and an origin that refused it with a 505, responses without Cache-Control that a shared cache stored and served after they changed (a kitchen's next order, an order's status), a "no-cache" menu that no shared cache would keep, so 1,000 requests were 1,000 full responses, and a contract check that classifies removing four optional, deprecated fields as breaking; the theory behind them (HTTP caching's freshness and validation, Postel's principle and its limits, semantic versioning for wire formats); how nginx reads Cache-Control, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 45 covers REST and resources (what REST is, resource modelling), HTTP semantics (methods, status codes, headers, content negotiation), working with collections (pagination, filtering and sorting), change and evolution (versioning, compatibility, idempotency and retries, conditional requests and ETags, PATCH formats, Problem Details, rate limits, HATEOAS) and beyond REST (gRPC, GraphQL, JSON-RPC).

resources HTTP semantics collections change and evolution what REST is constraints, not URLs resource modelling nouns, ids, relations gRPC, GraphQL, RPC when not REST an API is a promise to clients you can't see methods safe, idempotent status codes what the client does next headers caching, conditions, limits negotiation representations pagination offset or keyset filtering, sorting allow-listed fields chatty or batch round trips rate limits 429 and Retry-After versioning as rarely as possible compatibility expand, then contract idempotency, ETags safe retries, no lost updates Problem Details errors as data shapes or all are answered with plus drive with or bounded by avoided by plus fail as builds on: ch44 backend fundamentals · ch42 compatibility · goes on: ch48 Spring Web · ch51 jobs and messaging · ch53 caching exercises: P1–P9 OpenAPI, keyset cursors, idempotency keys, ETags, PATCH, deprecation, batching, rate limits, compression; C1–C3
Concept map of chapter 45, HTTP API design: REST and resources (what REST is, resource modelling), HTTP semantics (methods, status codes, headers, content negotiation), working with collections (pagination, filtering and sorting), change and evolution (versioning, compatibility, idempotency and retries, conditional requests and ETags, PATCH formats, Problem Details, rate limits, HATEOAS) and beyond REST (gRPC, GraphQL, JSON-RPC), with links such as an API as a promise and caching as part of the contract.

The links worth remembering:

  • An API is a promise to clients you can't see. Every field, status code and header you send is something someone may depend on, including caches and proxies between you and them.
  • HTTP's semantics are the API's semantics. A method's safety and idempotency decide what retries do; a response's headers decide what caches do. Leaving a header out is also a decision.
  • Change is expand, then contract. Add the new shape, move readers over, then remove the old one, with a check that tells you which change is which.

Explain it differently

1. Caching headers are the instructions on a parcel. "Fragile", "keep refrigerated", "do not open before". A parcel with no instructions gets handled however the courier usually does it. A response without Cache-Control is the same: each cache on the way applies its own default (Gaps 2).

2. A reverse proxy is a translator who speaks an older dialect. Out of the box, nginx speaks HTTP/1.0 to your server. If your server refuses to understand it, every request through the translator fails, though every request from a browser works (Gaps 1).

3. no-cache is "check with me before using it", not "don't keep it". A browser keeps it and asks whether it's still good; a shared cache like nginx doesn't keep it at all. Same words, different couriers (Gaps 3).

4. A contract check is a building inspector. You can move walls inside your flat; you can't remove a load-bearing one without a permit. Removing a field someone reads is a load-bearing wall, even if it was marked "optional" and "deprecated" (Gaps 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from nginx 1.24.0 (configured as a shared cache, exp/46/nginx.conf.in) in front of the build's stage 45 and 46 servers on OpenJDK 21.0.12, unless stated.

1. Your API's first client may be a proxy, and it may speak HTTP/1.0. The chapter's HTTP semantics assume HTTP/1.1. nginx's proxy_pass speaks HTTP/1.0 to the origin unless told otherwise (proxy_http_version 1.1), and TiffinBox's strict parser refused anything but 1.1:

Terminal
== the kitchen screen asks the edge for its next order
  GET /kitchens/k7/next    MISS   only HTTP/1.1 is supported
  GET /orders/o1           MISS   only HTTP/1.1 is supported

Every request through a default nginx failed with a 505, while every request from a browser worked. TiffinBox's own deployment (stage 31) sets the version, so it never noticed; the next team to put a cache or gateway in front would have. Stage 46 serves HTTP/1.0 (without keep-alive, and without requiring Host, which 1.0 didn't have) and refuses only other versions.

2. No Cache-Control doesn't mean "not cached". The chapter's caching discussion is about ETags and conditional requests between a client and the server. A shared cache in between, configured as many examples on the web do (proxy_cache_valid 200 1m: cache any 200 for a minute unless the response says otherwise), saw TiffinBox's API responses without a caching header:

Terminal
== the kitchen screen asks the edge for its next order
  GET /kitchens/k7/next    MISS   {"orderId":"o1","promisedAt":"2026-11-20T03:35:35.153Z"}
  GET /orders/o1           MISS   {"id":"o1","kitchenId":"k7","status":"Placed","at":"2026-11-20T03:05:35.153Z","totalPaise"
  (the kitchen accepts o1, marks it ready and hands it over; a second order o2 arrives)
  GET /kitchens/k7/next    HIT    {"orderId":"o1","promisedAt":"2026-11-20T03:35:35.153Z"}
  GET /orders/o1           HIT    {"id":"o1","kitchenId":"k7","status":"Placed","at":"2026-11-20T03:05:35.153Z","totalPaise"

After o1 was delivered, the kitchen was still told to cook o1 next, and the customer was told their order was placed. Stage 46 makes every response carry a caching decision: no-store unless the route chose something else, checked by a test over every route:

Terminal
  GET /kitchens/k7/next    MISS   {"orderId":"o2","promisedAt":"2026-11-20T03:35:40.700Z"}
  GET /orders/o1           MISS   {"id":"o1","kitchenId":"k7","status":"Delivered","at":"2026-11-20T03:05:40.686Z","totalPai

3. no-cache keeps shared caches from helping at all. TiffinBox's menu (stage 19) is no-cache with an ETag, so browsers revalidate and usually get a 304. The same header told nginx not to store it:

Terminal
== 1,000 menu requests through the edge, 20 at a time
  the origin served /menu.json 1000 times:  1000 "status":200

Stage 46 sends public, max-age=0, s-maxage=5, stale-while-revalidate=30: browsers still revalidate every time, while shared caches keep it for 5 seconds and serve it stale for up to 30 more while they fetch a new copy in the background:

Terminal
  the origin served /menu.json 7 times:  7 "status":200

From 1,000 full responses to 7, at the cost of a menu change taking up to about 5 seconds to reach the edge. Whether that's acceptable is a product decision, written into the response.

4. Removing an optional, deprecated field is still a breaking change. The chapter's compatibility rules are expand, then contract. Stage 46 contracts: it removes Order.discountPaise, payablePaise, freeDelivery and pricedBy, deprecated in 0.2 for Order.pricing and announced for removal in 0.3. A new check compares the contract with the last released one:

Terminal
# VERSION 0.3.0-dev
  breaking   Order.discountPaise removed (it was optional: readers that checked for it are fine)
  breaking   Order.freeDelivery removed (it was optional: readers that checked for it are fine)
  breaking   Order.payablePaise removed (it was optional: readers that checked for it are fine)
  breaking   Order.pricedBy removed (it was optional: readers that checked for it are fine)
contract: 4 changes since 0.2.0, 4 breaking; VERSION 0.3.0 allows them
# what if this were a 0.2 patch release?
contract: 4 changes since 0.2.0, 4 breaking; VERSION 0.2.1 does not: a breaking change needs a new minor version
exit 1

"Optional" in the contract (stage 30) means "may be absent", so a careful reader handles it; but a reader that used the field whenever it was there now silently loses it. Classifying that as breaking, and tying it to the version, makes the removal a decision with a version number rather than a cleanup. The order JSON went from 305 to 221 bytes.

Common misconceptions

Misconception What's actually true Where it's shown
"Every client speaks HTTP/1.1." A default nginx speaks HTTP/1.0 to its upstream. Gaps 1
"Responses without caching headers aren't cached." Shared caches apply their own defaults. Gaps 2
"no-cache means don't cache." It means revalidate; nginx won't store it at all. Gaps 3, Code walkthrough
"max-age=0 stops everything from caching." s-maxage overrides it for shared caches. Gaps 3
"Removing an optional field is safe." Readers that used it when present lose it. Gaps 4
"Adding an enum value is compatible." Only for clients that tolerate unknown values. Exercises P6
"A 304 is free." It still costs a round trip to the origin. Gaps 3

Theoretical gaps: the ideas behind the chapter

1. HTTP caching is freshness plus validation. RFC 9111 gives a stored response a freshness lifetime (max-age, or s-maxage for shared caches, or Expires); while fresh it's used without asking. When stale, it's validated with the origin (If-None-Match, If-Modified-Since), which answers 304 or a new response. Without explicit freshness, caches may compute a heuristic one; no-store forbids storing, private forbids shared caches, no-cache requires validation before each use. stale-while-revalidate (RFC 5861) lets a cache serve a stale copy while it validates in the background.

2. Postel's principle, and its limits. "Be conservative in what you send, liberal in what you accept" helps interoperation (Gaps 1: accept HTTP/1.0). It also lets ambiguity spread: request smuggling exists because two parsers were liberal in different ways (TiffinBox's parser stays strict about everything else: duplicate lengths, spaces before colons, Transfer-Encoding). RFC 9413 ("Maintaining Robust Protocols") argues for strictness plus active maintenance.

3. Versioning a wire format. Semantic versioning's major, minor and patch were written for code; for a schema, the question is who reads and who writes. For responses, removing or narrowing is breaking for readers; for requests, adding a required field is breaking for writers. Schema registries (Confluent's for Avro and Protobuf) encode these as compatibility modes (backward, forward, full); Gaps 4's check is a small backward-compatibility check for readers.

4. The robustness of the middle. Between client and server sit caches, proxies, gateways and CDNs, each with defaults. An API's real contract includes how it behaves through them: headers they read (Cache-Control, Vary, Connection), versions they speak, sizes they limit. Testing through one (as exp/46/edge.sh does) is the only way to know.

Applying it

Code walkthrough

Gaps 2 and 3 depend on how nginx reads Cache-Control. From nginx at release-1.24.0, src/http/ngx_http_upstream.c, ngx_http_upstream_process_cache_control.

Three words that stop caching

C
    if (ngx_strlcasestrn(start, last, (u_char *) "no-cache", 8 - 1) != NULL
        || ngx_strlcasestrn(start, last, (u_char *) "no-store", 8 - 1) != NULL
        || ngx_strlcasestrn(start, last, (u_char *) "private", 7 - 1) != NULL)
    {
        u->headers_in.no_cache = 1;
        return NGX_OK;
    }

A case-insensitive substring search over the whole header value. no-cache is treated like no-store: not stored at all, which is stricter than RFC 9111 (store, but revalidate). That's Gaps 3's 1,000 origin responses. It is a substring match, so a field-qualified no-cache="Set-Cookie" (which in the RFC means "you may store this, just not the Set-Cookie") also stops all caching.

Freshness: s-maxage first

C
    p = ngx_strlcasestrn(start, last, (u_char *) "s-maxage=", 9 - 1);
    offset = 9;

    if (p == NULL) {
        p = ngx_strlcasestrn(start, last, (u_char *) "max-age=", 8 - 1);
        offset = 8;
    }
    ...
        if (n == 0) {
            u->headers_in.no_cache = 1;
            return NGX_OK;
        }

        r->cache->valid_sec = ngx_time() + n;

s-maxage wins over max-age (so stage 46's max-age=0, s-maxage=5 gives the edge 5 seconds and browsers none), and a lifetime of 0 means "don't store". If neither appears, nothing sets valid_sec, and the configuration's proxy_cache_valid applies: Gaps 2's minute-long default.

Serving stale

C
    p = ngx_strlcasestrn(start, last, (u_char *) "stale-while-revalidate=",
                         23 - 1);
    ...
        r->cache->updating_sec = n;
        r->cache->error_sec = n;

stale-while-revalidate sets how long a stale copy may be served while it's being updated, and also while the origin is failing (error_sec), which acts like stale-if-error. It takes effect only with proxy_cache_use_stale updating (and proxy_cache_background_update on to update without making the first request wait), which exp/46/nginx.conf.in sets.

Debugging drills

D1. A new gateway, and every request fails

The platform team put an API gateway in front of a service. Browsers calling the service directly work; everything through the gateway gets 505 HTTP Version Not Supported, or 400 Bad Request: missing Host.

D2. Customers see yesterday's order status

After a CDN was enabled for the API's domain, some customers see "preparing" for orders that were delivered hours ago, while others see the right status. The API team says they never enabled caching.

D3. The CDN does nothing for the catalogue

The product catalogue sends Cache-Control: no-cache and an ETag; the CDN's hit ratio for it is 0%, and the origin's CPU is high every evening.

D4. A cleanup that broke a partner

A developer removed four response fields marked deprecated for a year. A partner's integration starts showing zero discounts. The fields were documented as optional.

Career-oriented

Interview prep

Mid-level 1: PUT or PATCH

Question. "When do you use PUT and when PATCH to update a resource?"

How to get there. What the body means, and what a retry does.

Mid-level 2: what status code

Question. "A client posts an order for a dish that's sold out. What status code do you return?"

How to get there. Whose fault is it, can retrying help, and what does the client do next?

Senior 1: caching an API

Question. "Our API sits behind a CDN. Design its caching headers."

How to get there. Classify responses by who may store them and how stale they may be.

Senior 2: removing a field

Question. "We want to rename totalPaise to amountPaise in a public API used by 200 partners. Plan it."

How to get there. Expand, migrate, contract, with measurements at each step.

Staff 1: API governance

Question. "We have 60 services with HTTP APIs and no consistency. How do you introduce governance without slowing teams down?"

How to get there. Make the rules executable and the review lightweight.

Staff 2: the edge as part of the API

Question. "We're moving all APIs behind a global CDN and API gateway. What can go wrong, and how do you de-risk it?"

How to get there. Everything between the client and the server changes; list what it reads and decides.