Lesson 26 of 28Decisions and evolution
Designing APIs That Last
Model resources that age well, know exactly what breaks a client, version and deprecate safely, and catch breaking changes in CI before they ship.
The last unit caught mistakes before they ship. This one is about change over years, in the APIs and structures other people depend on. A teammate renames total to total_cents in the orders API because the old name was ambiguous. The tests pass, the web app is updated in the same pull request, and the change ships on a Tuesday. By Wednesday the support queue is full: version 4.2 of the iOS app, still on a third of phones, reads total, gets nothing, and shows every order as free. Nobody did anything careless. They just treated a published API like internal code. This lesson is about the habits that stop that from happening: what counts as a breaking change, how to design so you rarely need one, and how to roll one out safely when you must.
Every observable behaviour is part of the contract
In API Design you met the basic rule: additive changes are safe, removals and renames are not. The real list is longer, and the subtle entries are the ones that cause incidents.
| Change | Breaking? | Why |
|---|---|---|
| Add an optional response field | Usually safe | Clients ignore fields they do not know, if they are written tolerantly |
| Remove or rename a response field | Yes | Clients that read it get nothing |
Change a field's type ("42" to 42) | Yes | Parsers and typed clients fail |
| A response field becomes nullable or optional | Yes | Code that assumed it was always there crashes |
| Add a value to a response enum | Often | Clients with an exhaustive switch or a strict generated enum fail |
| Add a required request field | Yes | Every existing caller now gets 400 |
| Tighten validation (max length 500 to 200) | Yes | Requests that worked yesterday are rejected |
Change a default (limit 50 to 20) | Yes | Behaviour changes with no code change on the client |
Change meaning (amount from dollars to cents) | Yes, and silent | Nothing fails. The numbers are just wrong |
| Change error codes or sort order | Often | Clients branch on these even if you never promised them |
The last row is Hyrum's law: with enough users, every observable behaviour of your API will be depended on by somebody, whatever the docs say. That includes field order, timing, and the exact text of error messages. You cannot avoid it. You can only make the behaviours you do promise explicit, and treat changes to everything else with care.
The usual defence on the client side is the tolerant reader: read only the fields you need, ignore unknown ones, and handle unknown enum values with a default branch. This is Postel's law ("be liberal in what you accept"), named after Jon Postel. It has limits. RFC 9413 argues that tolerating bad input forever turns quirks into permanent features, because once a sloppy client works, you can never reject its input again. The modern stance: clients should tolerate additions, servers should validate strictly from day one, because loosening validation later is safe and tightening it is not.
Here is a tiny breaking-change checker. It knows the rule that matters most: requests and responses break in opposite directions. Adding a required field is fine in a response you send, and breaking in a request you receive.
Press Run (⌘ Enter) to see what happens.Real tools such as oasdiff (OpenAPI) and buf breaking (protobuf) do the same thing with hundreds of rules. You will wire them into CI at the end of this lesson.
Design so you rarely need to break
Most breaking changes trace back to a shape that could not grow. A few early choices buy years of additive change.
Wrap lists in an object. GET /orders returning a bare JSON array can never gain next_cursor or total_count without breaking. Return { "data": [...], "next_cursor": null } from day one, even before you paginate.
Make ids strings. JavaScript numbers lose precision above 2^53. If your ids are 64-bit integers (Twitter's snowflake ids, for example), a JavaScript client silently rounds them. Twitter ended up adding an id_str field next to id for exactly this reason. Strings also let you add prefixes like ord_ later.
Use objects, not booleans, for things that will grow. "is_paid": true becomes a problem the day you add refunds. A status string, documented as an open set, can grow.
Name money and time precisely. amount_cents with a currency field, or a decimal string. Timestamps as RFC 3339 strings in UTC. Ambiguous units are how "silent" breaking changes happen.
Model actions that are not CRUD. Cancelling an order is not a PATCH of status (clients could then set any status they like). Two good shapes exist:
POST /v1/orders/ord_42:cancel # custom method, Google AIP-136 style
POST /v1/orders/ord_42/cancellation # model the action as a resource you createBoth keep the business rule on the server. The second also gives you a natural place to return details later (who cancelled, the refund id).
Make slow work a resource. For an export that takes minutes, return 202 Accepted with a Location header pointing to an operation, for example /v1/operations/op_9, and let clients poll it until it reports done with a link to the result. Google's AIP-151 describes this pattern. It also lets you move the work to a queue later without changing the contract.
Consistency is a feature
A large API is used by people who learn one endpoint and guess the rest. If pagination, filtering and errors work the same everywhere, their guesses are right. Write a short style guide and enforce it. You do not have to invent one: Google's AIPs, the Microsoft REST API Guidelines and Zalando's RESTful API Guidelines are all public and good starting points.
The style guide should fix: field case (snake_case or camelCase, once), the list envelope and cursor names, filter and sort syntax (?status=paid&sort=-created_at), partial responses if you support them (?fields=id,status), and the error format. For errors, use RFC 9457 Problem Details (it replaced RFC 7807), served as application/problem+json:
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Not enough stock",
"status": 422,
"detail": "Only 2 units of SKU MUG-01 are available.",
"instance": "/v1/orders/ord_42",
"sku": "MUG-01",
"available": 2
}The type URI is the stable thing clients branch on. The title and detail are for humans and can change freely. Extra members such as available are allowed, so you can add context without a new format.
Versioning strategies, compared
API Design showed the three places a version can live. The deeper question is what a version costs you to run.
| Strategy | Example | Good | Costly |
|---|---|---|---|
| URL major version | /v1/orders, /v2/orders | Obvious, easy to route and cache | A big-bang migration. Two codebases drift apart |
| Header or media type | Accept: application/vnd.acme.v2+json | Clean URLs | Hidden in logs and browsers, easy to forget |
| Date-based, per client | Stripe-Version: 2026-03-01 | Many small changes, each client upgrades on its own schedule | You must build and maintain the transformation layer |
Stripe's model is worth understanding because it is the most client-friendly. Each account is pinned to the API version that was current when it first integrated. The core code only ever produces the latest shape. A chain of small "version change" modules then walks the response backwards, one change at a time, until it matches the client's pinned version. Upgrading is per account, and every change is documented as one step.
Press Run (⌘ Enter) to see what happens.In the code above, a new client pins 2026-06-01. What does render print for it?
render("2026-06-01")Two ecosystems avoid versions altogether.
GraphQL has no version numbers by convention. Clients ask for exactly the fields they use, so you add fields freely and mark old ones with @deprecated(reason: "Use totalCents"). Because every query names its fields, the server can log precisely which clients still read a deprecated field, which is better telemetry than REST usually gets. The catch: you can still break clients by removing a field, making a nullable field non-null in an input, or adding a required argument.
Protocol Buffers identify fields on the wire by number, not name. Renaming a field is wire-safe, but reusing a number is a disaster: old clients decode new data into the wrong field with no error. When you delete a field, reserve both its number and its name so nobody can reuse them:
message Order {
reserved 3;
reserved "total";
string id = 1;
OrderStatus status = 2;
int64 total_cents = 4;
}Match each situation to the versioning approach that fits it best.
Deprecation is a process, not a header
Renaming a field safely uses the expand and contract pattern: add the new field, serve both, migrate clients, then remove the old one. The remove step is the hard part, because you need to know nobody still depends on it.
Week 0
Expand
Ship `total_cents` next to `total`. Both are always populated. Update the docs and your own clients.
Week 1
Announce
Mark `total` deprecated in the spec. Send `Deprecation` and `Sunset` headers on responses that include it. Publish a migration guide.
Weeks 1-20
Measure
Log every request that reads the old field by API key or client version. Contact the biggest remaining users directly.
Weeks 16-20
Brownouts
Remove the field for short, announced windows. Clients that were not paying attention notice in a controlled way.
Week 24
Contract
Usage is at or near zero. Remove `total` and keep a regression test that it stays gone.
Two standard headers carry the signal in a machine-readable form. The Deprecation header (RFC 9745) says when the resource was or will be deprecated, as a Unix timestamp prefixed with @. The Sunset header (RFC 8594) says when it will stop working, as an HTTP date. A Link with rel="deprecation" points to the migration guide.
HTTP/1.1 200 OK
Deprecation: @1788220800
Sunset: Fri, 01 Jan 2027 00:00:00 GMT
Link: <https://api.example.com/docs/migrations/total-cents>; rel="deprecation"Headers alone change nothing, because almost nobody reads them. What actually retires an old version is telemetry (you know who is still calling it), direct outreach to those clients, and a firm date. GitHub and others have used brownouts, short planned outages of the old behaviour, to flush out the clients whose owners never read email.
Put the steps for removing a field from a public API in order.
- Tap the steps below in the right order.
Retries and races belong in the contract
Two failure modes are invisible in a happy-path design and painful to add later.
Retries. A client sends POST /payments, the connection drops, and it does not know whether the charge happened. If it retries, does the customer pay twice? The standard answer is an idempotency key: the client generates a unique key per logical operation and sends it in an Idempotency-Key header. The server stores the key with the first result and returns that same result for any repeat. Stripe popularised this, and an IETF draft standardises the header. Decide it at design time, because retrofitting it means every client must change.
Lost updates. Two support agents open the same order. Both edit it and save. The second save silently overwrites the first. HTTP has a built-in fix: optimistic concurrency with ETags.
Agent A reads the order.
If you want every write to carry a precondition, the server can reject writes without If-Match using 428 Precondition Required. Like idempotency keys, this is far easier to require from the first release than to impose later.
PATCH arrives with If-Match set to an ETag that no longer matches the stored resource. What should the server return?Spec-first, and let CI say no
On a team, the API contract should be a file under review, not a side effect of code. Write the OpenAPI description first (3.1 is widely supported and aligns with JSON Schema; 3.2 was released in 2025, so check your tools before relying on it), review it like a design, then implement. Code-first frameworks like FastAPI generate the spec from your code, which is fine, as long as the generated spec is committed and diffed in review so changes are visible.
Then add three automatic checks:
- Lint for style. Spectral runs your style guide as rules (casing, pagination, error format) on every pull request.
- Fail on breaking changes.
oasdiffcompares the spec on your branch with the one onmain. For protobuf,buf breakingdoes the same. - Generate clients and types from the spec, so your own frontend breaks at compile time, not in production.
# OpenAPI: fail the build if the branch breaks the published contractoasdiff breaking main-openapi.yaml openapi.yaml --fail-on ERR# Protobuf: compare against mainbuf breaking --against '.git#branch=main'These checks catch changes in shape. They cannot catch changes in meaning, like dollars becoming cents, or a field that is now populated later in the order lifecycle. Consumer-driven contract tests cover more of that ground, and they are the subject of Contract Tests and Architecture Tests. Big API changes should also go through a short design doc or ADR. The Engineering at Work course teaches both, in Design Docs and RFCs and ADRs and Async Written Updates.
- breaking change
- Any change that can make a correct, existing client fail or misbehave, including tighter validation and new defaults.
- Hyrum's law
- With enough users, every observable behaviour of an API is depended on by someone, documented or not.
- tolerant reader
- A client that reads only what it needs and ignores unknown fields and enum values, so additions do not break it.
- expand and contract
- Changing a contract by adding the new form, migrating everyone, then removing the old form.
- problem details
- RFC 9457's standard JSON error format, with a stable
typeURI clients can branch on. - Sunset header
- An HTTP response header (RFC 8594) giving the date a resource or field will stop working.
- ETag
- A version tag for a resource state, used with
If-Matchto reject writes based on stale data.