REST API Design: Constraints, Resources, Idempotency, Versioning
"The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components." — Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapter 5, 2000
Summary: REST is a set of constraints, not a URL style; an HTTP API earns its benefits (caches, safe retries, generic tooling, independent evolution) only when it uses resources, methods, status codes and headers with the meaning HTTP gives them. Focus: Fielding's six constraints, resources and URI design, method semantics (safe, idempotent), JSON Patch vs JSON Merge Patch, precise status codes, content negotiation, HATEOAS and the Richardson maturity model, cursor/keyset pagination, filtering, sorting and sparse fieldsets, RFC 9457 Problem Details, the Idempotency-Key contract, ETag/If-Match optimistic concurrency, caching and RateLimit headers, bulk endpoints, long-running operations, a versioning summary, OpenAPI 3.1 contract-first, security basics and the big style guides, with a Go 1.22 net/http service and a Laravel 13 API. Learning goal: Given a domain, design its HTTP API on paper (resources, URIs, methods, codes, headers, pages, errors, concurrency, idempotency), write it down as an OpenAPI 3.1 contract, implement it in Go and Laravel, and defend every status code and header in a design review.
This chapter sits in the Networking & Protocols group after HTTP/1.1, HTTP/2, HTTP/3 (the wire) and before GraphQL, gRPC & Protocol Buffers and API Versioning & Evolution. It owns the design of one HTTP API: its resources, its contract and the HTTP semantics it relies on. It does not re-teach the neighbours: framing and connection reuse live in HTTP evolution; key storage, TTLs and crash recovery for idempotency live in API Idempotency; the SQL behind keyset pages lives in Pagination: Offset vs Keyset; version columns and retry loops in Optimistic vs Pessimistic Locking; token buckets in Rate Limiting; cache tiers in Caching and CDNs; deprecation and breaking-change policy in API Versioning; which style to use between services in Service Communication; the DDD view of REST resources in API Realization; and the Go router itself in net/http: Server, Client, 1.22 Routing.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why REST is constraints, not URLs | Why it exists, Where it comes from |
| Client-server, stateless, cacheable, uniform interface, layered, code on demand | Constraints |
| Resource, collection, sub-resource, URI design, nesting | Resources and URIs |
| GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS; safe vs idempotent | Methods |
| JSON Patch vs JSON Merge Patch | PATCH formats |
| Which status code, exactly | Status codes |
| Accept, Content-Type, media types, 406/415 | Representations |
| HATEOAS, Richardson maturity model | Hypermedia |
| Offset, cursor, keyset pages | Pagination |
| Filtering, sorting, sparse fieldsets | Query design |
| RFC 9457 error bodies | Problem Details |
| Idempotency-Key on POST | Idempotency keys |
| ETag, If-Match, 412, 428 | Optimistic concurrency |
| Cache-Control, 304, Vary | Caching headers |
| RateLimit, RateLimit-Policy, 429, Retry-After | Rate-limit headers |
| Batch create, partial success | Bulk endpoints |
| 202 Accepted and a status resource | Long-running operations |
| URI vs header vs media-type versions | Versioning summary |
| OpenAPI 3.1, contract-first, codegen | OpenAPI |
| Auth, scopes, 401 vs 403 vs 404 | Security basics |
| Google AIP, Microsoft, Zalando | Style guides |
| Knobs, header grammar, exact messages | Mechanics |
| Code | Go, Laravel |
| Classic API bugs and their fixes | Solving the classic problems |
| What to pick | Choosing |
| Monolith to distributed system | In architecture |
| curl against the Go server | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The constraints (Fielding, chapter 5.1). Each one buys a property and costs something.
| Constraint | In plain words | What it buys | What it costs |
|---|---|---|---|
| Client-server | UI and data storage are separate programs | Each side evolves and scales alone | A network between them |
| Stateless | Every request carries everything needed to understand it | Any server can answer; easy scaling, retries, crash recovery | Repeated data per request (tokens, context) |
| Cacheable | Responses say whether they may be reused | Fewer requests, lower latency | Staleness to manage |
| Uniform interface | Same methods, codes and media types for every resource | Generic clients, proxies, caches, tooling | Less efficient than a tailor-made protocol |
| Layered system | A component sees only the next layer | CDNs, gateways, load balancers can sit in between | Extra hops and latency |
| Code on demand (optional) | Server may send code the client runs | Thinner clients | Less visibility; optional for that reason |
The methods (RFC 9110, section 9).
| Method | Safe | Idempotent | Cacheable | Typical use | Typical success |
|---|---|---|---|---|---|
| GET | Yes | Yes | Yes | Read a resource or collection | 200, 206, 304 |
| HEAD | Yes | Yes | Yes | Headers only (size, ETag, existence) | 200 |
| OPTIONS | Yes | Yes | No | Capabilities, CORS preflight | 204 or 200 |
| POST | No | No | Only with explicit freshness, rarely used | Create in a collection, run a process | 201, 202, 200 |
| PUT | No | Yes | No | Replace or create at a known URI | 200, 201, 204 |
| PATCH | No | No (can be made so) | No | Partial update with a patch document | 200, 204 |
| DELETE | No | Yes | No | Remove | 204, 202, 200 |
The status codes you actually need.
| Code | Use it when | Never use it for |
|---|---|---|
| 200 OK | Success with a body | Errors with "ok": false inside |
| 201 Created | A new resource exists; send Location | Updates |
| 202 Accepted | Work queued; send a status URI | Work that already finished |
| 204 No Content | Success, nothing to return (DELETE) | Responses that have a body |
| 304 Not Modified | Conditional GET, client copy still valid | Anything but conditional requests |
| 400 Bad Request | Malformed syntax, bad query parameter, missing required header | Business-rule failures |
| 401 Unauthorized | No or invalid credentials; send WWW-Authenticate | Authenticated but not allowed |
| 403 Forbidden | Authenticated, not allowed, and existence is not secret | Hiding existence (use 404) |
| 404 Not Found | No such resource for this caller | Empty collections (that is 200 with []) |
| 409 Conflict | Request conflicts with current state (bad transition, duplicate) | Stale ETag (that is 412) |
| 412 Precondition Failed | If-Match / If-Unmodified-Since evaluated false | Missing precondition (428) |
| 422 Unprocessable Content | Well-formed JSON that breaks validation rules | Broken JSON (400) |
| 428 Precondition Required | Server demands a conditional write | Stale ETag |
| 429 Too Many Requests | Rate limit hit; send Retry-After | Server overload (503) |
| 503 Service Unavailable | Server overloaded or in maintenance; Retry-After | Client mistakes |
The header toolkit.
| Header | Direction | Job | Section |
|---|---|---|---|
Location | Response | URI of the created resource or status monitor | Status codes |
Accept / Content-Type | Both | Content negotiation and media type | Representations |
ETag / If-None-Match | Both | Cheap revalidation, 304 | Caching |
If-Match | Request | Lost-update protection, 412 | Concurrency |
Idempotency-Key | Request | Safe retry of POST | Idempotency |
Link | Response | Next page, related resources | Pagination |
Cache-Control | Response | Who may store, for how long | Caching |
RateLimit-Policy / RateLimit | Response | Quota and what is left | Rate limits |
Retry-After | Response | When to try again (429, 503, 202) | Rate limits |
Accept-Patch | Response | Which patch formats are accepted | PATCH |
The picture is Fielding's derivation: start from a style with no constraints and add one at a time. The uniform interface is the tallest step because it is four constraints in one, and code on demand is drawn dashed because it is the only optional one.
Why it exists
Before REST had a name, the Web already scaled to millions of servers that had never met their clients. Fielding's dissertation explains why: every request is self-contained, every response says whether it may be cached, and every component speaks the same small vocabulary, so caches, proxies and browsers can work without knowing the application. An API that tunnels procedure calls through POST /api throws all of that away: no cache can store it, no proxy can retry it, no client library knows what failed.
| RPC tunnelled over HTTP | Resource-oriented HTTP (REST-ish, level 2+) |
|---|---|
| One endpoint, verbs in the body | One URI per resource, verbs are HTTP methods |
| Always 200, error flag inside | Status code tells every intermediary what happened |
| Nothing cacheable | GET is cacheable, ETag gives 304 |
| Retries unsafe for everything | GET, PUT, DELETE retryable by definition; POST with a key |
| Client must read docs for every call | Generic clients, OpenAPI codegen, curl |
| Freedom to model anything as a call | Must find the noun (cancellation, not cancelOrder) |
| Lowest effort on day one | Some design effort up front, much less later |
The everyday picture. A public library. Every book has a shelf mark (the URI). There are a handful of standard forms everyone uses: borrow, return, reserve (the methods). The desk answers with a short set of stamps everybody understands: "on loan", "no such book", "come back tomorrow" (status codes). The catalogue card carries a "last updated" mark so you know whether your photocopy is still current (ETag), and a reservation slip has a number so handing it in twice does not reserve two copies (Idempotency-Key). Branch libraries can answer from their own copy of the catalogue without calling the central one (layered system and caching). The analogy returns throughout the page.
Three common misunderstandings, up front
- "REST means JSON over HTTP with nice URLs." REST is an architectural style with six constraints; JSON and pretty URLs are neither required nor sufficient. Most JSON APIs are Richardson level 2, which is useful but not what Fielding calls REST (Hypermedia).
- "POST is for create, PUT is for update." PUT means "store this representation at this URI" and is idempotent; it can create. POST means "process this according to your own rules" and is the right tool when the server picks the URI (Methods).
- "Idempotent means the same response every time." It means the same intended effect on the server. A second
DELETEmay answer 404 or 410 instead of 204 and still be idempotent (Methods).
Where it comes from
| Year | Event | Source |
|---|---|---|
| 1996–1999 | HTTP/1.0 (RFC 1945) and HTTP/1.1 (RFC 2068, then RFC 2616 in 1999); Fielding co-authors both | RFC 9110 lists the lineage |
| 2000 | Fielding's PhD dissertation, chapter 5 "Representational State Transfer (REST)" | ics.uci.edu |
| 2008 | Fielding, "REST APIs must be hypertext-driven" | roy.gbiv.com |
| 2008 | Leonard Richardson's QCon talk; Fowler writes it up as the Richardson Maturity Model on 18 March 2010 | martinfowler.com |
| March 2010 | RFC 5789 defines PATCH | rfc-editor.org |
| April 2012 | RFC 6585: 428, 429, 431, 511 | rfc-editor.org |
| April 2013 | RFC 6902 JSON Patch | rfc-editor.org |
| October 2014 | RFC 7396 JSON Merge Patch (obsoletes RFC 7386) | rfc-editor.org |
| March 2016 | RFC 7807 Problem Details for HTTP APIs | rfc-editor.org |
| 26 July 2017 | OpenAPI 3.0.0 published by the OpenAPI Initiative (the successor of Swagger 2.0) | spec.openapis.org |
| October 2017 | RFC 8288 Web Linking (the Link header) | rfc-editor.org |
| 2010s–2020s | Google AIP, Microsoft REST API Guidelines and Zalando RESTful API Guidelines published openly; the Azure guidelines changelog runs to 2024 | each guide |
| 15 February 2021 | OpenAPI 3.1.0: Schema Object becomes a superset of JSON Schema 2020-12 | spec.openapis.org |
| June 2022 | RFC 9110 HTTP Semantics and RFC 9111 HTTP Caching replace RFC 7230–7235 | rfc-editor.org |
| July 2023 | RFC 9457 Problem Details obsoletes RFC 7807 | rfc-editor.org |
| 2024-02-06 | Go 1.22: method and wildcard patterns in net/http.ServeMux | go.dev |
| 2026 | IETF HTTPAPI drafts: Idempotency-Key header (-09), RateLimit header fields (-12), still Internet-Drafts | datatracker.ietf.org |
Two points matter for the rest of the page. First, the dissertation describes the Web's architecture after the fact; it was never a specification for JSON APIs. Second, almost every rule in today's style guides (Google AIP, Microsoft, Zalando) is a pragmatic subset of RFC 9110 semantics plus conventions for what RFCs leave open (pagination, filtering, errors, long-running work).
The concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a definition, a request flow, real scenarios, how products and guides treat it, and the fix.
Fielding's constraints and statelessness Must-know
In plain words: REST is what you get when you take a client and a server and keep adding rules: keep them separate, forbid server-side session state, label responses as cacheable or not, make every resource speak the same interface, allow layers in between, and optionally let the server ship code.
Common misunderstanding: "Stateless means the server has no database." Statelessness is about session (application) state between requests, not resource state. Orders, users and carts in a database are resource state and are fine. What is ruled out is "remember what page this connection was on" in server memory, so request 2 only works on the server that saw request 1.
Definition: Fielding: "each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client." The uniform interface is four constraints: "identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state." Code on demand is "the only optional constraint" of the set.
Client Load balancer api-1 api-2
1 GET /orders?cursor=c1 -> answers page 2
Authorization: Bearer t
2 GET /orders?cursor=c2 -> answers page 3
(cursor and token travel with every request; api-2 never saw request 1)
3 api-1 crashes -> no session lost, the client just retries the GETReal scenario: an autoscaling group adds ten instances during a sale and none needs sticky sessions; a deploy kills pods mid-traffic and clients retry GETs transparently; a CDN serves GET /products/42 from an edge without asking the origin; an API gateway adds auth and rate limiting without the service changing (layered system).
What provides it / breaks it:
| Practice | Constraint it supports or breaks | Product example |
|---|---|---|
| Bearer token or signed cookie on every request | Supports stateless | OAuth 2.0 access tokens, Laravel Sanctum tokens |
| Server-side session in process memory | Breaks stateless (needs sticky sessions) | Default PHP file sessions on one box |
| Session in Redis keyed by cookie | Shared state, still not REST-stateless; scales | Laravel SESSION_DRIVER=redis |
Cache-Control, ETag on GET | Supports cacheable | NGINX proxy_cache, Cloudflare, Fastly |
POST /api for reads | Breaks cacheable and uniform interface | JSON-RPC, SOAP |
| CDN, reverse proxy, API gateway | Layered system | Cloudflare, AWS CloudFront, Envoy, Kong |
| JavaScript shipped to the browser | Code on demand | Any single-page app |
Fix / how to use it: carry identity in a token or cookie, carry position in a cursor, keep workflow state in resources (/carts/9, /checkouts/3) instead of server memory; see Scaling Strategies for stateless services and Web Sessions & Cookies for the browser side.
Resources, collections, sub-resources and URI design Must-know
In plain words: a resource is anything worth naming: an order, a customer, a collection of orders, "today's exchange rate", even a cancellation. Each gets a URI. Collections are plural nouns; items sit under them; things that only exist inside a parent are sub-resources.
Common misunderstanding: "Every database table is a resource and every resource is a table." Resources are the API's nouns, chosen for clients. /orders/7/cancellation or /payouts/3/approval may not be tables at all, while a join of three tables may be a single resource. Fielding: "Any information that can be named can be a resource."
Definition: a resource is the target of a URI; a collection resource lists and creates members (/orders); an item resource is one member (/orders/ord_01h...); a sub-resource is reachable only through its parent (/orders/{id}/items/{n}); a singleton sub-resource has exactly one instance per parent (/users/{id}/settings). Good URI design uses lowercase plural nouns, no verbs, no file extensions, no trailing slash, stable opaque ids, and at most one or two levels of nesting.
Client Orders API
1 GET /orders?status=paid -> 200 collection page
2 POST /orders {customer, total} -> 201 Location: /orders/ord_7
3 GET /orders/ord_7 -> 200 item, ETag "ord_7-v1"
4 GET /orders/ord_7/items -> 200 sub-collection
5 POST /orders/ord_7/cancellation -> 200 the state change is a resource
6 GET /customers/c_42/orders -> 200 the same orders, filtered viewReal scenario: a shop exposing /products, /carts/{id}/lines, /orders/{id}/shipments; a bank exposing /accounts/{id}/transactions with no PUT or DELETE (append-only); an admin action "approve payout" as POST /payouts/{id}/approval; a file API where /files/{id}/content is the binary and /files/{id} is the metadata.
How the guides name things:
| Rule | Google AIP-122 | Microsoft Azure guidelines | Zalando |
|---|---|---|---|
| Collection names | Plural, concise American English ("Collection identifiers must be concise American English terms") | Plural nouns | "MUST pluralize resource names" |
| Case in path | "Collection identifiers must be in camelCase", e.g. publishers/123/books | "DO use kebab-casing (preferred) or camel-casing for URL path segments" | "MUST use kebab-case for path segments" |
| Query parameters and JSON fields | snake_case in proto, camelCase in JSON | "DO use camel case for query parameter names" and for JSON fields | "MUST use snake_case (never camelCase) for query parameters" |
| Actions that are not CRUD | Custom method with a colon: POST /v1/{name=publishers/*/books/*}:archive (AIP-136) | .../collection/id:action pattern for actions | Model as sub-resource where possible |
| Nesting | Resource names encode the parent chain | Collection, id and action segments | "MUST identify resources and sub-resources via path segments" |
Fix / how to use it: name the nouns first (orders, lines, payments, refunds, cancellations); expose opaque public ids (ord_01hx..., ULID or UUID) instead of auto-increment keys; keep nesting to one level and offer flat lookups (/orders/{id} works even if /customers/{c}/orders/{id} exists); in Laravel, Route::apiResource('orders', ...) gives the five collection/item routes and ->shallow() keeps nested routes short; in Go 1.22, mux.HandleFunc("GET /orders/{id}", h) and r.PathValue("id").
Methods and their semantics: safe and idempotent Must-know
In plain words: a method tells everyone on the path what kind of action this is. Safe methods only read. Idempotent methods can be repeated with the same effect as once. Caches, browsers, proxies and retry libraries act on these two properties without knowing your API.
Common misunderstanding: "GET must never write anything." RFC 9110 allows a GET to log, count or warm a cache; what makes it safe is that "the client does not request, and does not expect, any state change on the origin server". A GET that charges a card or deletes a row is a bug; a GET that increments a view counter is acceptable but surprising.
Definition: RFC 9110 section 9.2.1: methods are safe "if their defined semantics are essentially read-only"; "the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe." Section 9.2.2: a method is idempotent "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." RFC 5789: "PATCH is neither safe nor idempotent". POST "requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics."
Client API Effect
1 PUT /users/7/avatar (bytes) -> 201 Created avatar stored
2 (timeout, retry) PUT again -> 200 OK same avatar, same state
3 DELETE /orders/ord_9 -> 204 deleted
4 (retry) DELETE /orders/ord_9 -> 410 Gone still deleted: idempotent
5 POST /payments {amount: 50} -> timeout
6 (retry) POST /payments -> 201 second payment! not idempotentReal scenario: a mobile client on a flaky network retries a PUT of profile settings safely; a reverse proxy retries a GET on another upstream after a connection reset (NGINX proxy_next_upstream: "normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server" once sent; Envoy retry policies are configured per route); a browser re-sends a GET after a back button but warns before re-sending a POST form; a payment POST without an idempotency key double-charges after a gateway timeout.
What each method is for:
| Method | Request body | Response body | Who chooses the URI | Retry by default in | Notes |
|---|---|---|---|---|---|
| GET | No meaning (avoid) | Representation | — | Browsers, proxies, Envoy, NGINX | Cacheable |
| HEAD | No | None, headers as GET | — | Same as GET | Go ServeMux: a GET pattern also matches HEAD |
| OPTIONS | Rare | Capabilities (Allow) | — | — | CORS preflight; see CORS |
| POST | Yes | Result or created resource | Server | Nobody (unsafe) | Add Idempotency-Key |
| PUT | Full representation | Optional | Client | Safe to retry | Missing fields mean "remove", not "keep" |
| PATCH | Patch document | Usually the new state | — | Not by default | Idempotent if it carries If-Match or only sets values |
| DELETE | Should not | Usually none | — | Safe to retry | 204 then 404/410 |
Fix / how to use it: pick the method by semantics, not by habit: client-chosen URI and full replacement is PUT, server-chosen id is POST to the collection, partial change is PATCH, an action is POST to a sub-resource; make POST retry-safe with an Idempotency-Key; make PATCH retry-safe with If-Match; answer a wrong method with 405 and an Allow header (Go's 1.22 mux does it for you).
PATCH formats: JSON Merge Patch vs JSON Patch Important
In plain words: PATCH sends a description of changes, and the Content-Type says which language that description is written in. Merge Patch is "here is a partial object, merge it in; null means delete". JSON Patch is "here is a list of operations: test, replace, add, remove, move, copy".
Common misunderstanding: "PATCH with application/json and a partial object is standard." It is a common convention, but the standardized partial-object format is application/merge-patch+json (RFC 7396). With plain application/json there is no agreed meaning for null, arrays or missing fields.
Definition: RFC 5789: "The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI." RFC 7396 merge patch: members present replace values, null removes the member, arrays are replaced whole. RFC 6902 JSON Patch: an array of operations, each with exactly one "op" (add, remove, replace, move, copy, test) and a JSON Pointer "path"; the document is applied atomically, so a failed test aborts everything.
Merge Patch (application/merge-patch+json) JSON Patch (application/json-patch+json)
1 {"status": "paid", "note": null} [{"op":"test","path":"/status","value":"pending"},
2 {"op":"replace","path":"/status","value":"paid"},
3 {"op":"remove","path":"/note"}]
4 note removed, status set same result, but only if status was still pending
5 cannot say "append to array" or "only if" can: test is a per-field preconditionReal scenario: a settings page saving only changed fields (merge patch); a collaborative editor that must change a field only if it still has the old value (JSON Patch test); inserting one element into a large array without resending it (JSON Patch add at /tags/-); Kubernetes accepting both plus its own strategic merge patch for lists.
| Format | Media type | Can delete a field | Array edits | Conditional per field | Who uses it |
|---|---|---|---|---|---|
| JSON Merge Patch | application/merge-patch+json | Yes, with null | Replace whole array | No | Microsoft Azure guidelines ("DO create and update resources using PATCH [RFC 5789] with JSON Merge Patch"), Laravel apps by convention |
| JSON Patch | application/json-patch+json | remove | add, remove, move by index | test | Kubernetes API ("JSON Patch, as defined in RFC6902") |
| Strategic merge patch | application/strategic-merge-patch+json | Directives | Merge lists by key | No | Kubernetes only |
| Field mask | update_mask field (AIP-134) | By listing it with no value | Replace | No | Google APIs (google.protobuf.FieldMask) |
| Plain partial JSON | application/json | Undefined | Undefined | No | Many APIs, ambiguous |
Fix / how to use it: accept application/merge-patch+json by default, add application/json-patch+json when clients need test or array operations, advertise both with Accept-Patch, answer 415 for anything else, and still require If-Match. Laravel parses +json bodies because isJson() checks for /json or +json; sometimes + nullable rules give merge-patch semantics. The Go example implements both formats in applyMerge and applyJSONPatch.
Status codes with precise use Must-know
In plain words: the status code is the one part of the response every intermediary understands. Pick the code that tells a generic client what to do next: use the body, follow a link, fix the request, authenticate, wait, or retry.
Common misunderstanding: "400 for every client error is fine, the body explains." A client library, an API gateway, a retry policy and a monitoring dashboard all branch on the code. 409 vs 412 vs 422 vs 429 lead to four different correct reactions (resolve, re-read, fix input, wait).
Definition: RFC 9110 section 15 groups codes into 1xx informational, 2xx successful, 3xx redirection, 4xx client error, 5xx server error, plus RFC 6585 for 428 and 429. Precise meanings used on this page: 202 "the request has been accepted for processing, but the processing has not been completed"; 303 "the server is redirecting the user agent to a different resource ... intended to provide an indirect response to the original request"; 412 "one or more conditions given in the request header fields evaluated to false"; 422 the server "understands the content type of the request content ... and the syntax of the request content is correct, but it was unable to process the contained instructions"; 428 "the origin server requires the request to be conditional"; 429 "the user has sent too many requests in a given amount of time".
Request Code Client's next move
1 POST /orders (Content-Type: text/plain) 415 send JSON
2 POST /orders {"customer": ""} 422 fix field customer
3 POST /orders no Idempotency-Key 400 add the header
4 PATCH /orders/7 no If-Match 428 GET, then send If-Match
5 PATCH /orders/7 If-Match: "7-v1" (now v2) 412 GET again, reapply, retry
6 PATCH /orders/7 {"status":"pending"} from shipped 409 show the user; do not retry
7 GET /orders (101st request this minute) 429 wait Retry-After seconds
8 GET /orders (database down) 503 retry with backoffReal scenario: a mobile client that retries on 5xx but not 4xx; an API gateway (Kong, AWS API Gateway) that turns upstream 502/504 into alerts; a CDN that caches 404 for a short time and 200 for longer; a payment client that must treat 409 "in flight" differently from 422 "key reused".
The full table with precise use:
| Code | Name (RFC 9110) | Precise use | Headers | Retry? |
|---|---|---|---|---|
| 200 | OK | Success with representation | ETag | — |
| 201 | Created | New resource; body is it | Location, ETag | — |
| 202 | Accepted | Queued; body is the status resource | Location, Retry-After | Poll |
| 204 | No Content | Success without body | ETag optional | — |
| 206 | Partial Content | Range request answered | Content-Range | — |
| 301 | Moved Permanently | URI moved forever; clients may change POST to GET | Location | Follow |
| 302 | Found | Temporary; same method change ambiguity | Location | Follow |
| 303 | See Other | Result lives elsewhere; always GET it | Location | Follow with GET |
| 304 | Not Modified | Conditional GET matched | ETag, Cache-Control | Use cache |
| 307 | Temporary Redirect | Temporary, method and body preserved | Location | Follow, same method |
| 308 | Permanent Redirect | Permanent, method and body preserved | Location | Follow, same method |
| 400 | Bad Request | Syntax, query parameter, header problems | — | No, fix |
| 401 | Unauthorized | Missing or invalid credentials | WWW-Authenticate | After auth |
| 403 | Forbidden | Known caller, not allowed | — | No |
| 404 | Not Found | Unknown, or hidden from this caller | — | No |
| 405 | Method Not Allowed | Path exists, method does not | Allow (required) | No |
| 406 | Not Acceptable | Cannot produce any type in Accept | — | No |
| 409 | Conflict | State conflict, duplicate, idempotency key in flight | — | After resolving |
| 410 | Gone | Existed, deliberately removed | — | No |
| 412 | Precondition Failed | If-Match false | — | After re-read |
| 415 | Unsupported Media Type | Body format not accepted | Accept or Accept-Patch | No, fix |
| 422 | Unprocessable Content | Semantic validation failed | — | No, fix |
| 428 | Precondition Required | Conditional request demanded | — | After adding If-Match |
| 429 | Too Many Requests | Rate limited | Retry-After, RateLimit | After delay |
| 500 | Internal Server Error | Unexpected bug | — | Maybe, idempotent only |
| 502 | Bad Gateway | Proxy got a bad upstream answer | — | Yes, idempotent only |
| 503 | Service Unavailable | Overload, maintenance | Retry-After | Yes, after delay |
| 504 | Gateway Timeout | Proxy's upstream did not answer in time | — | Idempotent only; the work may have happened |
Fix / how to use it: write the table for your API into the OpenAPI contract per operation; never return 200 with an error flag; reserve 5xx for your faults so 5xx rate is an honest SLI (SLOs); for redirects of non-GET requests use 307/308, not 301/302.
Representations and content negotiation Important
In plain words: the client never gets "the order", it gets a representation of it: JSON, CSV, a PDF, an older JSON shape. The client says what it can read with Accept; the server says what it sent with Content-Type.
Common misunderstanding: "Content-Type on a GET request matters." On a request, Content-Type describes the request body; a GET has none. What the client wants back is Accept. Mixing them up produces 415 on writes and wrong formats on reads.
Definition: a representation is a snapshot of resource state in a media type (application/json, application/problem+json, text/csv, vendor types such as application/vnd.api+json). Content negotiation (RFC 9110 section 12) is proactive: the server picks using Accept, Accept-Language, Accept-Encoding, and should send Vary listing the headers it used so caches keep variants apart. No acceptable type gives 406; an unreadable request body gives 415.
Client API / CDN
1 GET /orders/7/invoice Accept: application/pdf -> 200 Content-Type: application/pdf, Vary: Accept
2 GET /orders/7/invoice Accept: text/csv -> 200 Content-Type: text/csv (separate cache entry)
3 GET /orders/7/invoice Accept: image/png -> 406 Not Acceptable
4 POST /orders Content-Type: application/xml -> 415 Unsupported Media Type, Accept: application/jsonReal scenario: an export endpoint offering CSV and JSON Lines; errors as application/problem+json while successes are application/json; a JSON:API server answering application/vnd.api+json (Laravel 13's JsonApiResource "sets the Content-Type header to application/vnd.api+json"); a Zalando-style API versioning by media type.
| Product | Negotiation helper | Default |
|---|---|---|
Go net/http | None built in; parse Accept yourself, mime.ParseMediaType for Content-Type | http.DetectContentType sniffs if you do not set it |
| Laravel 13 | $request->expectsJson(), wantsJson(), accepts(), prefers(); error rendering picks JSON vs HTML "based on the Accept header" | JSON for api/* when the client accepts JSON |
| NGINX / Cloudflare | Cache key must include Accept if you negotiate on it | Cache key is URL only unless configured |
| JSON:API | application/vnd.api+json | Required media type |
Fix / how to use it: default to one JSON media type; negotiate only where clients really need several formats; always send Vary: Accept when you do; validate Content-Type on writes (Go: mime.ParseMediaType; Laravel: isJson()), answer 415 with what you accept.
HATEOAS and the Richardson maturity model Important
In plain words: HATEOAS ("hypermedia as the engine of application state") means the client discovers what it can do next from links in the response, like a person clicking through a website, instead of building URLs from documentation. The Richardson maturity model is a four-step ladder that shows how far an HTTP API has come toward that.
Common misunderstanding: "Level 3 is the only proper REST, so level 2 APIs are wrong." Fielding does say an API not driven by hypertext "cannot be RESTful and cannot be a REST API. Period." But Fowler is explicit that the model is "a tool to help us learn about the concepts and not something that should be used in some kind of assessment mechanism". Level 2 already gives caching, safe retries and tooling; level 3 pays off when clients are long-lived and many, or when the server wants to change URIs and workflows without client releases.
Definition: the model (Leonard Richardson, written up by Fowler on 18 March 2010): level 0 one endpoint and one method, HTTP as a tunnel ("the swamp of POX"); level 1 separate resources; level 2 HTTP verbs and status codes used as defined; level 3 hypermedia controls. Fielding 2008: "A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types".
Level 0 POST /api {"action":"cancelOrder","id":7} -> 200 {"ok":false}
Level 1 POST /orders/7 {"action":"cancel"} -> 200
Level 2 POST /orders/7/cancellation -> 200, or 409 if shipped
Level 3 GET /orders/7 -> {"status":"paid","links":{"cancel":"/orders/7/cancellation"}}
the client shows a Cancel button only when the link is presentWhy most APIs stop at level 2: clients are written against an OpenAPI document and generated SDKs, not discovered at runtime; JSON has no standard link format (HAL, JSON:API, Siren and RFC 8288 Link headers compete); the cost of adding links is small but the payoff needs clients that actually follow them. The pragmatic middle is "level 2 plus a few links": Link: rel="next" for pages, Location for created resources, and state-dependent action links such as cancel so the UI does not duplicate the server's state machine.
| Format | Where links live | Used by |
|---|---|---|
RFC 8288 Link header | Response header | Pagination: GitHub's REST API ("You can use the link header from the response to request additional pages"), this page's Go server |
HAL (application/hal+json) | _links object | An Internet-Draft format, common in hypermedia-first APIs |
| JSON:API | links and relationships | Laravel 13 JsonApiResource |
| Siren | actions with method and fields | Few, but the richest |
Ad hoc links object | Body | This page's Laravel OrderResource |
Fix / how to use it: add self, pagination and state-transition links where clients branch on state; keep URIs stable anyway, because most clients will hard-code them.
Pagination: offset, cursor and keyset Must-know
In plain words: never return an unbounded list. Offset pagination says "skip 400, give me 20"; cursor pagination says "give me 20 after this bookmark". The bookmark is usually built from the sort key (keyset), so the database jumps straight to it.
Common misunderstanding: "Cursor pagination is just a different spelling of page numbers." Offset pages shift when rows are inserted or deleted (you see duplicates or miss rows), and OFFSET 100000 makes the database read and discard 100,000 rows. A keyset cursor is stable under concurrent writes and costs the same on page 1 and page 10,000. What you lose is "jump to page 37" and, usually, an exact total count.
Definition: offset pagination: ?page=3&per_page=20 or ?offset=40&limit=20, SQL LIMIT 20 OFFSET 40. Keyset pagination: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 21, where the unique id makes the order total. Cursor pagination: the API wraps the keyset values (plus filters) in an opaque cursor string, returned as next_cursor and/or a Link: rel="next" header. Laravel's docs say it directly: "cursor pagination works by constructing "where" clauses that compare the values of the ordered columns". Deep SQL and index design: Pagination: Offset vs Keyset.
Offset under concurrent insert Keyset under the same insert
1 GET ?page=1 -> ids 20..11 GET ?limit=10 -> ids 20..11, cursor(11)
2 new order 21 inserted new order 21 inserted
3 GET ?page=2 -> ids 11..2 (11 shown twice) GET ?cursor(11) -> ids 10..1 (no duplicate)
4 a delete of id 15 instead would skip id 10 a delete changes nothing for later pagesReal scenario: an infinite-scroll feed; a sync job pulling every order changed since yesterday; an admin table that needs page numbers and a total (offset is fine there, under a few thousand rows); an export of 50 million rows (keyset or a long-running export, never offset).
| Product or guide | Style | Field names |
|---|---|---|
| Google AIP-158 | Opaque token | page_size, page_token, next_page_token; "The page_token field must not be required" |
| Microsoft Azure | Opaque link | value array plus nextLink absolute URL; "DO NOT return the nextLink field at all when returning the last page" |
| Zalando | Cursor preferred | "SHOULD prefer cursor-based pagination, avoid offset-based pagination" |
| Laravel 13 | paginate() offset with total, simplePaginate() offset without total, cursorPaginate() keyset | cursor query string, next_cursor in JSON |
| This page's Go server | Keyset cursor (base64url JSON of last id and filter) | limit, cursor, next_cursor, Link: rel="next" |
Fix / how to use it: default limit 20–50, cap at 100; return a cursor, not a page number, for anything that grows; include filters in the cursor or reject a cursor reused with different filters (the Go server answers 400 "invalid-cursor"); index (filter columns, sort column, id); if clients need totals, return an estimate or a separate /orders/count.
-- Keyset page for GET /orders?status=paid&limit=20, newest first.
-- Index: (customer_id, status, created_at, id) as in the Laravel migration.
SELECT public_id, status, total_cents, created_at, id
FROM orders
WHERE customer_id = $1
AND status = 'paid'
AND (created_at, id) < ($2, $3) -- values decoded from the cursor
ORDER BY created_at DESC, id DESC
LIMIT 21; -- one extra row tells you if there is a next pageFiltering, sorting and sparse fieldsets Important
In plain words: let clients narrow a collection (?status=paid), order it (?sort=-created_at) and ask for fewer fields (?fields=id,status), but only through an allow-list you can index and support forever.
Common misunderstanding: "Pass the sort and filter straight into the query builder, it is flexible." It is also SQL injection by column name, unindexed full scans and a contract you can never change. Every filter and sort you accept is a promise and an index.
Definition: filtering: query parameters per field (status=paid, created_after=...) or a small expression language (Google AIP-160 filter string, OData $filter). Sorting: a field list with direction (sort=-created_at,id; AIP-132 order_by, where "users append a " desc" suffix; for example: "foo desc, bar""). Sparse fieldsets: the client chooses returned fields (fields=id,status; JSON:API fields[orders]=...; Google field masks; Zalando "SHOULD support partial responses via filtering").
Client API
1 GET /orders?status=paid&sort=-created_at&fields=id,total_cents&limit=50
2 validate: status in enum, sort in allow-list,
3 fields subset of schema, limit <= 100
4 SELECT ... WHERE status='paid' ORDER BY created_at DESC, id DESC
5 <- 200 {"data":[{"id":"ord_9","total_cents":4999}, ...], "next_cursor":"..."}
6 GET /orders?sort=password_hash -> 400 invalid-parameterReal scenario: a mobile list screen that needs only id, title, thumbnail_url (sparse fieldsets cut payloads); a back-office search with ten filters (consider a search system instead of SQL); a partner integration syncing updated_after=... (needs an index on updated_at, id).
| Feature | Google AIP | Microsoft Azure | JSON:API / Laravel |
|---|---|---|---|
| Filter | AIP-160 filter string with a defined grammar | filter query option | filter[status]=paid (Spatie Laravel Query Builder is suggested by the Laravel docs) |
| Sort | AIP-132 order_by | orderby | sort=-created_at |
| Sparse fields | Field masks / read_mask | select | fields[orders]=id,status; Laravel JsonApiResource handles sparse fieldsets |
| Combined with pagination | Token must encode filters | nextLink includes them ("DO include any query parameters required by the service") | withQueryString() on the paginator |
Fix / how to use it: validate against allow-lists (Laravel Rule::in, Go map[string]bool), map public names to columns explicitly, add an index per supported combination, and put filters into the cursor so next links stay consistent.
Errors: Problem Details (RFC 9457) Must-know
In plain words: every error body has the same small shape: a type URI clients can switch on, a human title, the status, an optional detail and the instance it happened on, plus any extra fields you document.
Common misunderstanding: "Problem Details replaces status codes." The code still carries the class of failure; the body adds the specific reason. And title is for humans and may be translated, so clients branch on type, never on text.
Definition: RFC 9457 (July 2023, "This document obsoletes RFC 7807") defines "a "problem detail" to carry machine-readable details of errors in HTTP response content", serialized as application/problem+json, with members type, status, title, detail, instance, and extension members such as errors for field-level validation.
Client API
1 POST /orders {"customer":"","total_cents":0}
2 422 Content-Type: application/problem+json
3 {"type":"https://api.example.com/problems/validation",
4 "title":"Validation failed","status":422,"instance":"/orders",
5 "errors":[{"pointer":"#/customer","detail":"is required"}, ...]}
6 client maps pointer #/customer to the form field and shows "is required"Real scenario: a mobile app showing per-field validation; a partner SDK raising OutOfCreditError because type ends in out-of-credit; support staff searching logs by instance; an API gateway (Kong, Envoy) emitting its own 429 in the same format so clients have one parser.
| Product or guide | Error format |
|---|---|
| RFC 9457 | application/problem+json, type/title/status/detail/instance |
| Zalando | "MUST support problem JSON" |
| Microsoft Azure | Own envelope: {"error": {"code", "message", "target", "details", "innererror"} } plus x-ms-error-code header ("values are part of your API contract") |
| Google AIP-193 | google.rpc.Status with code, message, details |
| Laravel 13 default | {"message": ..., "errors": {...} } with 422; no Problem Details built in, so this page renders it in bootstrap/app.php |
Go net/http | http.Error writes text/plain; write your own helper (writeProblem here) |
Fix / how to use it: one helper in each stack; type URIs that resolve to documentation; never put stack traces or SQL in detail for 5xx; set Cache-Control: no-store on errors; keep the same shape at the gateway.
Idempotency keys for POST Must-know
In plain words: the client invents a unique key for one logical operation ("pay invoice 9, attempt group A") and sends it on every retry. The server remembers the key with the result, so the second, third and tenth try return the first result instead of doing the work again.
Common misunderstanding: "A unique constraint on the order table is enough." It stops a duplicate row, but the retry gets a 409 or 500 instead of the original 201, the client cannot tell success from failure, and side effects outside that table (the card charge, the email) still run twice. The key must cover the whole operation and its response.
Definition: the IETF draft (draft-ietf-httpapi-idempotency-key-header-09): "An idempotency key is a unique value generated by the client which the resource uses to recognize subsequent retries of the same request." The value is a structured-field String (Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"); "It is RECOMMENDED that a UUID [RFC9562] or a similar random identifier be used". The contract: missing key on an operation that requires it gives 400; a key reused "with a different request payload" gives 422; a retry "while the original request is still being processed" gives 409; a retry after completion gets "a response consistent with the request being completed". Servers detect payload reuse with an idempotency fingerprint and "SHOULD define such expiration policy and publish it". Stripe's API documents the same shape: keys "up to 255 characters long", pruned "after they're at least 24 hours old".
Client API Store
1 POST /payments Idempotency-Key: "k1" claim k1 (INSERT ... PK) k1 = in flight
2 charge card, 201 {id: pay_5} k1 = 201 + body
3 (response lost, client times out)
4 POST /payments Idempotency-Key: "k1" k1 exists, same fingerprint -> replay 201 {id: pay_5}
5 POST /payments "k1", amount changed fingerprint differs -> 422
6 two retries race while 2 is running second sees in flight -> 409, Retry-After: 1Real scenario: card payments and payouts; order submission from a mobile app that retries on reconnect; webhook senders that redeliver; an internal service calling another with a retry policy (Service Communication).
| Product | How POST is made retry-safe |
|---|---|
| IETF draft | Idempotency-Key request header; 400 / 409 / 422 contract |
| Stripe | Idempotency-Key; saves "the status code and body of the first request" (API v1) and replays them, "including 500 errors" |
| Google AIP-155 | request_id field (UUID4) on the request message; "This request is only idempotent if a request_id is provided" |
| Microsoft Azure | Repeatability-Request-ID and Repeatability-First-Sent headers; guidelines say "all HTTP methods are idempotent", POST included |
| Zalando | "MAY consider to support Idempotency-Key header", or a secondary key in the payload |
| Laravel 13 | No built-in middleware; this page's RequireIdempotencyKey uses a table whose primary key is the lock |
| Go | No built-in; this page's IdempotencyStore.Middleware |
Fix / how to use it: require the key on every non-idempotent POST that has side effects; scope keys per client; fingerprint method, path and body; store the response, not just "seen"; do not pin 4xx/5xx results to the key (this page deletes the row so a corrected request can reuse it; Stripe v1 chooses the opposite and replays 500s, so document your choice). Storage engines, TTL sweeps, crash between charge and save, and multi-region keys are in API Idempotency.
Concurrency control: ETag, If-Match and optimistic locking Must-know
In plain words: when you read a resource, the server gives you its version tag. When you write, you send the tag back: "only apply this if it is still the version I saw". If someone changed it in between, you get 412 and must re-read, instead of silently overwriting their work.
Common misunderstanding: "Our database transaction protects us." A transaction protects one request. The lost update here spans two requests minutes apart: Alice reads, Bob reads, Alice writes, Bob writes the old state back. Only a precondition that travels with the request (or a version in the body) catches it.
Definition: an ETag is an opaque validator for a representation; strong ETags must match byte for byte, weak ones (W/"...") mean semantically equivalent. If-Match makes a write conditional on a strong match; failure gives 412. If-None-Match on GET returns 304 when the tag still matches; If-None-Match: * on PUT means "create only if absent". RFC 6585 adds 428 for servers that require conditional writes, "to avoid the "lost update" problem". On the server this is optimistic concurrency: UPDATE ... SET version = version + 1 WHERE id = ? AND version = ? and check the affected-row count; mechanics in Optimistic vs Pessimistic Locking.
Alice API + DB Bob
1 GET /orders/7 -> ETag "7-v1" GET /orders/7 -> ETag "7-v1"
2 PATCH If-Match "7-v1" {status:paid} UPDATE ... WHERE version=1 (1 row)
3 <- 200 ETag "7-v2"
4 UPDATE ... WHERE version=1 (0 rows) <- PATCH If-Match "7-v1" {note:x}
5 412 Precondition Failed -> Bob re-reads v2, reapplies, PATCH "7-v2"
6 200 ETag "7-v3"Real scenario: two support agents editing the same ticket; a mobile app syncing an offline edit made yesterday; an inventory admin and an import job changing the same product; a configuration tool (Kubernetes uses resourceVersion the same way: when the version "provided is stale), the API server returns a 409 Conflict").
| Product or guide | Validator | Precondition | Failure |
|---|---|---|---|
| RFC 9110 | ETag | If-Match, If-Unmodified-Since | 412 |
| Google AIP-154 | etag field in the resource body | Sent back in the update request | ABORTED (HTTP 409) |
| Microsoft Azure | ETag header | "DO support caching and optimistic concurrency by honoring the If-Match, If-None-Match" | 412 |
| Kubernetes | metadata.resourceVersion | Body field | 409 Conflict |
| Laravel 13 | $response->setEtag() (Symfony) | Read If-Match yourself; compare-and-set with where('version', ...)->increment('version', 1, $changes) | Throw PreconditionFailedHttpException |
Go net/http | Set ETag header yourself | http.ServeContent handles If-Match for files; for APIs write precondition() | 412 |
Fix / how to use it: derive the ETag from a version column, not from hashing JSON on every request; require If-Match on PATCH/PUT/DELETE of shared resources (428 when absent); return the new ETag on every successful write; explain in the 412 body what to do.
Caching headers Important
In plain words: tell every cache on the path (browser, CDN, reverse proxy) whether it may keep a response, for how long, and how to check it is still fresh cheaply.
Common misunderstanding: "no-cache means do not cache." In RFC 9111 no-cache means "store it, but revalidate before every reuse"; the directive that forbids storing is no-store. Per-user API responses want private, no-cache plus an ETag; error responses and secrets want no-store.
Definition: Cache-Control directives (RFC 9111): max-age, s-maxage (shared caches only), public, private, no-cache, no-store, must-revalidate, stale-while-revalidate. Validators: ETag with If-None-Match, Last-Modified with If-Modified-Since. Vary names request headers that select the variant (Accept, Accept-Language; Authorization responses are not stored by shared caches unless explicitly allowed).
Browser CDN (Cloudflare) API
1 GET /products/42 miss 200 Cache-Control: public, max-age=60, s-maxage=300; ETag "p42-v8"
2 GET /products/42 (30 s later) browser cache hit, no request
3 GET /products/42 (2 min later) CDN hit (s-maxage 300)
4 GET /products/42 (6 min later) If-None-Match "p42-v8" -> 304, 0 bytes of bodyReal scenario: a public catalogue at 50,000 requests per second served almost entirely from a CDN; GET /me responses that must never be cached by a shared cache; a mobile app saving bandwidth with 304s; an outage page served stale-while-revalidate.
| Product | Knob |
|---|---|
| Laravel 13 | cache.headers middleware: cache.headers:public;max_age=30;s_maxage=300;stale_while_revalidate=600;etag |
Go net/http | Set Cache-Control/ETag headers; http.ServeContent answers conditional requests for byte content |
| NGINX | proxy_cache, proxy_cache_valid, proxy_cache_use_stale |
| Cloudflare / Fastly / CloudFront | Respect origin Cache-Control/s-maxage, plus their own cache rules |
Fix / how to use it: public read models get public, max-age, s-maxage; per-user reads get private, no-cache and an ETag; writes and errors get no-store; deeper cache design is in Caching and CDNs.
Rate-limit headers and Retry-After Important
In plain words: tell clients their quota and what is left before they hit it, and when they do hit it, answer 429 with how long to wait.
Common misunderstanding: "X-RateLimit-* is the standard." It is a widespread convention (GitHub, Laravel's throttle middleware) with no single meaning. The IETF HTTPAPI working group's draft defines RateLimit-Policy and RateLimit as structured fields; the syntax changed between drafts, so pin the draft version you implement.
Definition: RFC 6585 429 "MAY include a Retry-After header indicating how long to wait before making a new request". draft-ietf-httpapi-ratelimit-headers-12: RateLimit-Policy: burst;q=100;w=60,"daily";q=1000;w=86400 lists quota policies (q quota, w window seconds, qu unit, pk partition key); RateLimit: default;a=50;w=30 gives the available quota a and the effective window w. "If a response contains both the RateLimit and Retry-After fields, the Retry-After field MUST take precedence".
Client app-1 API (limit 100/min)
1 GET /orders 200 RateLimit-Policy: default;q=100;w=60
2 RateLimit: default;a=99;w=60
3 ... 99 more requests in 20 s ...
4 GET /orders 429 Retry-After: 40, RateLimit: default;a=0;w=40
5 client sleeps 40 s (plus jitter), resumesReal scenario: a public API with free and paid tiers; a partner integration that paces bulk syncs by reading a instead of failing; Laravel answering 429 automatically when a limiter is exceeded; NGINX limit_req at the edge, whose default is limit_req_status 503; (set it to 429).
| Product | Headers emitted |
|---|---|
Laravel 13 ThrottleRequests | X-RateLimit-Limit, X-RateLimit-Remaining; on 429 also Retry-After and X-RateLimit-Reset (framework source) |
| GitHub REST API | x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset (convention, not this page's source) |
| IETF draft -12 | RateLimit-Policy, RateLimit (and RateLimit-Partition) |
| Zalando | "MUST use code 429 with headers for rate limits" |
| This page's Go server | Draft -12 fields plus Retry-After |
Fix / how to use it: limit per authenticated client, not per IP when you can; send the fields on every response; 429 for quotas, 503 for overload (Load Shedding); algorithms (token bucket, sliding window, distributed counters) are in Rate Limiting.
Bulk and batch endpoints Good to know
In plain words: when clients must create or change hundreds of things, one request with many items beats hundreds of requests, but you must decide what happens when item 37 fails.
Common misunderstanding: "Return 200 and a list of results, done." Then a client that ignores the body thinks everything worked. Either make the batch atomic (all or nothing, a normal status code) or make partial success explicit (207-style per-item results or a long-running operation with a report).
Definition: a bulk endpoint accepts a collection of items in one request: POST /orders:batchCreate (Google AIP-233 custom method: "Some APIs need to allow users to create multiple resources in a single transaction"; AIP-233 discusses atomic vs partial success and restricts synchronous batch methods to atomic), or POST /orders/bulk. Sizes are capped; each item can carry its own idempotency key.
Client API
1 POST /orders:batchCreate {requests:[500 items]} Idempotency-Key: "b1"
2 validate all first; any invalid -> 422 listing pointers #/requests/37/total_cents
3 all valid -> one transaction -> 200 {orders:[...]}
4 too big for one transaction -> 202 + /operations/op_9, report lists per-item statusReal scenario: importing a CSV of products; a POS terminal uploading a day of offline sales; bulk-tagging 10,000 emails; marking notifications read.
| Choice | Status | When |
|---|---|---|
| Atomic synchronous batch | 200/201 or one 4xx | Small batches, one database |
| Partial success with per-item results | 200 with per-item status (or WebDAV 207) | Independent items, client can retry the failed ones |
| Asynchronous batch | 202 + status resource | Large or slow batches |
Fix / how to use it: cap items (100–1,000), validate everything before writing anything, make the batch idempotent, and never hide failures behind a bare 200.
Long-running operations Important
In plain words: if the work takes longer than a request should (exports, video transcodes, provisioning), accept it, answer at once with 202 and a URI where the client can watch it, and when it finishes, point to the result.
Common misunderstanding: "202 means it worked." RFC 9110: the request "might or might not eventually be acted upon"; "The 202 response is intentionally noncommittal." The status resource is the only place the outcome appears.
Definition: POST /exports → 202 Accepted, Location: /operations/op_1, Retry-After: 1, body is the operation {id, status: running}. GET /operations/op_1 → 200 while running; once done, either 200 with status: succeeded and a result link, or 303 See Other with Location of the result. Google AIP-151 returns a google.longrunning.Operation with a done field; Microsoft Azure returns 202 with an operation-location header to a status monitor.
Client API Worker
1 POST /exports?format=csv -> 202 Location: /operations/op_1, Retry-After: 1
2 enqueue job op_1 picks op_1
3 GET /operations/op_1 -> 200 {status: running}, Retry-After: 1
4 writes file, marks succeeded
5 GET /operations/op_1 -> 303 See Other, Location: /exports/exp_1
6 GET /exports/exp_1 -> 200 text/csv (or a presigned object-storage URL)Real scenario: a monthly statement export; an ML batch prediction job; creating a database cluster in a cloud console; a bulk import with a per-row report.
| Product or guide | Start | Poll | Done |
|---|---|---|---|
| Google AIP-151 | Method returns Operation | GET /v1/{name=operations/*} | done: true with response or error |
| Microsoft Azure | 202 + operation-location | Status monitor resource | status: Succeeded/Failed |
| This page (Go and Laravel) | 202 + Location + Retry-After | GET /operations/{id} | 303 to the result |
| Push alternatives | Webhook or SSE/WebSocket | — | Callback |
Fix / how to use it: make the start idempotent (Idempotency-Key), persist operations so a restart does not lose them, give results an expiry, and offer a webhook for clients that should not poll; job execution in Laravel is a queued job (Durable Workflows & Jobs).
Versioning summary Important
In plain words: design so that most changes are additive and need no version; when you must break, give the new contract a version and run both for a while.
Common misunderstanding: "Put /v1/ in every URL from day one and bump it for every change." A version bump is a migration for every client. Adding an optional field, a new endpoint or a new enum value (if clients were told to tolerate unknown values) is not breaking.
Definition: the main strategies are URI path (/v1/orders, Google APIs), query parameter (?api-version=2021-06-04, Microsoft Azure, which returns 400 "MissingApiVersionParameter" when it is absent), header (a custom version header such as Api-Version: 2026-11-01), and media type (Accept: application/vnd.example.order+json;version=2; Zalando "MUST use media type versioning" and "MUST not use URL versioning"). Breaking-change rules, deprecation headers, sunset policies and the expand/contract migration are in API Versioning & Evolution.
Change Breaking? Action
1 add optional response field "eta" No ship; clients ignore unknown fields
2 add optional request field No ship with a default
3 rename "total" to "total_cents" Yes add new field, deprecate old, remove in v2
4 make "note" required Yes new version or keep optional
5 change 200 to 202 for POST /orders Yes new version| Strategy | Example | Cache-friendly | Used by |
|---|---|---|---|
| URI path | /v1/orders | Yes | Google APIs (AIP examples use /v1/...), many public APIs |
| Query parameter | ?api-version=2021-06-04 | Yes | Microsoft Azure |
| Custom header | Api-Version: 2026-11-01 | Needs Vary | Date-pinned APIs |
| Media type | application/vnd.example+json;v=2 | Needs Vary: Accept | Zalando |
OpenAPI 3.1, contract-first and codegen Must-know
In plain words: write the API down as a machine-readable contract before (or while) you write the code, review it like code, and generate docs, client SDKs, server stubs, mocks and tests from it.
Common misunderstanding: "We generate the OpenAPI file from annotations, so we have a contract." Code-first output describes whatever the code happens to do, including accidental breaking changes. Contract-first means the contract is reviewed, versioned and diffed in CI, and the implementation is tested against it.
Definition: the OpenAPI Specification "defines a standard, programming language-agnostic interface description for HTTP APIs". In 3.1.0 (15 February 2021) "The Schema Object ... is a superset of JSON Schema Specification Draft 2020-12", so type: [string, 'null'] replaces 3.0's nullable: true, and webhooks are first-class. Contract-first (Zalando: "MUST follow API first principle") writes the document first; codegen turns it into clients and server interfaces (OpenAPI Generator, oapi-codegen for Go, Kiota); linting (Spectral) enforces the style guide; breaking-change diff (oasdiff) gates CI.
Step Tool (examples)
1 write orders.yaml, open a pull request editor, Spectral lint with your style rules
2 review resources, codes, headers humans
3 CI: diff against main oasdiff -> fail on breaking change
4 generate Go server interface + TS client oapi-codegen, OpenAPI Generator
5 mock for frontend work Prism
6 contract tests: real server vs document schemathesis or Pact-style testsThe contract for this page's service (both implementations follow it):
openapi: 3.1.0
info:
title: Orders API
version: 1.4.0
description: Contract-first definition of the orders resource used on this page.
servers:
- url: https://api.example.com
paths:
/orders:
get:
operationId: listOrders
parameters:
- { name: status, in: query, schema: { $ref: '#/components/schemas/Status' } }
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
- { name: cursor, in: query, description: 'Opaque; copy it from next_cursor or the Link header.', schema: { type: string } }
- { name: fields, in: query, description: 'Sparse fieldset, e.g. id,status', schema: { type: string } }
responses:
'200':
description: One page of orders.
headers:
Link: { description: 'rel="next" when another page exists', schema: { type: string } }
RateLimit: { schema: { type: string } }
content:
application/json:
schema:
type: object
required: [data]
properties:
data: { type: array, items: { $ref: '#/components/schemas/Order' } }
next_cursor: { type: string }
'400': { $ref: '#/components/responses/Problem' }
'429': { $ref: '#/components/responses/TooManyRequests' }
post:
operationId: createOrder
parameters:
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/NewOrder' }
responses:
'201':
description: Created.
headers:
Location: { required: true, schema: { type: string, format: uri-reference } }
ETag: { required: true, schema: { type: string } }
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'400': { $ref: '#/components/responses/Problem' }
'409': { $ref: '#/components/responses/Problem' }
'415': { $ref: '#/components/responses/Problem' }
'422': { $ref: '#/components/responses/Problem' }
/orders/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string, pattern: '^ord_[0-9a-z]+$' } }
get:
operationId: getOrder
parameters:
- { name: If-None-Match, in: header, schema: { type: string } }
responses:
'200':
description: The order.
headers:
ETag: { required: true, schema: { type: string } }
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'304': { description: Not modified; reuse your cached copy. }
'404': { $ref: '#/components/responses/Problem' }
'410': { $ref: '#/components/responses/Problem' }
patch:
operationId: updateOrder
parameters:
- { name: If-Match, in: header, required: true, schema: { type: string } }
requestBody:
required: true
content:
application/merge-patch+json:
schema: { $ref: '#/components/schemas/OrderPatch' }
application/json-patch+json:
schema:
type: array
items:
type: object
required: [op, path]
properties:
op: { enum: [add, remove, replace, test] }
path: { type: string }
value: {}
responses:
'200':
description: Updated; new ETag.
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'409': { $ref: '#/components/responses/Problem' }
'412': { $ref: '#/components/responses/Problem' }
'415': { $ref: '#/components/responses/Problem' }
'422': { $ref: '#/components/responses/Problem' }
'428': { $ref: '#/components/responses/Problem' }
delete:
operationId: deleteOrder
responses:
'204': { description: Deleted. }
'404': { $ref: '#/components/responses/Problem' }
'410': { $ref: '#/components/responses/Problem' }
components:
parameters:
IdempotencyKey:
name: Idempotency-Key
in: header
required: true
description: Structured-field string, e.g. "8e03978e-40d5-43e8-bc93-6894a57f9324". Kept 24 h.
schema: { type: string, maxLength: 257 }
schemas:
Status: { type: string, enum: [pending, paid, shipped, cancelled] }
NewOrder:
type: object
additionalProperties: false
required: [customer, total_cents]
properties:
customer: { type: string, minLength: 1 }
total_cents: { type: integer, minimum: 1 }
note: { type: [string, 'null'], maxLength: 500 }
OrderPatch:
type: object
additionalProperties: false
properties:
customer: { type: string, minLength: 1 }
status: { $ref: '#/components/schemas/Status' }
note: { type: [string, 'null'], description: 'null removes the note (RFC 7396)' }
Order:
type: object
required: [id, customer, status, total_cents, version, created_at]
properties:
id: { type: string, readOnly: true }
customer: { type: string }
status: { $ref: '#/components/schemas/Status' }
total_cents: { type: integer }
note: { type: [string, 'null'] }
version: { type: integer, readOnly: true }
created_at: { type: string, format: date-time, readOnly: true }
Problem:
type: object
properties:
type: { type: string, format: uri-reference }
title: { type: string }
status: { type: integer }
detail: { type: string }
instance: { type: string, format: uri-reference }
errors:
type: array
items:
type: object
properties:
pointer: { type: string }
detail: { type: string }
responses:
Problem:
description: RFC 9457 Problem Details.
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
TooManyRequests:
description: Rate limited.
headers:
Retry-After: { schema: { type: integer } }
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }| Tool | Role |
|---|---|
| OpenAPI 3.1 | The contract format |
| JSON Schema 2020-12 | Body schemas inside it |
| Spectral | Linting against a style guide |
| oapi-codegen (Go), OpenAPI Generator, Kiota | Server stubs and SDKs |
| Prism | Mock server |
| Laravel: Scribe, dedoc/scramble (third-party) | Generate docs from Laravel code (code-first) |
Security basics Important
In plain words: authenticate every request (stateless constraint), authorise every object (not just every route), never trust ids from the client, and leak nothing in errors.
Common misunderstanding: "The route has auth middleware, so the endpoint is secure." That checks who the caller is, not whether order 7 is theirs. Broken object-level authorization (changing the id in the URL to read someone else's data) is "API1:2023 Broken Object Level Authorization", the first item of the OWASP API Security Top 10.
Definition: 401 means no or invalid credentials and requires WWW-Authenticate; 403 means "I know you, and no"; 404 may be used instead of 403 to avoid revealing that a resource exists (Laravel Response::denyAsNotFound()). Tokens: OAuth 2.0 bearer tokens with scopes (OAuth 2.0 & OIDC, JWT), Laravel Sanctum personal tokens with abilities (tokenCan). Transport: TLS everywhere (Cryptography & TLS). Browser clients: CORS and CSRF (Sessions, Cookies & CORS).
Request Check Answer
1 GET /orders/ord_7 (no token) authentication 401 WWW-Authenticate: Bearer
2 GET /orders/ord_7 (token of user 42, owns it) policy view: allow 200
3 GET /orders/ord_8 (token of user 42, not his) policy view: deny 404 (not 403, hide existence)
4 PATCH /orders/ord_7 (token without orders:write) policy update: deny 404 or 403 by policy| Concern | Go | Laravel 13 |
|---|---|---|
| Authentication | Middleware verifying a JWT or session | auth:sanctum middleware |
| Object authorization | Check owner in the handler or a policy func | Policies + Gate::authorize('view', $order); Form Request authorize() returns 403 |
| Mass assignment | Decode into a request struct, DisallowUnknownFields | $fillable, $request->validated() |
| Input size | http.MaxBytesReader | post_max_size, validation max: |
| Errors | Problem Details without internals | render() callback, APP_DEBUG=false |
Deeper material: OWASP Top 10, Authorization Models, Authentication.
Naming conventions and API style guides Good to know
In plain words: pick one published API style guide, adopt it with a short list of exceptions, and lint against it, so 40 teams produce one API instead of 40.
Common misunderstanding: "Style guides are bikeshedding." They decide pagination, errors, long-running work, versioning and idempotency, which are expensive to change later; casing is the smallest part.
Definition: an API style guide is a set of normative rules (MUST/SHOULD) for an organisation's APIs. The three most cited: Google AIP (API Improvement Proposals, google.aip.dev: resource-oriented design AIP-121, resource names AIP-122, standard methods AIP-131 to 135, custom methods AIP-136, LRO AIP-151, etags AIP-154, request ids AIP-155, pagination AIP-158, filtering AIP-160, batch AIP-231 to 235); Microsoft REST API Guidelines (github.com/microsoft/api-guidelines, with the Azure-specific guidelines); Zalando RESTful API Guidelines (opensource.zalando.com).
Team writes orders.yaml -> Spectral ruleset "company-api-style" -> CI comment:
1 error path segment "/orderItems" must be kebab-case (Zalando rule)
2 error operation createOrder has no 4xx Problem response (house rule)
3 warn list operation without cursor parameter (house rule)| Topic | Google AIP | Microsoft Azure | Zalando |
|---|---|---|---|
| Pagination | page_token / next_page_token | nextLink | Cursor preferred |
| Errors | google.rpc.Status | error envelope + x-ms-error-code | Problem JSON |
| PATCH | Update with update_mask | JSON Merge Patch | JSON Merge Patch or JSON Patch |
| Idempotency | request_id | Repeatability headers | Idempotency-Key (MAY) |
| Versioning | Major version in path | api-version query parameter | Media type |
| Long-running | google.longrunning.Operation | 202 + operation-location | 202 + status resource |
| Casing | camelCase JSON | camelCase | snake_case JSON, kebab-case paths |
Mechanics
HTTP grammar you must get exactly right
| Thing | Exact form | Note |
|---|---|---|
| Strong ETag | ETag: "ord_000001-v2" | Quotes are part of the value |
| Weak ETag | ETag: W/"ord_000001-v2" | Never matches If-Match (strong comparison) |
If-Match list | If-Match: "a", "b" or * | * means "any current representation" |
Idempotency-Key | Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324" | Structured-field String: quoted |
Link next page | Link: </orders?cursor=eyJh...&limit=2>; rel="next" | RFC 8288; URI in angle brackets |
Retry-After | Retry-After: 40 or an HTTP-date | Seconds preferred (no clock skew) |
RateLimit-Policy | RateLimit-Policy: default;q=100;w=60 | Draft -12 syntax |
RateLimit | RateLimit: default;a=99;w=60 | a = available, w = window seconds |
Accept-Patch | Accept-Patch: application/merge-patch+json, application/json-patch+json | Send on 415 for PATCH and on OPTIONS |
Allow | Allow: DELETE, GET, HEAD, PATCH | Required with 405 |
Knobs in each stack
| Knob | Value used here | Why |
|---|---|---|
Go http.Server.ReadHeaderTimeout | 5 s | Slow-header (Slowloris) protection; the zero value means no limit |
Go http.MaxBytesReader | 1 MiB | Body cap per request |
Go json.Decoder.DisallowUnknownFields | on for create | Unknown members become 400 instead of silently ignored |
Page limit | default 20, max 100 | Bounded responses |
| Idempotency key TTL | 24 h | Published in the contract, matches Stripe's v1 minimum |
Laravel Limit::perMinute(120)->by('user:'.$id) | 120/min per user, 20/min per IP | Fair per-client quotas |
Laravel cursorPaginate(25) | 25 | Requires an orderBy on the paginated table's columns |
Laravel cache.headers | private;etag for user data | With etag it hashes the body (xxh128) when no ETag is set and calls isNotModified() |
Error messages you will actually see
| Where | Message | Meaning |
|---|---|---|
Go ServeMux, wrong method | 405 Method Not Allowed body Method Not Allowed with Allow | Pattern exists for other methods |
Go ServeMux, at registration | panic: pattern "GET /orders/{name}" (registered at main.go:8) conflicts with pattern "GET /orders/{id}" (registered at main.go:7): GET /orders/{name} matches the same requests as GET /orders/{id} | Two patterns match the same requests and neither is more specific (reproduced with Go 1.27) |
Go json.Decoder | json: unknown field "admin" | DisallowUnknownFields rejected a member |
Go http.MaxBytesReader | http: request body too large | Body exceeded the cap |
| Laravel validation | The total cents field must be at least 1. (422) | Form Request rule failed |
| Laravel, throttle | 429 Too Many Attempts. | ThrottleRequestsException thrown by ThrottleRequests |
| Laravel, policy denied | 403 This action is unauthorized. | AuthorizationException converted to 403 |
| Laravel, missing model | 404 No query results for model [App\Models\Order] ... | Route model binding found nothing (replace with Problem Details) |
| Azure | MissingApiVersionParameter (400) | No api-version query parameter |
Go
The module academy/rest-api-design (go 1.24 directive, standard library only) has the bad first version, the service package and a runnable server.
Before
An RPC tunnel: one URI, actions in the body, 200 for errors, offset paging over a map, last write wins, and a retried createOrder creates a second order.
// Command before is the RPC-over-HTTP shape many first APIs take.
// It works, but every request is POST /api, every answer is 200,
// errors hide in the body, nothing is cacheable and a retried
// "createOrder" creates a second order.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"sync"
)
type order struct {
ID int `json:"id"`
Customer string `json:"customer"`
Status string `json:"status"`
}
var (
mu sync.Mutex
nextID = 1
orders = map[int]*order{}
)
type call struct {
Action string `json:"action"`
Params json.RawMessage `json:"params"`
}
func api(w http.ResponseWriter, r *http.Request) {
var c call
_ = json.NewDecoder(r.Body).Decode(&c)
w.Header().Set("Content-Type", "application/json")
mu.Lock()
defer mu.Unlock()
switch c.Action {
case "createOrder":
var o order
_ = json.Unmarshal(c.Params, &o)
o.ID, o.Status = nextID, "pending"
nextID++
orders[o.ID] = &o
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
case "getOrder":
var p struct{ ID int }
_ = json.Unmarshal(c.Params, &p)
o, found := orders[p.ID]
if !found {
// 200 with an error flag: caches, proxies and clients see success.
_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": "not found"})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
case "listOrders":
// Offset paging over a map: unstable order, skipped and repeated rows.
var p struct{ Page, Size int }
_ = json.Unmarshal(c.Params, &p)
list := []*order{}
for _, o := range orders {
list = append(list, o)
}
start := p.Page * p.Size
if start > len(list) {
start = len(list)
}
end := min(start+p.Size, len(list))
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "orders": list[start:end], "total": strconv.Itoa(len(list))})
case "updateOrder":
// Last write wins: no version, no precondition, lost updates.
var o order
_ = json.Unmarshal(c.Params, &o)
orders[o.ID] = &o
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
default:
_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": fmt.Sprintf("unknown action %q", c.Action)})
}
}
func main() {
http.HandleFunc("/api", api)
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}After
Problem Details in one helper. kind becomes the last segment of type, so clients switch on a stable string.
// Package orders is a small REST service built on the Go 1.22+ net/http
// router: resources and collections, Problem Details (RFC 9457) errors,
// ETag/If-Match optimistic concurrency, cursor (keyset) pagination,
// sparse fieldsets, Idempotency-Key on POST, RateLimit headers and a
// long-running operation behind 202 Accepted.
package orders
import (
"encoding/json"
"net/http"
)
// ProblemTypeBase prefixes every problem "type" URI. A real API points it at
// documentation pages that explain each problem.
const ProblemTypeBase = "https://api.example.com/problems/"
// Problem is an RFC 9457 problem details object with one extension member.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []FieldError `json:"errors,omitempty"`
}
// FieldError is the "errors" extension used for 422 validation failures.
type FieldError struct {
Pointer string `json:"pointer"`
Detail string `json:"detail"`
}
// writeProblem sends application/problem+json. kind becomes the last segment of
// the type URI so clients can switch on it without parsing the title.
func writeProblem(w http.ResponseWriter, r *http.Request, status int, kind, title, detail string, errs ...FieldError) {
p := Problem{
Type: ProblemTypeBase + kind,
Title: title,
Status: status,
Detail: detail,
Instance: r.URL.Path,
Errors: errs,
}
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(p)
}The store keeps a Version per order (the ETag source), does compare-and-set updates, keeps tombstones for 410 and answers keyset queries.
package orders
import (
"errors"
"fmt"
"sort"
"sync"
"time"
)
// Order is the resource. Version is the optimistic-concurrency counter that
// the ETag is derived from; a SQL table carries it as a "version" column.
type Order struct {
ID string `json:"id"`
Customer string `json:"customer"`
Status string `json:"status"`
TotalCents int64 `json:"total_cents"`
Note *string `json:"note"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
}
// Errors the handlers map to status codes.
var (
ErrNotFound = errors.New("not found")
ErrGone = errors.New("gone")
ErrVersionMismatch = errors.New("version mismatch")
ErrBadTransition = errors.New("invalid status transition")
)
// allowed lists legal status transitions; anything else is a 409 Conflict.
var allowed = map[string][]string{
"pending": {"paid", "cancelled"},
"paid": {"shipped", "cancelled"},
"shipped": {},
"cancelled": {},
}
func canMove(from, to string) bool {
if from == to {
return true
}
for _, s := range allowed[from] {
if s == to {
return true
}
}
return false
}
// Store is an in-memory stand-in for a table ordered by primary key.
type Store struct {
mu sync.Mutex
seq int
rows map[string]*Order
deleted map[string]bool
now func() time.Time
}
// NewStore returns an empty store; now is injectable for tests.
func NewStore(now func() time.Time) *Store {
return &Store{rows: map[string]*Order{}, deleted: map[string]bool{}, now: now}
}
// Create inserts a new order with version 1. IDs are zero-padded so their
// string order equals insertion order, which keyset pagination relies on.
func (s *Store) Create(customer string, total int64, note *string) Order {
s.mu.Lock()
defer s.mu.Unlock()
s.seq++
o := &Order{
ID: fmt.Sprintf("ord_%06d", s.seq),
Customer: customer,
Status: "pending",
TotalCents: total,
Note: note,
Version: 1,
CreatedAt: s.now().UTC(),
}
s.rows[o.ID] = o
return *o
}
// Get returns a copy of one order, ErrGone for a deleted one.
func (s *Store) Get(id string) (Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.deleted[id] {
return Order{}, ErrGone
}
o, ok := s.rows[id]
if !ok {
return Order{}, ErrNotFound
}
return *o, nil
}
// Update applies fn only when the stored version equals want: the same
// compare-and-set as UPDATE ... WHERE id = $1 AND version = $2.
func (s *Store) Update(id string, want int64, fn func(*Order) error) (Order, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.deleted[id] {
return Order{}, ErrGone
}
o, ok := s.rows[id]
if !ok {
return Order{}, ErrNotFound
}
if o.Version != want {
return *o, ErrVersionMismatch
}
next := *o
if err := fn(&next); err != nil {
return *o, err
}
if !canMove(o.Status, next.Status) {
return *o, ErrBadTransition
}
next.Version++
*o = next
return next, nil
}
// Delete removes an order and keeps a tombstone so later reads answer 410.
func (s *Store) Delete(id string, want int64) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.deleted[id] {
return ErrGone
}
o, ok := s.rows[id]
if !ok {
return ErrNotFound
}
if want != 0 && o.Version != want {
return ErrVersionMismatch
}
delete(s.rows, id)
s.deleted[id] = true
return nil
}
// ListAfter is keyset pagination: rows with id > after, ordered by id,
// optionally filtered by status. It returns limit+1 rows at most so the
// caller can tell whether another page exists.
func (s *Store) ListAfter(after, status string, limit int) []Order {
s.mu.Lock()
defer s.mu.Unlock()
ids := make([]string, 0, len(s.rows))
for id := range s.rows {
ids = append(ids, id)
}
sort.Strings(ids)
out := []Order{}
for _, id := range ids {
if id <= after {
continue
}
o := s.rows[id]
if status != "" && o.Status != status {
continue
}
out = append(out, *o)
if len(out) == limit+1 {
break
}
}
return out
}The handlers use Go 1.22 patterns ("GET /orders/{id}", r.PathValue("id")). The mux answers 405 with Allow for a known path and wrong method, and a GET pattern also serves HEAD. Writes check Content-Type (415), PATCH needs If-Match (428, 412), merge patch and JSON Patch are both supported, the collection is cursor-paginated with a Link header and sparse fieldsets, deletes leave a 410 tombstone, cancellation is a sub-resource, and exports are a long-running operation (202, then 303).
package orders
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// Server wires the store, the idempotency layer and the rate limiter.
type Server struct {
store *Store
idem *IdempotencyStore
limiter *Limiter
mu sync.Mutex
ops map[string]*Operation
op int
// Exporter does the slow work behind POST /exports. Tests replace it.
Exporter func(format string) string
}
// Operation is the status resource of a long-running job (202 + poll).
type Operation struct {
ID string `json:"id"`
Status string `json:"status"` // running | succeeded
Result string `json:"result,omitempty"`
}
// New builds a server. limit is requests per window per client.
func New(store *Store, now func() time.Time, limit int, window time.Duration) *Server {
return &Server{
store: store,
idem: NewIdempotencyStore(now, 24*time.Hour),
limiter: NewLimiter(now, limit, window),
ops: map[string]*Operation{},
Exporter: func(string) string { time.Sleep(200 * time.Millisecond); return "exp_1" },
}
}
// Handler registers Go 1.22 method-and-wildcard patterns. The mux answers
// 405 with an Allow header for a known path and a wrong method, and a
// "GET" pattern also serves HEAD.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders", s.list)
mux.Handle("POST /orders", s.idem.Middleware(http.HandlerFunc(s.create)))
mux.HandleFunc("GET /orders/{id}", s.get)
mux.HandleFunc("PATCH /orders/{id}", s.patch)
mux.HandleFunc("DELETE /orders/{id}", s.delete)
mux.HandleFunc("POST /orders/{id}/cancellation", s.cancel)
mux.Handle("POST /exports", s.idem.Middleware(http.HandlerFunc(s.startExport)))
mux.HandleFunc("GET /operations/{id}", s.operation)
return s.limiter.Middleware(mux)
}
func etag(o Order) string { return fmt.Sprintf(`"%s-v%d"`, o.ID, o.Version) }
// versionFromETag turns `"ord_000001-v3"` back into 3 for that id.
func versionFromETag(tag, id string) (int64, bool) {
tag = strings.TrimSpace(tag)
if strings.HasPrefix(tag, "W/") { // If-Match needs strong comparison
return 0, false
}
tag = strings.Trim(tag, `"`)
prefix := id + "-v"
if !strings.HasPrefix(tag, prefix) {
return 0, false
}
v, err := strconv.ParseInt(strings.TrimPrefix(tag, prefix), 10, 64)
return v, err == nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func hasMediaType(r *http.Request, want ...string) bool {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return false
}
for _, w := range want {
if mt == w {
return true
}
}
return false
}
func (s *Server) storeError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, ErrNotFound):
writeProblem(w, r, http.StatusNotFound, "not-found", "Order not found", "")
case errors.Is(err, ErrGone):
writeProblem(w, r, http.StatusGone, "gone", "Order was deleted", "")
case errors.Is(err, ErrVersionMismatch):
writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed",
"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.")
case errors.Is(err, ErrBadTransition):
writeProblem(w, r, http.StatusConflict, "invalid-transition", "Status change not allowed", err.Error())
default:
writeProblem(w, r, http.StatusInternalServerError, "internal", "Internal error", "")
}
}
// ---- collection ----
type cursor struct {
After string `json:"a"`
Status string `json:"s,omitempty"`
}
func encodeCursor(c cursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func decodeCursor(s string) (cursor, error) {
var c cursor
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return c, err
}
return c, json.Unmarshal(b, &c)
}
var listable = map[string]bool{"id": true, "customer": true, "status": true, "total_cents": true, "note": true, "version": true, "created_at": true}
// sparse keeps only the requested top-level fields (fields=id,status).
func sparse(o Order, fields []string) map[string]any {
b, _ := json.Marshal(o)
var all map[string]any
_ = json.Unmarshal(b, &all)
if len(fields) == 0 {
return all
}
out := map[string]any{}
for _, f := range fields {
out[f] = all[f]
}
return out
}
func (s *Server) list(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit := 20
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > 100 {
writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Invalid limit", "limit must be an integer from 1 to 100",
FieldError{Pointer: "#/query/limit", Detail: "out of range"})
return
}
limit = n
}
c := cursor{Status: q.Get("status")}
if v := q.Get("cursor"); v != "" {
dc, err := decodeCursor(v)
if err != nil || (q.Has("status") && dc.Status != c.Status) {
writeProblem(w, r, http.StatusBadRequest, "invalid-cursor", "Invalid cursor",
"Use the cursor exactly as returned, with the same filters.")
return
}
c = dc
}
var fields []string
if v := q.Get("fields"); v != "" {
for _, f := range strings.Split(v, ",") {
if !listable[f] {
writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Unknown field", f,
FieldError{Pointer: "#/query/fields", Detail: "unknown field " + f})
return
}
fields = append(fields, f)
}
}
rows := s.store.ListAfter(c.After, c.Status, limit)
page := map[string]any{}
data := []map[string]any{}
for i, o := range rows {
if i == limit {
break
}
data = append(data, sparse(o, fields))
}
page["data"] = data
if len(rows) > limit {
next := encodeCursor(cursor{After: rows[limit-1].ID, Status: c.Status})
nq := url.Values{"cursor": {next}, "limit": {strconv.Itoa(limit)}}
if len(fields) > 0 {
nq.Set("fields", strings.Join(fields, ","))
}
page["next_cursor"] = next
w.Header().Set("Link", fmt.Sprintf(`</orders?%s>; rel="next"`, nq.Encode()))
}
w.Header().Set("Cache-Control", "private, no-cache")
writeJSON(w, http.StatusOK, page)
}
type createReq struct {
Customer string `json:"customer"`
TotalCents int64 `json:"total_cents"`
Note *string `json:"note"`
}
func (s *Server) create(w http.ResponseWriter, r *http.Request) {
if !hasMediaType(r, "application/json") {
writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Send application/json", "")
return
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
dec.DisallowUnknownFields()
var in createReq
if err := dec.Decode(&in); err != nil {
writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed request body", err.Error())
return
}
var errs []FieldError
if strings.TrimSpace(in.Customer) == "" {
errs = append(errs, FieldError{Pointer: "#/customer", Detail: "is required"})
}
if in.TotalCents <= 0 {
errs = append(errs, FieldError{Pointer: "#/total_cents", Detail: "must be greater than 0"})
}
if len(errs) > 0 {
writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Validation failed", "", errs...)
return
}
o := s.store.Create(in.Customer, in.TotalCents, in.Note)
w.Header().Set("Location", "/orders/"+o.ID)
w.Header().Set("ETag", etag(o))
writeJSON(w, http.StatusCreated, o)
}
// ---- item ----
func (s *Server) get(w http.ResponseWriter, r *http.Request) {
o, err := s.store.Get(r.PathValue("id"))
if err != nil {
s.storeError(w, r, err)
return
}
tag := etag(o)
w.Header().Set("ETag", tag)
w.Header().Set("Cache-Control", "private, no-cache")
for _, t := range strings.Split(r.Header.Get("If-None-Match"), ",") {
t = strings.TrimPrefix(strings.TrimSpace(t), "W/") // weak comparison for GET
if t == tag || t == "*" {
w.WriteHeader(http.StatusNotModified)
return
}
}
writeJSON(w, http.StatusOK, o)
}
// precondition enforces If-Match on writes: 428 when absent, 412 when it
// cannot match. It returns the version the client claims to have read.
func (s *Server) precondition(w http.ResponseWriter, r *http.Request, id string) (int64, bool) {
h := r.Header.Get("If-Match")
if h == "" {
writeProblem(w, r, http.StatusPreconditionRequired, "precondition-required", "If-Match required",
"GET the order and send its ETag in If-Match.")
return 0, false
}
v, ok := versionFromETag(h, id)
if !ok {
writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "ETag does not belong to this order")
return 0, false
}
return v, true
}
// applyMerge implements RFC 7396 for the writable members: a member with
// null removes the value, an absent member leaves it unchanged.
func applyMerge(o *Order, patch map[string]json.RawMessage) []FieldError {
var errs []FieldError
for k, raw := range patch {
switch k {
case "customer", "status":
var v string
if err := json.Unmarshal(raw, &v); err != nil || v == "" {
errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "must be a non-empty string"})
continue
}
if k == "customer" {
o.Customer = v
} else {
o.Status = v
}
case "note":
if string(raw) == "null" {
o.Note = nil
continue
}
var v string
if err := json.Unmarshal(raw, &v); err != nil {
errs = append(errs, FieldError{Pointer: "#/note", Detail: "must be a string or null"})
continue
}
o.Note = &v
default:
errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "is read-only or unknown"})
}
}
return errs
}
type jsonPatchOp struct {
Op string `json:"op"`
Path string `json:"path"`
Value json.RawMessage `json:"value"`
}
// applyJSONPatch supports the RFC 6902 ops that make sense on a flat
// resource: test, replace, add and remove. Any failed test aborts the whole
// document, which is how RFC 6902 makes a patch atomic.
func applyJSONPatch(o *Order, ops []jsonPatchOp) []FieldError {
for i, op := range ops {
name := strings.TrimPrefix(op.Path, "/")
ptr := fmt.Sprintf("#/%d", i)
switch op.Op {
case "test":
cur := sparse(*o, []string{name})[name]
var want any
_ = json.Unmarshal(op.Value, &want)
if fmt.Sprint(cur) != fmt.Sprint(want) {
return []FieldError{{Pointer: ptr, Detail: "test failed for " + op.Path}}
}
case "replace", "add":
if errs := applyMerge(o, map[string]json.RawMessage{name: op.Value}); errs != nil {
return errs
}
case "remove":
if name != "note" {
return []FieldError{{Pointer: ptr, Detail: "only /note can be removed"}}
}
o.Note = nil
default:
return []FieldError{{Pointer: ptr, Detail: "unsupported op " + op.Op}}
}
}
return nil
}
func (s *Server) patch(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
w.Header().Set("Accept-Patch", "application/merge-patch+json, application/json-patch+json")
merge := hasMediaType(r, "application/merge-patch+json")
if !merge && !hasMediaType(r, "application/json-patch+json") {
writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Unsupported patch format",
"Use application/merge-patch+json or application/json-patch+json")
return
}
want, ok := s.precondition(w, r, id)
if !ok {
return
}
body := http.MaxBytesReader(w, r.Body, 1<<20)
var mergeDoc map[string]json.RawMessage
var ops []jsonPatchOp
var err error
if merge {
err = json.NewDecoder(body).Decode(&mergeDoc)
} else {
err = json.NewDecoder(body).Decode(&ops)
}
if err != nil {
writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed patch document", err.Error())
return
}
var verrs []FieldError
o, err := s.store.Update(id, want, func(o *Order) error {
if merge {
verrs = applyMerge(o, mergeDoc)
} else {
verrs = applyJSONPatch(o, ops)
}
if verrs != nil {
return errors.New("validation")
}
return nil
})
if verrs != nil {
writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Patch cannot be applied", "", verrs...)
return
}
if err != nil {
s.storeError(w, r, err)
return
}
w.Header().Set("ETag", etag(o))
writeJSON(w, http.StatusOK, o)
}
func (s *Server) delete(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
var want int64
if h := r.Header.Get("If-Match"); h != "" {
v, ok := versionFromETag(h, id)
if !ok {
writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "")
return
}
want = v
}
if err := s.store.Delete(id, want); err != nil {
s.storeError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// cancel is a state change modelled as creating a "cancellation"
// sub-resource instead of a verb in the URI (POST /cancelOrder).
// Cancelling an already cancelled order returns the same 200: the
// effect is idempotent even though POST is not by definition.
func (s *Server) cancel(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
cur, err := s.store.Get(id)
if err != nil {
s.storeError(w, r, err)
return
}
o, err := s.store.Update(id, cur.Version, func(o *Order) error { o.Status = "cancelled"; return nil })
if err != nil {
s.storeError(w, r, err)
return
}
w.Header().Set("ETag", etag(o))
writeJSON(w, http.StatusOK, o)
}
// ---- long-running operation ----
func (s *Server) startExport(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.op++
op := &Operation{ID: fmt.Sprintf("op_%d", s.op), Status: "running"}
s.ops[op.ID] = op
snapshot := *op
s.mu.Unlock()
format := r.URL.Query().Get("format")
go func() {
res := s.Exporter(format)
s.mu.Lock()
op.Status, op.Result = "succeeded", "/exports/"+res
s.mu.Unlock()
}()
w.Header().Set("Location", "/operations/"+op.ID)
w.Header().Set("Retry-After", "1")
writeJSON(w, http.StatusAccepted, snapshot)
}
// operation answers 200 while the job runs and 303 See Other, pointing at
// the result, once it has finished.
func (s *Server) operation(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
op, ok := s.ops[r.PathValue("id")]
var snap Operation
if ok {
snap = *op
}
s.mu.Unlock()
if !ok {
writeProblem(w, r, http.StatusNotFound, "not-found", "Operation not found", "")
return
}
if snap.Status == "succeeded" {
w.Header().Set("Location", snap.Result)
w.WriteHeader(http.StatusSeeOther)
return
}
w.Header().Set("Retry-After", "1")
writeJSON(w, http.StatusOK, snap)
}Idempotency-Key middleware implementing the draft's 400/409/422/replay contract, scoped per client and fingerprinted on method, path and body:
package orders
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"strings"
"sync"
"time"
)
// IdempotencyStore implements the API contract of the IETF Idempotency-Key
// draft for POST: 400 when the key is missing, 409 while the first request
// is still running, 422 when the key is reused with a different payload, and
// a replay of the stored response otherwise. Storage design (SQL table,
// Redis, TTL sweeps) is the subject of /system-design/api-idempotency; this
// one is in memory.
type IdempotencyStore struct {
mu sync.Mutex
rows map[string]*idemRow
now func() time.Time
ttl time.Duration
}
type idemRow struct {
fingerprint string
done bool
status int
header http.Header
body []byte
expires time.Time
}
// NewIdempotencyStore keeps keys for ttl (the draft asks servers to publish it).
func NewIdempotencyStore(now func() time.Time, ttl time.Duration) *IdempotencyStore {
return &IdempotencyStore{rows: map[string]*idemRow{}, now: now, ttl: ttl}
}
// parseKey accepts the draft's sf-string form ("abc") and, leniently, a bare token.
func parseKey(h string) string {
h = strings.TrimSpace(h)
if len(h) >= 2 && h[0] == '"' && h[len(h)-1] == '"' {
h = h[1 : len(h)-1]
}
if len(h) > 255 {
return ""
}
return h
}
type recorder struct {
http.ResponseWriter
status int
buf bytes.Buffer
}
func (r *recorder) WriteHeader(code int) { r.status = code; r.ResponseWriter.WriteHeader(code) }
func (r *recorder) Write(b []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
r.buf.Write(b)
return r.ResponseWriter.Write(b)
}
// Middleware wraps a POST handler.
func (s *IdempotencyStore) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := parseKey(r.Header.Get("Idempotency-Key"))
if key == "" {
writeProblem(w, r, http.StatusBadRequest, "idempotency-key-missing", "Idempotency-Key is missing",
"This operation requires an Idempotency-Key header (1 to 255 characters).")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
writeProblem(w, r, http.StatusRequestEntityTooLarge, "too-large", "Body too large", "")
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
sum := sha256.Sum256(append([]byte(r.Method+" "+r.URL.Path+"\n"), body...))
fp := hex.EncodeToString(sum[:])
// Scope keys by caller so two tenants cannot collide or probe each other.
scoped := r.Header.Get("X-Client-Id") + "|" + key
s.mu.Lock()
row, seen := s.rows[scoped]
if seen && s.now().After(row.expires) {
delete(s.rows, scoped)
seen = false
}
switch {
case seen && row.fingerprint != fp:
s.mu.Unlock()
writeProblem(w, r, http.StatusUnprocessableEntity, "idempotency-key-reused", "Idempotency-Key is already used",
"The key was used with a different request payload.")
return
case seen && !row.done:
s.mu.Unlock()
w.Header().Set("Retry-After", "1")
writeProblem(w, r, http.StatusConflict, "idempotency-key-in-flight", "A request is outstanding for this Idempotency-Key", "")
return
case seen:
s.mu.Unlock()
for k, v := range row.header {
w.Header()[k] = v
}
w.Header().Set("Idempotent-Replayed", "true")
w.WriteHeader(row.status)
_, _ = w.Write(row.body)
return
}
row = &idemRow{fingerprint: fp, expires: s.now().Add(s.ttl)}
s.rows[scoped] = row
s.mu.Unlock()
rec := &recorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
s.mu.Lock()
defer s.mu.Unlock()
if rec.status >= 400 {
// Do not pin a failure to the key: the client may fix the request
// (4xx) or the server may recover (5xx) and the same key retried.
delete(s.rows, scoped)
return
}
// Replay only the headers that describe the result, not per-response
// ones such as RateLimit.
keep := http.Header{}
for _, k := range []string{"Content-Type", "Location", "ETag"} {
if v := w.Header().Values(k); len(v) > 0 {
keep[k] = v
}
}
row.done, row.status, row.header, row.body = true, rec.status, keep, rec.buf.Bytes()
})
}RateLimit headers (draft -12 syntax) on a fixed-window limiter:
package orders
import (
"fmt"
"net"
"net/http"
"strconv"
"sync"
"time"
)
// Limiter is a fixed-window counter per client that advertises its policy
// with the IETF RateLimit-Policy / RateLimit fields (draft-ietf-httpapi-
// ratelimit-headers-12 syntax) and answers 429 with Retry-After. The
// algorithms themselves live in /system-design/rate-limiting-algorithms.
type Limiter struct {
mu sync.Mutex
now func() time.Time
limit int
window time.Duration
counts map[string]*windowCount
}
type windowCount struct {
start time.Time
n int
}
// NewLimiter allows limit requests per window per client key.
func NewLimiter(now func() time.Time, limit int, window time.Duration) *Limiter {
return &Limiter{now: now, limit: limit, window: window, counts: map[string]*windowCount{}}
}
func clientKey(r *http.Request) string {
if id := r.Header.Get("X-Client-Id"); id != "" {
return id // an authenticated client id in a real API
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// Middleware applies the limit to every request.
func (l *Limiter) Middleware(next http.Handler) http.Handler {
w := int(l.window / time.Second)
policy := fmt.Sprintf("default;q=%d;w=%d", l.limit, w)
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
now := l.now()
l.mu.Lock()
c, ok := l.counts[clientKey(r)]
if !ok || now.Sub(c.start) >= l.window {
c = &windowCount{start: now}
l.counts[clientKey(r)] = c
}
c.n++
remaining := max(l.limit-c.n, 0)
reset := int((l.window - now.Sub(c.start) + time.Second - 1) / time.Second)
over := c.n > l.limit
l.mu.Unlock()
rw.Header().Set("RateLimit-Policy", policy)
rw.Header().Set("RateLimit", fmt.Sprintf("default;a=%d;w=%d", remaining, reset))
if over {
rw.Header().Set("Retry-After", strconv.Itoa(reset))
writeProblem(rw, r, http.StatusTooManyRequests, "rate-limited", "Too many requests",
fmt.Sprintf("Limit is %d requests per %d s. Retry after %d s.", l.limit, w, reset))
return
}
next.ServeHTTP(rw, r)
})
}Tests with httptest. httptest.NewServer runs the real handler on a loopback port; an injected clock makes rate-limit windows deterministic. They cover 201 + Location + ETag, the four Idempotency-Key outcomes, 422/415/400 as Problem Details, 304, 428, 412, a failing JSON Patch test, 409 on a bad transition, cursor pages that visit every row exactly once with sparse fields, 204 then 410, 405 with Allow, HEAD, 429 with Retry-After, and 202 then 303.
package orders
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type clock struct{ t time.Time }
func (c *clock) now() time.Time { return c.t }
func newTest(t *testing.T, limit int) (*Server, *httptest.Server, *clock) {
t.Helper()
c := &clock{t: time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)}
s := New(NewStore(c.now), c.now, limit, time.Minute)
ts := httptest.NewServer(s.Handler())
t.Cleanup(ts.Close)
return s, ts, c
}
func do(t *testing.T, ts *httptest.Server, method, path, body string, hdr ...string) *http.Response {
t.Helper()
req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
for i := 0; i+1 < len(hdr); i += 2 {
req.Header.Set(hdr[i], hdr[i+1])
}
cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := cl.Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { res.Body.Close() })
return res
}
func decode[T any](t *testing.T, res *http.Response) T {
t.Helper()
var v T
if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
t.Fatal(err)
}
return v
}
func create(t *testing.T, ts *httptest.Server, key, body string) *http.Response {
return do(t, ts, "POST", "/orders", body, "Content-Type", "application/json", "Idempotency-Key", `"`+key+`"`)
}
func TestCreateReturns201LocationAndETag(t *testing.T) {
_, ts, _ := newTest(t, 100)
res := create(t, ts, "k1", `{"customer":"c-42","total_cents":4999}`)
if res.StatusCode != 201 || res.Header.Get("Location") != "/orders/ord_000001" || res.Header.Get("ETag") != `"ord_000001-v1"` {
t.Fatalf("got %d %q %q", res.StatusCode, res.Header.Get("Location"), res.Header.Get("ETag"))
}
}
func TestIdempotencyKeyContract(t *testing.T) {
_, ts, _ := newTest(t, 100)
body := `{"customer":"c-42","total_cents":4999}`
if res := do(t, ts, "POST", "/orders", body, "Content-Type", "application/json"); res.StatusCode != 400 {
t.Fatalf("missing key: want 400, got %d", res.StatusCode)
}
first := decode[Order](t, create(t, ts, "k1", body))
replay := create(t, ts, "k1", body)
again := decode[Order](t, replay)
if replay.StatusCode != 201 || replay.Header.Get("Idempotent-Replayed") != "true" || again.ID != first.ID {
t.Fatalf("replay: %d %q %s vs %s", replay.StatusCode, replay.Header.Get("Idempotent-Replayed"), again.ID, first.ID)
}
if res := create(t, ts, "k1", `{"customer":"c-42","total_cents":1}`); res.StatusCode != 422 {
t.Fatalf("reuse with other payload: want 422, got %d", res.StatusCode)
}
if res := create(t, ts, "k2", body); decode[Order](t, res).ID == first.ID {
t.Fatal("a new key must create a new order")
}
}
func TestValidationIsProblemDetails(t *testing.T) {
_, ts, _ := newTest(t, 100)
res := create(t, ts, "k1", `{"customer":"","total_cents":0}`)
if res.StatusCode != 422 || res.Header.Get("Content-Type") != "application/problem+json" {
t.Fatalf("got %d %s", res.StatusCode, res.Header.Get("Content-Type"))
}
p := decode[Problem](t, res)
if p.Type != ProblemTypeBase+"validation" || len(p.Errors) != 2 || p.Status != 422 {
t.Fatalf("problem: %+v", p)
}
if res := do(t, ts, "POST", "/orders", `x`, "Content-Type", "text/plain", "Idempotency-Key", "k9"); res.StatusCode != 415 {
t.Fatalf("want 415, got %d", res.StatusCode)
}
if res := create(t, ts, "k8", `{"customer":"a","total_cents":1,"admin":true}`); res.StatusCode != 400 {
t.Fatalf("unknown member: want 400, got %d", res.StatusCode)
}
}
func TestConditionalGetAndOptimisticConcurrency(t *testing.T) {
_, ts, _ := newTest(t, 100)
create(t, ts, "k1", `{"customer":"c-42","total_cents":4999,"note":"leave at door"}`)
res := do(t, ts, "GET", "/orders/ord_000001", "")
tag := res.Header.Get("ETag")
if res := do(t, ts, "GET", "/orders/ord_000001", "", "If-None-Match", tag); res.StatusCode != 304 {
t.Fatalf("want 304, got %d", res.StatusCode)
}
merge := []string{"Content-Type", "application/merge-patch+json"}
if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, merge...); res.StatusCode != 428 {
t.Fatalf("no If-Match: want 428, got %d", res.StatusCode)
}
// Alice patches with the ETag she read: 200 and a new ETag.
ok := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid","note":null}`, append(merge, "If-Match", tag)...)
o := decode[Order](t, ok)
if ok.StatusCode != 200 || o.Version != 2 || o.Note != nil || ok.Header.Get("ETag") != `"ord_000001-v2"` {
t.Fatalf("patch: %d %+v", ok.StatusCode, o)
}
// Bob still holds the old ETag: 412, his write cannot silently win.
if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"customer":"bob"}`, append(merge, "If-Match", tag)...); res.StatusCode != 412 {
t.Fatalf("stale If-Match: want 412, got %d", res.StatusCode)
}
// JSON Patch with a failing test op changes nothing.
jp := []string{"Content-Type", "application/json-patch+json", "If-Match", `"ord_000001-v2"`}
if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 422 {
t.Fatalf("failed test op: want 422, got %d", res.StatusCode)
}
if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"paid"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 200 {
t.Fatalf("json patch: want 200, got %d", res.StatusCode)
}
// shipped -> pending is not a legal transition: 409.
if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"pending"}`, append(merge, "If-Match", `"ord_000001-v3"`)...); res.StatusCode != 409 {
t.Fatalf("bad transition: want 409, got %d", res.StatusCode)
}
if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, "Content-Type", "application/json", "If-Match", `"ord_000001-v3"`); res.StatusCode != 415 || res.Header.Get("Accept-Patch") == "" {
t.Fatalf("wrong patch type: want 415 + Accept-Patch, got %d", res.StatusCode)
}
}
func TestCursorPaginationWalksEveryRowOnce(t *testing.T) {
_, ts, _ := newTest(t, 1000)
for i := 0; i < 7; i++ {
create(t, ts, "k"+string(rune('a'+i)), `{"customer":"c","total_cents":100}`)
}
type page struct {
Data []map[string]any `json:"data"`
Next string `json:"next_cursor"`
}
seen := map[string]bool{}
path := "/orders?limit=3&fields=id,status"
for pages := 0; path != ""; pages++ {
res := do(t, ts, "GET", path, "")
p := decode[page](t, res)
for _, row := range p.Data {
if len(row) != 2 {
t.Fatalf("sparse fieldset ignored: %v", row)
}
id := row["id"].(string)
if seen[id] {
t.Fatalf("duplicate %s", id)
}
seen[id] = true
}
path = ""
if link := res.Header.Get("Link"); link != "" {
path = strings.TrimSuffix(strings.TrimPrefix(link, "<"), `>; rel="next"`)
}
if pages > 5 {
t.Fatal("too many pages")
}
}
if len(seen) != 7 {
t.Fatalf("saw %d rows, want 7", len(seen))
}
if res := do(t, ts, "GET", "/orders?cursor=not-a-cursor!", ""); res.StatusCode != 400 {
t.Fatalf("bad cursor: want 400, got %d", res.StatusCode)
}
}
func TestDeleteThen410AndMethodNotAllowed(t *testing.T) {
_, ts, _ := newTest(t, 100)
create(t, ts, "k1", `{"customer":"c","total_cents":100}`)
if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 204 {
t.Fatalf("want 204, got %d", res.StatusCode)
}
if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 410 {
t.Fatalf("second delete: want 410, got %d", res.StatusCode)
}
if res := do(t, ts, "GET", "/orders/ord_999999", ""); res.StatusCode != 404 {
t.Fatalf("want 404, got %d", res.StatusCode)
}
res := do(t, ts, "PUT", "/orders/ord_000001", "{}")
if res.StatusCode != 405 || !strings.Contains(res.Header.Get("Allow"), "PATCH") {
t.Fatalf("want 405 with Allow, got %d %q", res.StatusCode, res.Header.Get("Allow"))
}
if res := do(t, ts, "HEAD", "/orders", ""); res.StatusCode != 200 {
t.Fatalf("HEAD: want 200, got %d", res.StatusCode)
}
}
func TestRateLimitHeadersAnd429(t *testing.T) {
_, ts, c := newTest(t, 2)
res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
if res.Header.Get("RateLimit-Policy") != "default;q=2;w=60" || res.Header.Get("RateLimit") != "default;a=1;w=60" {
t.Fatalf("headers: %q %q", res.Header.Get("RateLimit-Policy"), res.Header.Get("RateLimit"))
}
do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
c.t = c.t.Add(20 * time.Second)
res = do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
if res.StatusCode != 429 || res.Header.Get("Retry-After") != "40" {
t.Fatalf("want 429 Retry-After 40, got %d %q", res.StatusCode, res.Header.Get("Retry-After"))
}
if res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-2"); res.StatusCode != 200 {
t.Fatalf("other client: want 200, got %d", res.StatusCode)
}
}
func TestLongRunningOperation(t *testing.T) {
s, ts, _ := newTest(t, 1000)
release := make(chan struct{})
s.Exporter = func(string) string { <-release; return "exp_7" }
res := do(t, ts, "POST", "/exports?format=csv", "", "Idempotency-Key", "e1")
if res.StatusCode != 202 || res.Header.Get("Location") != "/operations/op_1" {
t.Fatalf("want 202 + Location, got %d %q", res.StatusCode, res.Header.Get("Location"))
}
if res := do(t, ts, "GET", "/operations/op_1", ""); res.StatusCode != 200 {
t.Fatalf("running: want 200, got %d", res.StatusCode)
}
close(release)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
res := do(t, ts, "GET", "/operations/op_1", "")
if res.StatusCode == 303 {
if res.Header.Get("Location") != "/exports/exp_7" {
t.Fatalf("Location %q", res.Header.Get("Location"))
}
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("operation never finished")
}The server used in the lab:
// Command server runs the orders API on 127.0.0.1:8080 for the lab.
package main
import (
"log"
"net/http"
"time"
"academy/rest-api-design/orders"
)
func main() {
srv := orders.New(orders.NewStore(time.Now), time.Now, 100, time.Minute)
h := &http.Server{
Addr: "127.0.0.1:8080",
Handler: srv.Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Println("listening on", h.Addr)
log.Fatal(h.ListenAndServe())
}The Go angle
| Go feature | Use here | Note |
|---|---|---|
http.ServeMux patterns (Go 1.22+) | "GET /orders/{id}", "POST /orders/{id}/cancellation" | "the most specific pattern wins"; 405 + Allow automatic |
Request.PathValue | Read {id} | {path...} matches the rest; {$} matches only the exact path with trailing slash |
mime.ParseMediaType | 415 checks | Ignores parameters such as charset |
json.Decoder.DisallowUnknownFields | Strict create bodies | Use a separate decoder for PATCH |
http.MaxBytesReader | Body limits | Returns an error after the limit |
net/http/httptest | NewServer, NewRecorder for tests | No real network needed beyond loopback |
encoding/base64.RawURLEncoding | Opaque, URL-safe cursors | Sign or encrypt if cursors must not be forged |
http.ServeContent | Byte ranges (206) and conditional GET for files | Not for JSON resources |
| Ecosystem | oapi-codegen (OpenAPI to Go), chi, echo, gin routers | The stdlib mux is enough for most services since 1.22 |
Laravel
Before
Verbs in URIs, mass assignment from $request->all(), the model serialised as-is, 200 for "not found", no ownership check, offset pages with a client-controlled size.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* The shape many first Laravel APIs take: verbs in the URI, 200 for
* everything, the model serialized as-is, offset paging, no ownership
* check, last write wins and a retried POST creates a second order.
*
* Route::post('/api/createOrder', [OrderControllerBefore::class, 'create']);
* Route::get('/api/getOrders', [OrderControllerBefore::class, 'list']);
* Route::post('/api/updateOrder/{id}', [OrderControllerBefore::class, 'update']);
*/
class OrderControllerBefore
{
public function create(Request $request): JsonResponse
{
// Mass assignment straight from input, no validation.
$order = Order::create($request->all());
return response()->json(['success' => true, 'order' => $order]);
}
public function list(Request $request): JsonResponse
{
// Every column (internal ones too), offset paging, COUNT(*) per page.
$orders = Order::paginate($request->integer('per_page', 1000));
return response()->json(['success' => true, 'data' => $orders]);
}
public function update(Request $request, int $id): JsonResponse
{
$order = Order::find($id);
if ($order === null) {
// A "not found" that every cache and client reads as success.
return response()->json(['success' => false, 'error' => 'not found']);
}
$order->update($request->all());
return response()->json(['success' => true]);
}
}After
Routes. Route::apiResource registers index, store, show, update and destroy without the HTML-only create/edit routes; middlewareFor('store', ...) attaches the idempotency middleware to one action; withTrashed(['show']) lets soft-deleted orders reach show() so it can answer 410.
<?php
use App\Http\Controllers\OperationController;
use App\Http\Controllers\OrderController;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Support\Facades\Route;
// bootstrap/app.php loads this file with the "api" prefix, so these are
// /api/orders, /api/orders/{order}, /api/exports and /api/operations/{operation}.
Route::middleware(['auth:sanctum'])->group(function () {
// index, store, show, update, destroy; no HTML-only create/edit routes.
// {order} is resolved by Order::getRouteKeyName() (public_id).
// withTrashed(['show']) lets show() see soft-deleted rows and answer 410.
Route::apiResource('orders', OrderController::class)
->middlewareFor('store', RequireIdempotencyKey::class)
->withTrashed(['show']);
// A state change modelled as a sub-resource, not POST /cancelOrder.
Route::post('orders/{order}/cancellation', [OrderController::class, 'cancel'])
->name('orders.cancel');
// Long-running work: 202 Accepted + a status resource.
Route::post('exports', [OperationController::class, 'store'])
->middleware([RequireIdempotencyKey::class, 'throttle:exports'])
->name('exports.store');
Route::get('operations/{operation}', [OperationController::class, 'show'])
->whereUuid('operation')
->name('operations.show');
});The model: getRouteKeyName() makes route model binding resolve {order} by an opaque public_id; the version column feeds the ETag.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class Order extends Model
{
use HasFactory, SoftDeletes;
public const STATUSES = ['pending', 'paid', 'shipped', 'cancelled'];
private const TRANSITIONS = [
'pending' => ['paid', 'cancelled'],
'paid' => ['shipped', 'cancelled'],
'shipped' => [],
'cancelled' => [],
];
protected $fillable = ['customer_id', 'total_cents', 'note', 'status'];
protected $attributes = ['status' => 'pending', 'version' => 1];
protected static function booted(): void
{
// Public, non-guessable identifier; the integer key never leaves the database.
static::creating(fn (Order $order) => $order->public_id ??= 'ord_'.Str::lower((string) Str::ulid()));
}
/** Route model binding resolves {order} by this column. */
public function getRouteKeyName(): string
{
return 'public_id';
}
public function etag(): string
{
return "{$this->public_id}-v{$this->version}";
}
public function canMoveTo(string $status): bool
{
return $status === $this->status || in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
}
protected function casts(): array
{
return ['total_cents' => 'integer', 'version' => 'integer'];
}
}Form Requests. authorize() returning false gives 403 before the controller runs; failed rules give 422. sometimes plus nullable gives JSON Merge Patch semantics, and prohibited rejects read-only members.
<?php
namespace App\Http\Requests;
use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
class StoreOrderRequest extends FormRequest
{
/** A false return becomes 403 before the controller runs. */
public function authorize(): bool
{
return $this->user()->can('create', Order::class);
}
/** Failing rules become 422; bootstrap/app.php renders it as Problem Details. */
public function rules(): array
{
return [
'total_cents' => ['required', 'integer', 'min:1'],
'note' => ['nullable', 'string', 'max:500'],
];
}
}<?php
namespace App\Http\Requests;
use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* JSON Merge Patch (RFC 7396) semantics with Laravel rules: "sometimes"
* means an absent member is left unchanged, "nullable" lets null clear it.
* Laravel parses application/merge-patch+json because isJson() accepts
* any Content-Type containing "+json".
*/
class UpdateOrderRequest extends FormRequest
{
public function authorize(): bool
{
// Route model binding already resolved {order}.
return $this->user()->can('update', $this->route('order'));
}
public function rules(): array
{
return [
'status' => ['sometimes', 'required', Rule::in(Order::STATUSES)],
'note' => ['sometimes', 'nullable', 'string', 'max:500'],
// Read-only members are rejected, not silently ignored.
'id' => ['prohibited'],
'version' => ['prohibited'],
'total_cents' => ['prohibited'],
];
}
}API Resource: the representation is a contract, with sparse fieldsets and state-dependent links.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;
/**
* The representation is a contract, not the table: the integer key, the
* customer foreign key and deleted_at never leave the server.
*/
class OrderResource extends JsonResource
{
public const FIELDS = ['id', 'status', 'total_cents', 'note', 'version', 'created_at', 'links'];
public function toArray(Request $request): array
{
$data = [
'id' => $this->public_id,
'status' => $this->status,
'total_cents' => $this->total_cents,
'note' => $this->note,
'version' => $this->version,
'created_at' => $this->created_at?->toIso8601ZuluString(),
// A little hypermedia: what the client may do next.
'links' => array_filter([
'self' => route('orders.show', $this->resource),
'cancel' => $this->canMoveTo('cancelled') && $this->status !== 'cancelled'
? route('orders.cancel', $this->resource) : null,
]),
];
// Sparse fieldsets: ?fields=id,status (validated in the controller).
$fields = $request->query('fields');
return is_string($fields) ? Arr::only($data, explode(',', $fields)) : $data;
}
}Policy: someone else's order is a 404 via Response::denyAsNotFound(); writes need the orders:write Sanctum ability.
<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class OrderPolicy
{
public function viewAny(User $user): bool
{
return true; // the query is scoped to the user's own orders
}
/** Someone else's order answers 404, not 403, so ids cannot be probed. */
public function view(User $user, Order $order): Response
{
return $order->customer_id === $user->id
? Response::allow()
: Response::denyAsNotFound();
}
public function create(User $user): bool
{
return $user->tokenCan('orders:write');
}
public function update(User $user, Order $order): Response
{
return $this->view($user, $order)->allowed() && $user->tokenCan('orders:write')
? Response::allow()
: Response::denyAsNotFound();
}
public function delete(User $user, Order $order): Response
{
return $this->update($user, $order);
}
}Controller: cursorPaginate() with allow-listed filters and sorts, 201 + Location + ETag, conditional GET with isNotModified(), If-Match with a compare-and-set increment('version', 1, $changes), 204 on delete and 410 afterwards, cancellation as a sub-resource.
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;
class OrderController extends Controller
{
/** GET /api/orders?status=paid&sort=-created_at&fields=id,status&limit=25&cursor=... */
public function index(Request $request): AnonymousResourceCollection
{
Gate::authorize('viewAny', Order::class);
$q = $request->validate([
'status' => ['sometimes', Rule::in(Order::STATUSES)],
'sort' => ['sometimes', Rule::in(['created_at', '-created_at'])], // allow-list, never raw input
'fields' => ['sometimes', 'string', function (string $attr, string $value, \Closure $fail) {
if (array_diff(explode(',', $value), OrderResource::FIELDS) !== []) {
$fail('Unknown field in fields.');
}
}],
'limit' => ['sometimes', 'integer', 'between:1,100'],
]);
$dir = ($q['sort'] ?? '-created_at') === '-created_at' ? 'desc' : 'asc';
// Keyset under the hood: WHERE (created_at, id) < (?, ?) ORDER BY created_at, id.
// The id tie-breaker makes the order total, so no row is skipped or repeated.
$orders = Order::query()
->where('customer_id', $request->user()->id)
->when($q['status'] ?? null, fn ($query, $status) => $query->where('status', $status))
->orderBy('created_at', $dir)
->orderBy('id', $dir)
->cursorPaginate($q['limit'] ?? 25)
->withQueryString();
return OrderResource::collection($orders);
}
/** POST /api/orders (RequireIdempotencyKey runs first). */
public function store(StoreOrderRequest $request): JsonResponse
{
$order = Order::create([...$request->validated(), 'customer_id' => $request->user()->id]);
return $order->toResource(OrderResource::class)
->response()
->setStatusCode(201)
->header('Location', route('orders.show', $order))
->setEtag($order->etag());
}
/** GET /api/orders/{order}: ETag + If-None-Match gives 304. */
public function show(Request $request, Order $order): JsonResponse
{
Gate::authorize('view', $order);
if ($order->trashed()) {
throw new GoneHttpException('This order was deleted.');
}
$response = $order->toResource(OrderResource::class)
->response()
->setEtag($order->etag())
->header('Cache-Control', 'private, no-cache');
$response->isNotModified($request); // turns it into an empty 304 when the tag matches
return $response;
}
/** PATCH /api/orders/{order} with application/merge-patch+json and If-Match. */
public function update(UpdateOrderRequest $request, Order $order): JsonResponse
{
$expected = $this->versionFromIfMatch($request, $order);
$changes = $request->validated();
if (isset($changes['status']) && ! $order->canMoveTo($changes['status'])) {
throw new ConflictHttpException("Cannot move from {$order->status} to {$changes['status']}.");
}
// Compare-and-set: UPDATE orders SET ..., version = version + 1
// WHERE id = ? AND version = ? -- 0 rows means someone else won.
$affected = Order::query()
->whereKey($order->getKey())
->where('version', $expected)
->increment('version', 1, $changes);
if ($affected === 0) {
throw new PreconditionFailedHttpException('The order changed since you read it.');
}
$order->refresh();
return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
}
/** DELETE /api/orders/{order}: 204, then 410 on later reads. */
public function destroy(Request $request, Order $order): Response
{
Gate::authorize('delete', $order);
if ($request->hasHeader('If-Match')) {
$this->versionFromIfMatch($request, $order);
}
$order->delete();
return response()->noContent();
}
/** POST /api/orders/{order}/cancellation: repeating it changes nothing. */
public function cancel(Request $request, Order $order): JsonResponse
{
Gate::authorize('update', $order);
if (! $order->canMoveTo('cancelled')) {
throw new ConflictHttpException("A {$order->status} order cannot be cancelled.");
}
if ($order->status !== 'cancelled') {
$order->forceFill(['status' => 'cancelled', 'version' => $order->version + 1])->save();
}
return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
}
/** 428 when If-Match is missing, 412 when it names another version. */
private function versionFromIfMatch(Request $request, Order $order): int
{
$header = $request->header('If-Match');
if ($header === null) {
throw new PreconditionRequiredHttpException('Send the ETag you read in If-Match.');
}
$tag = trim($header);
if ($tag !== '"'.$order->etag().'"') { // strong comparison: W/ tags never match
throw new PreconditionFailedHttpException('The order changed since you read it.');
}
return $order->version;
}
}Idempotency-Key middleware with the table's primary key as the lock:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
/**
* The Idempotency-Key API contract (IETF draft): 400 without a key, 409
* while the first request with the key is still running, 422 when the key
* is reused with another payload, otherwise replay the stored response.
* The primary key (client_id, idempotency_key) is the lock. Storage design,
* TTL sweeps and crash recovery: /system-design/api-idempotency.
*/
class RequireIdempotencyKey
{
private const REPLAYED_HEADERS = ['Content-Type', 'Location', 'ETag'];
public function handle(Request $request, Closure $next): Response
{
$key = trim((string) $request->header('Idempotency-Key'), " \t\"");
if ($key === '' || strlen($key) > 255) {
return $this->problem(400, 'idempotency-key-missing', 'Idempotency-Key is missing',
'This operation requires an Idempotency-Key header (1 to 255 characters).');
}
$clientId = (string) ($request->user()?->getAuthIdentifier() ?? $request->ip());
$fingerprint = hash('sha256', $request->method().' '.$request->path()."\n".$request->getContent());
$where = ['client_id' => $clientId, 'idempotency_key' => $key];
try {
DB::table('idempotency_keys')->insert($where + [
'fingerprint' => $fingerprint,
'expires_at' => now()->addDay(),
'created_at' => now(),
]);
} catch (UniqueConstraintViolationException) {
$row = DB::table('idempotency_keys')->where($where)->first();
if ($row->fingerprint !== $fingerprint) {
return $this->problem(422, 'idempotency-key-reused', 'Idempotency-Key is already used',
'The key was used with a different request payload.');
}
if ($row->status_code === null) {
return $this->problem(409, 'idempotency-key-in-flight',
'A request is outstanding for this Idempotency-Key', null, ['Retry-After' => '1']);
}
return response($row->response_body, $row->status_code,
json_decode($row->response_headers, true) + ['Idempotent-Replayed' => 'true']);
}
$response = $next($request);
if ($response->getStatusCode() >= 400) {
// Do not pin a failure to the key: the client may fix the request and retry.
DB::table('idempotency_keys')->where($where)->delete();
return $response;
}
$headers = [];
foreach (self::REPLAYED_HEADERS as $name) {
if ($response->headers->has($name)) {
$headers[$name] = $response->headers->get($name);
}
}
DB::table('idempotency_keys')->where($where)->update([
'status_code' => $response->getStatusCode(),
'response_headers' => json_encode($headers),
'response_body' => $response->getContent(),
]);
return $response;
}
private function problem(int $status, string $kind, string $title, ?string $detail, array $headers = []): Response
{
return response()->json(array_filter([
'type' => "https://api.example.com/problems/{$kind}",
'title' => $title,
'status' => $status,
'detail' => $detail,
]), $status, $headers + ['Content-Type' => 'application/problem+json']);
}
}Rate limiting: named limiters in AppServiceProvider, plus a small middleware that adds the IETF fields next to Laravel's X-RateLimit-*:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Used by throttle:api ($middleware->throttleApi() in bootstrap/app.php).
// Over the limit Laravel answers 429 with Retry-After; bootstrap/app.php
// turns the ThrottleRequestsException into Problem Details.
RateLimiter::for('api', function (Request $request) {
return $request->user()
? Limit::perMinute(120)->by('user:'.$request->user()->id)
: Limit::perMinute(20)->by('ip:'.$request->ip());
});
// Expensive endpoints get their own, smaller bucket.
RateLimiter::for('exports', fn (Request $request) => Limit::perHour(10)->by('user:'.$request->user()?->id));
}
}<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Laravel's ThrottleRequests middleware emits X-RateLimit-Limit and
* X-RateLimit-Remaining (plus Retry-After and X-RateLimit-Reset on 429).
* This adds the IETF draft fields (draft-ietf-httpapi-ratelimit-headers-12)
* next to them so standard clients can pace themselves. Register it
* before throttling in the api group so it sees the throttle headers.
*/
class AddRateLimitFields
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$limit = $response->headers->get('X-RateLimit-Limit');
$remaining = $response->headers->get('X-RateLimit-Remaining');
if ($limit !== null && $remaining !== null) {
$response->headers->set('RateLimit-Policy', "api;q={$limit};w=60");
$retry = $response->headers->get('Retry-After');
$response->headers->set('RateLimit', "api;a={$remaining}".($retry !== null ? ";w={$retry}" : ''));
}
return $response;
}
}Problem Details exception rendering for everything under api/*:
<?php
use App\Http\Middleware\AddRateLimitFields;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->throttleApi(); // throttle:api on the api group
$middleware->prependToGroup('api', AddRateLimitFields::class);
})
->withExceptions(function (Exceptions $exceptions): void {
// Every error under /api/* becomes RFC 9457 Problem Details. By the time
// this runs Laravel has already mapped ModelNotFoundException to a 404
// and AuthorizationException to a 403 HttpException.
$exceptions->render(function (Throwable $e, Request $request) {
if (! $request->is('api/*')) {
return null; // keep the default HTML/JSON rendering elsewhere
}
[$status, $kind, $extra] = match (true) {
$e instanceof ValidationException => [422, 'validation', ['errors' => collect($e->errors())
->map(fn (array $messages, string $field) => [
'pointer' => '#/'.str_replace('.', '/', $field),
'detail' => $messages[0],
])->values()->all()]],
$e instanceof AuthenticationException => [401, 'unauthenticated', []],
$e instanceof HttpExceptionInterface => [$e->getStatusCode(), 'http-'.$e->getStatusCode(), []],
default => [500, 'internal', []],
};
$headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : [];
if ($status === 401) {
$headers['WWW-Authenticate'] = 'Bearer';
}
return response()->json([
'type' => "https://api.example.com/problems/{$kind}",
'title' => Response::$statusTexts[$status] ?? 'Error',
'status' => $status,
// Never leak exception messages from 5xx; 4xx messages are ours.
'detail' => $status < 500 && $e->getMessage() !== '' ? $e->getMessage() : null,
'instance' => '/'.$request->path(),
...$extra,
], $status, $headers + ['Content-Type' => 'application/problem+json', 'Cache-Control' => 'no-store']);
});
})->create();Long-running export: 202 + Location, a queued job, 303 when done.
<?php
namespace App\Http\Controllers;
use App\Jobs\ExportOrders;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Long-running operation: POST answers 202 with a status resource;
* the status resource answers 200 while running and 303 See Other to the
* result when done.
*/
class OperationController extends Controller
{
public function store(Request $request): JsonResponse
{
$request->validate(['format' => ['required', 'in:csv,jsonl']]);
$id = (string) Str::uuid();
DB::table('operations')->insert([
'id' => $id,
'user_id' => $request->user()->id,
'status' => 'running',
'created_at' => now(),
'updated_at' => now(),
]);
ExportOrders::dispatch($id, $request->user()->id, $request->input('format'));
return response()
->json(['id' => $id, 'status' => 'running'], 202)
->header('Location', route('operations.show', $id))
->header('Retry-After', '2');
}
public function show(Request $request, string $operation): JsonResponse|RedirectResponse
{
$op = DB::table('operations')
->where('id', $operation)
->where('user_id', $request->user()->id)
->first();
abort_if($op === null, 404);
if ($op->status === 'succeeded') {
return redirect()->to($op->result_url, 303);
}
return response()
->json(['id' => $op->id, 'status' => $op->status, 'error' => $op->error], 200)
->header('Retry-After', '2');
}
}<?php
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Throwable;
class ExportOrders implements ShouldQueue
{
use Queueable;
public function __construct(
public string $operationId,
public int $userId,
public string $format,
) {}
public function handle(): void
{
$path = "exports/{$this->operationId}.{$this->format}";
$lines = [];
Order::query()->where('customer_id', $this->userId)->orderBy('id')
->lazyById(1000)
->each(function (Order $o) use (&$lines) {
$lines[] = $this->format === 'csv'
? "{$o->public_id},{$o->status},{$o->total_cents}"
: json_encode(['id' => $o->public_id, 'status' => $o->status, 'total_cents' => $o->total_cents]);
});
Storage::put($path, implode("\n", $lines));
// temporaryUrl() needs a disk that supports it (S3, or local with 'serve' => true).
DB::table('operations')->where('id', $this->operationId)->update([
'status' => 'succeeded',
'result_url' => Storage::temporaryUrl($path, now()->addHour()),
'updated_at' => now(),
]);
}
public function failed(?Throwable $e): void
{
DB::table('operations')->where('id', $this->operationId)->update([
'status' => 'failed',
'error' => 'export_failed',
'updated_at' => now(),
]);
}
}Schema for orders (version column, keyset indexes, soft deletes), idempotency keys and operations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('public_id', 40)->unique(); // what URIs expose
$table->foreignId('customer_id')->constrained('users');
$table->string('status', 16)->default('pending');
$table->unsignedBigInteger('total_cents');
$table->string('note', 500)->nullable();
$table->unsignedInteger('version')->default(1); // ETag source, optimistic lock
$table->timestamps();
$table->softDeletes(); // deleted rows answer 410
// Keyset pagination: filter, then the sort key plus a unique tie-breaker.
$table->index(['customer_id', 'status', 'created_at', 'id']);
$table->index(['customer_id', 'created_at', 'id']);
});
Schema::create('idempotency_keys', function (Blueprint $table) {
$table->string('client_id', 64);
$table->string('idempotency_key', 255);
$table->char('fingerprint', 64);
$table->unsignedSmallInteger('status_code')->nullable(); // null = still running
$table->json('response_headers')->nullable();
$table->longText('response_body')->nullable();
$table->timestamp('expires_at')->index();
$table->timestamp('created_at');
$table->primary(['client_id', 'idempotency_key']); // the lock
});
Schema::create('operations', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('user_id')->constrained();
$table->string('status', 16); // running | succeeded | failed
$table->text('result_url')->nullable();
$table->string('error', 64)->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('operations');
Schema::dropIfExists('idempotency_keys');
Schema::dropIfExists('orders');
}
};Feature tests for 201/replay/422, Problem Details, 428/412 and 404/410:
<?php
namespace Tests\Feature;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class OrderApiTest extends TestCase
{
use RefreshDatabase;
public function test_create_is_201_with_location_and_replays_on_retry(): void
{
Sanctum::actingAs(User::factory()->create(), ['orders:write']);
$headers = ['Idempotency-Key' => '"k-1"'];
$first = $this->postJson('/api/orders', ['total_cents' => 4999], $headers)
->assertCreated()
->assertHeader('Location')
->assertHeader('ETag');
$this->postJson('/api/orders', ['total_cents' => 4999], $headers)
->assertCreated()
->assertHeader('Idempotent-Replayed', 'true')
->assertJsonPath('data.id', $first->json('data.id'));
$this->postJson('/api/orders', ['total_cents' => 1], $headers)->assertStatus(422);
$this->assertSame(1, Order::count());
}
public function test_validation_errors_are_problem_details(): void
{
Sanctum::actingAs(User::factory()->create(), ['orders:write']);
$this->postJson('/api/orders', ['total_cents' => 0], ['Idempotency-Key' => '"k-2"'])
->assertStatus(422)
->assertHeader('Content-Type', 'application/problem+json')
->assertJsonPath('errors.0.pointer', '#/total_cents');
}
public function test_patch_needs_if_match_and_rejects_a_stale_etag(): void
{
$user = User::factory()->create();
Sanctum::actingAs($user, ['orders:write']);
$order = Order::create(['customer_id' => $user->id, 'total_cents' => 100]);
$uri = "/api/orders/{$order->public_id}";
$merge = ['CONTENT_TYPE' => 'application/merge-patch+json'];
$body = json_encode(['status' => 'paid']);
$this->call('PATCH', $uri, [], [], [], $merge, $body)->assertStatus(428);
$this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
->assertOk()
->assertJsonPath('data.version', 2);
// Same old ETag again: someone (we) already moved it to version 2.
$this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
->assertStatus(412);
}
public function test_someone_elses_order_is_404_and_deleted_is_410(): void
{
$owner = User::factory()->create();
$order = Order::create(['customer_id' => $owner->id, 'total_cents' => 100]);
Sanctum::actingAs(User::factory()->create(), ['orders:write']);
$this->getJson("/api/orders/{$order->public_id}")->assertNotFound();
Sanctum::actingAs($owner, ['orders:write']);
$this->deleteJson("/api/orders/{$order->public_id}")->assertNoContent();
$this->getJson("/api/orders/{$order->public_id}")->assertStatus(410);
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
Route::apiResource() / apiResources() | Five REST routes per resource | Excludes create and edit |
->shallow(), ->scoped(), scopeBindings() | Nested resources | Child bindings scoped to the parent |
->middlewareFor(), ->withTrashed() | Per-action middleware, soft-deleted binding | Resource route registration |
Route model binding, getRouteKeyName() | {order} by public_id | Missing model becomes 404 |
Form Request (make:request) | authorize() 403, rules() 422 | $request->validated() only |
API Resource (JsonResource, toResource()) | Representation layer | whenLoaded() avoids N+1 |
JsonApiResource | JSON:API with sparse fieldsets and includes | Sets application/vnd.api+json |
Policies, Gate::authorize(), Response::denyAsNotFound() | Object-level authorization | AuthorizationException becomes 403 |
cursorPaginate(), simplePaginate(), paginate() | Keyset vs offset | Cursor needs orderBy |
RateLimiter::for(), Limit::perMinute()->by(), throttle: | Rate limiting | 429 automatic; $middleware->throttleApi() |
cache.headers middleware | Cache-Control and ETag | etag directive adds 304 handling |
$exceptions->render(), shouldRenderJsonWhen() | Problem Details | Runs after Laravel maps model-not-found to 404 |
response()->noContent() | 204 | — |
Solving the classic problems
Double order after a timeout
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Idempotency-Key | Client key per operation, server replays | Exact original response, covers side effects | A store with TTL |
| Client-chosen id + PUT | PUT /orders/{uuid} | Idempotent by method | Clients must generate ids |
| Natural unique constraint | UNIQUE(customer_id, cart_id) | No extra table | Retry gets an error, not the original result |
Preferred: Idempotency-Key (Go, Laravel); storage mechanics in API Idempotency.
Lost update between two editors
| Solution | How | Advantage | Cost |
|---|---|---|---|
| ETag + If-Match | 412 on stale writes, 428 without | Standard, works through proxies | Clients must keep the ETag |
| Version in body (Kubernetes, AIP-154) | version/etag field | Works in batch bodies | Not visible to HTTP tooling |
| Pessimistic lock endpoint | POST /docs/7/lock | Simple for humans | Lock expiry and abandonment |
-- What If-Match becomes in the database (the Laravel increment() call generates this shape)
UPDATE orders
SET status = 'paid', version = version + 1, updated_at = now()
WHERE id = 7 AND version = 1; -- 0 rows affected -> 412 Precondition FailedPages that skip or repeat rows
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Keyset cursor | (sort key, id) in an opaque cursor | Stable, fast at any depth | No random page jumps |
| Snapshot token | Cursor pins a snapshot time (as_of) | Consistent view | Needs history or MVCC reads |
| Offset with a stable sort | ORDER BY created_at, id | Page numbers | Still shifts under writes, slow when deep |
Errors nobody can handle
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Problem Details everywhere | One helper per stack, gateway included | One parser for clients | Migrating old shapes |
Stable type URIs | Documented catalogue | Clients switch on it | Must not change |
| Field pointers | errors[].pointer | Forms map errors to fields | Extension to document |
A slow endpoint that times out at the gateway
| Solution | How | Advantage | Cost |
|---|---|---|---|
| 202 + status resource | Queue, poll, 303 to result | Survives client and gateway timeouts | Job store, cleanup |
| Webhook on completion | Callback with signature | No polling | Client must expose an endpoint |
| Streaming response | Chunked or SSE | Progress visible | Connection held open |
Clients hammering the API
| Solution | How | Advantage | Cost |
|---|---|---|---|
| RateLimit + 429 + Retry-After | Per-client quota, visible headers | Clients self-pace | Shared counter store |
| Caching headers | ETag, max-age | Removes load entirely | Staleness |
| Bulk endpoint | One request for many items | Fewer round trips | Partial-failure design |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Public API, many unknown clients | REST level 2, OpenAPI 3.1, Problem Details | Style guide + lint, cursor pages | Tooling, caches and SDKs work |
| Internal service-to-service, high volume | gRPC or REST | See gRPC | Binary contracts, streaming |
| UI aggregating many entities per screen | REST + BFF, or GraphQL | See GraphQL | Avoid over/under-fetching |
| Payments, orders, anything with money | POST + Idempotency-Key, If-Match on updates | Outbox for events (Outbox) | Retries are certain |
| Collaborative edits | PATCH + If-Match, 412 | JSON Patch test for field-level checks | Lost updates are silent otherwise |
| Large or slow work | 202 + status resource | Webhook, presigned result URL | No request should run for minutes |
| Lists that grow | Cursor (keyset) pagination | Filters inside the cursor | Stable and O(page) |
| Admin table with page numbers, small data | Offset pagination | Total count | Simpler UI |
| Public read-mostly data | Cache headers + CDN | s-maxage, stale-while-revalidate | Most requests never reach you |
| Clients with long lifetimes and changing workflows | Add hypermedia links (level 3 parts) | State-dependent action links | Server can evolve without client releases |
In architecture: from a single process to a distributed system
The same API contract has to survive more and more machines behind it. What changes is where state lives, who can answer a request, and which guarantees still hold.
Monolith: one process, one database
A Laravel or Go monolith exposes /api/orders straight from its database. ETags come from a version column, idempotency keys from a table in the same database (so "claim key, insert order, save response" can be one transaction), cursors from an index. The simplest correct setup: apiResource, Form Requests, Policies, cursorPaginate(), Problem Details rendering, throttle:api. Everything on this page fits in one process.
Modular monolith: boundaries inside one deployable
Orders, Billing and Catalog are modules with their own tables. The public API is still one, but each module owns its resources (/orders, /invoices, /products) and its OpenAPI fragment; a shared middleware stack provides Problem Details, rate limits and idempotency. Rule: one module never writes another module's table through the API layer; cross-module actions are internal calls or events, not HTTP to yourself.
Microservices: every arrow is an API
Mobile app API gateway (Envoy/Kong) orders-svc billing-svc
1 POST /orders -> auth, RateLimit, 429 -> POST /orders Idempotency-Key k1
2 claim k1, insert order, outbox OrderPlaced
3 201 Location /orders/ord_7
4 relay -> broker consumes, charges
5 GET /orders/ord_7 -> gateway -> orders-svc -> 200 {"status":"paid", "links":{...}}What survives the boundary: status codes, Problem Details, the Idempotency-Key (forward it, or derive child keys such as k1:charge), ETags per service. What does not: a transaction spanning orders and billing, so cross-service consistency comes from sagas and the outbox, and the API shows it honestly (status: pending, 202, or a status link). Gateways and BFFs are covered in API Gateway, BFF & Service Mesh.
Distributed data: replicas, caches, regions
- Read replicas: a client creates an order (201) then immediately GETs it from a lagging replica and gets 404. Fixes: read-your-writes by routing reads after a write to the primary for a few seconds, or return the full representation in the 201 so the client does not need to read. See Replication Topologies.
- Caches and CDNs:
privatevspublic,Vary, and ETags that come from the version column so every node computes the same tag. A weak spot: ETags generated from an in-process hash differ between nodes and break 304s. - Idempotency across regions: a retry may land in another region; the key store must be global or keys must be region-affine. Details in API Idempotency.
- Rate limits across instances: a per-process counter multiplies the limit by the instance count; use Redis or the gateway (Rate Limiting).
Scaling path: 1x, 10x, 100x
| Load | What changes in the API | What changes behind it |
|---|---|---|
| 1x (hundreds of rps) | Contract-first, Problem Details, cursor pages, Idempotency-Key | One app, one database |
| 10x (thousands of rps) | Cache headers on reads, RateLimit headers, bulk endpoints for heavy clients | CDN, Redis for limits and keys, read replicas, more stateless app nodes |
| 100x (tens of thousands of rps and more) | 202 for anything heavy, webhooks instead of polling, stricter limits per tier, versioned contracts per client segment | Gateway in front, per-service APIs, sharded data (Sharding), regional deployments |
Lab: the Go service with curl
The Go server is a single process with an in-memory store, so this lab was run on this machine with go run ./cmd/server (Go 1.27 toolchain, module directive go 1.24); the outputs below are from that run, with Date headers removed. The Laravel steps at the end are expected, not run.
Setup
cd docs/snippets/system-design/rest-api-design/go
go test ./... # ok academy/rest-api-design/orders
go run ./cmd/server # listening on 127.0.0.1:80801. Create, then retry with the same key (replay), then reuse the key with another body (422).
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' \
-H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' -d '{"customer":"c-42","total_cents":4999}'
HTTP/1.1 201 Created
Content-Type: application/json
Etag: "ord_000001-v1"
Location: /orders/ord_000001
Ratelimit: default;a=99;w=60
Ratelimit-Policy: default;q=100;w=60
{"id":"ord_000001","customer":"c-42","status":"pending","total_cents":4999,"note":null,"version":1,...}
$ (same command again)
HTTP/1.1 201 Created
Etag: "ord_000001-v1"
Idempotent-Replayed: true
Location: /orders/ord_000001
$ (same key, "total_cents":1)
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/idempotency-key-reused","title":"Idempotency-Key is already used","status":422,...}Go's status text is still "Unprocessable Entity"; RFC 9110 renamed 422 to "Unprocessable Content". Clients must read the number, not the text.
2. Conditional GET and the lost-update protocol.
$ curl -si localhost:8080/orders/ord_000001 -H 'If-None-Match: "ord_000001-v1"'
HTTP/1.1 304 Not Modified
Cache-Control: private, no-cache
Etag: "ord_000001-v1"
$ curl -si -X PATCH localhost:8080/orders/ord_000001 -H 'Content-Type: application/merge-patch+json' -d '{"status":"paid"}'
HTTP/1.1 428 Precondition Required
Accept-Patch: application/merge-patch+json, application/json-patch+json
{"type":"https://api.example.com/problems/precondition-required","title":"If-Match required",...}
$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"status":"paid"}'
HTTP/1.1 200 OK
Etag: "ord_000001-v2"
$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"customer":"bob"}'
HTTP/1.1 412 Precondition Failed
{"type":"https://api.example.com/problems/stale-etag","title":"Precondition failed","status":412,
"detail":"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.",...}3. Method not allowed is free with the Go 1.22 mux.
$ curl -si -X PUT localhost:8080/orders/ord_000001 -d '{}'
HTTP/1.1 405 Method Not Allowed
Allow: DELETE, GET, HEAD, PATCH
Content-Type: text/plain; charset=utf-84. Cursor pages with sparse fieldsets (after creating five orders).
$ curl -si 'localhost:8080/orders?limit=2&fields=id,status'
HTTP/1.1 200 OK
Link: </orders?cursor=eyJhIjoib3JkXzAwMDAwMiJ9&fields=id%2Cstatus&limit=2>; rel="next"
{"data":[{"id":"ord_000001","status":"pending"},{"id":"ord_000002","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwMiJ9"}
$ curl -si 'localhost:8080/orders?limit=2&fields=id,status&cursor=eyJhIjoib3JkXzAwMDAwMiJ9'
{"data":[{"id":"ord_000003","status":"pending"},{"id":"ord_000004","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwNCJ9"}Decode the cursor (echo eyJhIjoib3JkXzAwMDAwMiJ9 | base64 -d prints {"a":"ord_000002"}): it is the last id, which is why it is stable. Real APIs sign or encrypt it so clients treat it as opaque.
5. Long-running export: 202, then 200 while running, then 303.
$ curl -si -X POST 'localhost:8080/exports?format=csv' -H 'Idempotency-Key: "e1"'
HTTP/1.1 202 Accepted
Location: /operations/op_1
Retry-After: 1
{"id":"op_1","status":"running"}
$ curl -si localhost:8080/operations/op_1
HTTP/1.1 200 OK
Retry-After: 1
{"id":"op_1","status":"running"}
$ curl -si localhost:8080/operations/op_1 # 300 ms later
HTTP/1.1 303 See Other
Location: /exports/exp_16. Delete twice, and the error contract.
$ curl -si -X DELETE localhost:8080/orders/ord_000005 -> HTTP/1.1 204 No Content
$ curl -si -X DELETE localhost:8080/orders/ord_000005 -> HTTP/1.1 410 Gone (application/problem+json)
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 400 Bad Request
{"type":"https://api.example.com/problems/idempotency-key-missing","title":"Idempotency-Key is missing",...}
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -H 'Idempotency-Key: "v1"' \
-d '{"customer":"","total_cents":0}'
HTTP/1.1 422 Unprocessable Entity
{"type":".../validation","title":"Validation failed","status":422,"instance":"/orders",
"errors":[{"pointer":"#/customer","detail":"is required"},{"pointer":"#/total_cents","detail":"must be greater than 0"}]}7. Laravel (expected, not run). In a Laravel 13 app with Sanctum, the snippets copied in and php artisan migrate:
$ php artisan route:list --path=api
GET|HEAD api/orders ................. orders.index › OrderController@index
POST api/orders ................. orders.store › OrderController@store
GET|HEAD api/orders/{order} ......... orders.show › OrderController@show
PUT|PATCH api/orders/{order} ......... orders.update › OrderController@update
DELETE api/orders/{order} ......... orders.destroy › OrderController@destroy
POST api/orders/{order}/cancellation orders.cancel
POST api/exports ................ exports.store
GET|HEAD api/operations/{operation} . operations.show
$ php artisan test --filter=OrderApiTest
PASS Tests\Feature\OrderApiTest (4 tests)Note that apiResource registers both PUT and PATCH for update; this controller treats both as merge patch. If you want PUT to mean full replacement, register update for PATCH only and add a separate replace action.
Common misconceptions
| Belief | Reality |
|---|---|
| REST means JSON and nice URLs | REST is six constraints; most JSON APIs are Richardson level 2 |
| Stateless means no database | It forbids server-side session state between requests, not resource state |
| PUT is update, POST is create | PUT stores at a client-known URI (and can create); POST lets the server decide |
| Idempotent means identical responses | Same intended effect; a second DELETE may get 404/410 |
| PATCH with a partial JSON object is standard | The standard formats are application/merge-patch+json and application/json-patch+json |
| 401 and 403 are interchangeable | 401 = who are you (with WWW-Authenticate); 403 = known, not allowed |
| 409 is the code for a stale ETag | Stale If-Match is 412; 409 is a state conflict |
no-cache forbids caching | It means revalidate before reuse; no-store forbids storing |
| 202 means success | It means accepted; the outcome lives in the status resource |
| A unique constraint makes POST idempotent | It blocks duplicates but does not replay the original response or cover side effects |
| Cursor pagination is just another page number | It is a bookmark from the sort key; stable under writes and cheap at depth |
| Level 3 hypermedia is required to be useful | Level 2 gives caching, retries and tooling; add links where clients branch on state |
X-RateLimit-* is a standard | Convention only; the IETF draft defines RateLimit-Policy and RateLimit |
Cheat sheet
| Topic | Remember |
|---|---|
| Constraints | Client-server, stateless, cacheable, uniform interface (4 parts), layered, code on demand (optional) |
| Safe methods | GET, HEAD, OPTIONS, TRACE |
| Idempotent methods | Safe ones + PUT + DELETE; POST and PATCH are not |
| Create | POST to the collection, 201 + Location + ETag; PUT when the client chooses the id |
| Partial update | PATCH with application/merge-patch+json (null deletes) or JSON Patch (test for preconditions) |
| Concurrency | ETag on read, If-Match on write, 412 stale, 428 missing |
| Retry-safe POST | Idempotency-Key: "uuid"; 400 missing, 409 in flight, 422 reused, replay otherwise |
| Validation vs syntax | 422 vs 400; 415 wrong media type |
| Errors | application/problem+json with type, title, status, detail, instance |
| Pagination | Opaque cursor from (sort key, id), Link: rel="next", cap the limit |
| Query design | Allow-listed filters and sorts, fields= for sparse fieldsets, indexes per combination |
| Long work | 202 + Location to a status resource, Retry-After, 303 to the result |
| Rate limits | 429 + Retry-After; RateLimit-Policy and RateLimit (draft) |
| Caching | private, no-cache + ETag for user data; public, s-maxage for shared data; no-store for errors |
| Contract | OpenAPI 3.1 first, lint (Spectral), diff in CI, generate clients |
| Style guide | Adopt Google AIP, Microsoft or Zalando; write down your exceptions |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name Fielding's six constraints and the one that is optional. Must-know
Answer
Answer: Client-server, stateless, cacheable, uniform interface, layered system, code on demand; code on demand is optional. See Constraints.
2 — A server keeps a user's search results in process memory and returns ?page=2 from them. Which constraint does that break, and what operational symptom will you see? Must-know
Answer
Answer: Stateless: request 2 depends on context stored on the server that handled request 1. Symptoms: sticky sessions required, wrong or missing pages after a deploy or failover, uneven load. Put the position in a cursor instead.
3 — Is DELETE /orders/7 still idempotent if the second call returns 410 instead of 204? Why? Must-know
Answer
Answer: Yes. Idempotency is about the intended effect on the server (the order is deleted), not about identical responses. See Methods.
4 — A client sends PATCH {"note": null}. What does that mean under JSON Merge Patch, and how would you express "change status only if it is still pending"? Important
Answer
Answer: Merge Patch: remove note. The conditional change needs JSON Patch: [{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"paid"}], plus If-Match for the whole resource. See PATCH formats.
5 — Pick the status code: (a) valid JSON but total_cents is negative; (b) the body is text/plain; (c) If-Match is stale; (d) no If-Match but the server requires it; (e) shipped order moved back to pending. Must-know
Answer
Answer: (a) 422, (b) 415, (c) 412, (d) 428, (e) 409. See Status codes.
6 — Why does offset pagination show duplicates under concurrent inserts, and what does a keyset cursor contain? Must-know
Answer
Answer: New rows shift every later offset, so the next page starts one row earlier and repeats one. A keyset cursor holds the last row's sort key and unique id (plus filters), and the next query is WHERE (created_at, id) < (...). See Pagination.
7 — Your POST /payments timed out. The client retries with the same Idempotency-Key while the first request is still running. What should it get, and what should it get after the first finishes? Must-know
Answer
Answer: 409 (request outstanding), ideally with Retry-After; after completion, a replay of the original response (for example the same 201 body). If the payload differs, 422. See Idempotency keys.
8 — Why do most public APIs stop at Richardson level 2, and what is a cheap step toward level 3? Good to know
Answer
Answer: Clients are generated from OpenAPI and hard-code URIs, JSON has no single link standard, and the payoff needs clients that follow links. Cheap step: Link: rel="next", Location, and state-dependent action links such as cancel. See Hypermedia.
9 — What is the difference between Cache-Control: no-cache and no-store, and which do you use for GET /me? Must-know
Answer
Answer: no-cache allows storing but requires revalidation; no-store forbids storing. For GET /me: private, no-cache with an ETag (or no-store if it contains secrets). See Caching.
10 — An export takes 4 minutes. Design the HTTP exchange. Must-know
Answer
Answer: POST /exports with an Idempotency-Key → 202 Accepted, Location: /operations/{id}, Retry-After; poll GET /operations/{id} → 200 running → 303 See Other to the result (or succeeded with a link); optionally a webhook. See Long-running operations.
11 — Name three things a contract-first OpenAPI workflow catches that code-first does not. Important
Answer
Answer: Accidental breaking changes (CI diff), style-guide violations before code exists (lint), and missing error responses or headers in review; it also lets frontend work start against a mock. See OpenAPI.
12 — User 42 requests /orders/ord_8, which belongs to user 7. 403 or 404, and how does Laravel express it? Must-know
Answer
Answer: Usually 404, so ids cannot be probed for existence; in Laravel a policy returns Response::denyAsNotFound(). See Security basics.
Glossary
| Term | Meaning |
|---|---|
| REST | Representational State Transfer, Fielding's architectural style: six constraints |
| Fielding constraints | Client-server, stateless, cacheable, uniform interface, layered system, code on demand |
| Stateless | Each request carries all information needed; no server-side session context |
| Cacheable | Responses label themselves as reusable or not |
| Uniform interface | Same methods, codes and media types for all resources: identification, representations, self-descriptive messages, HATEOAS |
| Layered system | Components see only the adjacent layer; enables proxies, CDNs, gateways |
| Code on demand | Optional constraint: server sends executable code |
| HATEOAS | Hypermedia as the engine of application state: clients follow links |
| Richardson maturity model | Levels 0 (tunnel), 1 (resources), 2 (verbs and codes), 3 (hypermedia) |
| Resource | Anything that can be named and has a URI |
| Collection | Resource that lists and creates members, e.g. /orders |
| Sub-resource | Resource reachable only through its parent, e.g. /orders/7/items |
| URI design | Naming rules: plural nouns, no verbs, opaque ids, shallow nesting |
| Representation | Resource state in a media type |
| Media type | type/subtype label such as application/json, application/problem+json |
| Content negotiation | Server chooses the representation using Accept and friends; Vary records it |
| Safe method | Read-only semantics: GET, HEAD, OPTIONS, TRACE |
| Idempotent method | Repeating has the same intended effect: safe methods, PUT, DELETE |
| GET / HEAD / OPTIONS | Read; read headers only; ask for capabilities |
| POST / PUT / PATCH / DELETE | Process or create; replace at URI; partial change; remove |
| JSON Patch | RFC 6902 list of operations (test, add, remove, replace, move, copy) |
| JSON Merge Patch | RFC 7396 partial document; null removes a member |
| Location header | URI of a created resource or a status monitor |
| Problem Details | RFC 9457 error format: type, title, status, detail, instance |
| RFC 9457 | The 2023 Problem Details RFC that obsoletes RFC 7807 |
| Offset pagination | Skip N rows; simple, unstable under writes, slow when deep |
| Keyset pagination | Continue after the last sort key and id; stable and fast |
| Cursor | Opaque token encoding the keyset position and filters |
| Filtering / sorting | Allow-listed query parameters that narrow and order a collection |
| Sparse fieldsets | Client chooses returned fields (fields=id,status) |
| ETag | Opaque validator of a representation; strong or weak |
| If-Match | Write only if the current ETag matches; else 412 |
| If-None-Match | GET: 304 if it matches; PUT with *: create only if absent |
| Optimistic concurrency | Detect conflicts at write time with a version, instead of locking at read time |
| Idempotency key / Idempotency-Key | Client-chosen unique key that lets the server replay the first result of a POST |
| Idempotency fingerprint | Hash of the request used to detect a key reused with another payload |
| Retry-After | Seconds (or a date) to wait before retrying (429, 503, 202 polling) |
| RateLimit headers | IETF draft RateLimit-Policy (quota) and RateLimit (available) fields |
| Bulk endpoint | One request carrying many items; atomic or with per-item results |
| Long-running operation | Work accepted with 202 and tracked through a status resource |
| OpenAPI | Machine-readable HTTP API description; 3.1 aligns with JSON Schema 2020-12 |
| Contract-first | Write and review the API contract before the implementation |
| Codegen | Generating clients, stubs and mocks from the contract |
| API style guide | Organisation-wide normative rules for APIs, e.g. Google AIP |
| Google AIP | Google's API Improvement Proposals (google.aip.dev) |
| apiResource | Laravel route registration for index, store, show, update, destroy |
| API Resource | Laravel JsonResource class that shapes a model into a representation |
| Form Request | Laravel request class with authorize() (403) and rules() (422) |
| Route model binding | Laravel resolving {order} into a model, 404 if missing |
| Policy | Laravel class holding per-model authorization rules |
References
- Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapter 5: Representational State Transfer, 2000; "REST APIs must be hypertext-driven", 2008
- Martin Fowler, "Richardson Maturity Model", 18 March 2010
- RFC 9110: HTTP Semantics, June 2022; RFC 9111: HTTP Caching, June 2022
- RFC 5789: PATCH Method for HTTP, March 2010; RFC 6902: JSON Patch, April 2013; RFC 7396: JSON Merge Patch, October 2014
- RFC 6585: Additional HTTP Status Codes (428, 429), April 2012; RFC 8288: Web Linking, October 2017
- RFC 9457: Problem Details for HTTP APIs, July 2023
- IETF HTTPAPI, The Idempotency-Key HTTP Header Field (draft-ietf-httpapi-idempotency-key-header-09) and RateLimit header fields for HTTP (draft-ietf-httpapi-ratelimit-headers-12), Internet-Drafts, work in progress
- OpenAPI Specification v3.1.0, 15 February 2021
- Google API Improvement Proposals: AIP-121 Resource-oriented design, AIP-122 Resource names, AIP-131, AIP-132 List, AIP-134 Update, AIP-136 Custom methods, AIP-151 Long-running operations, AIP-154 Etags, AIP-155 Request identification, AIP-158 Pagination, AIP-160 Filtering, AIP-233 Batch create
- Microsoft REST API Guidelines and the Azure REST API Guidelines (raw Markdown)
- Zalando RESTful API and Event Guidelines
- Stripe API reference, Idempotent requests
- Laravel 13: Routing (route model binding, rate limiting), Controllers (
apiResource,middlewareFor,withTrashed), Eloquent API Resources, Validation (Form Requests), Authorization (policies,denyAsNotFound), Rate Limiting, Pagination, Error Handling, HTTP Responses (cache.headers); framework source: ThrottleRequests, Exception Handler, InteractsWithContentTypes - Go: Go 1.22 release notes (enhanced routing patterns), Routing Enhancements for Go 1.22, Release history, net/http, net/http/httptest
- Also quoted inline: GitHub Docs, Rate limits for the REST API and Using pagination in the REST API; NGINX ngx_http_proxy_module and ngx_http_limit_req_module; Kubernetes API Concepts; OWASP API Security Top 10 2023; AIP-193 Errors; OpenAPI 3.0.0; RFC 7807