API Versioning & Evolution
"With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody." — Hyrum Wright, Hyrum's Law, hyrumslaw.com
Summary: An API is a promise that other people's running code depends on. Versioning is not "adding /v2"; it is the discipline of changing a system whose callers you cannot upgrade: classify every change as additive or breaking, make additive the default, and when you must break, run two contracts side by side, announce the end of the old one, measure who still uses it, and only then switch it off. Focus: What "breaking" means (backward and forward compatibility, tolerant reader, the robustness principle and its critique, Hyrum's law), the strategies (URI path, query parameter, custom header, vendor media type, no explicit version), semantic versioning for APIs, date-based versioning with version-transform layers (Stripe), the deprecation lifecycle with the Deprecation and Sunset headers, usage telemetry and kill switches, consumer-driven contracts, schema evolution for events, Protobuf and GraphQL, feature flags versus versions, versioning at the gateway, database coupling with expand/contract, SDKs and mobile long tails, OpenAPI and Protobuf diff tooling, and testing several versions, with Go and Laravel 13 code. Learning goal: Given a proposed change to a public or internal API, decide whether it is breaking, choose the cheapest versioning mechanism that fits your callers, write the transformation and the retirement plan, and prove with tooling and tests that no caller was surprised.
This chapter sits in the networking and protocols group, after REST API Design, GraphQL and gRPC & Protocol Buffers, and before Web Sessions, Cookies & CORS. REST resource design and idempotency are owned by the REST chapter; the wire details of Protobuf and GraphQL by their chapters. The architecture-level view of contracts and consumer-driven tests is in Service Communication and the gateway in API Gateway, BFF & Service Mesh. Event and message schemas are in Message Design & Schema Evolution; the database half of a rename is in Zero-Downtime Schema Migrations; ACLs between bounded contexts in Context Maps & Integration Patterns. This page owns the system-level decision: how an API changes over years without breaking the people who call it.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a version number is not the point | Why it exists |
| Postel, Hyrum, Fowler, Stripe, RFC 9745, semver | Where it comes from |
| What counts as a breaking change | Breaking and additive changes |
| Tolerant reader, robustness principle, Hyrum's law | Tolerant reader |
/v2, ?api-version=, Api-Version:, vnd.acme.v2+json | URI, Query, Header, Media type |
| Evolving without any version | Evolution only |
| MAJOR.MINOR.PATCH for an API | Semantic versioning |
| Stripe-style dated versions and transforms | Date-based versioning |
| Announce, dual run, sunset, kill switch | Deprecation lifecycle, Headers, Telemetry |
| Contract tests from consumers | Consumer-driven contracts |
| Events, Protobuf, GraphQL | Schema evolution |
| Flags or versions | Feature flags vs versions |
| Routing by version at the edge | Gateway |
| Renaming a column behind a live API | Database coupling |
| Old mobile apps, SDK numbers | SDKs and long tails |
oasdiff, buf breaking in CI | Diff tooling |
| Header syntax, status codes, caching | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Testing more than one version | Testing |
| Which strategy | Choosing |
| Monolith to distributed system | In architecture |
| Runnable experiment | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Which changes break callers. The test is not "does it compile" but "can a caller that worked yesterday fail today". oasdiff states the same rule for OpenAPI: a change is breaking if "a request that was valid before can now be rejected, or a response can now carry something clients were never written to handle".
| Change | Breaking? | Why | Safe way |
|---|---|---|---|
| Add an endpoint | No | Nobody calls it yet | Just ship |
| Add an optional response field | No, if callers are tolerant readers | Strict parsers fail on unknown fields | Document "ignore unknown fields" from day one |
| Add an optional request field with a default | No | Old requests keep their old behaviour | Default must equal the old behaviour |
| Add a required request field | Yes | Old requests are now invalid | New optional field, or a new version |
| Remove or rename a field | Yes | Callers read it | Expand, migrate, contract |
| Change a field type or unit | Yes, silently | "19.99" becomes 1999 | New field name |
| Add an enum value in a response | Maybe | Exhaustive switch statements fail | Declare enums open; callers keep an unknown branch |
| Tighten validation | Yes | Requests that passed now fail | Warn first, enforce in a new version |
| Change a default or ordering | Yes, often unnoticed | Hyrum's law | Treat as a breaking change |
| Change an error code or message callers match | Yes | Callers branch on it | Stable machine-readable code field |
Where the version lives.
| Strategy | Example | Visible in logs | Cache-friendly | Typical users |
|---|---|---|---|---|
| URI path | GET /v2/orders/42 | Yes | Yes, URL is the key | Many public REST APIs |
| Query parameter | GET /orders/42?api-version=2024-06-01 | Yes | Yes, if the query is in the cache key | Azure (api-version is required) |
| Custom header | Stripe-Version: 2024-06-20, X-GitHub-Api-Version: 2022-11-28 | If you log it | Needs Vary | Stripe, GitHub |
| Media type | Accept: application/vnd.acme.v2+json | If you log it | Needs Vary: Accept | Hypermedia purists, some enterprise APIs |
| No version | Additive evolution only | n/a | Yes | GraphQL (schema evolves with @deprecated), Protobuf field numbers |
The retirement clock.
| Stage | Signal to the caller | Server behaviour | Exit criterion |
|---|---|---|---|
| Announce | Changelog, email, Link: rel="deprecation" | Unchanged | Date and migration guide published |
| Deprecated | Deprecation: @1688169599 | Unchanged | Telemetry shows migration progressing |
| Brownouts | Same headers | Short scheduled 410 windows | Stragglers found and contacted |
| Sunset | Sunset: Sun, 30 Jun 2024 23:59:59 GMT | 410 Gone | Last caller migrated or accepted |
| Deleted | None | Code and tables removed | Contract phase of the database migration |
Why it exists
You can refactor a function because the compiler finds every caller. You cannot refactor an HTTP API that way: the callers are other companies' servers, mobile apps in a pocket for four years, a cron job nobody remembers writing. Stripe puts it as "an API represents a contract for communication that can't be changed without considerable cooperation and effort", and says it has "maintained compatibility with every version of our API since the company's inception in 2011" (Stripe engineering blog). The provider still has to move forward: new features, corrected mistakes, security fixes.
| Force | Pulls toward | Cost if you give in completely |
|---|---|---|
| Provider velocity | Change freely | Callers break, trust is gone |
| Caller stability | Never change | The API fossilises, mistakes live forever |
| Provider cost | One version, one code path | Breaking changes hurt callers |
| Caller migration cost | Many long-lived versions | Every version is code to test, secure and run |
Everyday picture: a public road system. You may add a lane or a new street whenever you like (additive). Closing a street, reversing its direction or renumbering exits (breaking) needs signs months ahead, a detour that stays open, and counters that tell you traffic has stopped before you pour the new asphalt. A version number is only the street sign; the work is the detour and the traffic counter.
Three common misunderstandings, up front
| Belief | Reality |
|---|---|
"We have /v1 in the URL, so we are versioned." | A label is not a policy. Without compatibility rules inside v1, deprecation dates and usage counters, /v1 just gets quietly broken in place. |
| "A new major version is the safe way to ship a change." | Each version is another contract to run, secure, document and test for years. The cheapest change is the additive one that needs no version. |
| "Clients should handle anything; we can change what we like." | Hyrum's law: callers depend on observable behaviour you never promised. Your promise is smaller than your real contract. |
Where it comes from
- Robustness principle. RFC 761 (TCP, 1980) says "be conservative in what you do, be liberal in what you accept from others" (RFC 761 section 2.10). For protocols it means a receiver should survive things it did not expect. The principle was later stretched into "accept malformed input and guess", which keeps bugs alive; RFC 9413, Maintaining Robust Protocols (2023) says some interpretations "help ensure the health of the Internet" while others "can negatively affect interoperability over time".
- Tolerant Reader. Martin Fowler's bliki entry (9 May 2011) names the consumer half of the bargain: be as tolerant as possible when reading, so additive provider changes do not break you (martinfowler.com).
- Consumer-driven contracts. Ian Robinson (12 June 2006) turned the question around: let the consumers state what they need and test the provider against it (article); Pact is the best-known tool (docs.pact.io).
- Hyrum's law. Observed at Google during large-scale library migrations; the name was popularised by Titus Winters (hyrumslaw.com). It explains why "we never documented that" is not a defence.
- Semantic Versioning 2.0.0. For libraries: increment MAJOR for incompatible API changes, MINOR for backward-compatible functionality, PATCH for backward-compatible fixes (semver.org).
- Google AIP-180 and AIP-181. Define source, wire and semantic compatibility, rules for what may change inside a major version, and stability levels (alpha, beta, stable) (AIP-180, AIP-181).
- Stripe, 5 August 2017. Date-based versions, a
Stripe-Versionheader, and "version change modules" that rewrite a head response back to the caller's pinned version (blog post). - RFC 8594 (May 2019) and RFC 9745 (March 2025). Standardised
SunsetandDeprecationresponse headers (RFC 8594, RFC 9745). - Microsoft REST API Guidelines. Azure requires an
api-versionquery parameter withYYYY-MM-DDvalues and forbids a version segment in paths (guidelines).
The concept catalogue
Breaking and additive changes: backward and forward compatibility Must-know
In plain words: A change is backward compatible if callers written for the old contract still work against the new server. It is forward compatible if callers written for the new contract still work against an old server or old data. Independent deployment needs both: servers are upgraded before some callers, and callers before some servers.
Common misunderstanding: "Breaking" means "removes something". Equally breaking: adding a required field, tightening validation, changing a default, changing sort order, changing an error code, changing units, adding an enum value to a response that callers switch on exhaustively, and making a call slower than a caller's timeout.
Definition: Google's AIP-180 distinguishes three kinds. Source compatibility: code written against the old library still compiles. Wire compatibility: old requests and responses still parse. Semantic compatibility: the same call still means the same thing. A wire-compatible change can be semantically breaking (a field that was seconds is now milliseconds), and only the caller notices, in production.
Provider (new) Caller (old, not redeployed)
1 adds field "tax" to Order reads id, amount, status
2 response now has 4 fields JSON decoder ignores "tax" -> works (tolerant reader)
3 adds "refunded" to status enum switch on status has no default -> panic in production (not tolerant)
4 makes "currency" required sends no currency -> 400, caller downReal scenarios: a mobile app released in 2023 still sending the old payload in 2027; a partner's nightly batch that parses a CSV column by position; a Terraform provider that reads an enum; a webhook consumer that rejects unknown event types.
| Compatibility | Backward | Forward |
|---|---|---|
| Question | Old caller, new server? | New caller, old server or data? |
| Protobuf | Add fields with new numbers | Old readers skip unknown fields |
| JSON over HTTP | Add optional fields | Callers send only fields the server knows |
| Event streams | Consumers upgraded first | Producers upgraded first; readers ignore unknowns |
| Needed for | Rolling deploys of the provider | Rolling deploys of callers, rollbacks, replay of old events |
Fix / how to use it: keep a written list of what you consider breaking (use AIP-180 or oasdiff's rule list as a start), make "is this breaking?" a checklist item in review and a tool in CI (Diff tooling), and prefer a new field name over changing an old one's meaning.
Tolerant reader, the robustness principle and Hyrum's law Must-know
In plain words: A tolerant reader takes only the fields it needs and ignores the rest. Hyrum's law is the other side of the table: the provider can never know which "extras" a caller already depends on.
Common misunderstanding: "Postel's law says be liberal, so accept anything." RFC 9413 warns that guessing at malformed input accumulates quirks that become the real specification. Be tolerant of unknown additions, strict about malformed input and attacks.
Definition: Fowler's Tolerant Reader recommends "to be as tolerant as possible when reading data from a service". Hyrum's law says that with enough callers "all observable behaviors of your system will be depended on by somebody". Together: consumers must tolerate additive change; providers must still assume someone relies on field order, a default page size, a typo in an error message, or a response time.
Provider change Hyrum-style dependency discovered after the release
1 sort order of /orders was "by id" caller assumed "newest first"; "improvement" to sort by name breaks a dashboard
2 error message "not found" reworded caller matched on the string
3 page size 100 -> 50 caller assumed one page covers the day
4 latency 80 ms -> 12 ms caller's race condition between two requests appearsReal scenarios: a Go service decoding with DisallowUnknownFields failing the day the provider adds a field; a Java client with a closed enum failing on refunded; a client that parses a Link header by regex.
| Behaviour | Tolerant reader | Strict reader |
|---|---|---|
| Unknown JSON field | Ignored | Rejected (outage on additive change) |
| Unknown enum value | Mapped to unknown, logged | Exception |
| Missing optional field | Default | Exception |
| Malformed JSON or wrong type | Rejected | Rejected (tolerance is not guessing) |
Fix / how to use it: Go's encoding/json ignores unknown fields by default; keep it that way and write an open enum type. The tolerant snippet below tests both behaviours.
// Package tolerant shows a Tolerant Reader: take only what you need, ignore the
// rest, and survive values you have never seen.
package tolerant
import (
"encoding/json"
"strings"
)
// Status is an open enum: unknown values are kept, not rejected.
type Status string
const (
Pending Status = "pending"
Succeeded Status = "succeeded"
Unknown Status = "unknown"
)
func (s *Status) UnmarshalJSON(b []byte) error {
var raw string
if err := json.Unmarshal(b, &raw); err != nil {
return err
}
switch Status(raw) {
case Pending, Succeeded:
*s = Status(raw)
default:
*s = Unknown // a newer provider added "refunded"; we keep working
}
return nil
}
// Order lists only the fields this consumer uses.
type Order struct {
ID string `json:"id"`
Status Status `json:"status"`
}
// ParseTolerant ignores unknown fields (the encoding/json default).
func ParseTolerant(body string) (Order, error) {
var o Order
err := json.NewDecoder(strings.NewReader(body)).Decode(&o)
return o, err
}
// ParseStrict rejects unknown fields. It is the anti-pattern for a consumer: any
// additive change by the provider becomes an outage.
func ParseStrict(body string) (Order, error) {
var o Order
dec := json.NewDecoder(strings.NewReader(body))
dec.DisallowUnknownFields()
err := dec.Decode(&o)
return o, err
}URI path versioning Must-know
In plain words: The version is part of the URL: /v1/orders, /v2/orders. Different versions are different addresses.
Common misunderstanding: "REST says a resource has one URI, so path versions are wrong." The purity argument is real (/v2/orders/42 and /v1/orders/42 name the same order), but it costs you nothing operationally that matters: every proxy, cache, log line, firewall rule and curl command understands a path.
Definition: The version is a leading path segment, usually only the major (v2), selected by the router before any handler runs.
1 GET /v1/orders/42 -> router: prefix /v1 -> handler set v1 -> 200 {"amount":"19.99"}
2 GET /v2/orders/42 -> router: prefix /v2 -> handler set v2 -> 200 {"amount_cents":1999}
3 GET /v3/orders/42 -> no route -> 404Real scenarios: public REST APIs with a /v1 or /2 prefix; AWS-style /2015-03-31/functions; versioned gateway routes (/v1/* to the old service, /v2/* to the new).
| Property | URI versioning |
|---|---|
| Discoverability | Best: visible in docs, logs, browser |
| Routing at NGINX, Envoy, Kong, AWS API Gateway | Trivial: path prefix match |
| Caching (CDN, browser) | Works with no extra headers |
| Granularity | Whole API; every resource moves to v2 together |
| Weakness | Pressure to "bump everything"; links stored in data embed v1 forever |
Fix / how to use it: keep v1 and v2 as thin route groups over shared domain code; version only the representation layer. See Laravel route groups and the Go resolve package below.
Query parameter versioning Important
In plain words: The version rides in the query string: ?api-version=2024-06-01.
Common misunderstanding: "Optional query parameters default to the latest." Azure does the opposite: the guidelines require api-version on every operation and answer 400 with MissingApiVersionParameter when it is missing, so a client never silently moves to a new contract.
Definition: Microsoft's guidelines: "DO use a required query parameter named api-version", with YYYY-MM-DD values, and "DO NOT include a version number segment in any operation path".
1 PUT /users/Jeff?api-version=2021-06-04 -> 200
2 PUT /users/Jeff -> 400 MissingApiVersionParameter
3 PUT /users/Jeff?api-version=2020-01-01 -> 400 UnsupportedApiVersionValueReal scenarios: Azure Resource Manager and Azure data-plane services; some SaaS APIs with ?v=.
| Property | Query parameter |
|---|---|
| Routing | Needs query-aware rules (NGINX $arg_api-version is awkward; Envoy can match query parameters) |
| Cache key | Must include the parameter; most CDNs include the query string by default |
| Per-resource versions | Easy |
| Weakness | Easy to drop when building nextLink pagination URLs (the Microsoft guidelines require carrying api-version in nextLink) |
Custom header versioning Important
In plain words: The URL stays the same; a request header names the contract: Stripe-Version: 2024-06-20, X-GitHub-Api-Version: 2022-11-28.
Common misunderstanding: "Headers are hidden so they are better." Hidden also means it is easy to forget in a log, a curl or a cache. A response that varies by a request header must say so with Vary, or a shared cache will serve one version's bytes to another version's caller.
Definition: The server reads the header, falls back to a pinned or default version when it is absent, and echoes the version actually used. GitHub documents that requests without X-GitHub-Api-Version "default to use the 2022-11-28 version" and that a previous version is supported "for at least 24 more months" after a new one ships (GitHub docs).
1 GET /v1/charges/ch_1 Stripe-Version: 2024-06-20 -> response shaped as of 2024-06-20
2 GET /v1/charges/ch_1 (no header) -> account's pinned version (set at first request)
3 GET /v1/charges/ch_1 Stripe-Version: 1999-01-01 -> 400 invalid version| Property | Custom header |
|---|---|
| Clean URLs, stable links | Yes |
Browser address bar and <img src> | Cannot send it |
| Cache | Add Vary: Api-Version |
| CORS | Custom headers trigger preflight; list it in Access-Control-Allow-Headers (Web Sessions, Cookies & CORS) |
Media type versioning and content negotiation Good to know
In plain words: The client asks for a representation by media type: Accept: application/vnd.acme.v2+json. The version belongs to the representation, not to the resource.
Common misunderstanding: "This is the only RESTful way, so use it." It is the most faithful to content negotiation (RFC 9110 section 12), and the hardest for callers: browsers, many HTTP clients, API explorers and gateways handle it poorly, and 406 Not Acceptable errors are opaque.
Definition: A vendor media type uses the vnd. tree defined in RFC 6838: application/vnd.acme.v2+json. The +json suffix says the structure is JSON. An alternative is a parameter: application/json; version=2.
1 Accept: application/vnd.acme.v2+json -> 200 Content-Type: application/vnd.acme.v2+json, Vary: Accept
2 Accept: application/json -> 200 default representation (state which in docs)
3 Accept: application/vnd.acme.v9+json -> 406 Not Acceptable
4 POST with Content-Type: ...v2+json -> 415 Unsupported Media Type if the server cannot read v2| Property | Media type |
|---|---|
| Purity | Highest |
| Tooling friendliness | Lowest |
| Per-resource versions | Natural |
| Weakness | Quality factors (q=), multiple values in Accept, easy mismatch between request and response types |
Evolution only: no explicit version Must-know
In plain words: Never break; only add. Unwanted things are marked deprecated and stay.
Common misunderstanding: "This only works for GraphQL." Protobuf works the same way (field numbers are never reused; removed fields get reserved), Google's AIPs require it inside a major version, and the Kubernetes API keeps GA versions for at least 12 months or 2 releases after deprecation (Kubernetes deprecation policy).
Definition: One contract that only grows. GraphQL's own guidance is to "design and evolve a type system over time without versions", using the @deprecated(reason: ...) directive (GraphQL best practices, schema docs).
1 schema: User { name: String @deprecated(reason: "Use fullName") fullName: String }
2 old clients keep asking for name -> still answered
3 field usage metrics for "name" reach zero -> remove it in a planned breaking window| Need | Evolution-only handles it? |
|---|---|
| New field, new endpoint | Yes |
| Rename | Partially: add the new name, keep the old as deprecated |
| Change a type or unit | No: new field |
| Remove behaviour that is unsafe (security fix) | No: needs a break, announced |
Fix / how to use it: make evolution-only the default and treat each exception as a deliberate, reviewed version bump.
Semantic versioning for APIs Important
In plain words: MAJOR.MINOR.PATCH: major = breaking, minor = backward-compatible feature, patch = backward-compatible fix.
Common misunderstanding: "Our API is 2.4.1, so callers pick 2.4.1." Semver was written for libraries that callers choose at build time. A web API runs one deployed version per URL, so only the major is part of the contract: v2. Minor and patch live in the changelog and info.version of the OpenAPI document, not in routes.
Definition: semver.org: "MAJOR version when you make incompatible API changes, MINOR version when you add functionality in a backward compatible manner, PATCH version when you make backward compatible bug fixes". Deprecation fits semver: update the documentation and "issue a new minor release with the deprecation in place" before the major that removes it.
| Where | What to number | Example |
|---|---|---|
| URL / header | Major only | v2 |
OpenAPI info.version | Full semver | 2.4.1 |
| SDK package | Full semver, plus minimum supported API version | acme-sdk 5.2.0 supports API 2023-09-01 and later |
| Protobuf package | Major in the package name | acme.billing.v2 |
| Pre-release | Labels or stability level | v1beta1, 2024-06-01-preview |
Fix / how to use it: generate the changelog from the OpenAPI diff and bump the version by the highest severity found (Diff tooling).
Date-based versioning and version transforms (Stripe) Must-know
In plain words: Instead of "v1, v2" the version is a date, and the server keeps one implementation (the newest) plus a pile of small "undo" functions, one per breaking change. An old caller gets the newest result passed back through the undo functions.
Common misunderstanding: "Date-based versions mean every date is a separate code base." The opposite: the point is that old versions cost only the small transformation module. Stripe's stated goals are "lightweight" upgrades, "first-class" versions that generate docs and changelogs, and "fixed-cost" old versions, "tightly encapsulating them in version change modules".
Definition: Stripe's design (2017): a caller's version comes from the Stripe-Version header, the version of an authorised OAuth app, or the version "pinned" at the account's very first request. The API formats the response at the current version, then "walks back through time and applies each version change module" until the target version is reached.
Request pinned to 2023-01-15
1 resolve version: header > OAuth app version > account pin -> 2023-01-15
2 request upgrade, oldest first: 2023-09-01, 2024-04-10, 2025-02-01 -> head-shaped request
3 handler runs at head only; one domain model
4 response downgrade, newest first: 2025-02-01, 2024-04-10, 2023-09-01 -> shape of 2023-01-15
5 Api-Version: 2023-01-15 on the responseReal scenarios: Stripe (dated versions, Stripe-Version), GitHub (X-GitHub-Api-Version, 24 months of support), Azure (api-version=YYYY-MM-DD). The Go versionchain snippet below is a self-contained miniature.
| Aspect | Path versions (v1/v2) | Dated versions with transforms |
|---|---|---|
| Granularity of a break | Whole API | One field, one change |
| Caller upgrade | Port to a new surface | Read one changelog entry, change the date |
| Provider cost per old version | Whole code path, tests, docs | A request/response transform pair |
| Risk | Two domain models drift | Transform bugs; transforms must be tested in sequence |
| Bad fit | n/a | Changes that alter behaviour (side effects), not just shape: Stripe notes that this "reduced encapsulation makes changes with side effects more complex to maintain" |
Fix / how to use it: keep transforms pure (document in, document out), declarative where possible (description, affected resources), write a test per change in both directions, and generate the changelog from them.
// Package versionchain implements Stripe-style date-based versioning.
//
// The handler always produces the newest ("head") shape. Each breaking change is
// a Change: a pair of small functions. A request pinned to an older version is
// upgraded to head on the way in; a head response is walked back through every
// change newer than the pinned version on the way out.
package versionchain
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sort"
"time"
)
// Doc is a decoded JSON object.
type Doc = map[string]any
// Change is one breaking change, introduced at Version (a YYYY-MM-DD date).
type Change struct {
Version string
Description string
// Upgrade rewrites a request body from the shape before this change to the
// shape after it. Applied oldest first.
Upgrade func(Doc)
// Downgrade rewrites a response from the shape after this change to the shape
// before it. Applied newest first. Each Downgrade may assume the document looks
// the way it did when the change was written, whatever newer changes exist.
Downgrade func(Doc)
}
// Chain is an ordered list of changes on top of a base version.
type Chain struct {
base string
changes []Change
}
// New validates that every version is a date and strictly later than the one before.
func New(base string, changes ...Change) (*Chain, error) {
prev := base
if _, err := time.Parse("2006-01-02", base); err != nil {
return nil, fmt.Errorf("base version %q: %w", base, err)
}
for _, c := range changes {
if _, err := time.Parse("2006-01-02", c.Version); err != nil {
return nil, fmt.Errorf("change version %q: %w", c.Version, err)
}
if c.Version <= prev {
return nil, fmt.Errorf("change %q must be later than %q", c.Version, prev)
}
prev = c.Version
}
return &Chain{base: base, changes: changes}, nil
}
// Head is the newest version, the shape the handlers produce.
func (c *Chain) Head() string {
if len(c.changes) == 0 {
return c.base
}
return c.changes[len(c.changes)-1].Version
}
// Known reports whether v is the base or the version of some change.
func (c *Chain) Known(v string) bool {
if v == c.base {
return true
}
i := sort.Search(len(c.changes), func(i int) bool { return c.changes[i].Version >= v })
return i < len(c.changes) && c.changes[i].Version == v
}
// UpgradeRequest applies, oldest first, every change newer than target.
func (c *Chain) UpgradeRequest(target string, d Doc) {
for _, ch := range c.changes {
if ch.Version > target && ch.Upgrade != nil {
ch.Upgrade(d)
}
}
}
// DowngradeResponse applies, newest first, every change newer than target.
func (c *Chain) DowngradeResponse(target string, d Doc) {
for i := len(c.changes) - 1; i >= 0; i-- {
ch := c.changes[i]
if ch.Version > target && ch.Downgrade != nil {
ch.Downgrade(d)
}
}
}
// Config wires a chain into HTTP.
type Config struct {
Chain *Chain
// Resolve returns the requested version, or "" when the client did not say.
Resolve func(*http.Request) string
// Pinned returns the version stored for the caller (for example per API key).
// It is only consulted when Resolve returns "". Return "" for "none".
Pinned func(*http.Request) string
}
// Middleware returns a handler wrapper that speaks the pinned version outside and head inside.
func Middleware(cfg Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
version := cfg.Resolve(r)
if version == "" && cfg.Pinned != nil {
version = cfg.Pinned(r)
}
if version == "" {
version = cfg.Chain.Head()
}
if !cfg.Chain.Known(version) {
writeProblem(w, http.StatusBadRequest, fmt.Sprintf("unsupported api version %q", version))
return
}
if err := upgradeBody(cfg.Chain, version, r); err != nil {
writeProblem(w, http.StatusBadRequest, err.Error())
return
}
rec := &buffered{header: http.Header{}, status: http.StatusOK}
next.ServeHTTP(rec, r)
body := rec.body.Bytes()
if isJSON(rec.header) && rec.status < 400 {
if out, ok := downgrade(cfg.Chain, version, body); ok {
body = out
rec.header.Del("Content-Length")
}
}
for k, v := range rec.header {
w.Header()[k] = v
}
w.Header().Set("Api-Version", version)
w.WriteHeader(rec.status)
_, _ = w.Write(body)
})
}
}
func upgradeBody(c *Chain, version string, r *http.Request) error {
if r.Body == nil || r.ContentLength == 0 {
return nil
}
if r.Method != http.MethodPost && r.Method != http.MethodPut && r.Method != http.MethodPatch {
return nil
}
raw, err := io.ReadAll(r.Body)
if err != nil {
return err
}
var d Doc
if err := json.Unmarshal(raw, &d); err != nil {
return errors.New("request body is not a JSON object")
}
c.UpgradeRequest(version, d)
out, err := json.Marshal(d)
if err != nil {
return err
}
r.Body = io.NopCloser(bytes.NewReader(out))
r.ContentLength = int64(len(out))
return nil
}
// downgrade handles a single object or a list envelope {"data":[...]}.
func downgrade(c *Chain, version string, raw []byte) ([]byte, bool) {
var d Doc
if err := json.Unmarshal(raw, &d); err != nil {
return nil, false
}
if list, ok := d["data"].([]any); ok {
for _, item := range list {
if m, ok := item.(map[string]any); ok {
c.DowngradeResponse(version, m)
}
}
} else {
c.DowngradeResponse(version, d)
}
out, err := json.Marshal(d)
if err != nil {
return nil, false
}
return out, true
}
type buffered struct {
header http.Header
status int
body bytes.Buffer
}
func (b *buffered) Header() http.Header { return b.header }
func (b *buffered) WriteHeader(code int) { b.status = code }
func (b *buffered) Write(p []byte) (int, error) { return b.body.Write(p) }
func isJSON(h http.Header) bool {
ct := h.Get("Content-Type")
return len(ct) >= 16 && ct[:16] == "application/json"
}
func writeProblem(w http.ResponseWriter, status int, detail string) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{"title": http.StatusText(status), "status": status, "detail": detail})
}package versionchain
import (
"fmt"
"strconv"
)
// OrderChain is the worked example from the chapter: three breaking changes to an
// order resource, written once each, never touched again by the handlers.
func OrderChain() *Chain {
c, err := New("2023-01-15",
Change{
Version: "2023-09-01",
Description: "amount (decimal string) replaced by amount_cents (integer)",
Upgrade: func(d Doc) {
if s, ok := d["amount"].(string); ok {
f, err := strconv.ParseFloat(s, 64)
if err == nil {
d["amount_cents"] = int64(f*100 + 0.5)
delete(d, "amount")
}
}
},
Downgrade: func(d Doc) {
if n, ok := d["amount_cents"].(float64); ok {
d["amount"] = fmt.Sprintf("%.2f", n/100)
delete(d, "amount_cents")
}
},
},
Change{
Version: "2024-04-10",
Description: "status value paid renamed to succeeded",
Upgrade: func(d Doc) {
if d["status"] == "paid" {
d["status"] = "succeeded"
}
},
Downgrade: func(d Doc) {
if d["status"] == "succeeded" {
d["status"] = "paid"
}
},
},
Change{
Version: "2025-02-01",
Description: "customer_id string replaced by customer object",
Upgrade: func(d Doc) {
if id, ok := d["customer_id"].(string); ok {
d["customer"] = Doc{"id": id}
delete(d, "customer_id")
}
},
Downgrade: func(d Doc) {
if cust, ok := d["customer"].(map[string]any); ok {
d["customer_id"] = cust["id"]
delete(d, "customer")
}
},
},
)
if err != nil {
panic(err)
}
return c
}The deprecation lifecycle Must-know
In plain words: Retirement is a project with stages, owners and a date, not a deletion in a release.
Common misunderstanding: "We emailed everyone, so we can turn it off." Emails reach a founder who left in 2022. The only reliable signal is traffic: the version has no callers, or the remaining callers are known and have accepted the date.
Definition: Announce, deprecate, run both (dual running), brown out, sunset, delete. RFC 8594 separates two stages: first "the API is not the preferred or recommended version anymore", still operational; second, "the API or a specific version of the API gets decommissioned".
Day -180 announce: changelog, email, docs banner, Link rel="deprecation"
1 Day -90 Deprecation header on every v1 response; usage report per client
2 Day -30 brownouts: v1 answers 410 for 10 minutes on a published schedule
3 Day -7 direct outreach to the clients still in the telemetry
4 Day 0 Sunset: v1 answers 410 Gone with a pointer to v2
5 Day +30 code, routes, tables (contract phase) removed| Product | Published policy |
|---|---|
| Kubernetes | GA API: 12 months or 2 releases after announced deprecation, whichever is longer; beta: 3 months or 1 release |
| GitHub REST | New version supported alongside the previous one for at least 24 months |
| Azure (guidelines) | Preview versions retired after at least 90 days' notice |
| Stripe | Compatibility with every version since 2011 (no sunset for pinned accounts) |
Fix / how to use it: write the policy before the first release (minimum notice, minimum overlap), automate the headers, and keep a gate: no sunset while telemetry shows active callers unless a named owner accepts the risk.
Deprecation and Sunset headers Must-know
In plain words: Two response headers tell machines "this is deprecated since X" and "this stops working at Y". A Link header points to the human documentation.
Common misunderstanding: "Deprecation and Sunset change behaviour." They do not. RFC 9745: "The act of deprecation does not change any behavior of the resource", and the header is "only a hint": clients "should always be implemented in ways that allow them to function without deprecation-related information".
Definition: Deprecation (RFC 9745) is an Item Structured Field Date: @ followed by Unix seconds. Sunset (RFC 8594) is an HTTP-date. "The timestamp given in the Sunset HTTP header field MUST NOT be earlier than the one given in the Deprecation header field." Links use the relation types deprecation and sunset; successor-version is a registered IANA relation commonly used to point at the replacement.
HTTP/1.1 200 OK
Deprecation: @1688169599
Sunset: Sun, 30 Jun 2024 23:59:59 GMT
Link: <https://developer.example.com/deprecation>; rel="deprecation"; type="text/html"
Link: <https://api.example.com/v2/orders>; rel="successor-version"| Header | Standard | Value | Meaning | Date format |
|---|---|---|---|---|
Deprecation | RFC 9745 (March 2025) | @1688169599 | Deprecated at (or from) this instant; may be in the future | Structured Field Date (Unix seconds) |
Sunset | RFC 8594 (May 2019) | Sun, 30 Jun 2024 23:59:59 GMT | URI is likely to become unresponsive then | HTTP-date |
Link rel="deprecation" | RFC 9745 | URL | Where the policy and migration guide live | n/a |
Link rel="sunset" | RFC 8594 | URL | Sunset policy, mitigation | n/a |
azure-deprecating | Azure guidelines | free text | Human-readable notice on a deprecating version | n/a |
Fix / how to use it: emit headers from one middleware driven by one policy table (Go lifecycle and Laravel DeprecateApiVersion); have your own SDKs log a warning when they see them.
// Package lifecycle announces, measures and finally enforces the end of an API version.
package lifecycle
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"sync"
"time"
)
// Window is a scheduled brownout: the version answers 410 for a short period.
type Window struct{ From, To time.Time }
// Policy is the retirement plan of one version.
type Policy struct {
Deprecated time.Time // Deprecation header (RFC 9745); may be in the future
Sunset time.Time // Sunset header (RFC 8594); the version stops answering
DocsURL string // Link rel="deprecation"
Successor string // Link rel="successor-version"
Brownouts []Window
}
// Validate enforces the RFC 9745 rule that Sunset must not be earlier than Deprecation.
func (p Policy) Validate() error {
if !p.Sunset.IsZero() && !p.Deprecated.IsZero() && p.Sunset.Before(p.Deprecated) {
return fmt.Errorf("sunset %s is earlier than deprecation %s", p.Sunset, p.Deprecated)
}
return nil
}
// SetHeaders writes the announcement headers.
func (p Policy) SetHeaders(h http.Header) {
if !p.Deprecated.IsZero() {
// RFC 9745: an Item Structured Field Date, "@" plus Unix seconds.
h.Set("Deprecation", "@"+strconv.FormatInt(p.Deprecated.Unix(), 10))
}
if !p.Sunset.IsZero() {
// RFC 8594: an HTTP-date.
h.Set("Sunset", p.Sunset.UTC().Format(http.TimeFormat))
}
if p.DocsURL != "" {
h.Add("Link", fmt.Sprintf(`<%s>; rel="deprecation"; type="text/html"`, p.DocsURL))
}
if p.Successor != "" {
h.Add("Link", fmt.Sprintf(`<%s>; rel="successor-version"`, p.Successor))
}
}
// Usage counts calls per (version, client) so a sunset can wait for the last caller.
type Usage struct {
mu sync.Mutex
counts map[[2]string]int64
}
func NewUsage() *Usage { return &Usage{counts: map[[2]string]int64{}} }
func (u *Usage) Hit(version, client string) {
u.mu.Lock()
u.counts[[2]string{version, client}]++
u.mu.Unlock()
}
// Clients returns the clients that still call version, busiest first.
func (u *Usage) Clients(version string) []string {
u.mu.Lock()
defer u.mu.Unlock()
type row struct {
c string
n int64
}
var rows []row
for k, n := range u.counts {
if k[0] == version {
rows = append(rows, row{k[1], n})
}
}
sort.Slice(rows, func(i, j int) bool { return rows[i].n > rows[j].n || (rows[i].n == rows[j].n && rows[i].c < rows[j].c) })
out := make([]string, len(rows))
for i, r := range rows {
out[i] = r.c
}
return out
}
// Config wires the lifecycle into HTTP.
type Config struct {
Policies map[string]Policy
Version func(*http.Request) string
Client func(*http.Request) string
Usage *Usage
Now func() time.Time
// Killed is an operator switch (a feature flag): true answers 410 immediately.
Killed func(version string) bool
}
// Middleware counts usage, announces deprecation, and enforces brownouts, kill switch and sunset.
func Middleware(cfg Config) func(http.Handler) http.Handler {
if cfg.Now == nil {
cfg.Now = time.Now
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
version := cfg.Version(r)
now := cfg.Now()
pol, hasPolicy := cfg.Policies[version]
if cfg.Usage != nil {
cfg.Usage.Hit(version, cfg.Client(r))
}
if hasPolicy {
pol.SetHeaders(w.Header())
}
if gone(cfg, version, pol, hasPolicy, now) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusGone)
_ = json.NewEncoder(w).Encode(map[string]any{
"title": "Gone",
"status": http.StatusGone,
"detail": fmt.Sprintf("api version %s has been retired; see the successor-version link", version),
})
return
}
next.ServeHTTP(w, r)
})
}
}
func gone(cfg Config, version string, p Policy, has bool, now time.Time) bool {
if cfg.Killed != nil && cfg.Killed(version) {
return true
}
if !has {
return false
}
if !p.Sunset.IsZero() && !now.Before(p.Sunset) {
return true
}
for _, b := range p.Brownouts {
if !now.Before(b.From) && now.Before(b.To) {
return true
}
}
return false
}Usage telemetry and kill switches Must-know
In plain words: Count who calls which version. Keep an operator switch that can turn a version off (or back on) in seconds.
Common misunderstanding: "Total request count per version is enough." You need per client counts (API key, OAuth client, User-Agent and SDK version) so you know who to contact, and you need the trend, because 0.1% of traffic can be your largest customer.
Definition: Record (api_version, client_id, endpoint, day) as a low-cardinality metric or an aggregated log table. The kill switch is a runtime flag that makes a version answer 410 immediately: for emergencies, for brownouts, and for a fast rollback of a premature sunset.
-- Which clients still call v1, busiest first (PostgreSQL; request_log is an aggregated daily table)
SELECT client_id, sum(calls) AS calls, max(day) AS last_seen
FROM api_usage_daily
WHERE api_version = '1' AND day >= current_date - 30
GROUP BY client_id
ORDER BY calls DESC;| Signal | What it tells you | Where to get it |
|---|---|---|
| Calls per version per day | Migration progress | Prometheus counter api_requests_total{version=...} |
| Calls per version per client | Who to contact | Gateway access logs, API key id |
| SDK/User-Agent version | Which SDK to ship a fix for | User-Agent, X-Client-Version |
| Error rate per version after brownout | Hidden dependants | Metrics, support tickets |
Fix / how to use it: keep client id out of high-cardinality Prometheus labels (aggregate in logs or a warehouse and keep only version as a metric label); see Observability.
Consumer-driven contracts Important
In plain words: Each consumer writes down the parts of the API it really uses as executable examples. The provider runs them before shipping.
Common misunderstanding: "An OpenAPI file is the contract, so we are covered." OpenAPI describes everything the provider may do; a consumer-driven contract describes what consumers actually use. Pact calls itself "contract by example" and notes that a Pact contract "is enforced by executing a collection of test cases".
Definition: The consumer test generates a pact file (request, expected response); the provider verifies it in its own CI. pact-broker can-i-deploy --pacticipant Foo --version 23 --to-environment production tells you whether a version is safe to release. For the architecture view see Service Communication.
1 consumer CI: test against a mock provider -> pact file "orders-web -> orders-api"
2 publish pact to the broker, tagged with consumer version and branch
3 provider CI: replay every pact against the real provider -> pass or fail
4 before deploy: can-i-deploy asks "does every deployed consumer's pact still pass?"
5 a field no consumer reads can be removed safely; a field one consumer reads cannot| Question | Pact answers? | OpenAPI diff answers? |
|---|---|---|
| Did the shape change? | Only for fields consumers use | Everything in the schema |
| Who breaks if I remove field X? | Yes, by consumer name | No |
| Can I delete this deprecated field? | Yes, when no pact references it | Only with telemetry |
| Works for message queues | Yes (message pacts) | AsyncAPI diff tools |
Fix / how to use it: use both: a schema diff catches accidental breaks in public APIs; pacts prove the last internal consumer has moved.
Schema evolution for events, Protobuf and GraphQL Must-know
In plain words: Messages stay in logs and queues for months. Old and new producers and consumers meet in the same stream, so the rules are stricter than for HTTP.
Common misunderstanding: "We version events by adding v2 to the topic name." That doubles the topics and strands replays. Prefer compatible evolution (add optional fields, never reuse or retype), and a new event type only for a genuinely different fact. Details in Message Design & Schema Evolution and gRPC & Protocol Buffers.
Definition: For Protobuf: "Don't re-use a tag number", "do reserve tag numbers for deleted fields", "don't change the type of a field", "don't add a required field" (Protobuf Dos and Don'ts). buf breaking enforces this with the rule categories FILE, PACKAGE, WIRE_JSON and WIRE.
| Rule | JSON events | Protobuf / Avro | GraphQL |
|---|---|---|---|
| Add an optional field | Safe | Safe (new number / default) | Safe (new field) |
| Remove a field | Breaking for readers | Reserve the number; readers see default | @deprecated, remove later |
| Rename | Breaking | Wire-safe (number), breaks JSON and code | Add new field, deprecate old |
| Change type | Breaking | Breaking | Breaking |
| Add enum value | Readers need an unknown branch | Same; keep an UNSPECIFIED = 0 | Clients need a default branch |
| Version marker | schema_version in the envelope | Package v1, v2 | Evolve; avoid versions |
1 v1: message Order { string id = 1; string customer_name = 2; }
2 v2: customer_name removed -> "reserved 2; reserved "customer_name";" ; new: Customer customer = 3
3 old consumer reads a v2 message: field 2 absent -> default ""; unknown field 3 is skipped
4 a retry from the dead-letter queue replays v1 messages into a v2 consumer: must still parseFeature flags versus versions Important
In plain words: A version is a contract a caller chooses and keeps for years. A feature flag is a switch the provider flips, for a percentage of traffic or one customer, and removes in weeks.
Common misunderstanding: "Flags let us avoid versioning." A flag that changes the shape of a response for a caller who did not ask for it is a breaking change delivered in disguise. Use flags to roll out behaviour inside one contract (rollout, canary, kill switch), and versions to promise a contract.
Definition: Flag scopes: provider-wide, per tenant, per user, per request header. Opt-in headers (X-Feature-Beta: new-search) are a hybrid: caller-chosen, short-lived.
| Version | Feature flag | Opt-in beta header | |
|---|---|---|---|
| Chosen by | Caller | Provider | Caller |
| Lifetime | Months to years | Days to weeks | Weeks to a release |
| Changes response shape for callers who did not ask | No | Must not | No |
| Typical use | Breaking change | Gradual rollout, kill switch | Early access |
| Cleanup | Sunset process | Delete flag in code | Promote to stable |
Fix / how to use it: the kill switch in the lifecycle middleware is a flag over a version; the shape of each version is not behind a flag.
Versioning at the gateway: routing and translation layers Important
In plain words: The edge can pick the backend by version, and can also translate: accept a v1 request, call a v2 service.
Common misunderstanding: "The gateway is the right place to solve all version differences." A gateway that rewrites bodies becomes a second application with no tests and a team nobody owns. Route at the gateway; transform in code that is owned and tested next to the service.
Definition: Two patterns. Routing by version: the gateway matches path, header or query and forwards to a version-specific upstream (NGINX map/location, Envoy route match on header or prefix, Kong and AWS API Gateway stages). Translation layer / anticorruption layer (ACL): an adapter that converts the old contract to the new domain model so the new service never sees legacy shapes; this is the ACL of Context Maps & Integration Patterns.
1 client v1 -> gateway: path /v1/* or Api-Version: 1
2 gateway: policy check, rate limit, usage counter by (version, client)
3 route A: /v1/* -> orders-v1 service (legacy, frozen)
4 route B: /v2/* -> orders-service (current)
5 route C (strangler): /v1/* -> v1-adapter (ACL) -> orders-service; legacy service retired| Layer | Good at | Bad at |
|---|---|---|
| Gateway routing (NGINX, Envoy, Kong, AWS API Gateway, Apigee) | Pick upstream by path/header, count, throttle | Transforming bodies safely |
| Adapter service (ACL) | Full-language transforms, tests | One more deployable |
| In-process transform chain | Cheapest, versioned with the code | Only inside one service |
| Service mesh | mTLS, traffic split by header | Contract semantics |
See Strangler Fig for retiring the legacy upstream and API Gateway, BFF & Service Mesh for the edge itself.
Database schema coupling: expand and contract Must-know
In plain words: The API is a mask over tables. If the mask changes in one deploy and the table in another, something breaks in between. Change the table in additive steps that every running version tolerates.
Common misunderstanding: "ALTER TABLE ... RENAME COLUMN is one statement, so it is atomic and safe." The statement is atomic; the fleet is not. During a rolling deploy old and new application instances run together, and old instances still use the old name.
Definition: Expand and contract (parallel change): expand the schema, run old and new code against it, migrate, then contract (remove the old). Each phase is a separate deploy. Mechanics and lock behaviour: Zero-Downtime Schema Migrations.
-- 1. Expand (PostgreSQL): additive, instant, no rewrite for a nullable column
ALTER TABLE orders ADD COLUMN amount_cents bigint;
-- 2. Backfill in small batches, outside the migration transaction
UPDATE orders SET amount_cents = round(amount * 100)
WHERE id BETWEEN 1 AND 10000 AND amount_cents IS NULL;
-- 3. Application dual-writes amount and amount_cents; v1 mapper reads amount, v2 reads amount_cents
-- 4. Constrain only after the backfill is complete
ALTER TABLE orders ADD CONSTRAINT orders_amount_cents_nn CHECK (amount_cents IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_amount_cents_nn;
-- 5. Contract, only after v1 is sunset and telemetry shows no v1 caller
ALTER TABLE orders DROP COLUMN amount;| Step | Deploys | Old API version works? | Rollback possible? |
|---|---|---|---|
| Expand | Schema | Yes | Yes |
| Dual write + backfill | App | Yes | Yes |
| Switch reads | App | Yes (mapper per version) | Yes |
| Contract | Schema | Only versions that no longer exist | No (one-way door) |
Fix / how to use it: tie the contract migration to the sunset date in the same ticket, so the column cannot be dropped early or forgotten.
SDKs, client versioning and mobile long tails Important
In plain words: Your SDK is part of your API. Callers pin it, forget it, and ship it inside apps you cannot update.
Common misunderstanding: "We can force users to update." On the web, mostly yes. On mobile, the app store lag and users who never update leave a long tail: the 2022 build still calls the API in 2027. Plan the sunset for the slowest meaningful cohort, not the average.
Definition: Three versions interact: the API version, the SDK version (semver), and the app version. A good SDK sends User-Agent: acme-sdk/5.2.0 (go1.24) and the API version it was generated for, pins that API version by default (so an SDK upgrade is the opt-in), and warns on Deprecation/Sunset headers.
| Technique | Mobile long tail | Server-to-server |
|---|---|---|
| Minimum supported app version, remote config | Forces update dialog ("kill switch for clients") | n/a |
| Keep old version alive | Years | Months |
| Pin API version inside the SDK | Yes | Yes |
| Telemetry by app version | Required | By API key |
| Feature discovery | Capabilities endpoint | OpenAPI document per version |
Fix / how to use it: log X-Client-Version; publish SDKs from the OpenAPI document so the "supports API" range is generated, not typed.
OpenAPI diff, buf breaking and other tooling Must-know
In plain words: A tool compares the old contract with the new one in CI and fails the build when a break appears.
Common misunderstanding: "Reviewers will notice a breaking change." They do not; a removed required: true or a narrowed enum looks harmless in a diff. oasdiff checks each change against its rule set (its site cites 792 checks) so the decision is repeatable.
Definition: oasdiff breaking base.yaml revision.yaml lists changes that break clients; oasdiff changelog lists breaking and non-breaking; --fail-on ERR exits with code 1 when there is an error, --fail-on WARN on a warning too. buf breaking --against '.git#branch=main' compares a Protobuf module to its past version, with rule categories FILE (strictest), PACKAGE, WIRE_JSON and WIRE (most lenient).
# OpenAPI: fail CI on breaking changes against the main branch
git show origin/main:openapi.yaml > /tmp/base.yaml
oasdiff breaking /tmp/base.yaml openapi.yaml --fail-on ERR
# Changelog for release notes
oasdiff changelog /tmp/base.yaml openapi.yaml
# Protobuf: compare to main, wire-level rules only for an internal service
buf breaking --against '.git#branch=main'| Tool | Input | Detects | Notes |
|---|---|---|---|
| oasdiff | OpenAPI 3.x | Breaking and non-breaking changes with severities | breaking, changelog, `--fail-on ERR |
buf breaking | Protobuf | Source, JSON and wire breaks | Categories FILE, PACKAGE, WIRE_JSON, WIRE |
| Pact / Pact Broker | Consumer tests | What consumers really use | can-i-deploy |
Fix / how to use it: run the diff on every pull request; make "breaking" a label that needs a named approver and a changelog entry.
Testing several versions Important
In plain words: Every supported version needs a test that proves it still behaves as promised, and the old tests must not be edited.
Common misunderstanding: "The v2 tests cover v1 because v1 is a subset." Version-specific behaviour (field names, enum values, error shapes, defaults) is exactly what differs; shared tests prove nothing about it.
Definition: Four layers: (1) golden-file or snapshot tests per version for each resource, frozen in the repository; (2) request/response round-trip tests per transform (up and down); (3) contract tests for consumers; (4) a synthetic canary that calls every supported version in production on a schedule.
1 fixtures/orders/2023-01-15.json (frozen: never edited, only added)
2 test: head output -> downgrade to 2023-01-15 == fixture
3 test: fixture request -> upgrade -> head request is valid
4 CI: tests for every row in the support matrix; deleting a version deletes its fixtures in the same pull request
5 canary: GET each supported version every minute; alert on shape change or 5xx| Test | Catches | Cost |
|---|---|---|
| Golden files per version | Accidental shape change | Low |
| Transform up/down tests | Wrong or missing transform | Low |
| Pact | Breaking a real consumer | Medium |
| Canary per version | Version rotting after unrelated deploys | Medium |
Property test: downgrade(upgrade(x)) == x | Information loss in transforms | Medium |
Mechanics
Status codes and what they mean for versions
| Situation | Status | Body / header | Notes |
|---|---|---|---|
| Missing required version | 400 | Problem Details, code MissingApiVersionParameter (Azure) | Never silently default for a required-version API |
| Unknown or retired version string | 400 or 404 | Supported versions listed | Azure: UnsupportedApiVersionValue |
| Conflicting version sources (path says 2, header says 3) | 400 | Say which sources conflicted | Do not guess |
| Media type not available | 406 Not Acceptable | Available types | Content negotiation |
| Request body in an unsupported version media type | 415 Unsupported Media Type | Accepted types | Content-Type negotiation |
| Version past its sunset | 410 Gone | Link: rel="successor-version" | 404 hides the cause |
| Deprecated, still working | 200 | Deprecation, Sunset, Link | Headers only |
| Unsupported Protobuf/gRPC method after removal | gRPC UNIMPLEMENTED | message | Mirror of 404/410 |
| Too many requests while migrating | 429 | Retry-After | Not a version error |
Header syntax
| Item | Syntax | Source |
|---|---|---|
Deprecation | Deprecation: @1688169599 (Structured Field Date) | RFC 9745 section 2.1 |
Sunset | Sunset: Sat, 31 Dec 2018 23:59:59 GMT (HTTP-date) | RFC 8594 |
| Constraint | Sunset MUST NOT be earlier than Deprecation | RFC 9745 section 4 |
| Links | Link: <https://example.net/sunset>;rel="sunset";type="text/html" | RFC 8594 |
| Scope | The header describes the resource in the response; APIs may define a wider scope (for example "only on the home document") | RFC 9745 section 2.2 |
| Hint, not a switch | Clients must work without it | RFC 9745 |
Caching and Vary
A response that depends on a request header must list it in Vary, otherwise a shared cache (CDN, corporate proxy, browser) can serve version 1 bytes to a version 2 caller. For Accept-based and Api-Version-based versions send Vary: Accept, Api-Version. The path and query strategies need no Vary, but the CDN must include the query string in its cache key (CDNs).
Knobs and exact rule names
| Tool | Setting | Effect |
|---|---|---|
| oasdiff | --fail-on ERR / WARN / (changelog) INFO | Exit code 1 at or above that level |
| oasdiff | oasdiff breaking vs oasdiff changelog | Errors and warnings only vs all three levels |
| buf | breaking: use: [FILE] in buf.yaml | Strictness category |
| buf | buf breaking --against '.git#branch=main' | Baseline |
| Laravel | withRouting(api: ..., apiPrefix: 'api') in bootstrap/app.php | Global API path prefix |
| Laravel | Route::prefix('v2')->group(...) | Version segment per group |
| Laravel | $middleware->alias([...]) and name:param | Named middleware with a parameter |
| Go | http.NewServeMux() patterns "GET /v2/orders/{id}", r.PathValue("id") | Method and wildcard routing in net/http |
| Go | http.TimeFormat | Layout for HTTP-date (Sunset) |
| Stripe | Stripe-Version, account pin, OAuth app version | Order of version resolution |
Go
The Go module academy/api-versioning has one package per idea, all standard library. Every package has tests; go vet and go test ./... pass.
Before
Two copies of the handler, no shared code, no headers, no counters. A fix has to be written twice and nobody knows whether /v1 can be removed.
// Before: every version is a full copy of the handler. Nothing is shared,
// nothing is measured, and nothing tells the client that v1 will go away.
package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {
mux := http.NewServeMux()
// v1 and v2 each own a copy of the business logic. A bug fix must be made twice.
mux.HandleFunc("GET /v1/orders/{id}", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": r.PathValue("id"),
"amount": "19.99",
"currency": "EUR",
"status": "paid",
"customer_id": "cus_1",
})
})
mux.HandleFunc("GET /v2/orders/{id}", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": r.PathValue("id"),
"amount_cents": 1999,
"currency": "EUR",
"status": "succeeded",
"customer": map[string]any{"id": "cus_1"},
})
})
// No Deprecation header, no Sunset header, no per-version usage counter:
// nobody knows who still calls /v1, so /v1 can never be switched off.
log.Fatal(http.ListenAndServe(":8080", mux))
}After
Resolve the version from path, query, header or vendor media type, in a fixed precedence, and reject requests that carry two different versions.
// Package resolve extracts an API version from a request using the four classic
// strategies, in a fixed precedence, and reports which one won.
package resolve
import (
"mime"
"net/http"
"regexp"
"strings"
)
// Source says where the version came from.
type Source string
const (
None Source = ""
Path Source = "path"
Query Source = "query"
Header Source = "header"
MediaType Source = "media-type"
)
var (
pathRe = regexp.MustCompile(`^/v([0-9]+)(?:/|$)`)
vendorR = regexp.MustCompile(`^application/vnd\.[a-z0-9.\-]+\.v([0-9]+)\+json$`)
)
// Version returns the version and its source. Precedence: path, query, header,
// media type. A request that carries two different versions is ambiguous, so the
// caller gets conflict == true and should answer 400 rather than guess.
func Version(r *http.Request) (version string, src Source, conflict bool) {
found := map[Source]string{}
if m := pathRe.FindStringSubmatch(r.URL.Path); m != nil {
found[Path] = m[1]
}
if v := r.URL.Query().Get("api-version"); v != "" {
found[Query] = v
}
if v := r.Header.Get("Api-Version"); v != "" {
found[Header] = v
}
if v := fromAccept(r.Header.Get("Accept")); v != "" {
found[MediaType] = v
}
for _, s := range []Source{Path, Query, Header, MediaType} {
if v, ok := found[s]; ok {
if version == "" {
version, src = v, s
} else if v != version {
conflict = true
}
}
}
return version, src, conflict
}
// fromAccept understands application/vnd.acme.v2+json and application/json;version=2.
func fromAccept(accept string) string {
for _, part := range strings.Split(accept, ",") {
mt, params, err := mime.ParseMediaType(strings.TrimSpace(part))
if err != nil {
continue
}
if m := vendorR.FindStringSubmatch(mt); m != nil {
return m[1]
}
if mt == "application/json" && params["version"] != "" {
return params["version"]
}
}
return ""
}Transform chain (shown above): the middleware upgrades the request, runs the head handler, downgrades the response. A table of tests checks every version and a list envelope.
Lifecycle middleware (shown above): counts usage per (version, client), sets Deprecation, Sunset and Link, and answers 410 Gone after the sunset, during a brownout window, or when an operator flag says so. The test replays the RFC 9745 example (@1688169599).
The Go angle
- Go 1.22's
ServeMuxsupports"GET /v2/orders/{id}"andr.PathValue("id"), so a path version can be a plain prefix mount:mux.Handle("/v2/", http.StripPrefix("/v2", v2))(net/http). - Middleware is a function from
http.Handlertohttp.Handler; a response transformer must buffer the body becausehttp.ResponseWritercannot be rewound once written. Buffer only JSON and only bounded sizes; stream-heavy endpoints should not pass through a transform. encoding/jsonignores unknown fields by default (DisallowUnknownFieldsturns that off); decode intomap[string]anyfor transforms so numbers arrive asfloat64; cents are exact up to 2^53, but IDs larger than that must be strings.- Use
http.TimeFormatforSunset; it is GMT, matching the HTTP-date grammar. - Generated clients (oapi-codegen,
protoc-gen-go) pin the API version at generation time; commit the generated code and the version it was built from. - A circuit breaker around a version-specific upstream keeps a failing legacy backend from taking the new version with it.
Laravel
Laravel 13 versioning is routes plus resources. The snippets are written against the documented 13.x APIs; they are not part of a booted application here (only php -l was run).
Before
The usual start: one route, one resource, a column rename, and a Slack message. Nothing records who still reads the old field.
Route::get('/api/orders/{order}', fn (Order $order) => new OrderResource($order));
// OrderResource::toArray() returns ['amount' => $this->amount] and is edited in place.After
Bootstrap and aliases register the two middleware under names, so a route can say api.negotiate:2.
<?php
// bootstrap/app.php (Laravel 13): the version lives in the route group, so the
// framework prefix stays plain "api" and each group adds /v1 or /v2.
use App\Http\Middleware\DeprecateApiVersion;
use App\Http\Middleware\NegotiateApiVersion;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
apiPrefix: 'api',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'api.negotiate' => NegotiateApiVersion::class,
'api.deprecated' => DeprecateApiVersion::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})
->create();Routes: one group per version for URI versioning, one ungrouped route that negotiates by header or media type.
<?php
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;
// 1) URI versioning: the version is part of the path, each group is a contract.
// The middleware parameter tells the shared middleware which version it serves.
Route::prefix('v1')
->middleware(['api.negotiate:1', 'api.deprecated:1'])
->group(function () {
Route::get('orders/{order}', [OrderController::class, 'show']);
});
Route::prefix('v2')
->middleware(['api.negotiate:2', 'api.deprecated:2'])
->group(function () {
Route::get('orders/{order}', [OrderController::class, 'show']);
});
// 2) Header / media-type versioning: one URL, the middleware reads Api-Version or
// Accept: application/vnd.acme.v2+json and falls back to the oldest stable version.
Route::middleware(['api.negotiate', 'api.deprecated'])
->get('orders/{order}', [OrderController::class, 'show']);Policy table: one place for deprecation and sunset dates.
<?php
// config/api_versions.php: the retirement plan of every version, in one place.
// "deprecated" and "sunset" are UTC dates; null means "not announced".
return [
'current' => '2',
'default' => '1', // what a client that sends no version gets (pin it, never "latest")
'supported' => ['1', '2'],
'policies' => [
'1' => [
'deprecated' => '2026-06-30T23:59:59Z',
'sunset' => '2027-06-30T23:59:59Z',
'docs' => 'https://developer.example.com/deprecation',
'successor' => 'https://api.example.com/v2/orders',
],
'2' => [
'deprecated' => null,
'sunset' => null,
],
],
];Version negotiation middleware reads Api-Version or Accept: application/vnd.acme.v2+json, rejects unknown versions with Problem Details, and sets Vary.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Decides which API version this request speaks and stores it as a request attribute.
* With a parameter (api.negotiate:2) the route already fixed the version (URI versioning).
* Without one, the Api-Version header or a vendor media type decides.
*/
class NegotiateApiVersion
{
public function handle(Request $request, Closure $next, ?string $fixed = null): Response
{
$version = $fixed ?? $this->fromHeaders($request) ?? config('api_versions.default');
if (! in_array($version, config('api_versions.supported'), true)) {
return response()->json([
'title' => 'Bad Request',
'status' => 400,
'detail' => "Unsupported api version '{$version}'. Supported: ".implode(', ', config('api_versions.supported')),
], 400, ['Content-Type' => 'application/problem+json']);
}
$request->attributes->set('api_version', $version);
$response = $next($request);
// The response varies by these inputs, so caches must key on them.
$response->headers->set('Api-Version', $version);
$response->headers->set('Vary', 'Accept, Api-Version');
return $response;
}
private function fromHeaders(Request $request): ?string
{
if ($request->hasHeader('Api-Version')) {
return $request->header('Api-Version');
}
// application/vnd.acme.v2+json
if (preg_match('#application/vnd\.acme\.v(\d+)\+json#', (string) $request->header('Accept'), $m)) {
return $m[1];
}
return null;
}
}Deprecation middleware counts usage with Cache::increment, sets Deprecation, Sunset and Link headers, and returns 410 after the sunset.
<?php
namespace App\Http\Middleware;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
/**
* Counts usage per version and client, announces deprecation (RFC 9745) and sunset
* (RFC 8594), and answers 410 Gone once the sunset instant has passed.
* Register it AFTER NegotiateApiVersion so the attribute exists.
*/
class DeprecateApiVersion
{
public function handle(Request $request, Closure $next, ?string $fixed = null): Response
{
$version = $fixed ?? $request->attributes->get('api_version', config('api_versions.default'));
$policy = config("api_versions.policies.{$version}", []);
$client = (string) ($request->header('X-Client-Id') ?? 'anonymous');
// Usage telemetry: the sunset waits until this counter is zero for real clients.
Cache::increment("api_hits:{$version}:{$client}:".now()->format('Y-m-d'));
$sunset = ! empty($policy['sunset']) ? CarbonImmutable::parse($policy['sunset']) : null;
$response = ($sunset && now()->greaterThanOrEqualTo($sunset))
? response()->json([
'title' => 'Gone',
'status' => 410,
'detail' => "API version {$version} has been retired.",
], 410, ['Content-Type' => 'application/problem+json'])
: $next($request);
if (! empty($policy['deprecated'])) {
// Structured Field Date: "@" followed by Unix seconds.
$response->headers->set('Deprecation', '@'.CarbonImmutable::parse($policy['deprecated'])->getTimestamp());
}
if ($sunset) {
$response->headers->set('Sunset', $sunset->utc()->format('D, d M Y H:i:s \G\M\T'));
}
if (! empty($policy['docs'])) {
$response->headers->set('Link', '<'.$policy['docs'].'>; rel="deprecation"; type="text/html"', false);
}
if (! empty($policy['successor'])) {
$response->headers->set('Link', '<'.$policy['successor'].'>; rel="successor-version"', false);
}
return $response;
}
}API Resources per version keep each contract in its own class; the controller picks one from the negotiated version.
<?php
namespace App\Http\Resources\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** The frozen v1 contract. Do not edit; add a V2 class instead. */
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'amount' => number_format($this->amount_cents / 100, 2, '.', ''),
'currency' => $this->currency,
'status' => $this->status === 'succeeded' ? 'paid' : $this->status,
'customer_id' => $this->customer_id,
];
}
}<?php
namespace App\Http\Resources\V2;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** v2 contract: integer cents, renamed status value, customer as an object. */
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'amount_cents' => $this->amount_cents,
'currency' => $this->currency,
'status' => $this->status,
'customer' => ['id' => $this->customer_id],
];
}
}<?php
namespace App\Http\Controllers;
use App\Http\Resources\V1\OrderResource as OrderResourceV1;
use App\Http\Resources\V2\OrderResource as OrderResourceV2;
use App\Models\Order;
use Illuminate\Http\Request;
class OrderController extends Controller
{
/** One controller, one query, one domain model; only the representation varies. */
private const RESOURCES = [
'1' => OrderResourceV1::class,
'2' => OrderResourceV2::class,
];
public function show(Request $request, Order $order)
{
$resource = self::RESOURCES[$request->attributes->get('api_version')];
return new $resource($order);
}
}Feature tests assert both shape and headers:
<?php
namespace Tests\Feature;
use App\Models\Order;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ApiVersioningTest extends TestCase
{
use RefreshDatabase;
public function test_v1_keeps_the_old_shape_and_announces_its_retirement(): void
{
$order = Order::factory()->create(['amount_cents' => 1999, 'status' => 'succeeded']);
$this->getJson("/api/v1/orders/{$order->id}")
->assertOk()
->assertJsonPath('data.amount', '19.99')
->assertJsonPath('data.status', 'paid')
->assertHeader('Deprecation')
->assertHeader('Sunset', 'Wed, 30 Jun 2027 23:59:59 GMT');
}
public function test_v2_has_the_new_shape_and_no_deprecation_header(): void
{
$order = Order::factory()->create(['amount_cents' => 1999, 'status' => 'succeeded']);
$this->getJson("/api/v2/orders/{$order->id}")
->assertOk()
->assertJsonPath('data.amount_cents', 1999)
->assertJsonMissingPath('data.amount');
}
public function test_header_versioning_and_unknown_versions(): void
{
$order = Order::factory()->create();
$this->getJson("/api/orders/{$order->id}", ['Accept' => 'application/vnd.acme.v2+json'])
->assertOk()
->assertHeader('Api-Version', '2');
$this->getJson("/api/orders/{$order->id}", ['Api-Version' => '9'])
->assertStatus(400);
}
}The Laravel angle
Route::prefix('v1')->group(...)andRoute::middleware([...])are documented in Routing;apiPrefixis set inwithRouting(same page). If you setapiPrefix: 'api/v1'globally you cannot serve two versions from one application, so keep the global prefixapiand version per group.- Middleware takes parameters after
$next:api.negotiate:2callshandle($request, $next, '2')(Middleware). Alias names are registered inwithMiddlewarewith$middleware->alias([...]). - API Resources (
JsonResource,toArray(Request $request)) wrap output indataby default; keep that identical across versions or callwithoutWrapping()in both (Eloquent: API Resources). Cache::increment($key)(Cache) is fine for a coarse daily counter on Redis; for per-client analytics write to your metrics pipeline instead of the cache store.- Never switch versions with a global
Acceptcheck inside controllers; keep it in one middleware and read$request->attributes->get('api_version'). - Feature tests use
getJson(...)->assertHeader('Sunset', ...)(HTTP Tests).
Solving the classic problems
| Problem | Symptom | Solution | Cost |
|---|---|---|---|
| A rename breaks a partner on release day | 400s from one API key | Expand/contract; keep old field until telemetry is empty | Two fields for a while |
Nobody knows who uses v1 | Fear of deleting | Per-client counters, brownouts | Metrics work up front |
| Caches serve the wrong version | Mixed shapes for one URL | Vary: Accept, Api-Version or path versions | Lower hit rate on header strategies |
Version sprawl (v1..v6 all alive) | Slow releases, security patches on old code | Support window policy, transform chain instead of code copies | Policy discipline |
| Breaking change slipped in a "patch" | Support tickets | oasdiff breaking in CI as a required check | One CI job |
| Strict client breaks on new field | Outage after additive change | Tolerant reader tests and SDK guidance | Documentation |
| Old mobile app after sunset | Crash on 410 | Minimum version in remote config, graceful screen | Client work |
| Event consumers break on replay | DLQ full | Compatible schema evolution, schema registry | Registry to run |
| Gateway rewrites become unmaintainable | Untested regex bodies | Move transforms into owned code (ACL) | One more service or package |
A partner is stuck on v1 past the sunset
1 telemetry shows client acme still on v1 five days before sunset
2 open a ticket with the account owner; share the diff and the migration guide
3 if they cannot move: per-client exception in the lifecycle policy (explicit expiry date, logged)
4 brownouts continue for everyone else; exception expires on its own date
5 after the date: 410 for everyone, no manual stepNever extend a sunset globally for one client; make exceptions per client with their own expiry.
Testing multiple versions in CI
1 pull request touches openapi.yaml
2 job A: oasdiff breaking base head --fail-on ERR -> fails if a breaking change lacks the label
3 job B: golden tests for every version in the support matrix
4 job C: Pact provider verification for all pacts tagged "deployed"
5 job D: buf breaking against main for .proto changesChoosing
| Situation | Recommended mechanism | Extra technique | Reason |
|---|---|---|---|
| Public REST API, many unknown callers | URI major (/v1) plus additive evolution | oasdiff in CI, Sunset headers | Simple, cache-friendly, easy to support |
| Public API with frequent small breaking changes | Date-based header (Stripe, GitHub) with transforms | Pin version per account | Small, cheap upgrades |
| Azure-style platform with many resource types | api-version query parameter, dated | Per-resource previews | Clean paths, explicit required version |
| Internal service-to-service REST | Additive only; Pact | oasdiff for the spec | You can find and move every caller |
| gRPC / Protobuf | Package v1 plus field-number discipline | buf breaking | The wire format already tolerates additions |
| GraphQL | No version, @deprecated | Operation-level usage metrics | Callers choose fields, so unused ones are removable |
| Events / Kafka topics | Compatible evolution with a schema registry | Schema version in the envelope | Replays mix old and new |
| Mobile app backend | URI major, long support window | Minimum app version, remote kill switch | Slowest cohort sets the sunset |
| Security fix requiring a break | Break now, announce loudly | Emergency kill switch for the old behaviour | Safety outweighs notice |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One deploy updates the server and its single web client together, so most changes can be breaking without a version. The first external caller changes that: a mobile app or a partner. Start with a rule ("additive only inside a major"), a /v1 prefix, and a thin presentation layer (Laravel API Resources, Go DTO structs) separate from domain objects. Example: the order JSON is a OrderResource, never the Eloquent model, so a column rename does not change the contract.
Modular monolith: boundaries without the network
Each module exposes an internal interface; versioning is a compile-time question, solved by refactoring plus deprecation markers (@deprecated in PHP docblocks, // Deprecated: in Go). Keep a single public HTTP contract and a separate internal one. Module-to-module contracts are tested with plain unit tests, which is cheaper than Pact.
Microservices: every arrow is a decision
Now each service deploys alone. Rules that survive: additive changes only on internal APIs; breaking changes through expand/contract across services (provider ships both shapes, consumers migrate, provider removes); consumer-driven contracts tell you when the last consumer moved; the gateway version is separate from internal service versions. Example: orders renames customer_id to customer.id; billing, notifications and web-bff each read it. orders emits both, the three consumers publish pacts, can-i-deploy goes green when the last one switches, and orders drops the old field.
Distributed data: replicas, caches, regions
Versions interact with state that lives elsewhere. Responses cached at a CDN or in Redis need the version in the key. During a multi-region rollout a new version exists in one region before another; a global client must tolerate both or pin. Events replayed from Kafka may be a year old, so consumers must read every historic schema. A replica that lags behind a column backfill serves nulls; read the new column only after the backfill is verified. See Replication Topologies and Caching.
Scaling path: 1x, 10x, 100x
| Scale | Callers | What to have | Typical failure if missing |
|---|---|---|---|
| 1x: one client | One team | Additive habit, a /v1 prefix | Breaking the only client |
| 10x: partners and a mobile app | Dozens, unknown | Policy doc, Sunset headers, per-client counters, oasdiff in CI | A partner breaks on release day |
| 100x: public platform | Thousands | Dated versions with transforms, pinned accounts, changelog generation, SDKs, brownouts | Version sprawl, security patches on five code paths |
Lab: add a breaking change and retire the old shape (expected, not run)
Setup: the Go module in docs/snippets/system-design/api-versioning/go.
cd docs/snippets/system-design/api-versioning/go
go test ./... # all packages pass
go test -run TestDowngrade -v ./versionchainExperiments (each is a few lines of Go in a scratch main):
- Call the head handler with
Api-Version: 2023-01-15. Expected:amountis"19.99", statuspaid,customer_idpresent; response headerApi-Version: 2023-01-15. - Add a fourth
Changedated2025-09-01that renamescurrencytocurrency_codewith upgrade and downgrade functions; run the tests. Expected: the four old tests still pass; add one for the new version. - Put a policy for version
1withDeprecatedin the past andSunsetone hour ahead; call/orderstwice. Expected:Deprecation: @<unix>andSunset: ...GMTon both;Usage.Clients("1")lists the calling client. - Set a brownout window around now. Expected:
410withapplication/problem+jsonand theSunsetheader still present; remove the window and the next call returns200. - Switch the kill-switch function to return
truefor version2. Expected:410immediately, no deploy needed.
expected output (not run):
ok academy/api-versioning/lifecycle
ok academy/api-versioning/resolve
ok academy/api-versioning/tolerant
ok academy/api-versioning/versionchainCommon misconceptions
| Belief | Reality |
|---|---|
| Adding a field is always safe | Safe only for tolerant readers; strict parsers and closed enums fail |
/v2 solves breaking changes | It moves them; you now run two contracts |
Semver 2.4.1 goes in the URL | Only the major belongs in the contract surface |
Deprecation/Sunset headers disable the version | They are hints; the server must enforce the sunset itself |
| Header versioning is cache-safe | Only with Vary for that header |
| GraphQL has no breaking changes | Removing a field or changing a type still breaks operations |
| An OpenAPI spec is the contract | It is the intended contract; callers depend on observed behaviour (Hyrum) |
| We can force mobile users to update | Only with a minimum-version mechanism you shipped in advance |
| Dated versions mean separate code per date | Old dates cost a small transform module each |
| A kill switch replaces a deprecation process | It is the last step, not a substitute for notice |
Cheat sheet
| Topic | What to remember |
|---|---|
| Default | Additive changes; one contract per major |
| Breaking test | Can a working caller fail tomorrow? |
| Tolerant reader | Ignore unknown fields, open enums, reject malformed input |
| URI | /v2, easiest to route and cache |
| Query | api-version=YYYY-MM-DD, required, 400 if missing (Azure) |
| Header | Pin per account, echo the used version, send Vary |
| Media type | application/vnd.acme.v2+json; 406 and 415 on mismatch |
| Date-based | Handler at head; per-change transforms up and down |
Deprecation | RFC 9745, @unix |
Sunset | RFC 8594, HTTP-date; never before Deprecation |
| Retirement | Announce, dual run, brownout, sunset, delete |
| Telemetry | Per version and per client; gate the sunset on it |
| Database | Expand, migrate, contract; contract only after sunset |
| Tools | oasdiff breaking --fail-on ERR, buf breaking, Pact can-i-deploy |
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 — Is adding an optional response field breaking? Must-know
Answer
Answer: Not for a tolerant reader, but yes for a caller using strict decoding. State "ignore unknown fields" in your contract and test a tolerant client.
2 — Why are path versions easier to operate than media-type versions? Important
Answer
Answer: Routers, caches, logs and tools all understand paths natively; headers need Vary and extra tooling, and many clients cannot set Accept easily.
3 — What does Deprecation: @1688169599 mean, and how does Sunset differ? Good to know
Answer
Answer: Deprecated at that Unix second (RFC 9745); it changes no behaviour. Sunset (RFC 8594) is an HTTP-date after which the resource is likely unresponsive, and must not be earlier than the deprecation date.
4 — How does Stripe keep old versions cheap? Good to know
Answer
Answer: Handlers produce only the newest shape; each breaking change is a version change module that walks the response back to the caller's pinned version. Old versions cost only those modules.
5 — A column rename is needed behind a live API. List the phases. Must-know
Answer
Answer: Expand (add new column), dual-write and backfill, switch readers per version, contract (drop old) only after the old API version has sunset.
6 — Why is "total requests per version" insufficient before a sunset? Important
Answer
Answer: You need to know which clients remain to contact them, and a small percentage can be a key customer. Count per client.
7 — What is the difference between a feature flag and a version? Must-know
Answer
Answer: A version is a contract chosen by the caller for a long time; a flag is a provider-side switch for rollout. A flag must not change the shape for callers who did not opt in.
8 — What does buf breaking check, and what are its categories? Good to know
Answer
Answer: Changes to Protobuf schemas versus a past version; categories from strictest to most lenient: FILE, PACKAGE, WIRE_JSON, WIRE.
9 — Why can a consumer-driven contract be better than an OpenAPI diff for deleting a field? Important
Answer
Answer: It names the consumers that actually read the field; when no pact references it, removal is safe for known consumers.
10 — What status code should a retired version return, and why not 404? Important
Answer
Answer: 410 Gone, with a link to the successor; 404 suggests a typo and hides the cause.
Glossary
| Term | Meaning |
|---|---|
| API versioning | Naming and running more than one contract of an API at once |
| Breaking change | A change after which a previously working caller can fail |
| Additive change | A change that only adds optional capability |
| Backward compatibility | New server works with old callers |
| Forward compatibility | Old server or data works with new callers |
| Tolerant reader | Consumer that ignores unknown fields and unknown enum values |
| Robustness principle (Postel) | Conservative in what you send, liberal in what you accept |
| Hyrum's law | With enough users, every observable behaviour is depended on |
| URI versioning | Version in the path (/v2/...) |
| Query parameter versioning | Version in the query (?api-version=...) |
| Header versioning | Version in a custom header (Api-Version, Stripe-Version) |
| Media type versioning | Version in Accept / Content-Type |
| Content negotiation | Choosing a representation using Accept and related headers |
| Vendor media type | application/vnd.<vendor>.<name>+json tree from RFC 6838 |
| Semantic versioning | MAJOR.MINOR.PATCH rules from semver.org |
| Deprecation | Marking something as discouraged and scheduled for removal |
| Deprecation header | RFC 9745 response header carrying the deprecation date |
| Sunset header | RFC 8594 response header carrying the date of unresponsiveness |
| Link rel sunset / deprecation | Link relations pointing to policy documents |
| Dual running | Serving old and new versions side by side |
| Sunset (verb) | Stop serving a version |
| Brownout | Scheduled short outages of a deprecated version to flush out callers |
| Usage telemetry | Counts of calls per version and client |
| Kill switch | Operator flag that disables a version immediately |
| Consumer-driven contract | Contract written by consumers as executable examples |
| Pact | Consumer-driven contract testing tool |
| Schema evolution | Changing message or API schemas while old data and readers exist |
| Date-based versioning | Versions identified by release date |
| Version transform (version change module) | Function pair that converts between adjacent versions |
| Feature flag | Provider-controlled runtime switch |
| Gateway routing | Choosing an upstream by version at the edge |
| Anticorruption layer | Adapter that translates a legacy contract to the new domain model |
| Expand/contract | Parallel change: add, migrate, remove |
| SDK versioning | Numbering and pinning of client libraries |
| OpenAPI diff | Comparing two OpenAPI documents for breaking changes |
| oasdiff | CLI that diffs OpenAPI documents |
| buf breaking | Protobuf breaking-change detector |
| Stripe versioning | Dated versions with a header, pins and version change modules |
| Problem Details | RFC 9457 error body (application/problem+json) |
References
- Hyrum Wright, Hyrum's Law
- Martin Fowler, Tolerant Reader, 9 May 2011; Ian Robinson, Consumer-Driven Contracts: A Service Evolution Pattern, 12 June 2006
- IETF, RFC 761 (TCP), RFC 9413 Maintaining Robust Protocols, RFC 8594 The Sunset HTTP Header Field, RFC 9745 The Deprecation HTTP Response Header Field, RFC 9110 HTTP Semantics, RFC 6838 Media Type Specifications
- Stripe, APIs as infrastructure: future-proofing Stripe with versioning, 5 August 2017
- GitHub, API versions (REST)
- Semantic Versioning, semver.org 2.0.0
- Google, AIP-180 Backwards compatibility, AIP-181 Stability levels
- Microsoft, Azure REST API Guidelines, Microsoft Graph guidelines
- Kubernetes, Deprecation Policy
- Pact, Introduction, can-i-deploy
- oasdiff, oasdiff.com, Breaking changes and changelog
- Buf, Detecting breaking changes, Rules and categories
- Protocol Buffers, Dos and Don'ts; GraphQL, Schemas and Types, Best Practices
- OpenAPI, OpenAPI Specification v3.1.0
- Laravel 13: Routing, Middleware, Eloquent: API Resources, Cache, HTTP Tests
- Go:
net/http