API Lifecycle Management (API Design #14)
The email goes out Tuesday: “v1 sunsets in 90 days.” Within an hour, your biggest customer’s CTO is in your inbox — their integration was written three years ago by someone who left, and nobody knows what breaks. Meanwhile your own engineers can’t say how many clients still call v1, because nobody metered versions. The sunset that should have been a scheduled non-event becomes a negotiation, then an exception, then “v1 lives forever.”
APIs are easy to launch and hard to run for years. Lifecycle management is the discipline for the years: a defined path from design to deprecation, governance that keeps forty endpoints consistent, versioning and sunset mechanics that customers can plan around, and two correctness tools every long-lived API needs — idempotency for safe retries and RFC 7807 for errors clients can actually handle.
By the end you will be able to write a deprecation policy that survives contact with reality, and implement idempotency keys so a retried payment can never charge twice.
The lifecycle, as a loop
An endpoint has a life, and each stage has an owner and an artifact:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=1.9cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=orange!16] (d) at (0,0) {design\\(spec)};
\node[b, fill=blue!10] (b) at (2.6,0) {build};
\node[b, fill=green!10] (p) at (5.2,0) {publish\\(docs)};
\node[b, fill=gray!12] (o) at (7.8,0) {operate\\(observe)};
\node[b, fill=red!14] (s) at (10.4,0) {sunset};
\draw[a] (d) -- (b); \draw[a] (b) -- (p); \draw[a] (p) -- (o); \draw[a] (o) -- (s);
\draw[a, dashed] (o.north) to[bend left=30] node[above, font=\rmfamily\scriptsize] {lessons, usage data} (d.north);
\end{tikzpicture}
The dashed arrow is the point: usage data and incident lessons feed the next design. Teams without this loop design v2 from opinions; teams with it design v2 from which v1 fields nobody reads and which errors everyone hits.
Governance: consistency at forty endpoints
One endpoint designed by one person is consistent for free. Forty endpoints by eight people drifts: created_at vs createdAt vs created, ?limit vs ?page_size, three error shapes. Governance is how you keep the API feeling like one mind designed it — without a central committee reviewing every line:
- A written style guide — naming, pagination, error format, versioning rules. Two pages, opinionated, the same answers this course gives.
- Linting in CI — spectral-style rules on the OpenAPI spec: every operation has a description, paths are kebab-case, error responses use the standard shape. Machines nag; humans discuss real trade-offs.
- Review for the contract, not just code — spec diffs reviewed like schema migrations, because that is what they are.
Governance fails in two directions: none (drift), and bureaucracy (a monthly board that blocks everything and teaches teams to ship undocumented shadow endpoints). Linting absorbs the tedium so review can stay fast. A Spectral ruleset makes the style guide executable:
# .spectral.yaml — CI fails the spec, not feelings
rules:
operation-description: error # every operation documented
path-keys-kebab-case: error
oas3-schema:
message: "every response needs a schema"
severity: error
given: "$.paths.*.*.responses.*"
then: { field: content, function: truthy }
Rules live in the repo, evolve by PR like everything else, and apply identically to a first endpoint and a fiftieth — which is exactly the property human review lacks at 6 p.m. on a Friday.
Versioning and deprecation: the social contract
Chapter 3 covered version schemes; lifecycle covers version policy — the promises that let customers plan:
- Additive within a version. New optional fields and new endpoints land in v1 freely. Anything that breaks existing clients — renames, type changes, removed fields, tightened validation — waits for v2.
- Two live versions, maximum. Each additional live version is a permanent tax on every change (and, per Chapter 9, a security liability: the forgotten v1 running last year’s auth logic).
- Announced sunsets with headers, not just emails. Responses carry the notice where developers will actually see it:
HTTP/1.1 200 OK
Deprecation: true
Sunset: Sat, 31 Jan 2027 00:00:00 GMT
Link: <https://api.example.com/v2-migration>; rel="deprecation"
- Metered by version. You cannot sunset what you cannot count. Per-version, per-key analytics tell you exactly which customers still call v1 — turning “who’s left?” from a panic into a report.
The timeline that works in practice: announce at T−180 days with a migration guide, email stragglers at T−90 (you know who they are — see 4), brownout windows at T−30 (v1 disabled for one hour, then restored — the last wake-up call nobody ignores), sunset at T. The brownout feels harsh; it is kinder than discovering at T+0 that a critical customer never read the email.
Breaking vs additive: know the difference cold
| Additive (safe within a version) | Breaking (needs a new version) |
|---|---|
| new endpoint | renaming/removing a field |
| new optional request field | changing a field’s type or meaning |
| new enum value in responses (with docs warning) | removing an enum value clients send |
| relaxing validation (accept more) | tightening validation (reject what worked) |
| new optional response header | changing error codes/shape |
The subtle rows are the middle ones: a new enum value can crash clients with exhaustive switch statements (warn in docs; forward-compatible clients ignore unknowns), and tightened validation breaks clients who were getting away with it. When in doubt: if any conforming client could observe a difference, it’s breaking.
Idempotency: making retries safe
Networks fail ambiguously: the POST /payments timed out, but did it land? The client must retry — and without protection, a retry can execute the operation twice. Idempotency keys close the hole: the client generates a unique key per logical operation and sends it on every attempt:
POST /payments
Idempotency-Key: 9f3c2a1b-…
{"order_id": "42", "amount": 1999}
The server stores the key with its result; a repeat of the key returns the stored result instead of re-executing:
def post_payment(key: str, body: dict):
if (stored := idem_store.get(key)) is not None:
return stored.response, stored.status # replay, don't re-charge
result = charge_card(body) # exactly once
idem_store.set(key, result, ttl=86400) # remember for 24 h
return result.response, result.status
Three details make it correct: the store write and the operation must be atomic (or at least locked per key, so concurrent retries don’t both execute); the key expires after a window (24 h is typical — long enough to cover retry storms, short enough to bound storage); and the key scopes to the endpoint, so the same key on /refunds is a different operation. Stripe built a reputation on this one mechanism. The rule: any non-idempotent endpoint a client might retry should accept an idempotency key — which is to say, every POST that moves money or mutates state.
The expected damage without keys is a product of three small numbers that are all larger than you’d like:
\[ E[\text{duplicates}] = N \cdot p_{\text{timeout}} \cdot p_{\text{retry}} \]
At \(N = 10{,}000\) payments/day, a 0.5% ambiguous-timeout rate, and clients that retry, that’s ~50 double-charge risks daily — each one a support ticket, a refund, and a trust deduction. Idempotency keys drive the product to zero for the cost of one unique-index lookup.
RFC 7807: errors worth integrating against
Chapter 1 demanded structured errors; RFC 7807 (application/problem+json) is the standard shape:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/insufficient-funds",
"title": "Insufficient funds",
"status": 422,
"detail": "Capture of 1999 exceeds authorized 1500 for order 42.",
"instance": "/payments/pay_8871",
"balance_remaining": 1500
}
type is a stable, documentable URI identifying the kind of problem (clients switch on it, unlike prose); title is the human summary; instance points at this occurrence; extensions (balance_remaining) carry machine-readable specifics. The payoff is that error handling becomes integration, not parsing: a client can branch on type values you publish in your spec (Chapter 8), and every error from your API — from any endpoint, any team — arrives in one shape.
Pitfalls
- Sunsetting without metrics. You email “everyone” and hope. Meter version usage per key, or the sunset is a negotiation with unknowns.
- Breaking changes smuggled as patches. “It’s just tightening validation” breaks every client sending the old shape. The additive/breaking table is review checklist, not trivia.
- Retry without idempotency. Clients will retry your
POSTs — timeouts guarantee it. No idempotency key means double charges are a when, not an if. - One error shape per team. JSON here, HTML from the gateway there, plain text from the legacy service. Adopt problem+json at the edge and the spec, everywhere.
- Governance by meeting. A review board that gates every endpoint teaches teams to ship shadow APIs. Style guide + linting + fast spec review.
- v1 forever. Keeping versions alive “because one customer” compounds security and maintenance debt. Sunset dates with escalation paths, and hold them.
Classify: adding an optional note field to invoice creation; renaming total to total_cents; rejecting emails without +-tags that were previously accepted; adding a new invoice status value. A client’s POST /payments times out twice and succeeds on the third try — walk through what the idempotency key does on each attempt. Why include a brownout in a sunset plan?
ASolution
Optional note: additive (safe within the version). Renaming total: breaking (new version). Rejecting previously accepted emails: breaking — tightened validation fails conforming clients. New status value: additive but documented — exhaustive-switch clients may need warning, so announce it. First attempt: the key is absent from the store, the charge executes, and key→result is stored atomically; second attempt: key found, stored result returned, no charge; third attempt: same replay — the card is charged exactly once and the client receives one consistent outcome. A brownout (temporary v1 shutdown before the final date) surfaces every remaining dependency as a recoverable scare while rollback is still possible — it converts silent non-migrators into informed migrators before the irreversible sunset.
Next: Standards and Compliance (API Design #15) — GDPR, CCPA, PCI DSS, HIPAA, and designing APIs that can answer a regulator.