SD·132
API Architecture
Choosing and designing the interfaces between clients and services: REST resource design (methods, status codes, pagination, filtering, errors with RFC 9457, versioning, idempotency, caching, long-running operations), GraphQL (schema, resolvers, N+1 and DataLoader, federation, security), gRPC (Protocol Buffers, streaming, deadlines, load balancing, gRPC-Web and Connect), asynchronous APIs (AsyncAPI, 202 + status resources), webhooks, Server-Sent Events, WebSockets at scale, HTTP/2 and HTTP/3, a decision framework based on data shape, clients, latency, coupling, streaming and operational complexity, and API governance.
Start here: designing the conversation between programs
An API is a contract other programs build on, often programs you'll never see. Once it's public, every choice in it (names, shapes, how lists are paged, how errors look) becomes hard to change. Good API design is mostly about three things: fitting the resources and operations clients actually need, keeping the number of round trips low, and leaving room to evolve without breaking anyone.
Paging through long lists: offset versus keyset
A client pages through orders 20 at a time. Two ways to ask for "the next page":
?offset=N&limit=20 ?after_id=X&limit=20
first page 0.16 ms 0.12 ms
page at row 10,000 1.17 ms 0.37 ms
page at row 100,000 8.48 ms 0.14 ms
page at row 1,000,000 70.21 ms 0.37 ms
OFFSET 1000000 makes the database walk past a million rows to throw them away, so deep pages get slower and slower. Keyset (cursor) pagination says "the 20 rows after the last one you saw", which an index finds directly: the millionth page costs the same as the first. It also behaves better when rows are inserted while you page (no skipped or repeated items). Public APIs usually hand clients an opaque next_cursor that encodes the last key.
Round trips: the N+1 problem
A cart of 30 dishes, fetched two ways:
per cart requests
one GET /dishes/{id} per item 20.62 ms 30
one GET /dishes?ids=1,2,…,30 1.26 ms 1
Thirty small requests cost 16× one batched request, on the same machine; across a real network with 1 ms or more per round trip the gap grows. The same problem hides inside servers (one database query per item in a loop) and in GraphQL resolvers, where batching loaders (the DataLoader pattern) collect IDs and issue one query. Design endpoints around what the client screen needs, not one row at a time.
Building this measurement exposed a classic network trap: the first run took 45 ms per request, not 0.7 ms. Python's simple HTTP server wrote the headers and body in two separate packets; the client's TCP stack delayed its acknowledgement (up to 40 ms) and the server's Nagle algorithm waited for that acknowledgement before sending the body. Setting TCP_NODELAY on the server socket removed the stall. Production servers do this by default; hand-rolled ones often don't.
Don't send what the client already has
GET /menu → 200, 37,984 bytes, ETag "e0e9c9677b57ddb0"
GET /menu with If-None-Match: "e0e9…" → 304 Not Modified, 0 bytes
An ETag is a fingerprint of the response. A client that sends it back gets a tiny 304 when nothing changed, saving bandwidth and server work; with Cache-Control: max-age=60 it doesn't even ask for a minute.
How deep to go in API architecture
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain REST resources, methods, status codes and when GraphQL or gRPC fit |
| L2 | Design endpoints with cursor pagination, consistent errors, idempotency and caching headers |
| L3 | Explain versioning and evolution, N+1 and batching, long-running operations and streaming |
| L4 | Diagnose slow or chatty APIs from traces and fix round trips, pagination and payloads |
| L5 | Choose API styles and gateways for a system and set its evolution and deprecation policy |
| L6 | Govern API design standards, reviews and lifecycles across an organisation |
APIs are architecture
An API is the most durable decision in a system: once clients (especially external ones) depend on it, changing it is slow and expensive. API architecture covers style (REST, GraphQL, gRPC, events, streams), shape (resources, operations, payloads), behaviour (errors, pagination, consistency, idempotency), evolution (versioning and compatibility) and operation (gateways, security, rate limits, observability; Vol. 10 ch. 110).
REST
Resources and methods
REST (Representational State Transfer, Roy Fielding, 2000) models an API as resources identified by URIs, manipulated through a uniform interface (HTTP methods), with representations (JSON) and stateless requests. In practice "RESTful" HTTP APIs follow these conventions:
| Method | Semantics | Safe | Idempotent | Typical use |
|---|---|---|---|---|
GET |
Retrieve a representation | ✓ | ✓ | GET /orders/9817, GET /orders?status=PAID |
HEAD |
Headers only | ✓ | ✓ | Existence/metadata checks |
POST |
Create a subordinate resource or perform a non-idempotent action | ✗ | ✗ (make it so with idempotency keys) | POST /orders, POST /orders/9817/cancel |
PUT |
Replace a resource at a known URI (create if absent) | ✗ | ✓ | PUT /users/42/avatar |
PATCH |
Partial update (JSON Merge Patch RFC 7396, JSON Patch RFC 6902) | ✗ | ✗ (can be) | PATCH /users/42 |
DELETE |
Remove | ✗ | ✓ | DELETE /sessions/abc |
Resource design tips:
- Nouns for resources, plural collections (
/customers/42/orders), shallow nesting (one level), IDs opaque to clients. - Model actions that don't fit CRUD as sub-resources or controller resources (
POST /orders/9817/cancellation) rather than verbs everywhere. - Use standard status codes precisely:
200,201 CreatedwithLocation,202 Accepted,204 No Content,400,401,403,404,409 Conflict,412 Precondition Failed,415,422 Unprocessable Content,429,500,502,503,504. - Consistent naming (camelCase or snake_case, pick one), ISO-8601 UTC timestamps, money as minor units + currency, enums as strings.
Errors
Use Problem Details (RFC 9457, superseding RFC 7807) for machine-readable errors:
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 422,
"detail": "Only 1 unit of book-1 is available.",
"instance": "/orders/requests/7c1e",
"errors": [{ "pointer": "/items/0/qty", "detail": "must be ≤ 1" }],
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736"
}
Spring (ProblemDetail), ASP.NET Core, FastAPI (with handlers), Go libraries and most gateways support it. Never leak stack traces or internal details (Vol. 10 ch. 108).
Pagination, filtering, sorting
- Offset pagination (
?limit=50&offset=1000): simple, supports jumping to pages, but slow for deep offsets (the database scans and discards rows) and unstable when data changes (items shift between pages). - Cursor (keyset) pagination (
?limit=50&after=eyJpZCI6...): the cursor encodes the last item's sort key; queries useWHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 50. Fast at any depth, stable under inserts. Default for large or changing collections. - Return
nextlinks/cursors (andLinkheaders if useful); caplimit. - Filtering via query parameters with clear operators (
?status=PAID&createdAfter=2026-10-01); sorting via?sort=-createdAt; sparse fieldsets (?fields=id,status) for bandwidth.
-- Keyset pagination: next page after (created_at, id) of the last item seen
SELECT id, status, total_minor, created_at
FROM orders
WHERE customer_id = $1
AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 50;
-- index: (customer_id, created_at DESC, id DESC)
Idempotency, concurrency and caching
- Idempotency keys for
POST(Idempotency-Key: 8f3c…header, IETF draft; Stripe-style): store the key with the result; replays return the same response (Vol. 5 ch. 74). - Optimistic concurrency with
ETag/If-Match→412(chapter 129). - HTTP caching for
GET:Cache-Control,ETag/If-None-Match→304(chapter 126).
Long-running operations
When work takes longer than a request should (report generation, video processing, bulk imports):
POST /v1/exports → 202 Accepted
Location: /v1/operations/op_7f2c
{ "id": "op_7f2c", "status": "RUNNING", "progress": 0 }
GET /v1/operations/op_7f2c → 200 { "status": "RUNNING", "progress": 45 }
GET /v1/operations/op_7f2c → 200 { "status": "SUCCEEDED", "result": { "url": "https://…/export.csv" } }
Clients poll with backoff (honour Retry-After), or receive a webhook/push notification on completion. Google's AIP-151 and Azure's long-running operation guidelines formalise this.
Versioning
Evolve compatibly whenever possible (additive changes, tolerant clients). When breaking changes are unavoidable:
| Approach | Example | Notes |
|---|---|---|
| URI version | /v1/orders, /v2/orders |
Explicit, cache-friendly, easy routing; most common for public APIs |
| Header/media type | Accept: application/vnd.acme.v2+json |
Cleaner URIs; harder to test in browsers |
| Date-based versions | Stripe-Version: 2026-09-30 |
Per-client pinned versions with server-side transformation layers; fine-grained evolution |
| Query parameter | ?api-version=2026-10-01 |
Used by Azure |
Communicate deprecation (Deprecation and Sunset headers, changelogs, emails), measure usage of old versions, and give long migration windows for external clients.
Describing REST APIs
OpenAPI (3.1, aligned with JSON Schema; 3.2 published in 2025) is the standard description format: design-first (write the spec, generate server stubs and clients, mock servers) or code-first (generate the spec from annotations, e.g. springdoc, FastAPI, utoipa for Rust, huma for Go). Lint with Spectral; check breaking changes with oasdiff (Vol. 11 ch. 117).
GraphQL
Model
GraphQL exposes a typed schema of objects and fields through a single endpoint; clients send queries specifying exactly the fields they need (nested across relationships), mutations for changes, and subscriptions for real-time updates.
type Query {
order(id: ID!): Order
orders(first: Int = 20, after: String, status: OrderStatus): OrderConnection!
}
type Order {
id: ID!
status: OrderStatus!
total: Money!
customer: Customer!
items: [OrderItem!]!
}
type Mutation {
cancelOrder(input: CancelOrderInput!): CancelOrderPayload!
}
# Client asks for exactly what the screen needs, across relationships, in one round trip
query OrderScreen($id: ID!) {
order(id: $id) {
status
total { amountMinor currency }
customer { name }
items { qty product { name imageUrl } }
}
}
Strengths: avoids over-fetching and under-fetching; one round trip for complex screens (great for mobile); strongly typed schema with introspection and excellent tooling (codegen, IDEs); evolves by adding fields and deprecating old ones (@deprecated) rather than versioning; aggregates many back-end services behind one graph.
Resolvers and the N+1 problem
Each field is computed by a resolver. Naively, resolving items { product { name } } for 50 items calls the product service 50 times (N+1 queries). DataLoader batches and caches loads within a request: collect all product IDs requested in one tick, fetch them in one batched call.
// DataLoader: batch product lookups per request
import DataLoader from "dataloader";
export function createLoaders(products: ProductClient) {
return {
product: new DataLoader<string, Product>(async (ids) => {
const found = await products.getMany([...ids]); // one batched call
const byId = new Map(found.map((p) => [p.id, p]));
return ids.map((id) => byId.get(id) ?? new Error(`product ${id} not found`));
}),
};
}
const resolvers = {
OrderItem: {
product: (item: OrderItem, _args: unknown, ctx: Ctx) => ctx.loaders.product.load(item.productId),
},
};
Federation
In larger organisations, one team can't own the whole graph. Federation (Apollo Federation, GraphQL Hive/Mesh, WunderGraph Cosmo, Netflix DGS with federation) composes subgraphs owned by different teams into a supergraph served by a router; entities (Order, Product) can be extended across subgraphs with @key. The GraphQL Foundation's composite schema work aims to standardise this.
GraphQL operational concerns
- Caching: a single
POSTendpoint defeats HTTP caching; use persisted queries viaGET, client-side normalised caches (Apollo Client, urql, Relay), and response caching per field/type with care. - Security and cost: arbitrary nested queries can be very expensive: enforce depth limits, query cost analysis, pagination limits, timeouts, and persisted/trusted documents (allow-list operations) for first-party clients; authorise in resolvers or the data layer (Vol. 10 ch. 110).
- Errors: partial results with an
errorsarray (HTTP 200 even with errors in many servers): monitoring must inspect payloads, not only status codes. - Observability: per-field/resolver tracing; operation names required.
Best fit: client-facing APIs for complex UIs (web/mobile) aggregating multiple back ends, especially with many client variants; less ideal for simple CRUD, file transfers, or high-throughput service-to-service calls.
gRPC
Model
gRPC is an RPC framework using Protocol Buffers for interface definitions and binary serialisation over HTTP/2 (multiplexed streams, header compression, flow control).
syntax = "proto3";
package pricing.v1;
service PricingService {
rpc Quote(QuoteRequest) returns (QuoteResponse); // unary
rpc WatchPrices(WatchPricesRequest) returns (stream PriceUpdate); // server streaming
rpc UploadEvents(stream Event) returns (UploadSummary); // client streaming
rpc Chat(stream ChatMessage) returns (stream ChatMessage); // bidirectional
}
message QuoteRequest {
string cart_id = 1;
repeated LineItem items = 2;
string currency = 3;
}
message LineItem { string sku = 1; int32 qty = 2; }
message QuoteResponse { int64 total_minor = 1; string currency = 2; repeated Discount discounts = 3; }
Strengths: compact binary encoding and efficient parsing; generated, type-safe clients and servers in many languages; four call types including streaming; built-in deadlines and cancellation propagation; rich status codes; interceptors for auth, metrics and tracing; schema evolution via field numbers (buf breaking, Vol. 11 ch. 117).
// Go gRPC client: deadline per call; status codes for error handling
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
resp, err := client.Quote(ctx, &pricingv1.QuoteRequest{CartId: id, Currency: "INR"})
if err != nil {
switch status.Code(err) {
case codes.DeadlineExceeded, codes.Unavailable:
return fallbackQuote(), nil // degrade
case codes.InvalidArgument:
return nil, badRequest(err)
default:
return nil, err
}
}
Operational concerns
- Load balancing: long-lived HTTP/2 connections defeat L4 balancers; use L7 proxies (Envoy, service mesh), client-side balancing with name resolution (xDS, DNS with multiple addresses), or headless Kubernetes services with client-side round robin.
- Browsers can't speak native gRPC (no control over HTTP/2 framing/trailers): use gRPC-Web via a proxy, or the Connect protocol (Buf), which serves gRPC, gRPC-Web and a simple HTTP/JSON protocol from the same handlers; or transcoding (Envoy's gRPC-JSON transcoder,
google.api.httpannotations, grpc-gateway) to expose REST/JSON for external clients. - Debugging: binary payloads need tools (grpcurl, Postman/Insomnia gRPC support, server reflection in non-production).
- Schema management: a central proto registry (Buf Schema Registry, a monorepo of protos), lint and breaking-change checks in CI.
Best fit: internal service-to-service communication, polyglot microservices, low-latency high-throughput calls, streaming between services, mobile clients where bandwidth matters (with care).
Asynchronous APIs
Some interactions are better as messages than as request/response:
- Command/event APIs over brokers (chapter 128, 131), described with AsyncAPI (channels, messages, schemas, bindings for Kafka/AMQP/MQTT/WebSockets), with generated documentation and code.
- Callback URLs in requests ("POST the result to this URL when done").
- Request + webhook for partners: accept the job synchronously, deliver the result by webhook.
Contracts for async APIs need the same rigour as HTTP APIs: schemas, compatibility rules, documentation, ownership, and SLAs (delivery latency, ordering, duplicates).
Webhooks
Webhooks are HTTP callbacks: your system POSTs an event to a URL the subscriber registered when something happens (payment succeeded, repository pushed). They're the standard way to push events to external systems over the internet.
Provider-side design (Standard Webhooks, a community specification, codifies many of these):
- Signed payloads (HMAC-SHA256 or asymmetric signatures) including a timestamp and message ID; publish verification code samples (Vol. 10 ch. 107, 110).
- At-least-once delivery with retries and exponential backoff over hours or days; subscribers must deduplicate by event ID.
- Fast acknowledgement: expect a 2xx within a few seconds; subscribers should enqueue and process asynchronously.
- Ordering not guaranteed: include versions/timestamps; consider "thin" events with a fetch-latest API.
- Delivery dashboard: logs of attempts, manual redelivery, endpoint disabling after persistent failures with notification.
- SSRF-safe sending: validate destination URLs, send from isolated egress (Vol. 10 ch. 108).
- Secret rotation with overlapping secrets; per-endpoint event type filters.
Consumer-side: verify signatures on the raw body, check timestamps, dedupe, respond fast, process asynchronously, and reconcile periodically via the provider's API (webhooks can be missed).
Server-Sent Events
SSE streams events from server to browser over a single long-lived HTTP response (Content-Type: text/event-stream), using the browser's EventSource API:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 1042
event: order-status
data: {"orderId":"9817","status":"OUT_FOR_DELIVERY"}
id: 1043
event: order-status
data: {"orderId":"9817","status":"DELIVERED"}
- One-directional (server → client); client → server uses normal HTTP requests.
- Plain HTTP: works through proxies, CDNs (with streaming support) and HTTP/2 (multiplexed, so many streams share one connection; HTTP/1.1 browsers limit ~6 connections per origin).
- Built-in reconnection with
Last-Event-ID, so the server can resume from the last event. - Text-only (UTF-8); good for notifications, live feeds, progress updates, dashboards, and LLM token streaming (most AI APIs stream responses as SSE).
// Browser
const es = new EventSource("/api/orders/9817/events", { withCredentials: true });
es.addEventListener("order-status", (e) => render(JSON.parse((e as MessageEvent).data)));
es.onerror = () => { /* EventSource reconnects automatically */ };
// Go server: stream SSE events from a subscription until the client disconnects
func (h *Handler) OrderEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
rc := http.NewResponseController(w)
sub := h.bus.Subscribe(r.Context(), "order:"+r.PathValue("id"), r.Header.Get("Last-Event-ID"))
for {
select {
case <-r.Context().Done():
return
case ev := <-sub:
fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", ev.Seq, ev.Type, ev.JSON)
if err := rc.Flush(); err != nil { return }
case <-time.After(25 * time.Second):
fmt.Fprint(w, ": keep-alive\n\n") // comment line keeps proxies from timing out
rc.Flush()
}
}
}
WebSockets
WebSocket (RFC 6455) upgrades an HTTP connection into a persistent, full-duplex channel for messages in both directions with low overhead. Use for chat, collaborative editing, multiplayer games, trading UIs, live cursors: interactive, bidirectional, low-latency.
Architecture at scale:
Concerns:
- Statefulness: each connection lives on one gateway; deploys and scale-in must drain connections gracefully (clients reconnect with jitter to avoid reconnect storms).
- Fan-out: delivering to a user or room requires knowing which gateways hold the relevant sockets: a pub/sub backbone (Redis pub/sub, NATS, Kafka) and/or a presence registry.
- Authentication at connect time (token in the first message or a cookie; not in the URL where it's logged), with re-authentication for long sessions and authorisation per channel/message.
- Heartbeats/pings to detect dead connections through NATs and proxies; idle timeouts at load balancers.
- Backpressure: slow clients can't receive as fast as you send; bound per-connection queues and drop or disconnect.
- Resumption: sequence numbers and resume tokens to replay missed messages after reconnects.
- Protocols on top: define message types, versions and acknowledgements (or use STOMP, MQTT over WebSocket, Socket.IO, Phoenix Channels, SignalR, Centrifugo, managed services such as AWS API Gateway WebSockets, Azure Web PubSub, Ably, Pusher).
- Capacity: memory per connection (tens of KB), file descriptors, kernel tuning; runtimes with cheap concurrency (Go, Erlang/Elixir BEAM, Rust Tokio, Java virtual threads/Netty, Node) handle hundreds of thousands per node.
WebTransport (over HTTP/3/QUIC) is an emerging alternative offering multiple streams and unreliable datagrams, useful for games and media; browser support is broad in Chromium and Firefox, with Safari catching up.
Transport considerations: HTTP/2 and HTTP/3
- HTTP/2: multiplexes many requests over one TCP connection (no head-of-line blocking at the HTTP layer, but TCP packet loss still stalls all streams), header compression (HPACK); used by gRPC; default between browsers and CDNs.
- HTTP/3 (over QUIC, UDP-based): independent streams without TCP head-of-line blocking, faster connection setup (combined transport and TLS 1.3 handshake, 0-RTT resumption), connection migration across networks (Wi-Fi to mobile); widely supported by browsers and CDNs, increasingly by servers and load balancers. Biggest gains on lossy, high-latency mobile networks.
- Advertise HTTP/3 via
Alt-Svcor DNSHTTPSrecords; keep HTTP/2 fallback (some networks block UDP).
Choosing an API style
Use the roadmap's criteria:
| Criterion | REST | GraphQL | gRPC | Async/events | Webhooks | SSE | WebSocket |
|---|---|---|---|---|---|---|---|
| Data shape | Resource-oriented, CRUD-ish | Graph of related entities, varying views | Procedure/operation-oriented, typed messages | Facts and commands | Event notifications | Server → client event stream | Arbitrary bidirectional messages |
| Clients | Anyone (public, partners, browsers, scripts) | First-party UIs (web/mobile), many variants | Internal services, polyglot, mobile (with care) | Internal services, partners via brokers | External servers | Browsers/apps receiving updates | Interactive apps |
| Latency | Good; caching helps a lot | One round trip for complex screens; resolver cost | Lowest overhead per call | Asynchronous by design | Seconds to minutes (retries) | Real time | Real time, lowest |
| Coupling | Low (HTTP, hypermedia possible) | Schema couples clients to graph; evolvable | Generated stubs couple to proto (evolvable with rules) | Lowest temporal coupling | Low | Low | Higher (stateful sessions, custom protocol) |
| Streaming | Limited (chunked, SSE alongside) | Subscriptions (WebSocket/SSE) | First-class (all directions) | Native | No | Server → client | Bidirectional |
| Operational complexity | Lowest; universal tooling, HTTP caching | Medium–high: cost limits, N+1, caching, federation | Medium: L7 balancing, proxies for browsers, binary debugging | Medium–high: brokers, schemas, idempotency | Medium (delivery infra) | Low–medium (long-lived HTTP) | High (stateful fleet, fan-out, reconnects) |
Common combination: REST (or GraphQL) at the edge for clients, gRPC between internal services, events for asynchronous integration and data propagation, webhooks for external notifications, SSE/WebSockets for live updates in the UI.
API governance
For organisations with many APIs:
- API style guide (naming, errors, pagination, versioning, security); Google AIPs, Microsoft REST guidelines and Zalando's guidelines are good references.
- Design reviews for new public APIs; contract-first specs (OpenAPI, proto, GraphQL SDL, AsyncAPI) in repositories with linting and breaking-change checks in CI.
- Catalogue and discovery (developer portal, Backstage) with ownership, docs, SLAs and lifecycle status.
- Consistent cross-cutting concerns at gateways: authentication, rate limits, logging, metrics, tracing.
- Deprecation policy and usage analytics to retire old versions safely.
Lab: pagination, round trips and conditional requests
PostgreSQL 16 (the 1.37-million-row orders_flat table from chapter 127, with a B-tree index on id; a 200-row dish table), a Python http.server API using HTTP/1.1 keep-alive, and an http.client client on one persistent connection, all on the lab machine. Times are averages of 5 runs (pagination) or 20 carts (round trips).
Experiment 1: OFFSET versus keyset
select id, total from orders_flat order by id limit 20 offset %s; -- offset
select id, total from orders_flat where id > %s order by id limit 20; -- keyset
| Page starts at row | OFFSET | Keyset |
|---|---|---|
| 0 | 0.16 ms | 0.12 ms |
| 10,000 | 1.17 ms | 0.37 ms |
| 100,000 | 8.48 ms | 0.14 ms |
| 1,000,000 | 70.21 ms | 0.37 ms |
The script asserted both queries returned identical rows. OFFSET cost grows linearly with depth (about 70 µs per thousand skipped rows here); keyset stays flat. For multi-column sorts, use a row comparison the index can satisfy: where (created_at, id) < (%s, %s) order by created_at desc, id desc. Encode the cursor (base64 of the last key, perhaps signed) so clients can't construct arbitrary ones and you can change its format later. Trade-off: keyset can't jump to "page 37"; offer search and filters instead, or cap offsets.
Experiment 2: N+1 round trips, and a TCP surprise
| Server sockets | 30 × GET /dishes/{id} |
1 × GET /dishes?ids=… |
|---|---|---|
| default | 1,349 ms per cart (≈45 ms each) | 44.6 ms |
TCP_NODELAY set |
20.62 ms per cart (≈0.69 ms each) | 1.26 ms |
The default row is a real bug, not noise: BaseHTTPRequestHandler flushed headers and body as two writes; with Nagle's algorithm on, the second small segment waited for the ACK of the first, and the client's delayed-ACK timer held that ACK for up to 40 ms. Every keep-alive request paid it. Production servers (nginx, Go's net/http, Netty, Tomcat) set TCP_NODELAY or coalesce writes; if you see latencies stuck at multiples of 40 ms, suspect exactly this. With the fix, batching was 16× faster per cart and did 1 database query instead of 30.
Experiment 3: ETags and conditional GET
GET /menu → 200, 37,984 bytes, ETag "e0e9c9677b57ddb0", Cache-Control: max-age=60
GET /menu If-None-Match: "e0e9…" → 304, 0 bytes
Strong ETags (a hash of the bytes) suit static representations; for database-backed resources a version column or updated_at makes a cheap weak ETag (W/"v42"). The same header enables optimistic concurrency for writes: PUT /orders/42 with If-Match: "v42" returns 412 Precondition Failed if someone else changed it, which is chapter 129's lost-update fix at the API layer.
Experiment 4: choosing a style
| Style | Strengths | Costs | Fits |
|---|---|---|---|
| REST/JSON over HTTP | universal, cacheable, debuggable | chattiness, loose contracts without OpenAPI | public APIs, CRUD, browsers |
| GraphQL | client chooses fields, one round trip per screen | caching is harder, N+1 inside resolvers, query cost limits needed | many client types with varied needs |
| gRPC (Protobuf over HTTP/2) | typed contracts, streaming, deadlines, compact | not browser-native (needs gRPC-Web), less human-readable | internal service-to-service |
| async (events, webhooks) | decoupled, no waiting | eventual consistency, delivery semantics | notifications, integrations (chapters 128, 131) |
Try it yourself
- Add
(created_at, id)keyset pagination with a base64 cursor and test it while concurrently inserting rows; confirm no item is skipped or repeated. - Build the cart endpoint as GraphQL with Strawberry or Graphene, first naively (N+1) and then with a DataLoader, and count database queries.
- Implement
If-MatchonPUT /dishes/{id}and show a 412 when two clients race. - Measure the same cart with HTTP/2 multiplexing (e.g.
httpxwithhttp2=Trueagainst a server that supports it) and compare 30 parallel requests with one batched request.
Revision sheet: API architecture
Key ideas
- Resources and operations shaped by client use cases; nouns for resources, HTTP methods for verbs; status codes used correctly.
- Pagination: cursor/keyset for large or changing lists; opaque cursors; limits.
- Errors: consistent, machine-readable (RFC 9457 problem details), with stable codes.
- Idempotency: PUT/DELETE by definition; POST with idempotency keys.
- Caching and concurrency: Cache-Control, ETag/If-None-Match (304), If-Match (412) for optimistic writes.
- Long-running operations: 202 + status resource, or webhooks/events.
- Evolution: additive changes; tolerant readers; versioning (URL, header, media type) only for breaking changes; deprecation with sunset dates.
- Styles: REST, GraphQL (field selection, DataLoader, cost limits), gRPC (Protobuf, deadlines, streaming), async APIs (AsyncAPI).
- Round trips dominate; design for one call per screen or use batching.
Numbers to remember
- Lab: OFFSET at row 1,000,000 took 70 ms; keyset 0.37 ms.
- Lab: 30 per-item requests 20.6 ms vs 1 batched request 1.3 ms (16×).
- Lab: Nagle + delayed ACK added ≈40 ms per keep-alive request until
TCP_NODELAY. - Lab: a 38 KB menu became a 0-byte 304 with an ETag.
Pitfalls
- OFFSET pagination on large tables; unbounded list endpoints.
- Chatty APIs that force N+1 round trips.
- Ad-hoc error formats; 200 responses with error bodies.
- Breaking changes without versioning or notice; strict deserialisers.
- GraphQL without depth/cost limits or batching.
- POST retries without idempotency keys.
Glossary
- Keyset (cursor) pagination: "rows after this key".
- ETag: response version identifier for caching and concurrency.
- Problem details: RFC 9457 JSON error format.
- DataLoader: batches and caches per-request lookups in GraphQL.
- Sunset header: announces when a deprecated API will be removed.