Workbench / Volume 3 Exercises: The Backend
V3·45
HTTP API Design
Exercises for Volume 3, chapter 45: what REST is and resource modelling; HTTP methods, status codes, headers and content negotiation; pagination, filtering and sorting; versioning and backward/forward compatibility; idempotency and retries; conditional requests and ETags; JSON Merge Patch and JSON Patch; Problem Details; rate limits; HATEOAS awareness; and gRPC, GraphQL and JSON-RPC. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. Code is Java 21 with the JDK HttpServer and HttpClient, plus Jackson 2.21. Every quoted output is real, apart from P8's rate-limiter numbers, which come from a simulation and are labelled as such. Four outputs are worth knowing before you start:
- P3. A client's request timed out twice and then succeeded. Without an idempotency key, the server charged three times. With one, it charged once. The stored response came back on every retry.
- P4. Two admins edited the same dish. The second PUT, carrying the same
If-Match: "v1", got 412 with{"code":"version_mismatch","current":"v2"}. A PUT with noIf-Matchgot 428. A conditional GET withIf-None-Matchgot 304 with a 0-byte body. - P5. A JSON Merge Patch of
{"note":null,"tags":["veg"],"nutrition":{"kcal":360}}deletednote, replaced the wholetagsarray with["veg"], and mergednutrition, keepingprotein: 7. - P8. In a simulated token bucket (capacity 10, refilling at 5 per second), a burst of 30 requests in 0.6 s let 12 through and returned 18 × 429.
The chapter's lab measured these, and the exercises build on them rather than repeat them:
- OFFSET against keyset pagination: 107.39 ms against 0.24 ms at page 50,000;
- OFFSET repeating a row when a new order arrived between pages;
- 50 sequential GETs at 2,277 ms against one batch GET at 50 ms;
- gzip making JSON 94% smaller;
- Nagle's algorithm and delayed ACK adding about 45 ms to every request.
Coverage map.
| Chapter component | Exercises |
|---|---|
| what REST is; resource modelling | T1, P1 |
| HTTP methods; safety and idempotency | T2, P3 |
| status codes; headers | T2, P4 |
| content negotiation; compression | T3, P9 |
| pagination; filtering and sorting | T4, P2 |
| versioning; backward/forward compatibility | T5, P6 |
| idempotency and retries | T6, P3 |
| conditional requests and ETags | T7, P4 |
| PATCH: JSON Merge Patch and JSON Patch | T7, P5 |
| Problem Details | T8, P6 |
| rate limits | T8, P8 |
| HATEOAS | T1 |
| gRPC, GraphQL, JSON-RPC; chatty vs batch | T9, P7 |
Theory
T1. REST and resource modelling
- What did Fielding's REST define? - client–server; - stateless; - cacheable; - uniform interface (resources identified by URIs, manipulated through representations, self-descriptive messages, hypermedia as the engine of application state); - layered system; - code on demand.
Which of these do most "REST APIs" actually follow, and which do they ignore (hypermedia)? Does it matter?
2. Model TiffinBox's resources: kitchens, menus, dishes, carts, orders, order lines, payments, cancellations, refunds and the kitchen queue. Model actions that aren't CRUD: accepting an order, cancelling it, a refund. Should they be sub-resources (POST /orders/{id}/cancellation), state fields (PATCH /orders/{id} {"status":"cancelled"}), or RPC-style verbs (POST /orders/{id}:cancel)?
3. Design identifiers and URIs:
- opaque string ids with prefixes (ord_01JD…);
- nesting depth (one level: /kitchens/{k}/orders);
- plural nouns;
- no verbs in paths, except for controlled actions;
- stable URIs.
Why avoid exposing database auto-increment ids?
T2. HTTP methods, status codes and headers
- Fill in the method table: safe, idempotent and cacheable, for GET, HEAD, OPTIONS, POST, PUT, PATCH and DELETE. Why do proxies, browsers and HTTP clients retry idempotent requests automatically on connection failures, and what does that mean for a POST that charges money (P3)?
- Choose status codes for TiffinBox's operations:
- 200, 201 (with
Location), 202 (accepted, processing async), 204; - 301/308 (moved), 304 (P4); - 400 against 422; - 401 against 403 (and 404 for hiding); - 404, 405, 406, 409, 410, 412 (P4), 413, 415; - 428 (P4: PUT withoutIf-Match), 429 (P8); - 500, 502, 503 (withRetry-After), 504.
Give one example request for each.
3. Name the headers that matter:
- Content-Type with charset;
- Accept;
- Location;
- ETag, If-Match, If-None-Match and Last-Modified;
- Cache-Control (Volume 2 ch19);
- Idempotency-Key;
- Retry-After;
- RateLimit-*;
- Link;
- Vary;
- Traceparent.
Which headers must a CDN or cache respect for correctness?
T3. Content negotiation and representations
- Explain proactive negotiation (
Accept,Accept-Language,Accept-Encoding) and theVaryheader. When does an API need more than JSON: CSV exports, PDF invoices, protobuf for internal clients? How do you express them (Accept: text/csvagainst/orders.csvagainst?format=csv)? - Compression: the lab's 1,000 dishes went from 146,420 bytes to 9,218 with gzip (94% smaller). Cover Brotli against gzip, the CPU cost, the minimum size threshold, not compressing images, BREACH with secrets, and where to compress (the proxy or CDN against the application).
- Localised representations. The menu in English, Hindi and Telugu:
Accept-LanguagewithVary, or?lang=, or separate fields (name: {en, hi, te})? Consider caching, CDN keys, and the frontend's needs (Volume 2 ch21).
T4. Pagination, filtering and sorting
- Compare offset and keyset (cursor) pagination. The lab measured OFFSET at 107.39 ms against keyset at 0.24 ms at page 50,000 (the database discarded 999,980 rows), and OFFSET repeated a row when an order arrived between pages. Design TiffinBox's cursor:
- an opaque base64 of
(createdAt, id); - thenextlink; - stable sort with a tiebreaker; - handling a deleted cursor row; - total counts (expensive) againsthasMore. - Filtering and sorting: query parameter conventions (
status=placed,cooking,placedAfter=2026-11-01T00:00:00+05:30,sort=-placedAt), allowlists for fields, index alignment (ch49), and the injection risk of passing sort fields to SQL. When should a filter become its own endpoint? - Limits and defaults: maximum
limit(e.g. 100), default (20), errors for too-large limits against clamping, and export and sync use cases (a full sync withupdatedSinceplus cursor, change feeds).
T5. Versioning and compatibility
- Classify these API changes as backward compatible (existing clients keep working) or breaking: - adding an optional request field; - adding a response field; - adding an enum value; - making an optional request field required; - renaming a field; - changing a field's type (number to string); - changing defaults; - tightening validation; - removing an endpoint; - changing pagination; - changing error codes.
Which "compatible" changes still break badly written clients (strict deserialisation, exhaustive enum switches)?
2. Compare versioning strategies:
- URI (/v1/orders);
- a header (Accept: application/vnd.tiffinbox.v2+json, or Api-Version);
- query parameters;
- date-based (Stripe's Stripe-Version: 2026-11-01);
- no versioning plus evolution (additive changes only, with deprecations).
What does TiffinBox choose for its public partner API and for its own mobile app?
3. Deprecation and sunset:
- the Deprecation and Sunset headers (RFC 8594, 9745);
- usage tracking per client;
- communication;
- grace periods;
- mobile apps in the field for years (force-upgrade flows);
- consumer-driven contract tests (ch54) to know who uses what.
T6. Idempotency and retries
- P3: after two timed-out attempts and a success, the server without idempotency keys charged 3 times and created
ord_3. WithIdempotency-Key: k-123it charged once, and every retry got the same response. Design the idempotency store: - the key scope (per client or account); - the request fingerprint (reject a reused key with a different body: 422); - the stored response (status, headers, body); - TTL (24 hours); - concurrent requests with the same key (409 or wait while in flight); - storage in the same database transaction as the order. - Retry policy for clients:
- retry only idempotent operations, or POSTs with keys;
- exponential backoff with jitter;
- a maximum number of attempts and a retry budget;
- honour
Retry-After; - distinguish retryable (timeouts, 502, 503, 504, 429, connection reset) from non-retryable (400, 401, 403, 404, 409, 422) failures.
What happens in a deep call chain if every layer retries 3 times (3 × 3 × 3 = 27× amplification)? 3. Idempotency beyond HTTP: payment providers (Razorpay and Stripe idempotency keys), message consumers (deduplication by message id, ch51), and the database (unique constraints as the final guard: ch38's T6).
T7. Conditional requests, ETags and PATCH
- ETags for caching and concurrency:
- strong (
"v2") against weak (W/"…"); - generation (a version column, a content hash); - conditional GET (If-None-Match→ 304: P4 returned 0 bytes); - optimistic concurrency (If-Match→ 412 on mismatch: P4's second admin got{"code":"version_mismatch","current":"v2"}); - requiring preconditions (428: P4).
How does this map to JPA's @Version (ch49)?
2. JSON Merge Patch (RFC 7396) against JSON Patch (RFC 6902). P5's merge patch deleted note (null means remove), replaced tags entirely and merged nutrition recursively. What can't merge patch express (setting a field to null, appending to an array, changing one array element)? When do you need JSON Patch ([{"op":"add","path":"/tags/-","value":"jain"}]), and what are its risks (path manipulation, atomicity, test operations)?
3. Lost updates without preconditions: two kitchen staff edit a dish's price and availability at the same time, and one change silently disappears. Design the dish-edit API (GET with an ETag, then PATCH with If-Match; 412 handling in the UI: reload, show a diff, retry), and explain why last-write-wins is acceptable for some fields and not for others.
T8. Problem Details and rate limits
- Recap RFC 9457 (ch44's T9) from an API-design angle:
-
typeURIs that resolve to documentation; - stablecodeextensions; -errorsarrays for validation; -instance; - linkingtraceId; - theapplication/problem+jsonmedia type.
Should error formats be versioned?
2. Rate limiting algorithms: fixed window, sliding window, token bucket (P8's simulation: capacity 10 at 5 per second; a burst of 30 got 12 through and 18 × 429; then steady 4 per second all passed) and leaky bucket. Where do you enforce limits (edge or gateway, service, per dependency), and per what key (IP, API key, user, kitchen)?
3. Communicate limits:
- 429 with Retry-After;
- RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (or the IETF draft's RateLimit and RateLimit-Policy);
- documentation of quotas per plan;
- distributed rate limiting (a Redis token bucket with Lua, ch53) against local limits.
What happens to clients that ignore Retry-After?
T9. Chatty versus batch, and beyond REST
- The lab: 50 sequential GETs took 2,277 ms, 50 parallel 109 ms, and one batch
GET /dishes?ids=…50 ms. Design batch and embedding options for TiffinBox's order screen (an order with its lines, dishes and kitchen): -?include=lines,kitchen; - sparse fieldsets (?fields=); - a BFF endpoint per screen (Volume 2).
What are the caching and authorisation trade-offs of embedding?
2. Compare gRPC (protobuf, HTTP/2, streaming, deadlines, codegen, binary), GraphQL (client-selected fields, one endpoint, N+1 resolvers and DataLoader, caching and complexity limits) and JSON-RPC. Where does each fit at TiffinBox?
3. The 40 ms mystery from the lab: Nagle's algorithm plus delayed ACK added about 45 ms per request on localhost until TCP_NODELAY was set. What does this teach about measuring API latency, and how would you detect it in production (latency clustering at 40 ms or 200 ms)?
Programming exercises
P1. Resource model and OpenAPI
Write an OpenAPI 3.1 specification for TiffinBox's order API:
- POST /orders (with an Idempotency-Key header);
- GET /orders (cursor pagination, filters);
- GET /orders/{id} (ETag);
- PATCH /orders/{id} (merge patch, with If-Match);
- POST /orders/{id}/cancellation;
- GET /kitchens/{k}/queue.
Include the schemas (paise as integers, timestamps as date-time, enums documented as extensible), the problem-details responses, and examples. Lint it with Spectral, or by eye against a checklist.
P2. Keyset pagination with opaque cursors
Implement GET /orders over an in-memory list of 1 million orders (or PostgreSQL if available), sorted by (placedAt DESC, id DESC), with:
- an opaque base64url cursor;
- a next link;
- limit handling;
- filters with allowlists.
Then:
- reproduce the lab's OFFSET duplicate under an insert, and show the keyset version is stable;
- attempt SQL injection through sort and show the allowlist rejecting it.
P3. Idempotency keys
Implement POST /orders with an Idempotency-Key store. Reproduce P3's client behaviour: two timeouts at 100 ms against a 300 ms server, then a success. Count the charges without and with the key. Then add:
- the request fingerprint, with 422 for a reused key with a different body;
- 409 for a concurrent in-flight request with the same key;
- atomic storage with the order (in-memory transaction simulation, or PostgreSQL);
- a TTL.
P4. ETags, conditional GET and optimistic concurrency
Implement GET and PUT (or PATCH) for /dishes/{id} with:
- a version-based ETag;
- conditional GET (304);
- If-Match (412 on mismatch);
- 428 when the precondition is missing.
Reproduce P4's two-admin conflict. Then build the UI flow for 412 (fetch the current representation, show a diff, reapply), and measure bytes saved by 304s for a menu polled every 10 s.
P5. JSON Merge Patch and JSON Patch
Implement RFC 7396 merge patch (P5) and a subset of RFC 6902 JSON Patch (add, remove, replace, test) over Jackson trees. Show:
- merge patch deleting with null, replacing arrays and merging objects;
- the field that merge patch can't set to null;
- JSON Patch appending to tags with a test precondition.
Add a path allowlist (only /name, /available and /tags are patchable by kitchen staff) and atomic application.
P6. Compatibility and deprecation
Take P1's API and make these changes, classifying each and testing an old client against the new server:
- add a response field;
- add an enum value (on_hold);
- rename totalPaise to amountPaise;
- make couponCode required.
Write a tolerant Java client (ignores unknown fields, maps unknown enums to OTHER) and a strict one, and show which breaks. Then add Deprecation and Sunset headers to an old endpoint, and per-client usage metrics.
P7. Chatty, parallel and batch
Reproduce the lab's 50 sequential against 50 parallel against 1 batch GET. Then implement:
- GET /dishes?ids= with a limit of 100;
- GET /orders/{id}?include=lines,kitchen with authorisation checks per embedded resource;
- sparse fieldsets.
Measure the response sizes and latency for the order screen with each approach. Finally, sketch the GraphQL query for the same screen and the DataLoader that prevents N+1 resolvers.
P8. Rate limiting
Implement a token bucket (capacity 10, refill 5 per second) per API key and simulate a burst of 30 requests in 0.6 s followed by steady traffic. Return 429 with Retry-After and RateLimit-* headers. Then make it distributed (a Redis Lua script if Redis is available: redis-server is installed here), and test with two "instances" sharing it. Compare fixed-window behaviour at a window boundary.
P9. Negotiation, compression and the 40 ms trap
Implement:
- Accept negotiation for JSON and CSV on GET /orders/export, with 406 for others;
- gzip for responses over 1 KB with Vary: Accept-Encoding;
- ?lang= menus.
Then reproduce the lab's Nagle and delayed-ACK effect with the JDK HttpServer (50 sequential requests with and without -Dsun.net.httpserver.nodelay=true), and show how a latency histogram reveals it.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–45)
C1. The TiffinBox public order API, done properly
Extend ch44's C1 service into a full API with: - the OpenAPI spec (P1) as the source of truth, with server stubs or validation from it; - keyset pagination (P2); - idempotent order creation stored atomically (P3); - ETags and conditional writes (P4); - merge-patch edits with a path allowlist (P5); - problem details with a code catalogue (ch44's C2); - rate limits per key (P8); - compression and negotiation (P9); - deprecation support (P6).
Write a contract test suite run against the server from the spec, plus a client SDK with tolerant parsing and the retry policy (T6).
Combines: Volume 2's API client and caching work (ch19), ch36's typed Result and Page, ch37's functional core, ch38's concurrency, ch44's service skeleton, and this chapter.
C2. Sync API and webhooks for a delivery partner
A delivery partner needs to sync TiffinBox orders ready for pickup and receive changes quickly. Design and implement:
- GET /partner/orders?updatedSince=&cursor= (stable keyset over (updatedAt, id));
- webhooks (order.ready, order.cancelled) with HMAC signatures, retries with backoff, idempotent delivery ids and a replay endpoint;
- the partner's rate limits;
- a versioned contract (/v1).
Simulate the partner as a client that must never miss or double-process an order.
Combines: Volume 1's networking reliability, Volume 2's webhooks and SSE awareness (ch19), ch38's concurrency, ch44's lifecycle, and this chapter's pagination, idempotency and versioning.
C3. REST against GraphQL against gRPC spike
Implement the kitchen display's data needs (open orders with lines and dishes, live status changes) three ways: - REST plus SSE; - GraphQL with subscriptions; - gRPC with server streaming (described if tools are unavailable).
Compare payload sizes, round trips, latency for a status change, caching, authorisation complexity and tooling, and recommend one.
Combines: Volume 2's real-time UI (ch19, ch25), ch38's concurrency models, ch41's measurement method, and this chapter.
What the chapter leaves out
Long-running operations
Some requests start work that takes minutes: exports, refunds through a slow bank, menu imports. The standard pattern is 202 Accepted with Location: /operations/{id}. The client polls the operation resource (status: running | succeeded | failed, result link, progress), or subscribes via webhooks or SSE. Google's AIP-151 and Azure's guidelines formalise this. Combine it with idempotency keys so retries don't start duplicate jobs.
API security patterns
API design interacts with security everywhere:
- object-level authorisation on every id (BOLA, the top OWASP API risk: a customer requesting another's /orders/{id});
- function-level authorisation (kitchen endpoints from customer tokens);
- mass assignment (ch44's P3);
- excessive data exposure (returning whole entities);
- resource limits (P8, pagination limits);
- SSRF in webhook URLs (validate and restrict partner callback URLs).
Chapter 50 covers authentication and authorisation, and the OWASP API Security Top 10 is a checklist.
API governance and design reviews
In organisations with many teams, consistency needs governance: - a style guide (naming, pagination, errors, versioning: Google AIP, Microsoft REST guidelines, Zalando's guidelines); - linting in CI (Spectral rulesets); - design reviews for new public endpoints; - an API catalogue (Backstage).
Governance should mostly be automated, so reviews focus on modelling rather than style.
Caching APIs at the edge
Public, unauthenticated GETs (menus, kitchen lists) can be cached at a CDN with Cache-Control: public, s-maxage=60, stale-while-revalidate=300, with ETags for revalidation and purge APIs on changes. Personalised responses must be private or no-store. Getting Vary and keys right (T2, T3) is the hard part. ch53 covers caching layers, and Volume 2 ch19 covered browser caching.
Event-driven APIs and AsyncAPI
Webhooks, Kafka topics and SSE streams are APIs too, with schemas, versioning and compatibility rules. AsyncAPI documents them the way OpenAPI documents HTTP, and schema registries (Avro, Protobuf, JSON Schema) enforce compatibility for event payloads (ch51). Treat event contracts with the same care as HTTP contracts: additive changes, tolerant consumers, deprecation.
Senior exercises
S1. Write TiffinBox's API style guide
Write the one-page guide for every HTTP API: - naming and ids; - resources versus actions; - methods and status codes; - pagination (keyset, opaque cursors, limits); - filtering and sorting allowlists; - errors (RFC 9457 plus codes); - idempotency keys for creates; - ETags and preconditions for edits; - PATCH formats; - versioning and deprecation; - compatibility rules for clients and servers; - rate-limit headers; - compression; - linting.
Tie each rule to an output from this chapter.
S2. Review an API design proposal
A proposal for the refunds API:
- GET /refund?orderId=123&amount=40.50&action=create (creates a refund);
- PUT /refunds/{id} with the full object to change status;
- errors as {"success": false, "error": "Something went wrong"} with status 200;
- offset pagination with page and pageSize (max 10,000);
- a new required field reasonCode added to v1;
- no rate limits ("internal partners only").
Write the review.
S3. Decide on a versioning strategy for a growing partner ecosystem
TiffinBox now has 40 integration partners (POS systems, delivery fleets, accounting tools), and the order model must change significantly next year: multiple kitchens per order, split payments. Options:
- /v2 alongside /v1;
- Stripe-style date versions with transforms;
- no versioning with GraphQL for partners.
Decide, with a migration and support plan, and the cost of maintaining both versions.
S4. Teach "APIs are promises" with five outputs
Prepare a 20-minute session using: - the lab's OFFSET duplicate row; - P3's 3 charges against 1; - P4's 412 for the second admin; - P6's strict client failing on a new enum value; - the lab's 50 sequential calls against 1 batch.
For each: the promise involved, the output, and the design rule.
S5. Design the API platform: gateway, docs, SDKs and governance
Plan TiffinBox's API platform for public and partner APIs: - the gateway (authentication, rate limits, routing, request validation against OpenAPI); - the developer portal (docs from specs, a sandbox, API keys, usage dashboards); - SDK generation (Java, TypeScript, Python) with tolerant parsing and retries; - governance (Spectral in CI, design reviews, breaking-change detection with oasdiff); - observability per partner; - the change process.
Give the components, ownership, rollout and success metrics.