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.
Your company has many internal teams calling each other's APIs and a set of external partners calling the public ones. Should internal and external APIs follow the same versioning and deprecation rules? Lay out what you would standardize, what you would relax internally, and how you would automate enforcement.
Sample Answer
The idea in plain words
Standardize the definitions and the machinery; relax the ceremony and the calendar. What counts as a breaking change is a fact about the data, not a matter of policy: a renamed field breaks every piece of code that reads the old name, whoever wrote that code, whether a partner or the team next door. What differs is how many consumers you have, whether you can name and contact them, and how long they need to move. Internal consumers are enumerable, so notice can be shorter and migrations can be pushed by the provider; external consumers are not, so they get long notice, concurrent versions and public documents.
What to standardize (the same for everyone)
- One definition of breaking (a short written table: removing, renaming, retyping, tightening validation (rejecting input that used to be accepted), new required input, changing error shapes, and so on).
- A machine-readable contract in a registry (a shared catalogue where every released contract is stored with its version): OpenAPI, GraphQL schema or
.proto, published on every release and stored with its version. - One version identifier scheme per protocol (for example a major version in the URL for REST, a package version for gRPC, additive evolution for GraphQL).
- Deprecation signals:
DeprecationandSunsetresponse headers (RFC 9745, RFC 8594),@deprecatedin GraphQL (the schema marker that flags a field as going away),deprecatedoptions in OpenAPI and protobuf. - Telemetry with caller identity: every call tagged with a consumer id (API key externally, service identity internally) so usage per consumer per version is a query.
- A breaking-change gate in CI and a deprecation record (owner, dates, consumers, status) for every planned break.
What to relax internally
| Aspect | External (partners) | Internal teams |
|---|---|---|
| Notice before sunset (assumed) | 12 months | 90 days |
| Concurrent old versions | Yes, until the sunset date | Usually one old major, sometimes none |
| Who does the migration work | The partner, helped by guides and tooling | The provider can open the pull requests with a codemod |
| Public changelog and sandbox | Required | A registry entry and a channel |
| Exceptions | Per-contract, approved by product | Approved by the owning engineering manager with an expiry date |
| Lockstep release | Not possible | Allowed when contract tests are green in both repos |
Do not relax the classification, the registry, the telemetry or the CI gate. Dropping those is how an internal outage is caused by a "harmless" rename. The 90 days is an assumption; set it from how often consumer teams deploy, not from a number copied elsewhere.
Worked calendar
Assumptions: an Inventory API v1 has 9 internal consumers and 40 external partner integrations.
Internal (90 days): day 0 is Wednesday 2027-09-01 (an assumed date).
- Day 0, 2027-09-01: deprecation record opened, headers on, registry marks v1 deprecated, each of the 9 consumers gets a ticket generated from telemetry.
- Day 14, 2027-09-15 (Wednesday): all 9 owners have acknowledged and chosen a date; unacknowledged ones go to their manager.
- Day 61, 2027-11-01: the provider disables v1 in the staging environment (the test copy of production) so integration tests expose stragglers. Day 61 is 29 days before the production cut-off on day 90, which leaves about four weeks to fix what fails.
- Day 90, 2027-11-30 (Tuesday): v1 off in production for internal callers, except exceptions with expiry dates.
External (12 months): the same day 0, but sunset on Friday 2028-09-01, which is 366 days later (the span includes 2028-02-29), with a published schedule, partner notices and brownouts (short announced windows in which the old version is made to fail on purpose so forgotten callers notice).
Automating enforcement
- CI gate: the contract diff runs on every pull request and blocks breaking changes unless the pull request links an open deprecation record. The check reads the record's dates and compares today with the latest sunset date among the audiences still calling that contract, so a removal that lands before the notice period has run out fails the build, and a closed record cannot be reused to license a later break.
- Consumer-driven contract tests: each consumer writes down the requests it sends and the responses it relies on and publishes them to a broker (a shared service that stores those expectations); the provider's pipeline verifies them on every change. This works best internally, where every consumer can be required to publish.
- Registry and discovery: gateway or mesh telemetry (a service mesh is a layer of proxies carrying traffic between internal services, and its logs show who calls whom) fills a registry of "service A calls API B at version N". Architecture diagrams are generated from it, so version annotations cannot drift away from reality as hand-drawn diagrams do.
- Deadline bot: opens tickets and pull requests in consumer repositories (using a codemod, a script that rewrites caller source code automatically, where the change is mechanical), posts a weekly digest of consumers still on the old version, and escalates at fixed points (day 14 acknowledgement, day 61 staging cut-off).
- Policy as code: the rules above (notice lengths, required headers, required contract file) live as files in a repository and are checked by the same pipeline, instead of living in a wiki page.
Start with the shared definition, the registry and the CI gate: they are cheap and the other tools read from them. Contract tests, the deadline bot and policy as code are added as the number of teams grows.
What a deprecation record and a failing gate look like
Illustrative record (the format is an example, not a standard):
id: DEP-0142
api: inventory
deprecated: v1
replacement: v2
announced: 2027-09-01
sunset_internal: 2027-11-30
sunset_external: 2028-09-01
owner: inventory-team
status: open
Illustrative gate output when a pull request removes a response property and links no record:
contract-diff: BREAKING in inventory/openapi.yaml
removed response property 'quantity_on_hand' from GET /v1/items/{id}
deprecation record: none linked
RESULT: FAIL (link an open deprecation record to allow a breaking change)
If the same pull request links DEP-0142 on 2027-10-15, the check fails with the record named, because the notice period has not run out:
contract-diff: BREAKING in inventory/openapi.yaml
removed response property 'quantity_on_hand' from GET /v1/items/{id}
deprecation record: DEP-0142 (open), sunset_internal 2027-11-30, sunset_external 2028-09-01
RESULT: FAIL (sunset not reached: 46 days to the internal date, 322 days to the external date)
The same removal passes on or after the latest sunset date of the audiences still calling the contract, so the pipeline enforces the notice period instead of relying on memory.
This is a small rule set meant as a starting point. It covers contract shape, signals and deadlines. A real programme also handles behavioural changes, ownership changes, undocumented consumers (traffic with no identity) and shared libraries that hide which service really calls.
Coordinating product, engineering and infra on timelines
Use the deprecation record as the single artifact all three sign: product owns partner commitments and the external dates (it knows the contracts), engineering owns the migration plan and tooling, infra owns the routing table, capacity for running two versions, and the brownout schedule. One calendar, one record, one owner per row; a date changes only through the record.
Recommendation
Same rules and tooling for both audiences, two calendars. If a team asks for "no process internally", the reply is that the internal process is already lighter: the notice is 90 days instead of 12 months and the provider may carry the migration pull requests; the registry and gate cost almost nothing once built.
What would change this: if internal consumers cannot be identified (no telemetry), you cannot shorten anything and internal APIs must be treated like external ones until you can.
Common mistakes
- Skipping the registry internally and finding consumers only after something breaks.
- Letting internal deprecations have no end date because "we can just ask".
- Using one blanket notice period for every API.
- Drawing version diagrams by hand.
An API is served worldwide through CDNs and owned by several teams. How do you design version selection so that canarying a new version, retiring an old one and caching at the edge all keep working? What breaks cache hit rate and how do you avoid it?
Sample Answer
The idea in plain words
A CDN (content delivery network, a fleet of cache servers in many regions) stores a response under a cache key: by default the full URL. If a response can differ by a request header, the origin names that header in Vary (RFC 9110 and RFC 9111), and the cache then stores one copy per distinct value of that header. So a version scheme interacts with caching in one place: how many distinct cache keys the same logical resource turns into. A version in the path gives each version its own URL for free. A version in a header works only if the edge (the CDN's cache servers near users, as opposed to the origin, your own servers) normalizes that header, meaning it rewrites the many spellings into a small, stable set of values, before it becomes part of the key.
Design of version selection
- One platform-owned routing table. Several teams own services, but the version is a property of the whole API. A single table maps (version, path prefix) to an upstream and a traffic weight. Teams deploy behind it; they do not invent their own version tokens.
- Resolve the version once, at the edge, to a canonical token. From the path (
/v2/...) or, if headers are supported, from a version header orAcceptmedia type; apply a documented default; reject unknown values with 400. Put only the canonical token (v1,v2) in the cache key and forward it to the origin. - Make
Varytruthful and narrow. The origin lists only headers that change the body, such asAccept-Encoding. AvoidVaryon the rawAcceptheader: browsers and libraries send many distinct values for the same meaning, and each becomes a separate copy. - Canary by stable assignment, not by coin flip per request. Canarying means sending a small share of callers to the new version first, so a problem shows up on a few clients before everyone has it. Assign each API key to a track by a hash (for example
hash(api_key) mod 100 < 5is canary). In words: a hash turns the key into a whole number,mod 100takes the remainder after dividing by 100 (so 0 to 99), and remainders 0 to 4 are canary. With an illustrative hash of 1,234,567,837 forkey_abc, the remainder is 37, which is not below 5, so that key always stays on stable; a key whose hash ends in 03 has remainder 3 and is always canary. The same key always gives the same number, so it never flips between tracks, and because a good hash spreads keys evenly, 5 of the 100 remainders is about 5 percent of keys. Put the track (stableorcanary) in the cache key for the versions being canaried. A random per-request choice at the edge would let one cached answer serve both cohorts and make a single client flip between behaviours. - Retire by route removal, after usage proves it. Count requests per version from edge logs. When a version's traffic is gone, remove its route from the table and return
410 Goneon its paths.
What breaks the hit rate, with numbers
Model (assumptions): 1,000 hot resources, 100 requests per second spread evenly, a 60-second TTL (time to live), and one edge cache. Simplified rule: once a key is in steady demand, it misses once per TTL, so hit ratio = 1 - 1 / n, where n is requests per key per TTL. The reason: in each TTL window the first request for a key finds nothing stored and goes to the origin (a miss), and the other n - 1 requests in that window are served from the cache (hits), so the hit share is (n - 1) / n = 1 - 1 / n.
- No fragmentation: n = 100 x 60 / 1,000 = 6 requests per key per TTL. Hit ratio = 1 - 1/6 = 0.833 (83.3%). Origin load = 100 x (1/6) = 16.7 requests per second.
- Raw
Acceptcreates 4 equally common variants: each key now gets n = 6 / 4 = 1.5. Hit ratio = 1 - 1/1.5 = 0.333 (33.3%). Origin load = 100 x (2/3) = 66.7 requests per second. - Ratio of origin loads = 66.7 / 16.7 = 4. Fragmenting the key four ways quadruples origin load in this model, as it multiplies the number of keys by four.
- A 5 percent canary track adds its own keys: 5 requests per second over 1,000 keys x 60 s = 0.3 requests per key per TTL. With n below 1 almost every request misses, so the canary cohort hits the origin on nearly all of its roughly 5 requests per second. That is the price of an isolated canary; keep it small and short, or raise the TTL for canary traffic.
The 1 - 1/n rule assumes steady arrivals and ignores request coalescing (the cache sends one request to the origin when several arrive for the same missing key and shares the answer) and cache tiering (a second cache layer between the edge and the origin); it shows direction and rough size, not a forecast.
What the fragmentation looks like with two concrete values. Client A sends Accept: application/json; client B sends Accept: application/json, text/plain;q=0.9, */*;q=0.8. Both want the same JSON. If the origin answers Vary: Accept, the cache stores one copy per exact header string, so A and B never share a copy; four such spellings give four copies of the same body, which is the four-way split in the model above.
Illustrative exchange
Request (version in the path):
GET /v2/orders/ord_123 HTTP/1.1
Host: api.example.com
Accept: application/json
Accept-Encoding: gzip
Illustrative response from the edge:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 45
Cache-Control: public, max-age=60
Vary: Accept-Encoding
{"id":"ord_123","status":"paid","total":2500}
max-age=60 lets shared caches reuse it for 60 seconds, Vary: Accept-Encoding stores a gzip and an identity copy separately, and Content-Length matches the 45-byte body. The version lives in the URL, so no version header needs to be listed in Vary.
Retiring a version without breaking the cache
- Before sunset, responses carry
DeprecationandSunset(RFC 9745, RFC 8594) so every cache layer forwards the signal. - Brownouts (scheduled short windows when the old version is made to fail on purpose) should send
Cache-Control: no-storeso a cache does not keep serving the failure after the window ends. A 410 may be stored by a cache even without explicit freshness headers (RFC 9110 lists it as cacheable by default), so the final410 Gonecan be cached, which is acceptable once the removal is permanent.
Feature flags, negotiation, and the microservices platform
- Feature flags (server-side on/off switches) are good for rolling out an implementation to a cohort and switching it off, and are the better tool for risky internals. They are a poor replacement for versions when the contract itself differs, because per-client flag state becomes an undocumented version matrix and also multiplies cache keys.
- Client negotiation: external partners select a version explicitly (path or documented header); internal clients inside the platform call services directly, rely on additive changes and consumer contract tests (tests written by the calling team recording the requests it sends and the responses it relies on, replayed against the provider), and do not use the public version scheme. A service mesh (a layer of proxies that carries traffic between internal services) can route by version for them.
- Removal policy: remove a version's route only after the notice period and after edge logs show its traffic at the agreed floor; keep the 410 route for a further period so late callers get an explanation.
Recommendation
For the external API, put the major version in the path, canonicalize anything else at the edge, keep Vary to Accept-Encoding, canary by stable hash with a separate cache key, and retire by route removal. Header or media-type selection is acceptable if the edge maps it to a canonical token before the cache key is formed.
Common mistakes
- Using raw
Acceptor user-agent strings in the cache key. - Canarying with a per-request random choice behind a shared cache.
- Giving each team its own version scheme.
- Removing a route before checking edge logs for remaining callers.
Roll a breaking API change from v1 to v2 with zero downtime. Describe how old and new implementations run side by side, how traffic moves gradually, how the data store changes without breaking either version, and what triggers a rollback.
Sample Answer
The idea in plain words
"Zero downtime" for a breaking change means two separate things moving gradually: the code that serves requests (old and new implementations running together) and the data they share (a schema that both can read and write). The rule that makes both safe is that every step must be compatible with the step before it, so that at any moment you can stop or go back. For data, that rule is called expand-contract: first expand the schema so it holds both shapes, then migrate, and only at the very end contract by deleting what the old version needed.
Note the two meanings of "gradually": consumers moving from /v1 to /v2 is slow (months) and under their control; your own traffic shifting between old and new server code behind a contract is fast (days) and under yours. The first is deprecation; the second is the rollout described here.
Step 1: run old and new side by side
- Keep the v1 contract unchanged and add v2 as a separate route (
/v2/...) or media type (the format name the client sends in itsAcceptheader) served by the same deployment, or by a new deployment next to the old one. - Put both behind the same entry point: an API gateway, an ingress (the component that admits outside traffic into a cluster of servers and routes it) or a service mesh (a layer of small proxies, one beside each service, that handles routing between services). Each request is tagged with its version and routed to the right backend.
- Where the breaking change is internal (v1 stays but is re-implemented), the same entry point sends a percentage of v1 traffic to the new implementation.
Step 2: change the data store with expand-contract
Assumed change: v1 stores full_name in one column; v2 needs given_name and family_name. In the table, dual-write means writing the same data in both the old and the new shape, and a backfill job is a batch job that fills the new columns for rows that already exist.
| Phase | Schema and code | Safe to roll back? |
|---|---|---|
| 1. Expand | Add nullable columns given_name, family_name; no code reads them | Yes, nothing uses them |
| 2. Dual-write | Code on both versions writes full_name and the two new columns, in the same transaction so they cannot disagree | Yes, old columns are still complete |
| 3. Backfill | A batch job fills the new columns for existing rows | Yes |
| 4. Switch reads | Behind a feature flag, v2 reads the new columns; v1 reads the old column; compare results in the background | Yes, flip the flag |
| 5. Contract | After v1 is sunset and a quiet period, stop writing full_name and drop it | No, this is the only irreversible step |
Backfill sizing (assumptions: 120,000,000 rows, 5,000 rows per second sustained so as not to starve live traffic): 120,000,000 / 5,000 = 24,000 seconds, and 24,000 / 3,600 = 6.67 hours. Run it in small batches with a restart point so it can pause.
Step 3: shift traffic gradually
Use percentage routing that is sticky by consumer: compute a hash of the API key (or user id) and compare its bucket (0 to 99) with the current percentage. A consumer then stays on one side while the percentage holds (the routing is called sticky), instead of flipping between implementations request to request, which would make bugs impossible to reproduce. The bucket is the SHA-256 hash of the key read as a number and reduced modulo 100; a key is routed to the new implementation when its bucket is below the current percentage. A feature flag service or a weighted route in a service mesh can implement this; in Kubernetes with a mesh such as Istio, the usual shape is two deployments (one per version) and a routing rule that sets the weights, with a header match to pin chosen consumers. Exact configuration syntax is version dependent; check your mesh's documentation.
Illustrative ramp (assumed): 1 percent for 24 hours, 5 percent for 24 hours, 25 percent for 48 hours, 50 percent for 48 hours, then 100 percent. Total time at stages before reaching 100 percent: 24 + 24 + 48 + 48 = 144 hours = 6 days. Hold at each stage until the rollback criteria below stay green for the hold time.
The program traces ten example keys through the ramp and applies the comparison rule used in step 4.
import hashlib
def bucket(api_key):
return int(hashlib.sha256(api_key.encode()).hexdigest(), 16) % 100
def on_new_path(api_key, percent):
return bucket(api_key) < percent
keys = [f"key_{name}" for name in
("bank", "web", "mobile", "acme", "globex", "initech", "umbrella", "hooli", "stark", "wayne")]
for percent in (1, 5, 25):
print(f"{percent:2} percent:", sorted(k for k in keys if on_new_path(k, percent)))
# A key on the new path at 1 percent stays there at 5 and 25 percent.
assert all(on_new_path(k, 5) for k in keys if on_new_path(k, 1))
assert all(on_new_path(k, 25) for k in keys if on_new_path(k, 5))
print({k: bucket(k) for k in keys[:5]})
# Background comparison: sampled read requests are answered by v1 code AND by the new code.
sampled = 20000
for mismatches in (14, 25):
rate = 100 * mismatches / sampled
print(f"{mismatches} mismatches in {sampled} sampled reads = {rate:.3f} percent ->",
"roll back" if rate > 0.1 else "hold the ramp")
Output:
1 percent: ['key_bank']
5 percent: ['key_bank', 'key_mobile', 'key_web']
25 percent: ['key_bank', 'key_globex', 'key_mobile', 'key_umbrella', 'key_web']
{'key_bank': 0, 'key_web': 1, 'key_mobile': 2, 'key_acme': 78, 'key_globex': 10}
14 mismatches in 20000 sampled reads = 0.070 percent -> hold the ramp
25 mismatches in 20000 sampled reads = 0.125 percent -> roll back
Read-out: at 1 percent only key_bank (bucket 0) is on the new path; at 5 percent key_web (bucket 1) and key_mobile (bucket 2) join it; at 25 percent key_globex (10) and key_umbrella (15) join too, and the two assertions confirm that nobody on the new path at a lower percentage ever drops off at a higher one. The last two lines apply the rollback rule from step 5: 14 mismatches in 20,000 sampled reads is 14 / 20,000 = 0.07 percent, under the 0.1 percent limit, so the ramp holds; 25 is 25 / 20,000 = 0.125 percent, over it, so the percentage goes to 0.
Step 4: observe per version
Tag every metric, log line and trace with api_version, the implementation version and a consumer id. Compare the two sides: error rate (5xx: the share of responses with a status from 500 to 599, which means the server failed), p99 latency (the time that 99 percent of requests beat; the slowest 1 percent take longer), and a correctness signal, the mismatch rate. The mismatch rate works like this: for a sample of incoming read requests (say 1 percent of v1 reads, chosen at random), the entry point lets the old implementation answer the consumer as usual and also sends a copy to the new implementation in the background. A comparison job diffs the two response bodies after dropping fields that differ on every call, such as request ids and timestamps. Mismatch rate = requests whose bodies differ / requests sampled. Writes are not compared this way because running them twice would change data.
Step 5: rollback triggers (illustrative numbers)
Roll back immediately, by setting the percentage to 0, when any of these holds over a 10-minute window:
- 5xx rate on the new path exceeds the old path's rate by 0.5 percentage points or more.
- p99 latency on the new path is more than 1.3 times the old path's.
- The background comparison mismatch rate exceeds 0.1 percent.
- Any sign of data loss or corruption (this one has no threshold).
Because phases 1 to 4 keep the old columns complete, rollback means changing a flag, with no data restore. Rollback of the contract phase is a restore from backup, which is why it waits until v1 has been gone for an agreed quiet period.
What a real process must also handle
These numbers and rules are an illustration of the shape. A real rollout also needs: dual-write failure handling (what happens when the second write fails; the same transaction is the simplest answer), writes arriving during backfill, replicas lagging when you compare reads, long-running requests that straddle a switch, caches keyed on the old shape, and consumers who send idempotency keys (unique tokens that let the server recognise a retried request and not repeat it) across the switch.
Common mistakes
- Doing the schema change and the code change in one deploy.
- Using random per-request routing and so showing one consumer two behaviours.
- Dropping the old column while some v1 clients or a rollback target still need it.
- Having rollback triggers that name no number, so nobody dares to call them.
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.
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.
That is every published API Versioning, Deprecation and Backward Compatibility question for Cloud Architect so far. Browse the other topics in this category, or practice this one interactively.