API Versioning, Deprecation and Backward Compatibility Questions
Evolving an API without breaking existing consumers: versioning schemes (URI, header, media type, semantic versioning), classifying breaking versus non-breaking changes including behavioural ones such as defaults and error text, deprecation and sunset policy and timelines (including accelerated retirement), running multiple versions concurrently, and planning consumer migrations at scale including SDK, partner, mobile and long-tail client impact. Also covers finding who still calls an old version, catching accidental breaks with contract checks in CI, expand-then-contract evolution of fields and stored data, gradual rollout with per-version monitoring, and compatibility between independently deployed services, streams and libraries. Covers compatibility guarantees across REST, GraphQL and gRPC consumers. Excludes general API surface design, payload and OpenAPI schema design, protobuf field-level mechanics, writing the notices themselves, rate limiting, gateways and database schema migration.
You must move thousands of customers from API v1 to v2, and v2 breaks compatibility. Plan the migration: what do you build for clients, how do you communicate, how do you track adoption, what happens to customers who cannot move quickly, and what are your rollback and success criteria?
Sample Answer
The idea in plain words
Moving thousands of customers across a breaking change is a product launch aimed at your own users: you cut each customer's migration cost, you segment them so effort goes where it matters, you measure progress per key (an API key identifies one integration) and not in aggregate, and you keep a way back until the end. Compatible changes can ship silently; a break needs time, tooling and a published end condition. The plan below uses a worked scenario with stated assumptions.
Scenario assumptions (illustrative, not facts about any company)
- 4,000 active keys call v1. Segments: 40 top accounts managed by account managers, 360 mid-tier, 3,600 self-serve. 40 + 360 + 3,600 = 4,000.
- The 40 top accounts send 55% of request volume (assumption). They are 40 / 4,000 = 1% of keys, so a request-share chart would look healthy long before the key count does. Track both.
- Announcement Tuesday 2027-05-04; public sunset (the date the old version stops working) Thursday 2028-05-04, 12 months later (366 days, 2028 being a leap year).
What you build for clients
- A field-by-field mapping guide and a dated changelog, so a developer can see every difference before writing code.
- A v2 SDK (software development kit, the client library) with a compatibility mode: a thin adapter that accepts v1-shaped objects and calls v2, logging a warning for each translated call. Customers replace one dependency instead of editing every call site. A tiny illustration (invented field names, illustrative only):
call in the customer's code (v1 style): create_order(customer="c-9", amount="19.99")
request the adapter sends to v2: POST /v2/orders {"customer_id":"c-9","total_minor":1999}
warning the adapter logs: create_order(customer, amount) is v1 style; use create_order(customer_id, total_minor)
- A codemod (a script that rewrites source code mechanically) for base URL and renamed fields, and a sandbox with test keys.
- A replay checker: the customer uploads a sample of their recorded v1 requests; it runs them against v2 in the sandbox and prints response differences.
- Opt-in early access: a per-key setting that enables v2 before general availability, with a direct support channel.
- Dual-run for reads: the platform serves the v1 response as before and also runs the same read request through v2 in the background, storing a diff report on the customer's dashboard. Writes cannot be duplicated safely, so write paths use the sandbox and the replay checker.
- A per-key migration dashboard: which endpoints still call v1, last call time, SDK version, and the customer's own before and after numbers.
If the reason for the break is latency (for example, v2 no longer inlines an expensive related object), publish the benefit as each customer's own measured v1 versus v2 numbers from their dashboard, and first ask whether the same gain could be offered compatibly inside v1 (an opt-in parameter, for instance). A break should be the cheapest way to get the benefit, not the first idea.
Communication
- Channels: email to key owners, in-product banner, response headers
Deprecation(RFC 9745) andSunset(RFC 8594), docs, webinars and office hours. - Segmented ownership: account managers contact the 40 top accounts individually; mid-tier customers get scheduled office hours and a named migration contact; self-serve customers get the guide, the tools and email nudges that carry their own usage.
- Legal reviews the notice wording for accounts whose contracts mention v1 or an SLA (service level agreement). Sales aligns extension offers with renewal dates so exceptions are traded, not given away.
- Support gets macros (pre-written answers) and a list of top ten migration errors before the announcement.
Tracking adoption
The migration runs in waves. A wave (also called a cohort) is a group of keys asked to move in the same period; for example, the 360 mid-tier keys split into 4 waves of 90 by signup date, while the top 40 are handled one by one. The next wave starts only when the health check under Rollback holds for the previous one.
Classify each key weekly into four states: not started (no v2 calls), testing (sandbox or under 5% v2 requests, an assumed cut-off), partial (v2 calls and v1 calls), complete (no v1 calls for 14 days). Report keys complete over the 4,000 baseline, request share, and the status of the top 40 individually.
Illustrative target curve, as numbers of keys complete:
| Date | Day | Target share | Keys complete (share x 4,000) |
|---|---|---|---|
| 2027-08-03 | Tue | 25% | 1,000 |
| 2027-11-02 | Tue | 60% | 2,400 |
| 2028-02-01 | Tue | 90% | 3,600 |
| 2028-04-04 | Tue | 98% | 3,920 (80 keys remaining, 30 days before sunset) |
| 2028-05-04 | Thu | sunset |
Support load estimate: assume 8% of customers contact support once, 1.5 hours each. 4,000 x 0.08 = 320 contacts; 320 x 1.5 = 480 hours; at 40 hours per person-week that is 12 person-weeks, which sets the minimum migration-support staffing.
Customers who cannot move quickly
In order: assisted migration (a services engineer or a partner does the work); then a dated extension for that key; then, for simple read-only integrations, a gateway translation layer (a proxy in front of the API that rewrites a v1 request into a v2 request and the response back) kept only for allowlisted keys (an explicit list of keys permitted to use it) with an end date. Extensions are per key, with milestones, and tied to the contract renewal where one exists. Keys that never respond are contacted through account owners and, finally, receive the brownout calendar like everyone else (a published schedule of short windows, such as an hour on set dates, when v1 deliberately returns errors so silent callers notice), then 410 Gone (the HTTP status meaning the resource is permanently removed) on the sunset date.
Rollback
- Customer level: until sunset a migrated key can be pinned back to v1; nothing is deleted on v1.
- Wave level: if v2 misbehaves for a cohort, pause promotion of the next cohort. Illustrative rule: if the v1 server-error baseline (the share of v1 requests that failed with a 5xx status before the migration) is 0.20% of requests and migrated keys' v2 error rate rises above baseline by more than 0.10 percentage points over a week, pause. A percentage point is the plain difference between two percentages: 0.35% minus 0.20% is 0.15 points, whereas as a relative change it would be 0.15 / 0.20 = 75 percent, so the rule is stated in points. At 0.28% the difference is 0.08 points and the wave continues; at 0.35% it is 0.15 points and the wave stops until the cause is found. This rule covers one metric on one week; a real process also watches latency, specific endpoints and customer reports.
- Platform level: v2 deploys have their own rollback; v1 stays untouched and live throughout.
Success criteria and end of life
- At 30 days before sunset, at least 98% of baseline keys are complete, and the other keys each have a recorded owner and plan.
- All 40 top accounts are complete or on a signed extension.
- For migrated keys, v2 error rate is within the 0.10-point band for four consecutive weeks.
- Support contacts per migrated key are flat or falling.
- End of life: zero requests to v1 from keys outside the allowlist for 30 days after sunset, then code removal.
Pitfalls
- Reporting request share only: it hides the long tail of keys.
- Deleting v1 on the sunset date and losing the rollback.
- Giving the biggest customers private deadlines that are never written down.
A security vulnerability in your authentication scheme can only be fixed with a breaking change, and many third-party clients have ignored migration notices. Design the emergency migration: do you break, patch in place or keep the old behaviour for a while, who approves, and how do you keep the service available while enforcing the cutover?
Sample Answer
The idea in plain words
You have a flaw in how clients prove who they are, and the proper fix changes what clients must send. To keep the choices concrete, assume (an illustration) that the flaw is this: the legacy scheme gives clients a long-lived access token (a secret string sent with each request to prove identity) that is not tied to the client that received it, so a token copied from a log or a leaked backup can be replayed from anywhere. The new scheme issues short-lived tokens bound to more context, so a copied token is useless. Two clocks pull against each other: the risk clock (how long attackers can use the flaw) and the migration clock (how long third parties need to change code). The job is to shorten the risk clock first with measures that do not need client changes, then move clients on a published, enforced schedule, and keep the service up by cutting over in steps (a brownout, meaning a short announced period in which the old behaviour is deliberately rejected, is the key tool). A single "break now or wait" choice is rarely the right framing; the usual answer is "mitigate now, migrate on a short fixed schedule, cut hard at the end".
Step 1: decide between break, patch in place, or keep for a while
Terms used below. A compensating control is a safeguard that lowers the risk while the flaw is still present, without fixing it: for the assumed flaw, examples are alerting when one token is used from two networks, a stricter rate limit on the vulnerable call, and a shorter token lifetime (the time before a token expires). Residual risk is the risk that remains after the controls. Binding a token to more context means the server records something about the client at issue time, such as the client identifier or network, and rejects the token when it arrives with something different. A hard cut is switching the old scheme off completely on a stated date, with no further grace. The incident commander is the person who runs a security incident: assigns roles, keeps a timeline and makes sure decisions are taken and recorded.
| Option | Choose it when | Cost |
|---|---|---|
| Break now (reject the old scheme immediately) | The flaw is being actively exploited, or the data exposed is severe, and no server-side mitigation closes it | Clients still on the old scheme fail at once; support load spikes |
| Patch in place (change the server so the old scheme is safe) | A server-side change removes the flaw without client changes, for example refusing the exact dangerous input pattern, binding tokens to more context, or shortening token lifetimes (with the assumed flaw: reject a token presented from a network other than the one it was issued to) | Only works when the flaw is on the server side; may carry a small behaviour change |
| Keep the old behaviour for a limited time, behind compensating controls | The flaw needs a specific attacker position or is hard to exploit, and a mitigation lowers the risk to a level security accepts (with the assumed flaw: tokens last 15 minutes instead of 1 hour and a same-token-two-networks alert pages the security on-call) | The risk remains for the duration, so the end date must be fixed and enforced |
My recommendation: do patch plus compensating controls first, run the new scheme beside the old one on a short fixed schedule, and hard cut at the end. Switch to break-now for any capability that shows signs of active exploitation. What flips the choice is evidence: exploitation in logs, the severity of what can be reached, and whether a server-side mitigation really closes the hole (security must test that, not assume it).
Who approves. A written decision record signed by: the security lead (owns the severity and the residual risk), the engineering owner of the API (owns the plan and its feasibility), and a business owner with authority over customer impact (for example the engineering director or head of product). The incident commander runs the process. Legal and customer-facing teams are told before the first notice, because contract terms and regulatory duties can set minimum notice.
Step 2: the emergency schedule (all numbers are assumptions)
Assume 1,000 active third-party clients, day 0 = Monday 4 January 2027 (the day the fix is deployed and the new scheme is live beside the old one).
| Day | Date | Action |
|---|---|---|
| 0 | Mon 4 Jan 2027 | Mitigations on (monitoring for the flaw, narrower token lifetimes, rate limits on the vulnerable call). Old and new schemes both accepted. Deprecation and Sunset headers on every old-scheme response. Direct notices to every registered client owner |
| 14 | Mon 18 Jan | Checkpoint: assume 620 of 1,000 clients migrated, so 1,000 - 620 = 380 remain (38 percent). Personal outreach to the remaining owners, largest first |
| 21 | Mon 25 Jan | Brownout 1: old scheme rejected for 10 minutes, announced in advance |
| 28 | Mon 1 Feb | Brownout 2: 60 minutes. Assume 150 clients (15 percent) remain |
| 35 | Mon 8 Feb | Brownout 3: 4 hours (240 minutes). Assume 40 clients (4 percent) remain. Cumulative brownout time so far: 10 + 60 + 240 = 310 minutes, or 5 hours 10 minutes |
| 42 | Mon 15 Feb 2027 | Hard cutoff for everyone not on the exception list |
A decision rule that agrees with this timeline (an illustration): if at day 35 more than 5 percent of clients remain (more than 50 of 1,000), do not move the global date; instead give each remaining client a named, expiring exception with compensating controls (for example a stricter rate limit and extra logging), approved by the security lead. Here 40 remain, which is below 50, so the date holds. The exceptions list is reviewed weekly and each entry ends on a stated date.
Illustrative response from the old scheme during the window (all values are examples):
HTTP/1.1 200 OK
Content-Type: application/json
Deprecation: @1799020800
Sunset: Mon, 15 Feb 2027 00:00:00 GMT
Link: <https://api.example.com/docs/auth-migration>; rel="deprecation"; type="text/html"
Link: <https://api.example.com/docs/auth-migration>; rel="sunset"; type="text/html"
Deprecation: @1799020800 is the deprecation time as a Unix timestamp (seconds since 1 January 1970 UTC) in the structured-field date form of RFC 9745 (1799020800 is 4 January 2027 00:00:00 UTC); Sunset is the HTTP-date after which the resource may stop responding (RFC 8594). During a brownout and after the cutoff, reject with 401 Unauthorized and a WWW-Authenticate header (a 401 response must carry one, RFC 9110; it tells the client which authentication scheme to use, and Bearer is the scheme name for tokens sent as Authorization: Bearer <token>), plus a body that points to the migration guide:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="legacy credential scheme retired"
Content-Type: application/json
Content-Length: 106
{"error":"legacy_scheme_retired","guide":"https://api.example.com/docs/auth-migration","request_id":"r-1"}
The 106 is the byte count of that body.
Step 3: keeping the service available while enforcing
- Run both schemes in the same deployment behind a flag per phase and per client, so enforcement is a configuration change and can be undone in seconds.
- Announce brownouts in advance with exact UTC times, on the status page and by direct notice. They are short, increase in length, and are scheduled away from known peak periods of large clients.
- Watch the brownout: old-scheme rejections by client identifier, new-scheme error rate, and support volume. Stop the brownout early if the new scheme itself is failing.
- Give clients a way to test early: a test environment that already enforces the new scheme.
- Capacity: the new scheme must be load tested at full client volume before day 0, since every migrated client moves its traffic onto it.
- Rollback. Roll back enforcement (re-accept the old scheme for a named client) freely; never roll back the security fix itself without the security lead.
The planned variant: retiring legacy tokens over several releases
When no incident forces speed, the same ideas stretch over releases. Assume legacy access tokens last 1 hour and legacy refresh tokens last 30 days. A refresh token is a longer-lived secret that a client exchanges for a new access token when the old one expires, so it decides how long a client can keep going without logging in again.
| Release | Day | Behaviour |
|---|---|---|
| R1 | 0 | New token format available; both accepted; documentation and notices published |
| R2 | 30 | New clients get only the new format; legacy responses carry Deprecation and Sunset |
| R3 | 60 | The server stops issuing legacy tokens. Existing ones are accepted until they expire, at most 30 days for refresh tokens |
| R4 | 90 | Legacy tokens rejected (60 + 30 = 90, so nothing valid should remain except for the 1 hour of any access token minted at the last moment) |
Stopping issuance first is the key step: it makes the remaining legacy population shrink by itself, and the cutoff date becomes a fact about token expiry rather than a surprise.
Pitfalls
- Announcing a date and never enforcing it; ignored notices then become the norm.
- Cutting off without first measuring who is still calling (by client identifier).
- Skipping the brownouts, so the first outage a laggard sees is the permanent one.
- Granting exceptions without expiry or compensating controls.
- Treating the hole as closed when only the new scheme exists; the old path must actually be switched off and verified with a test that tries the old credential.
The thresholds and schedule above are illustrations. A real plan also needs a path for clients who cannot reach the migration guide, treatment of embedded or mobile clients that update slowly, contractual notice terms, key and token revocation for credentials believed to be compromised, and a post-incident review.
You need to let consumers keep working while a new API contract rolls out. When would you use side-by-side adapters, a facade or proxy translation layer, or a compatibility shim service, and how would you route traffic to test the translation before relying on it?
Sample Answer
The idea in plain words
When the contract changes, something has to turn old-style requests into the new behaviour (or the reverse) for as long as old consumers exist. There are three places to put that translation, and they differ in how much they can translate and how long they should live:
- Side-by-side adapters: one codebase where each contract version has its own thin entry layer (controllers or handlers, the code that receives a request) mapping into one shared core. Old and new are two views of the same logic.
- Facade or proxy translation layer: a component in front of the new service (an API gateway plugin, a reverse proxy rule set, which is a server that sits in front of another server and forwards requests to it, or a small proxy service) that rewrites old requests into new ones and new responses back into old ones. The new service knows nothing about the old contract.
- Compatibility shim service: a separate service that implements the old contract in full, with its own logic and sometimes its own state, calling the new API behind it. It is a product with an owner, tests and a retirement date.
A few more terms appear in the table that follows. Idempotency means that repeating the same request has the same effect as sending it once (an idempotency key is a token the client sends so the server can recognise a retry). A pagination cursor is an opaque token the server returns to say where the next page of results starts. An SLO (service level objective) is a measurable target, such as 99.9 percent of requests succeeding. Orchestration means one component coordinating several calls to finish a job. A service mesh is a layer of small proxies, one beside each service, that handles routing between services. A canary is a small share of real traffic sent through the new path first. Sticky routing means the same consumer always lands on the same path.
How to choose
The deciding question is whether the old contract can be expressed as a stateless mapping of fields.
| Situation | Choice | Why |
|---|---|---|
| Differences are shape only: renamed fields, moved fields, changed formats, different header names; same operations and same meaning | Facade at the gateway or proxy | Cheap, no change to the new service, easy to remove |
| Same domain logic, but old and new differ in validation, defaults or small business rules, and the old version must live a while | Side-by-side adapters in the service | The adapter can call internal functions, not just wire formats; one deploy |
| Old semantics cannot be derived by mapping: old call was synchronous, new one is asynchronous; old response combined data that now lives in two services; old behaviour needs state (for example idempotency or pagination cursors in the old format) | Compatibility shim service | Needs orchestration and state, so it deserves its own code and tests |
| Old contract must live for years for regulated or embedded clients | Shim service with an owner, SLO and a retirement plan | Long lived means it needs real operational ownership |
I would commit to the cheapest layer that can express the difference, and move up a row only when a concrete old-contract behaviour cannot be mapped there. Costs to name: every layer adds a hop (latency and one more thing that can fail), another place for bugs (translation bugs look like API bugs to the consumer), and a risk of becoming permanent. A removal date and an owner are part of the design.
Worked translation (illustrative, assumed contracts)
Old GET /v1/orders/1042 returns:
{"id": 1042, "total": 1999, "status": "SHIPPED"}
where total is an integer count of the currency's smallest unit (cents for USD, whole yen for JPY) and the currency is implied by the account. New GET /v2/orders/1042 returns:
{"id": 1042, "amount": {"value": "19.99", "currency": "USD"}, "state": "shipped"}
The translation layer maps amount.value to total by shifting the decimal point by the number of decimal places the currency uses (2 for USD, so 19.99 x 100 = 1999; 0 for JPY, so 1999 stays 1999), upper-cases state into status, and passes id through. It must also set Content-Length correctly for the rewritten body, and keep the old error body format for error responses. The same applies in the request direction for writes.
Testing the translation before relying on it
- Contract tests first. For each old endpoint, a fixed set of recorded old requests and the old responses they used to get. The translation layer in front of the new service must reproduce them.
- Shadow traffic (mirroring). Real production requests for read-only endpoints are copied: the old path serves the consumer as before, and a duplicate goes through the translation layer to the new service, with its response discarded after comparison. Many proxies and service meshes can mirror requests (the proxy answers the consumer from the old path and sends a duplicate to the new path in the background); the key rule is to mirror only safe, side-effect-free requests (GET). Mirroring writes would create duplicate real changes unless the new side writes to a throwaway store.
- Compare and classify. A comparison job normalises volatile fields (timestamps, request ids: values that differ on every call and would otherwise look like mismatches) and diffs the old response with the translated one. Suppose 10,000 mirrored requests produce 37 mismatches: 37 / 10,000 = 0.37 percent. Suppose the breakdown is 30 where a first version of the mapping always shifted two places even for a zero-decimal currency such as JPY, and 7 where a null value is rendered differently. The 30 and the 7 are two translation bugs to fix before going on, and 30 + 7 = 37 accounts for every mismatch.
- Gate on a number. Illustrative rule: proceed only when the mismatch rate stays under 0.1 percent over at least a day of traffic and every remaining mismatch is explained. 0.37 percent fails this rule, so fix the two bugs and run again. A real process would also segment by consumer, endpoint and time of day, and review rare endpoints separately because 10,000 samples can contain none of them.
- Canary with sticky routing. Route a small share of real consumers (for example 1 percent of API keys, chosen by hashing the key into a number from 0 to 99 and sending the key through the layer when its number is below the percentage, so a consumer always lands on the same path) through the translation layer for live traffic, watching error rate and latency per path. Then 10 percent, 50 percent, 100 percent, keeping the direct path available as the instant rollback.
The translation, the diff line and the canary buckets, run
The program translates the new response back into the old shape, compares it with what the old path returned for the same order (ignoring request_id, which differs on every call), and prints one line per mismatch. It runs the first mapping (always shifting two places) and the fixed one (the currency decides). It then shows the hash-the-key canary on four example keys.
import hashlib
from decimal import Decimal
PLACES = {"USD": 2, "JPY": 0} # decimal places in each currency's smallest unit
def to_v1(v2, shift=None):
places = PLACES[v2["amount"]["currency"]] if shift is None else shift
return {"id": v2["id"], "total": int(Decimal(v2["amount"]["value"]) * 10**places),
"status": v2["state"].upper(), "request_id": v2["request_id"]}
def diff(old, translated, volatile=("request_id",)):
return [f"order {old['id']}: {k} old={old[k]} translated={translated[k]}"
for k in old if k not in volatile and old[k] != translated[k]]
# Mirrored pairs: what the old path returned, and what the new service returned for the copy.
pairs = [
({"id": 1042, "total": 1999, "status": "SHIPPED", "request_id": "a1"},
{"id": 1042, "amount": {"value": "19.99", "currency": "USD"}, "state": "shipped", "request_id": "b9"}),
({"id": 2077, "total": 1999, "status": "SHIPPED", "request_id": "a2"},
{"id": 2077, "amount": {"value": "1999", "currency": "JPY"}, "state": "shipped", "request_id": "b8"}),
]
for label, shift in (("first mapping (always shifts 2 places)", 2), ("fixed mapping (currency decides)", None)):
lines = [d for old, new in pairs for d in diff(old, to_v1(new, shift))]
print(label, "->", lines if lines else "no mismatches")
def bucket(api_key):
return int(hashlib.sha256(api_key.encode()).hexdigest(), 16) % 100
for key in ("key_bank", "key_mobile", "key_acme", "key_globex"):
b = bucket(key)
print(f"{key:13} bucket={b:2} 1 percent canary: {b < 1!s:5} 5 percent canary: {b < 5}")
Output:
first mapping (always shifts 2 places) -> ['order 2077: total old=1999 translated=199900']
fixed mapping (currency decides) -> no mismatches
key_bank bucket= 0 1 percent canary: True 5 percent canary: True
key_mobile bucket= 2 1 percent canary: False 5 percent canary: True
key_acme bucket=78 1 percent canary: False 5 percent canary: False
key_globex bucket=10 1 percent canary: False 5 percent canary: False
Read-out: with the first mapping the yen order 2077 comes back as 199900 where the old path said 1999, so the diff prints one line that names the order, the field and both values; that is the kind of line the comparison job counts. With the currency table the translated output equals the old response for both orders, so nothing prints. In the canary lines, key_bank hashes to bucket 0 and is in the 1 percent group; key_mobile has bucket 2, so it joins only when the share rises to 5 percent and stays in every larger share; key_acme (78) and key_globex (10) are in neither. A key never moves back out as the percentage grows, which is what sticky means.
Common mistakes
- Choosing a shim service when a header and field rewrite would do, and creating a new system to operate.
- Mirroring writes.
- Judging the translation on average mismatch rate while one important consumer's traffic is wrong.
- Having no end date, so the translation layer outlives its reason.
Running the code
Paste the program into a file and run it with Python 3.12; it needs no extra packages and prints exactly the output shown.
Two teams disagree on how to version a public API: one wants the version in the URL, the other wants it in a request header. Build a short evaluation rubric to settle it, say which you would choose for your situation, and explain how you would announce the decision and its migration timeline to external integrators.
Sample Answer
The idea in plain words
The URL-versus-header argument is really an argument about which costs each team is willing to carry. A URI version puts the number in the path (/v2/orders); every request is self-describing, caches and routers see it without extra rules, and it is easy to test with a browser or curl. A header version (a custom header such as API-Version: 2, or a versioned media type, a vendor-specific content type that carries the version, such as Accept: application/vnd.example.v2+json) keeps the URL stable as the name of the resource, which is purer, but the version is invisible in logs, links and caches unless you make it visible. A rubric turns the disagreement into explicit weights and scores that both teams can argue about.
Questions I ask before choosing
- How fast can clients update? Server-side integrations can move in weeks; mobile apps and partners that ship on a fixed calendar (release trains) take months. This sets the notice period and whether concurrent versions are needed.
- What do partner contracts promise? A contract with a 12-month notice clause fixes the minimum timeline no matter which scheme wins.
- What can we see? If we cannot count callers per version (gateway logs, API-key telemetry), neither scheme lets us retire anything safely.
- Who calls us? Browsers, low-code tools and scripts favour a visible URL; sophisticated SDK clients cope with headers.
- Is there a CDN or cache in front? A CDN (content delivery network) is a set of cache servers near users. It determines how much the scheme costs at the edge, because a cache compares the URL by default and needs an extra rule (a
Varyheader) to also compare a version header.
The evaluation rubric
Assumed situation for the scoring: a public partner API with about 300 integrators, a CDN in front, a mix of SDK users and hand-written scripts, a 12-month contractual notice clause for breaking changes. Weights sum to 100. Scores are judgements from 1 (poor) to 5 (strong), assumptions rather than measurements.
| Criterion | Weight | URL | Header |
|---|---|---|---|
| Cacheability at the CDN | 15 | 5 | 3 |
| Routing and gateway simplicity | 15 | 5 | 3 |
| Debuggability (curl, browser, logs) | 15 | 5 | 3 |
| Discoverability in docs and analytics | 15 | 5 | 3 |
| Fit for versioning one resource independently | 10 | 2 | 4 |
| Safe behaviour when the client omits the version | 10 | 5 | 2 |
| Migration cost for existing clients | 10 | 3 | 4 |
| Alignment with "a URL names a resource" | 10 | 2 | 4 |
What the rows measure. Cacheability: how easily a CDN keeps separate copies per version (the URL is the cache key by default, so URL scores 5; a header needs a Vary rule at every cache, so 3). Routing: how simply a gateway or router picks the right deployment (a path prefix match versus parsing a header). Debuggability and discoverability: whether the version is visible in curl, a browser, logs and analytics. Fit for versioning one resource independently: whether /orders can move to a new version while /customers stays (a header handles that more naturally, a path major moves everything). Safe behaviour when the client omits the version: with a path there is no way to omit it, while a missing header must fall back to some default. Migration cost: how much existing clients must change. Alignment with "a URL names a resource": whether the URL stays the permanent name of the thing.
Weighted score out of 100 = sum of (weight x score) divided by 5. Why 5: the weights sum to 100, so an option scoring 5 on every row would total 100 x 5 = 500, and dividing by 5 turns that perfect 500 into 100.
- URL: 15x5 + 15x5 + 15x5 + 15x5 + 10x2 + 10x5 + 10x3 + 10x2 = 75 + 75 + 75 + 75 + 20 + 50 + 30 + 20 = 420. 420 / 5 = 84.
- Header: 15x3 + 15x3 + 15x3 + 15x3 + 10x4 + 10x2 + 10x4 + 10x4 = 45 + 45 + 45 + 45 + 40 + 20 + 40 + 40 = 320. 320 / 5 = 64.
Sensitivity: remove the cacheability row (suppose no CDN). The remaining weights sum to 100 - 15 = 85, so a perfect score would be 85 x 5 = 425. URL: 420 - 75 = 345 of 425, which is 345 / 425 x 100 = 81.2 out of 100. Header: 320 - 45 = 275 of 425, which is 275 / 425 x 100 = 64.7. Remove cacheability and routing together (70 weight left, perfect score 350): URL = 270 / 350 x 100 = 77.1 and header = 230 / 350 x 100 = 65.7. The URL scheme still leads in this situation, so the decision is not an artefact of the CDN assumption.
What I would choose, and what would flip it
Choose the major version in the URL (/v1/, /v2/) for breaking changes only, with additive changes shipped inside a version without a new number. Reasons: partners are many and varied, a CDN sits in front, and a missing header silently pinning clients to some default is a real hazard. This follows the weights above: the four criteria worth 15 each all favour the URL.
It flips toward headers or media types when: there is no CDN and no hand-written clients, versioning of individual resources matters more than whole-API versions, or the platform is a hypermedia API (responses carry links telling the client what it can do next, so representations are already negotiated by media type).
Three alternatives and their trade-offs
| Approach | What it is | Strength | Cost |
|---|---|---|---|
| Major versions side by side | /v1 and /v2 run together | Clear contract, easy to route and measure | Two code paths to run, test and secure until sunset |
| In-place evolution with deprecation windows | One version; add, deprecate, remove per field with notice | No migration event for additive changes | Every removal needs its own notice and usage proof; hard for sweeping changes |
| Adapters | One internal model; adapters (small translation layers at the edge) present old shapes | Old clients keep working while the core moves on | Adapter bugs, hidden coupling, and a permanent layer if never retired |
In practice these combine: in-place evolution for small changes, a new major version for a real break, and adapters to run the old major cheaply during its notice period.
Announcing the decision and the timeline
The dates here are assumptions that satisfy the assumed 12-month clause. Announce Tuesday 2027-06-01. Version 2 reaches general availability Wednesday 2027-09-01 (92 days after the announcement). Version 1 returns Deprecation and Sunset headers from that date (RFC 9745, RFC 8594) with a sunset of Thursday 2028-06-01, which is 366 days after the announcement (the span includes 2028-02-29) and 274 days after general availability. Checkpoints on the way: a reminder to every caller still on v1 on 2028-03-01 (92 days before sunset), a test brownout (a short announced window in which v1 is made to fail on purpose so forgotten callers notice) on 2028-05-01 (31 days before) and a final warning on 2028-05-15 (17 days before).
What the announcement carries, in the channels integrators actually read:
- the decision and the rubric result in two sentences, the date table, and the migration guide;
- a per-integrator message listing which of their keys still call v1 and how many calls per day;
- a changelog entry, a status-page notice, and headers on the responses themselves;
- a named contact and a sandbox with v2 enabled so teams can test before they commit.
Common mistakes
- Debating taste instead of scoring criteria against the real consumer base.
- Letting a missing header default to the oldest version forever.
- Picking a scheme without telemetry to count callers per version.
- Announcing a date shorter than the contract notice.
You are shipping the first public version of an API that many third-party developers will integrate with. What are the ways a client could select or pin an API version, and what does each option cost you in caching, routing, discoverability and developer experience? Which would you pick and why?
Sample Answer
The idea in plain words
An API (application programming interface) is a contract between your server and the programs that call it, called consumers. A breaking change is an edit that makes a correct, existing consumer fail (renaming a field, making a new request field required, changing a type). A version selector is the part of each request that tells the server which edition of the contract the consumer expects. Once thousands of outside developers depend on you, you cannot fix their code, so the selector is how you ship a breaking change without forcing everyone to change on the same day.
There are five places a selector can live. For a first public API with many third-party developers I would put the major version in the URL path (/v1/orders), promise that nothing breaking ever lands inside a major version, and run deprecation (announcing that something is going away while it still works) as a dated program when /v2 ships, ending in a sunset (the date the old version stops working). The table below shows what each option costs, and the sections after it show what would change my mind.
The five options and what each costs
| Option | Example | Caching | Routing | Discoverability | Developer experience |
|---|---|---|---|---|---|
| 1. URL path | GET /v1/orders/17 | Each version is a different URL, so a shared cache (a CDN, a content delivery network of cache servers near users, or a proxy between client and server) keeps separate entries with no configuration | The gateway (the front-door server that applies shared rules and routes requests) matches a prefix and sends it to a deployment | Visible in docs, logs, browser bar, curl | Copy-paste friendly; every link a client stored changes when the major changes |
| 2. Query parameter | GET /orders/17?version=2 | Usually part of the cache key (what a cache compares to decide two requests are the same), but some caches drop or reorder query strings, so it must be tested | Needs query-aware rules | Visible, but easy to omit, which silently selects a default | Easy to try; clutters every URL |
| 3. Custom request header | API-Version: 2 | Same URL, different body: unsafe unless every response carries Vary: API-Version | Needs header-matching rules at the gateway | Invisible in the URL, absent from most logs unless you add it | Clean URLs; harder to test in a browser; a forgotten header means the default version |
4. Media type in Accept | Accept: application/vnd.example.v2+json | Needs Vary: Accept, and Accept values differ between clients, so cache entries fragment | Parse the media type, then route | Invisible | Matches HTTP content negotiation (the client lists the formats it accepts in the Accept header and the server picks one); most unfamiliar to newcomers |
| 5. Version pinned to the account | key created on 2027-03-02 is pinned to the 2027-03-02 contract | Response depends on who asks, so shared caching is lost (private or Vary: Authorization) | Look up the pin per request | Hidden; "which version am I on?" needs a dashboard | Best stability for the client and fine-grained dated versions; most server-side compatibility code |
Option 5 is the least familiar, so here is how it runs. A dated version is a contract named by the date it was published. On an account's first call the server records the date as the account's pin, and every later call is answered in that contract even months afterwards. Illustration: the key created on 2027-03-02 makes its first call, the server stores pin = 2027-03-02, and a call in 2028 still gets the 2027-03-02 response shapes unless the request carries a header overriding the pin; a key created on 2027-09-01 is pinned to the 2027-09-01 contract.
Vary is the response header (RFC 9110, caching rules in RFC 9111) that tells a cache which request headers changed the response, so it must key its stored copy on them.
The caching failure in an illustrative exchange
Both exchanges below are illustrative (not captures from a real server) and internally consistent: the Content-Length values equal the body byte counts.
GET /orders/ord_17 HTTP/1.1
Host: api.example.com
API-Version: 1
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 75
Cache-Control: public, max-age=300
{"id":"ord_17","status":"shipped","total":{"amount":4200,"currency":"USD"}}
Forty-two seconds later a second client asks for version 2 through the same shared cache:
GET /orders/ord_17 HTTP/1.1
Host: api.example.com
API-Version: 2
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 75
Cache-Control: public, max-age=300
Age: 42
{"id":"ord_17","status":"shipped","total":{"amount":4200,"currency":"USD"}}
The cache matched on method and URL only, so the version 2 client received the version 1 body. Reading the headers: public allows shared caches to store the response, max-age=300 lets a cache reuse it for 300 seconds without asking the origin, and Age: 42 says the stored copy is 42 seconds old. The fix is Vary: API-Version on the origin response; the cache then stores one entry per header value. The cost is a lower hit ratio (the share of requests answered from cache), and each CDN's handling of Vary on custom headers has to be checked, which is exactly the configuration burden that path versioning avoids.
Why the path wins for this situation
- The people you cannot talk to are the people you are optimising for. They paste a curl line from the docs. A path version works in a browser, in a log grep and in a bug report with no extra explanation.
- Operations get cheaper. Routing is a prefix match, caching needs no
Varytuning, and the version appears in every access log line, so "who still calls v1" is a search of the access log (the server's record of every request) rather than a header-parsing project. - Coarse versions fit a public contract. A major version moves all endpoints together, so there are few, large, well-announced migrations rather than a stream of small ones.
Inside a major version the rule is additive only: new optional fields, new endpoints, new enum values that the documentation told consumers to tolerate. Anything breaking waits for the next major.
What would change the choice
- If breaking changes arrive many times a year, path majors force you to ship
/v2,/v3,/v4constantly. Account-pinned dated versions (option 5) fit that pace, at the price of compatibility code for every dated change. - If resource URLs are stored as identities (bookmarks, citations, links inside stored data), keep the identifier stable across majors (
/v1/datasets/42and/v2/datasets/42name the same dataset) so a move to v2 is a prefix swap. - A public read-only data API is heavily cached and its URLs get cited and bookmarked, so path versioning is an even stronger fit there than for a transactional API.
SDKs and semantic versioning
An SDK (software development kit, the client library you publish) carries its own version. Semantic versioning writes it MAJOR.MINOR.PATCH: MAJOR for changes that break the SDK's own interface, MINOR for backward-compatible additions, PATCH for backward-compatible fixes. A new optional API field becomes an SDK minor release. API v2 becomes SDK 2.0.0 because v2 forces changed method signatures. The SDK also removes a long-deprecated method in a major bump even if the API did not change. The SDK should hard-code the API major it targets and never depend on a server default; the README keeps a table of which SDK major talks to which API major.
Rollout and measuring migration
On launch day, before anything needs deprecating: publish the stability promise (what counts as breaking), version the OpenAPI document (the machine-readable description of every endpoint and its shapes), write the version into every log line, and make the SDK send it explicitly. When /v2 ships, measure migration with three numbers, because they disagree.
Illustrative assumption for one week: 1,000 active keys; 640 call only v1, 260 call only v2, 100 call both. Requests: 8.0 million to v1, 2.0 million to v2.
- Request share on v2: 2.0 / (8.0 + 2.0) = 20%.
- Keys that touched v2: (260 + 100) / 1,000 = 36%.
- Keys fully migrated (no v1 call): 260 / 1,000 = 26%.
Retirement depends on the last number, because a key that still calls v1 even once will break on the sunset date.
Pitfalls
- Calling an addition "non-breaking" when consumers parse strictly or use closed enums (code that accepts only the listed values of a field with a fixed set of choices, so a new value fails). State the tolerance rule in the contract.
- Letting a missing selector default to the newest version. Default to the oldest supported or reject the request.
- Choosing a header scheme for URL elegance and discovering later that logs and caches ignore it.
Unlock Full Question Bank
Get access to all 6 API Versioning, Deprecation and Backward Compatibility interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.