Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a version number is not the pointWhy it exists
Postel, Hyrum, Fowler, Stripe, RFC 9745, semverWhere it comes from
What counts as a breaking changeBreaking and additive changes
Tolerant reader, robustness principle, Hyrum's lawTolerant reader
/v2, ?api-version=, Api-Version:, vnd.acme.v2+jsonURI, Query, Header, Media type
Evolving without any versionEvolution only
MAJOR.MINOR.PATCH for an APISemantic versioning
Stripe-style dated versions and transformsDate-based versioning
Announce, dual run, sunset, kill switchDeprecation lifecycle, Headers, Telemetry
Contract tests from consumersConsumer-driven contracts
Events, Protobuf, GraphQLSchema evolution
Flags or versionsFeature flags vs versions
Routing by version at the edgeGateway
Renaming a column behind a live APIDatabase coupling
Old mobile apps, SDK numbersSDKs and long tails
oasdiff, buf breaking in CIDiff tooling
Header syntax, status codes, cachingMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
Testing more than one versionTesting
Which strategyChoosing
Monolith to distributed systemIn architecture
Runnable experimentLab
Wrong beliefs, summary, quiz, termsMisconceptions, 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".

ChangeBreaking?WhySafe way
Add an endpointNoNobody calls it yetJust ship
Add an optional response fieldNo, if callers are tolerant readersStrict parsers fail on unknown fieldsDocument "ignore unknown fields" from day one
Add an optional request field with a defaultNoOld requests keep their old behaviourDefault must equal the old behaviour
Add a required request fieldYesOld requests are now invalidNew optional field, or a new version
Remove or rename a fieldYesCallers read itExpand, migrate, contract
Change a field type or unitYes, silently"19.99" becomes 1999New field name
Add an enum value in a responseMaybeExhaustive switch statements failDeclare enums open; callers keep an unknown branch
Tighten validationYesRequests that passed now failWarn first, enforce in a new version
Change a default or orderingYes, often unnoticedHyrum's lawTreat as a breaking change
Change an error code or message callers matchYesCallers branch on itStable machine-readable code field

Where the version lives.

StrategyExampleVisible in logsCache-friendlyTypical users
URI pathGET /v2/orders/42YesYes, URL is the keyMany public REST APIs
Query parameterGET /orders/42?api-version=2024-06-01YesYes, if the query is in the cache keyAzure (api-version is required)
Custom headerStripe-Version: 2024-06-20, X-GitHub-Api-Version: 2022-11-28If you log itNeeds VaryStripe, GitHub
Media typeAccept: application/vnd.acme.v2+jsonIf you log itNeeds Vary: AcceptHypermedia purists, some enterprise APIs
No versionAdditive evolution onlyn/aYesGraphQL (schema evolves with @deprecated), Protobuf field numbers
1. URI pathGET /v2/orders/42 (visible, cacheable, easy to route)2. Query parameterGET /orders/42?api-version=2024-06-01 (Azure style)3. Custom headerApi-Version: 2024-06-01 (Stripe-Version style)4. Media typeAccept: application/vnd.acme.v2+jsonRoutergateway ormiddlewareresolve versionreject conflictsadd Vary headerhandler v1handler v2400 unsupportedversionHeader and media-type versions need Vary: Accept / Api-Version so a shared cache never serves v1 bytes to a v2 client.

The retirement clock.

StageSignal to the callerServer behaviourExit criterion
AnnounceChangelog, email, Link: rel="deprecation"UnchangedDate and migration guide published
DeprecatedDeprecation: @1688169599UnchangedTelemetry shows migration progressing
BrownoutsSame headersShort scheduled 410 windowsStragglers found and contacted
SunsetSunset: Sun, 30 Jun 2024 23:59:59 GMT410 GoneLast caller migrated or accepted
DeletedNoneCode and tables removedContract 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.

ForcePulls towardCost if you give in completely
Provider velocityChange freelyCallers break, trust is gone
Caller stabilityNever changeThe API fossilises, mistakes live forever
Provider costOne version, one code pathBreaking changes hurt callers
Caller migration costMany long-lived versionsEvery 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 ​

BeliefReality
"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-Version header, 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 Sunset and Deprecation response headers (RFC 8594, RFC 9745).
  • Microsoft REST API Guidelines. Azure requires an api-version query parameter with YYYY-MM-DD values 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.

text
        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 down

Real 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.

CompatibilityBackwardForward
QuestionOld caller, new server?New caller, old server or data?
ProtobufAdd fields with new numbersOld readers skip unknown fields
JSON over HTTPAdd optional fieldsCallers send only fields the server knows
Event streamsConsumers upgraded firstProducers upgraded first; readers ignore unknowns
Needed forRolling deploys of the providerRolling 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.

text
        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 appears

Real 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.

BehaviourTolerant readerStrict reader
Unknown JSON fieldIgnoredRejected (outage on additive change)
Unknown enum valueMapped to unknown, loggedException
Missing optional fieldDefaultException
Malformed JSON or wrong typeRejectedRejected (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.

go
// 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.

text
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                               -> 404

Real 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).

PropertyURI versioning
DiscoverabilityBest: visible in docs, logs, browser
Routing at NGINX, Envoy, Kong, AWS API GatewayTrivial: path prefix match
Caching (CDN, browser)Works with no extra headers
GranularityWhole API; every resource moves to v2 together
WeaknessPressure 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".

text
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 UnsupportedApiVersionValue

Real scenarios: Azure Resource Manager and Azure data-plane services; some SaaS APIs with ?v=.

PropertyQuery parameter
RoutingNeeds query-aware rules (NGINX $arg_api-version is awkward; Envoy can match query parameters)
Cache keyMust include the parameter; most CDNs include the query string by default
Per-resource versionsEasy
WeaknessEasy to drop when building nextLink pagination URLs (the Microsoft guidelines require carrying api-version in nextLink)

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).

text
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
PropertyCustom header
Clean URLs, stable linksYes
Browser address bar and <img src>Cannot send it
CacheAdd Vary: Api-Version
CORSCustom 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.

text
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
PropertyMedia type
PurityHighest
Tooling friendlinessLowest
Per-resource versionsNatural
WeaknessQuality 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).

text
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
NeedEvolution-only handles it?
New field, new endpointYes
RenamePartially: add the new name, keep the old as deprecated
Change a type or unitNo: 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.

WhereWhat to numberExample
URL / headerMajor onlyv2
OpenAPI info.versionFull semver2.4.1
SDK packageFull semver, plus minimum supported API versionacme-sdk 5.2.0 supports API 2023-09-01 and later
Protobuf packageMajor in the package nameacme.billing.v2
Pre-releaseLabels or stability levelv1beta1, 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.

text
        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 response
Clientpinned to2023-01-152023-09-01upgrade2024-04-10upgrade2025-02-01upgradeHandleronly knows thehead shape2023-09-01downgrade2024-04-10downgrade2025-02-01downgradeDomainone modelrequest: oldest change firstresponse: newest change first, stop at the pinned version

Real 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.

AspectPath versions (v1/v2)Dated versions with transforms
Granularity of a breakWhole APIOne field, one change
Caller upgradePort to a new surfaceRead one changelog entry, change the date
Provider cost per old versionWhole code path, tests, docsA request/response transform pair
RiskTwo domain models driftTransform bugs; transforms must be tested in sequence
Bad fitn/aChanges 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.

go
// 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})
}
go
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".

text
        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
1. Announcechangelog, email2. Dual runv1 and v2 both live3. Brownoutsshort 410 windows4. Sunset410 Gone, then deleteLink rel=deprecationdocs + migration guideDeprecation: @unix on every responseSunset: HTTP-dateusage per client countedfind callers who ignoredheaders and emailskill switch readySunset never beforeDeprecationGate between 2 and 4: advance only when telemetry shows no active caller, or a named owner accepted the risk.time
ProductPublished policy
KubernetesGA API: 12 months or 2 releases after announced deprecation, whichever is longer; beta: 3 months or 1 release
GitHub RESTNew version supported alongside the previous one for at least 24 months
Azure (guidelines)Preview versions retired after at least 90 days' notice
StripeCompatibility 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.

text
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"
HeaderStandardValueMeaningDate format
DeprecationRFC 9745 (March 2025)@1688169599Deprecated at (or from) this instant; may be in the futureStructured Field Date (Unix seconds)
SunsetRFC 8594 (May 2019)Sun, 30 Jun 2024 23:59:59 GMTURI is likely to become unresponsive thenHTTP-date
Link rel="deprecation"RFC 9745URLWhere the policy and migration guide liven/a
Link rel="sunset"RFC 8594URLSunset policy, mitigationn/a
azure-deprecatingAzure guidelinesfree textHuman-readable notice on a deprecating versionn/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.

go
// 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.

sql
-- 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;
SignalWhat it tells youWhere to get it
Calls per version per dayMigration progressPrometheus counter api_requests_total{version=...}
Calls per version per clientWho to contactGateway access logs, API key id
SDK/User-Agent versionWhich SDK to ship a fix forUser-Agent, X-Client-Version
Error rate per version after brownoutHidden dependantsMetrics, 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.

text
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
QuestionPact answers?OpenAPI diff answers?
Did the shape change?Only for fields consumers useEverything in the schema
Who breaks if I remove field X?Yes, by consumer nameNo
Can I delete this deprecated field?Yes, when no pact references itOnly with telemetry
Works for message queuesYes (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.

RuleJSON eventsProtobuf / AvroGraphQL
Add an optional fieldSafeSafe (new number / default)Safe (new field)
Remove a fieldBreaking for readersReserve the number; readers see default@deprecated, remove later
RenameBreakingWire-safe (number), breaks JSON and codeAdd new field, deprecate old
Change typeBreakingBreakingBreaking
Add enum valueReaders need an unknown branchSame; keep an UNSPECIFIED = 0Clients need a default branch
Version markerschema_version in the envelopePackage v1, v2Evolve; avoid versions
text
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 parse

Feature 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.

VersionFeature flagOpt-in beta header
Chosen byCallerProviderCaller
LifetimeMonths to yearsDays to weeksWeeks to a release
Changes response shape for callers who did not askNoMust notNo
Typical useBreaking changeGradual rollout, kill switchEarly access
CleanupSunset processDelete flag in codePromote 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.

text
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
LayerGood atBad at
Gateway routing (NGINX, Envoy, Kong, AWS API Gateway, Apigee)Pick upstream by path/header, count, throttleTransforming bodies safely
Adapter service (ACL)Full-language transforms, testsOne more deployable
In-process transform chainCheapest, versioned with the codeOnly inside one service
Service meshmTLS, traffic split by headerContract 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.

ExpandADD COLUMN amount_centsDual write + backfillwrite both, copy old rowsMigrate readersv2 reads new, v1 reads oldContractDROP COLUMN amountAPI v1: reads amount (decimal), a mapper derives it from centsAPI v2: reads and writes amount_centsOld app instances still write amount during the rolling deployDrop only after v1 sunset + zero hits in telemetryOne-way door: no rollback
sql
-- 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;
StepDeploysOld API version works?Rollback possible?
ExpandSchemaYesYes
Dual write + backfillAppYesYes
Switch readsAppYes (mapper per version)Yes
ContractSchemaOnly versions that no longer existNo (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.

TechniqueMobile long tailServer-to-server
Minimum supported app version, remote configForces update dialog ("kill switch for clients")n/a
Keep old version aliveYearsMonths
Pin API version inside the SDKYesYes
Telemetry by app versionRequiredBy API key
Feature discoveryCapabilities endpointOpenAPI 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).

sh
# 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'
ToolInputDetectsNotes
oasdiffOpenAPI 3.xBreaking and non-breaking changes with severitiesbreaking, changelog, `--fail-on ERR
buf breakingProtobufSource, JSON and wire breaksCategories FILE, PACKAGE, WIRE_JSON, WIRE
Pact / Pact BrokerConsumer testsWhat consumers really usecan-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.

text
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
TestCatchesCost
Golden files per versionAccidental shape changeLow
Transform up/down testsWrong or missing transformLow
PactBreaking a real consumerMedium
Canary per versionVersion rotting after unrelated deploysMedium
Property test: downgrade(upgrade(x)) == xInformation loss in transformsMedium

Mechanics ​

Status codes and what they mean for versions ​

SituationStatusBody / headerNotes
Missing required version400Problem Details, code MissingApiVersionParameter (Azure)Never silently default for a required-version API
Unknown or retired version string400 or 404Supported versions listedAzure: UnsupportedApiVersionValue
Conflicting version sources (path says 2, header says 3)400Say which sources conflictedDo not guess
Media type not available406 Not AcceptableAvailable typesContent negotiation
Request body in an unsupported version media type415 Unsupported Media TypeAccepted typesContent-Type negotiation
Version past its sunset410 GoneLink: rel="successor-version"404 hides the cause
Deprecated, still working200Deprecation, Sunset, LinkHeaders only
Unsupported Protobuf/gRPC method after removalgRPC UNIMPLEMENTEDmessageMirror of 404/410
Too many requests while migrating429Retry-AfterNot a version error

Header syntax ​

ItemSyntaxSource
DeprecationDeprecation: @1688169599 (Structured Field Date)RFC 9745 section 2.1
SunsetSunset: Sat, 31 Dec 2018 23:59:59 GMT (HTTP-date)RFC 8594
ConstraintSunset MUST NOT be earlier than DeprecationRFC 9745 section 4
LinksLink: <https://example.net/sunset>;rel="sunset";type="text/html"RFC 8594
ScopeThe 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 switchClients must work without itRFC 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 ​

ToolSettingEffect
oasdiff--fail-on ERR / WARN / (changelog) INFOExit code 1 at or above that level
oasdiffoasdiff breaking vs oasdiff changelogErrors and warnings only vs all three levels
bufbreaking: use: [FILE] in buf.yamlStrictness category
bufbuf breaking --against '.git#branch=main'Baseline
LaravelwithRouting(api: ..., apiPrefix: 'api') in bootstrap/app.phpGlobal API path prefix
LaravelRoute::prefix('v2')->group(...)Version segment per group
Laravel$middleware->alias([...]) and name:paramNamed middleware with a parameter
Gohttp.NewServeMux() patterns "GET /v2/orders/{id}", r.PathValue("id")Method and wildcard routing in net/http
Gohttp.TimeFormatLayout for HTTP-date (Sunset)
StripeStripe-Version, account pin, OAuth app versionOrder 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.

go
// 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.

go
// 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 ServeMux supports "GET /v2/orders/{id}" and r.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.Handler to http.Handler; a response transformer must buffer the body because http.ResponseWriter cannot be rewound once written. Buffer only JSON and only bounded sizes; stream-heavy endpoints should not pass through a transform.
  • encoding/json ignores unknown fields by default (DisallowUnknownFields turns that off); decode into map[string]any for transforms so numbers arrive as float64; cents are exact up to 2^53, but IDs larger than that must be strings.
  • Use http.TimeFormat for Sunset; 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.

php
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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(...) and Route::middleware([...]) are documented in Routing; apiPrefix is set in withRouting (same page). If you set apiPrefix: 'api/v1' globally you cannot serve two versions from one application, so keep the global prefix api and version per group.
  • Middleware takes parameters after $next: api.negotiate:2 calls handle($request, $next, '2') (Middleware). Alias names are registered in withMiddleware with $middleware->alias([...]).
  • API Resources (JsonResource, toArray(Request $request)) wrap output in data by default; keep that identical across versions or call withoutWrapping() 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 Accept check 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 ​

ProblemSymptomSolutionCost
A rename breaks a partner on release day400s from one API keyExpand/contract; keep old field until telemetry is emptyTwo fields for a while
Nobody knows who uses v1Fear of deletingPer-client counters, brownoutsMetrics work up front
Caches serve the wrong versionMixed shapes for one URLVary: Accept, Api-Version or path versionsLower hit rate on header strategies
Version sprawl (v1..v6 all alive)Slow releases, security patches on old codeSupport window policy, transform chain instead of code copiesPolicy discipline
Breaking change slipped in a "patch"Support ticketsoasdiff breaking in CI as a required checkOne CI job
Strict client breaks on new fieldOutage after additive changeTolerant reader tests and SDK guidanceDocumentation
Old mobile app after sunsetCrash on 410Minimum version in remote config, graceful screenClient work
Event consumers break on replayDLQ fullCompatible schema evolution, schema registryRegistry to run
Gateway rewrites become unmaintainableUntested regex bodiesMove transforms into owned code (ACL)One more service or package

A partner is stuck on v1 past the sunset ​

text
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 step

Never extend a sunset globally for one client; make exceptions per client with their own expiry.

Testing multiple versions in CI ​

text
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 changes

Choosing ​

SituationRecommended mechanismExtra techniqueReason
Public REST API, many unknown callersURI major (/v1) plus additive evolutionoasdiff in CI, Sunset headersSimple, cache-friendly, easy to support
Public API with frequent small breaking changesDate-based header (Stripe, GitHub) with transformsPin version per accountSmall, cheap upgrades
Azure-style platform with many resource typesapi-version query parameter, datedPer-resource previewsClean paths, explicit required version
Internal service-to-service RESTAdditive only; Pactoasdiff for the specYou can find and move every caller
gRPC / ProtobufPackage v1 plus field-number disciplinebuf breakingThe wire format already tolerates additions
GraphQLNo version, @deprecatedOperation-level usage metricsCallers choose fields, so unused ones are removable
Events / Kafka topicsCompatible evolution with a schema registrySchema version in the envelopeReplays mix old and new
Mobile app backendURI major, long support windowMinimum app version, remote kill switchSlowest cohort sets the sunset
Security fix requiring a breakBreak now, announce loudlyEmergency kill switch for the old behaviourSafety 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 ​

ScaleCallersWhat to haveTypical failure if missing
1x: one clientOne teamAdditive habit, a /v1 prefixBreaking the only client
10x: partners and a mobile appDozens, unknownPolicy doc, Sunset headers, per-client counters, oasdiff in CIA partner breaks on release day
100x: public platformThousandsDated versions with transforms, pinned accounts, changelog generation, SDKs, brownoutsVersion 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.

sh
cd docs/snippets/system-design/api-versioning/go
go test ./...                       # all packages pass
go test -run TestDowngrade -v ./versionchain

Experiments (each is a few lines of Go in a scratch main):

  1. Call the head handler with Api-Version: 2023-01-15. Expected: amount is "19.99", status paid, customer_id present; response header Api-Version: 2023-01-15.
  2. Add a fourth Change dated 2025-09-01 that renames currency to currency_code with upgrade and downgrade functions; run the tests. Expected: the four old tests still pass; add one for the new version.
  3. Put a policy for version 1 with Deprecated in the past and Sunset one hour ahead; call /orders twice. Expected: Deprecation: @<unix> and Sunset: ...GMT on both; Usage.Clients("1") lists the calling client.
  4. Set a brownout window around now. Expected: 410 with application/problem+json and the Sunset header still present; remove the window and the next call returns 200.
  5. Switch the kill-switch function to return true for version 2. Expected: 410 immediately, no deploy needed.
text
expected output (not run):
ok  academy/api-versioning/lifecycle
ok  academy/api-versioning/resolve
ok  academy/api-versioning/tolerant
ok  academy/api-versioning/versionchain

Common misconceptions ​

BeliefReality
Adding a field is always safeSafe only for tolerant readers; strict parsers and closed enums fail
/v2 solves breaking changesIt moves them; you now run two contracts
Semver 2.4.1 goes in the URLOnly the major belongs in the contract surface
Deprecation/Sunset headers disable the versionThey are hints; the server must enforce the sunset itself
Header versioning is cache-safeOnly with Vary for that header
GraphQL has no breaking changesRemoving a field or changing a type still breaks operations
An OpenAPI spec is the contractIt is the intended contract; callers depend on observed behaviour (Hyrum)
We can force mobile users to updateOnly with a minimum-version mechanism you shipped in advance
Dated versions mean separate code per dateOld dates cost a small transform module each
A kill switch replaces a deprecation processIt is the last step, not a substitute for notice

Cheat sheet ​

TopicWhat to remember
DefaultAdditive changes; one contract per major
Breaking testCan a working caller fail tomorrow?
Tolerant readerIgnore unknown fields, open enums, reject malformed input
URI/v2, easiest to route and cache
Queryapi-version=YYYY-MM-DD, required, 400 if missing (Azure)
HeaderPin per account, echo the used version, send Vary
Media typeapplication/vnd.acme.v2+json; 406 and 415 on mismatch
Date-basedHandler at head; per-change transforms up and down
DeprecationRFC 9745, @unix
SunsetRFC 8594, HTTP-date; never before Deprecation
RetirementAnnounce, dual run, brownout, sunset, delete
TelemetryPer version and per client; gate the sunset on it
DatabaseExpand, migrate, contract; contract only after sunset
Toolsoasdiff breaking --fail-on ERR, buf breaking, Pact can-i-deploy

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
API versioningNaming and running more than one contract of an API at once
Breaking changeA change after which a previously working caller can fail
Additive changeA change that only adds optional capability
Backward compatibilityNew server works with old callers
Forward compatibilityOld server or data works with new callers
Tolerant readerConsumer that ignores unknown fields and unknown enum values
Robustness principle (Postel)Conservative in what you send, liberal in what you accept
Hyrum's lawWith enough users, every observable behaviour is depended on
URI versioningVersion in the path (/v2/...)
Query parameter versioningVersion in the query (?api-version=...)
Header versioningVersion in a custom header (Api-Version, Stripe-Version)
Media type versioningVersion in Accept / Content-Type
Content negotiationChoosing a representation using Accept and related headers
Vendor media typeapplication/vnd.<vendor>.<name>+json tree from RFC 6838
Semantic versioningMAJOR.MINOR.PATCH rules from semver.org
DeprecationMarking something as discouraged and scheduled for removal
Deprecation headerRFC 9745 response header carrying the deprecation date
Sunset headerRFC 8594 response header carrying the date of unresponsiveness
Link rel sunset / deprecationLink relations pointing to policy documents
Dual runningServing old and new versions side by side
Sunset (verb)Stop serving a version
BrownoutScheduled short outages of a deprecated version to flush out callers
Usage telemetryCounts of calls per version and client
Kill switchOperator flag that disables a version immediately
Consumer-driven contractContract written by consumers as executable examples
PactConsumer-driven contract testing tool
Schema evolutionChanging message or API schemas while old data and readers exist
Date-based versioningVersions identified by release date
Version transform (version change module)Function pair that converts between adjacent versions
Feature flagProvider-controlled runtime switch
Gateway routingChoosing an upstream by version at the edge
Anticorruption layerAdapter that translates a legacy contract to the new domain model
Expand/contractParallel change: add, migrate, remove
SDK versioningNumbering and pinning of client libraries
OpenAPI diffComparing two OpenAPI documents for breaking changes
oasdiffCLI that diffs OpenAPI documents
buf breakingProtobuf breaking-change detector
Stripe versioningDated versions with a header, pins and version change modules
Problem DetailsRFC 9457 error body (application/problem+json)

References ​

Built by Morteza Negahi